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