1 //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that keeps track of @llvm.assume intrinsics in
11 // the functions of a module.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/AssumptionCache.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Dominators.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/IR/PatternMatch.h"
23 #include "llvm/Support/Debug.h"
25 using namespace llvm::PatternMatch;
28 VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
29 cl::desc("Enable verification of assumption cache"),
32 SmallVector<WeakTrackingVH, 1> &
33 AssumptionCache::getOrInsertAffectedValues(Value *V) {
34 // Try using find_as first to avoid creating extra value handles just for the
35 // purpose of doing the lookup.
36 auto AVI = AffectedValues.find_as(V);
37 if (AVI != AffectedValues.end())
40 auto AVIP = AffectedValues.insert(
41 {AffectedValueCallbackVH(V, this), SmallVector<WeakTrackingVH, 1>()});
42 return AVIP.first->second;
45 void AssumptionCache::updateAffectedValues(CallInst *CI) {
46 // Note: This code must be kept in-sync with the code in
47 // computeKnownBitsFromAssume in ValueTracking.
49 SmallVector<Value *, 16> Affected;
50 auto AddAffected = [&Affected](Value *V) {
51 if (isa<Argument>(V)) {
52 Affected.push_back(V);
53 } else if (auto *I = dyn_cast<Instruction>(V)) {
54 Affected.push_back(I);
56 // Peek through unary operators to find the source of the condition.
58 if (match(I, m_BitCast(m_Value(Op))) ||
59 match(I, m_PtrToInt(m_Value(Op))) ||
60 match(I, m_Not(m_Value(Op)))) {
61 if (isa<Instruction>(Op) || isa<Argument>(Op))
62 Affected.push_back(Op);
67 Value *Cond = CI->getArgOperand(0), *A, *B;
70 CmpInst::Predicate Pred;
71 if (match(Cond, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
75 if (Pred == ICmpInst::ICMP_EQ) {
76 // For equality comparisons, we handle the case of bit inversion.
77 auto AddAffectedFromEq = [&AddAffected](Value *V) {
79 if (match(V, m_Not(m_Value(A)))) {
86 // (A & B) or (A | B) or (A ^ B).
87 if (match(V, m_BitwiseLogic(m_Value(A), m_Value(B)))) {
90 // (A << C) or (A >>_s C) or (A >>_u C) where C is some constant.
91 } else if (match(V, m_Shift(m_Value(A), m_ConstantInt(C)))) {
101 for (auto &AV : Affected) {
102 auto &AVV = getOrInsertAffectedValues(AV);
103 if (std::find(AVV.begin(), AVV.end(), CI) == AVV.end())
108 void AssumptionCache::AffectedValueCallbackVH::deleted() {
109 auto AVI = AC->AffectedValues.find(getValPtr());
110 if (AVI != AC->AffectedValues.end())
111 AC->AffectedValues.erase(AVI);
112 // 'this' now dangles!
115 void AssumptionCache::copyAffectedValuesInCache(Value *OV, Value *NV) {
116 auto &NAVV = getOrInsertAffectedValues(NV);
117 auto AVI = AffectedValues.find(OV);
118 if (AVI == AffectedValues.end())
121 for (auto &A : AVI->second)
122 if (std::find(NAVV.begin(), NAVV.end(), A) == NAVV.end())
126 void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
127 if (!isa<Instruction>(NV) && !isa<Argument>(NV))
130 // Any assumptions that affected this value now affect the new value.
132 AC->copyAffectedValuesInCache(getValPtr(), NV);
133 // 'this' now might dangle! If the AffectedValues map was resized to add an
134 // entry for NV then this object might have been destroyed in favor of some
135 // copy in the grown map.
138 void AssumptionCache::scanFunction() {
139 assert(!Scanned && "Tried to scan the function twice!");
140 assert(AssumeHandles.empty() && "Already have assumes when scanning!");
142 // Go through all instructions in all blocks, add all calls to @llvm.assume
144 for (BasicBlock &B : F)
145 for (Instruction &II : B)
146 if (match(&II, m_Intrinsic<Intrinsic::assume>()))
147 AssumeHandles.push_back(&II);
149 // Mark the scan as complete.
152 // Update affected values.
153 for (auto &A : AssumeHandles)
154 updateAffectedValues(cast<CallInst>(A));
157 void AssumptionCache::registerAssumption(CallInst *CI) {
158 assert(match(CI, m_Intrinsic<Intrinsic::assume>()) &&
159 "Registered call does not call @llvm.assume");
161 // If we haven't scanned the function yet, just drop this assumption. It will
162 // be found when we scan later.
166 AssumeHandles.push_back(CI);
169 assert(CI->getParent() &&
170 "Cannot register @llvm.assume call not in a basic block");
171 assert(&F == CI->getParent()->getParent() &&
172 "Cannot register @llvm.assume call not in this function");
174 // We expect the number of assumptions to be small, so in an asserts build
175 // check that we don't accumulate duplicates and that all assumptions point
176 // to the same function.
177 SmallPtrSet<Value *, 16> AssumptionSet;
178 for (auto &VH : AssumeHandles) {
182 assert(&F == cast<Instruction>(VH)->getParent()->getParent() &&
183 "Cached assumption not inside this function!");
184 assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) &&
185 "Cached something other than a call to @llvm.assume!");
186 assert(AssumptionSet.insert(VH).second &&
187 "Cache contains multiple copies of a call!");
191 updateAffectedValues(CI);
194 AnalysisKey AssumptionAnalysis::Key;
196 PreservedAnalyses AssumptionPrinterPass::run(Function &F,
197 FunctionAnalysisManager &AM) {
198 AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
200 OS << "Cached assumptions for function: " << F.getName() << "\n";
201 for (auto &VH : AC.assumptions())
203 OS << " " << *cast<CallInst>(VH)->getArgOperand(0) << "\n";
205 return PreservedAnalyses::all();
208 void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
209 auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
210 if (I != ACT->AssumptionCaches.end())
211 ACT->AssumptionCaches.erase(I);
212 // 'this' now dangles!
215 AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) {
216 // We probe the function map twice to try and avoid creating a value handle
217 // around the function in common cases. This makes insertion a bit slower,
218 // but if we have to insert we're going to scan the whole function so that
220 auto I = AssumptionCaches.find_as(&F);
221 if (I != AssumptionCaches.end())
224 // Ok, build a new cache by scanning the function, insert it and the value
225 // handle into our map, and return the newly populated cache.
226 auto IP = AssumptionCaches.insert(std::make_pair(
227 FunctionCallbackVH(&F, this), llvm::make_unique<AssumptionCache>(F)));
228 assert(IP.second && "Scanning function already in the map?");
229 return *IP.first->second;
232 void AssumptionCacheTracker::verifyAnalysis() const {
233 // FIXME: In the long term the verifier should not be controllable with a
234 // flag. We should either fix all passes to correctly update the assumption
235 // cache and enable the verifier unconditionally or somehow arrange for the
236 // assumption list to be updated automatically by passes.
237 if (!VerifyAssumptionCache)
240 SmallPtrSet<const CallInst *, 4> AssumptionSet;
241 for (const auto &I : AssumptionCaches) {
242 for (auto &VH : I.second->assumptions())
244 AssumptionSet.insert(cast<CallInst>(VH));
246 for (const BasicBlock &B : cast<Function>(*I.first))
247 for (const Instruction &II : B)
248 if (match(&II, m_Intrinsic<Intrinsic::assume>()) &&
249 !AssumptionSet.count(cast<CallInst>(&II)))
250 report_fatal_error("Assumption in scanned function not in cache");
254 AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) {
255 initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
258 AssumptionCacheTracker::~AssumptionCacheTracker() {}
260 INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
261 "Assumption Cache Tracker", false, true)
262 char AssumptionCacheTracker::ID = 0;