1 //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains a pass that keeps track of @llvm.assume intrinsics in 10 // the functions of a module. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/AssumptionCache.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/AssumeBundleQueries.h" 19 #include "llvm/Analysis/TargetTransformInfo.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/InstrTypes.h" 23 #include "llvm/IR/Instruction.h" 24 #include "llvm/IR/Instructions.h" 25 #include "llvm/IR/PassManager.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <cassert> 34 #include <utility> 35 36 using namespace llvm; 37 using namespace llvm::PatternMatch; 38 39 static cl::opt<bool> 40 VerifyAssumptionCache("verify-assumption-cache", cl::Hidden, 41 cl::desc("Enable verification of assumption cache"), 42 cl::init(false)); 43 44 SmallVector<AssumptionCache::ResultElem, 1> & 45 AssumptionCache::getOrInsertAffectedValues(Value *V) { 46 // Try using find_as first to avoid creating extra value handles just for the 47 // purpose of doing the lookup. 48 auto AVI = AffectedValues.find_as(V); 49 if (AVI != AffectedValues.end()) 50 return AVI->second; 51 52 auto AVIP = AffectedValues.insert( 53 {AffectedValueCallbackVH(V, this), SmallVector<ResultElem, 1>()}); 54 return AVIP.first->second; 55 } 56 57 static void 58 findAffectedValues(CallBase *CI, TargetTransformInfo *TTI, 59 SmallVectorImpl<AssumptionCache::ResultElem> &Affected) { 60 // Note: This code must be kept in-sync with the code in 61 // computeKnownBitsFromAssume in ValueTracking. 62 63 auto AddAffected = [&Affected](Value *V, unsigned Idx = 64 AssumptionCache::ExprResultIdx) { 65 if (isa<Argument>(V) || isa<GlobalValue>(V)) { 66 Affected.push_back({V, Idx}); 67 } else if (auto *I = dyn_cast<Instruction>(V)) { 68 Affected.push_back({I, Idx}); 69 70 // Peek through unary operators to find the source of the condition. 71 Value *Op; 72 if (match(I, m_PtrToInt(m_Value(Op)))) { 73 if (isa<Instruction>(Op) || isa<Argument>(Op)) 74 Affected.push_back({Op, Idx}); 75 } 76 } 77 }; 78 79 for (unsigned Idx = 0; Idx != CI->getNumOperandBundles(); Idx++) { 80 if (CI->getOperandBundleAt(Idx).Inputs.size() > ABA_WasOn && 81 CI->getOperandBundleAt(Idx).getTagName() != IgnoreBundleTag) 82 AddAffected(CI->getOperandBundleAt(Idx).Inputs[ABA_WasOn], Idx); 83 } 84 85 Value *Cond = CI->getArgOperand(0), *A, *B; 86 AddAffected(Cond); 87 if (match(Cond, m_Not(m_Value(A)))) 88 AddAffected(A); 89 90 CmpInst::Predicate Pred; 91 if (match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) { 92 AddAffected(A); 93 AddAffected(B); 94 95 if (Pred == ICmpInst::ICMP_EQ) { 96 if (match(B, m_ConstantInt())) { 97 Value *X; 98 // (X & C) or (X | C) or (X ^ C). 99 // (X << C) or (X >>_s C) or (X >>_u C). 100 if (match(A, m_BitwiseLogic(m_Value(X), m_ConstantInt())) || 101 match(A, m_Shift(m_Value(X), m_ConstantInt()))) 102 AddAffected(X); 103 } 104 } else if (Pred == ICmpInst::ICMP_NE) { 105 Value *X; 106 // Handle (X & pow2 != 0). 107 if (match(A, m_And(m_Value(X), m_Power2())) && match(B, m_Zero())) 108 AddAffected(X); 109 } else if (Pred == ICmpInst::ICMP_ULT) { 110 Value *X; 111 // Handle (A + C1) u< C2, which is the canonical form of A > C3 && A < C4, 112 // and recognized by LVI at least. 113 if (match(A, m_Add(m_Value(X), m_ConstantInt())) && 114 match(B, m_ConstantInt())) 115 AddAffected(X); 116 } else if (CmpInst::isFPPredicate(Pred)) { 117 // fcmp fneg(x), y 118 // fcmp fabs(x), y 119 // fcmp fneg(fabs(x)), y 120 if (match(A, m_FNeg(m_Value(A)))) 121 AddAffected(A); 122 if (match(A, m_FAbs(m_Value(A)))) 123 AddAffected(A); 124 } 125 } else if (match(Cond, m_Intrinsic<Intrinsic::is_fpclass>(m_Value(A), 126 m_Value(B)))) { 127 AddAffected(A); 128 } 129 130 if (TTI) { 131 const Value *Ptr; 132 unsigned AS; 133 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(Cond); 134 if (Ptr) 135 AddAffected(const_cast<Value *>(Ptr->stripInBoundsOffsets())); 136 } 137 } 138 139 void AssumptionCache::updateAffectedValues(AssumeInst *CI) { 140 SmallVector<AssumptionCache::ResultElem, 16> Affected; 141 findAffectedValues(CI, TTI, Affected); 142 143 for (auto &AV : Affected) { 144 auto &AVV = getOrInsertAffectedValues(AV.Assume); 145 if (llvm::none_of(AVV, [&](ResultElem &Elem) { 146 return Elem.Assume == CI && Elem.Index == AV.Index; 147 })) 148 AVV.push_back({CI, AV.Index}); 149 } 150 } 151 152 void AssumptionCache::unregisterAssumption(AssumeInst *CI) { 153 SmallVector<AssumptionCache::ResultElem, 16> Affected; 154 findAffectedValues(CI, TTI, Affected); 155 156 for (auto &AV : Affected) { 157 auto AVI = AffectedValues.find_as(AV.Assume); 158 if (AVI == AffectedValues.end()) 159 continue; 160 bool Found = false; 161 bool HasNonnull = false; 162 for (ResultElem &Elem : AVI->second) { 163 if (Elem.Assume == CI) { 164 Found = true; 165 Elem.Assume = nullptr; 166 } 167 HasNonnull |= !!Elem.Assume; 168 if (HasNonnull && Found) 169 break; 170 } 171 assert(Found && "already unregistered or incorrect cache state"); 172 if (!HasNonnull) 173 AffectedValues.erase(AVI); 174 } 175 176 llvm::erase(AssumeHandles, CI); 177 } 178 179 void AssumptionCache::AffectedValueCallbackVH::deleted() { 180 AC->AffectedValues.erase(getValPtr()); 181 // 'this' now dangles! 182 } 183 184 void AssumptionCache::transferAffectedValuesInCache(Value *OV, Value *NV) { 185 auto &NAVV = getOrInsertAffectedValues(NV); 186 auto AVI = AffectedValues.find(OV); 187 if (AVI == AffectedValues.end()) 188 return; 189 190 for (auto &A : AVI->second) 191 if (!llvm::is_contained(NAVV, A)) 192 NAVV.push_back(A); 193 AffectedValues.erase(OV); 194 } 195 196 void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) { 197 if (!isa<Instruction>(NV) && !isa<Argument>(NV)) 198 return; 199 200 // Any assumptions that affected this value now affect the new value. 201 202 AC->transferAffectedValuesInCache(getValPtr(), NV); 203 // 'this' now might dangle! If the AffectedValues map was resized to add an 204 // entry for NV then this object might have been destroyed in favor of some 205 // copy in the grown map. 206 } 207 208 void AssumptionCache::scanFunction() { 209 assert(!Scanned && "Tried to scan the function twice!"); 210 assert(AssumeHandles.empty() && "Already have assumes when scanning!"); 211 212 // Go through all instructions in all blocks, add all calls to @llvm.assume 213 // to this cache. 214 for (BasicBlock &B : F) 215 for (Instruction &I : B) 216 if (isa<AssumeInst>(&I)) 217 AssumeHandles.push_back({&I, ExprResultIdx}); 218 219 // Mark the scan as complete. 220 Scanned = true; 221 222 // Update affected values. 223 for (auto &A : AssumeHandles) 224 updateAffectedValues(cast<AssumeInst>(A)); 225 } 226 227 void AssumptionCache::registerAssumption(AssumeInst *CI) { 228 // If we haven't scanned the function yet, just drop this assumption. It will 229 // be found when we scan later. 230 if (!Scanned) 231 return; 232 233 AssumeHandles.push_back({CI, ExprResultIdx}); 234 235 #ifndef NDEBUG 236 assert(CI->getParent() && 237 "Cannot register @llvm.assume call not in a basic block"); 238 assert(&F == CI->getParent()->getParent() && 239 "Cannot register @llvm.assume call not in this function"); 240 241 // We expect the number of assumptions to be small, so in an asserts build 242 // check that we don't accumulate duplicates and that all assumptions point 243 // to the same function. 244 SmallPtrSet<Value *, 16> AssumptionSet; 245 for (auto &VH : AssumeHandles) { 246 if (!VH) 247 continue; 248 249 assert(&F == cast<Instruction>(VH)->getParent()->getParent() && 250 "Cached assumption not inside this function!"); 251 assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) && 252 "Cached something other than a call to @llvm.assume!"); 253 assert(AssumptionSet.insert(VH).second && 254 "Cache contains multiple copies of a call!"); 255 } 256 #endif 257 258 updateAffectedValues(CI); 259 } 260 261 AssumptionCache AssumptionAnalysis::run(Function &F, 262 FunctionAnalysisManager &FAM) { 263 auto &TTI = FAM.getResult<TargetIRAnalysis>(F); 264 return AssumptionCache(F, &TTI); 265 } 266 267 AnalysisKey AssumptionAnalysis::Key; 268 269 PreservedAnalyses AssumptionPrinterPass::run(Function &F, 270 FunctionAnalysisManager &AM) { 271 AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F); 272 273 OS << "Cached assumptions for function: " << F.getName() << "\n"; 274 for (auto &VH : AC.assumptions()) 275 if (VH) 276 OS << " " << *cast<CallInst>(VH)->getArgOperand(0) << "\n"; 277 278 return PreservedAnalyses::all(); 279 } 280 281 void AssumptionCacheTracker::FunctionCallbackVH::deleted() { 282 auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr())); 283 if (I != ACT->AssumptionCaches.end()) 284 ACT->AssumptionCaches.erase(I); 285 // 'this' now dangles! 286 } 287 288 AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) { 289 // We probe the function map twice to try and avoid creating a value handle 290 // around the function in common cases. This makes insertion a bit slower, 291 // but if we have to insert we're going to scan the whole function so that 292 // shouldn't matter. 293 auto I = AssumptionCaches.find_as(&F); 294 if (I != AssumptionCaches.end()) 295 return *I->second; 296 297 auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>(); 298 auto *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr; 299 300 // Ok, build a new cache by scanning the function, insert it and the value 301 // handle into our map, and return the newly populated cache. 302 auto IP = AssumptionCaches.insert(std::make_pair( 303 FunctionCallbackVH(&F, this), std::make_unique<AssumptionCache>(F, TTI))); 304 assert(IP.second && "Scanning function already in the map?"); 305 return *IP.first->second; 306 } 307 308 AssumptionCache *AssumptionCacheTracker::lookupAssumptionCache(Function &F) { 309 auto I = AssumptionCaches.find_as(&F); 310 if (I != AssumptionCaches.end()) 311 return I->second.get(); 312 return nullptr; 313 } 314 315 void AssumptionCacheTracker::verifyAnalysis() const { 316 // FIXME: In the long term the verifier should not be controllable with a 317 // flag. We should either fix all passes to correctly update the assumption 318 // cache and enable the verifier unconditionally or somehow arrange for the 319 // assumption list to be updated automatically by passes. 320 if (!VerifyAssumptionCache) 321 return; 322 323 SmallPtrSet<const CallInst *, 4> AssumptionSet; 324 for (const auto &I : AssumptionCaches) { 325 for (auto &VH : I.second->assumptions()) 326 if (VH) 327 AssumptionSet.insert(cast<CallInst>(VH)); 328 329 for (const BasicBlock &B : cast<Function>(*I.first)) 330 for (const Instruction &II : B) 331 if (match(&II, m_Intrinsic<Intrinsic::assume>()) && 332 !AssumptionSet.count(cast<CallInst>(&II))) 333 report_fatal_error("Assumption in scanned function not in cache"); 334 } 335 } 336 337 AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) { 338 initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry()); 339 } 340 341 AssumptionCacheTracker::~AssumptionCacheTracker() = default; 342 343 char AssumptionCacheTracker::ID = 0; 344 345 INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker", 346 "Assumption Cache Tracker", false, true) 347