xref: /aosp_15_r20/external/llvm/lib/Analysis/LazyValueInfo.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file defines the interface for lazy computation of value constraint
11*9880d681SAndroid Build Coastguard Worker // information.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LazyValueInfo.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseSet.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CFG.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ConstantRange.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/ValueHandle.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
34*9880d681SAndroid Build Coastguard Worker #include <map>
35*9880d681SAndroid Build Coastguard Worker #include <stack>
36*9880d681SAndroid Build Coastguard Worker using namespace llvm;
37*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
38*9880d681SAndroid Build Coastguard Worker 
39*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "lazy-value-info"
40*9880d681SAndroid Build Coastguard Worker 
41*9880d681SAndroid Build Coastguard Worker char LazyValueInfoWrapperPass::ID = 0;
42*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
43*9880d681SAndroid Build Coastguard Worker                 "Lazy Value Information Analysis", false, true)
44*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
45*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
46*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
47*9880d681SAndroid Build Coastguard Worker                 "Lazy Value Information Analysis", false, true)
48*9880d681SAndroid Build Coastguard Worker 
49*9880d681SAndroid Build Coastguard Worker namespace llvm {
createLazyValueInfoPass()50*9880d681SAndroid Build Coastguard Worker   FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
51*9880d681SAndroid Build Coastguard Worker }
52*9880d681SAndroid Build Coastguard Worker 
53*9880d681SAndroid Build Coastguard Worker char LazyValueAnalysis::PassID;
54*9880d681SAndroid Build Coastguard Worker 
55*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
56*9880d681SAndroid Build Coastguard Worker //                               LVILatticeVal
57*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
58*9880d681SAndroid Build Coastguard Worker 
59*9880d681SAndroid Build Coastguard Worker /// This is the information tracked by LazyValueInfo for each value.
60*9880d681SAndroid Build Coastguard Worker ///
61*9880d681SAndroid Build Coastguard Worker /// FIXME: This is basically just for bringup, this can be made a lot more rich
62*9880d681SAndroid Build Coastguard Worker /// in the future.
63*9880d681SAndroid Build Coastguard Worker ///
64*9880d681SAndroid Build Coastguard Worker namespace {
65*9880d681SAndroid Build Coastguard Worker class LVILatticeVal {
66*9880d681SAndroid Build Coastguard Worker   enum LatticeValueTy {
67*9880d681SAndroid Build Coastguard Worker     /// This Value has no known value yet.  As a result, this implies the
68*9880d681SAndroid Build Coastguard Worker     /// producing instruction is dead.  Caution: We use this as the starting
69*9880d681SAndroid Build Coastguard Worker     /// state in our local meet rules.  In this usage, it's taken to mean
70*9880d681SAndroid Build Coastguard Worker     /// "nothing known yet".
71*9880d681SAndroid Build Coastguard Worker     undefined,
72*9880d681SAndroid Build Coastguard Worker 
73*9880d681SAndroid Build Coastguard Worker     /// This Value has a specific constant value.  (For integers, constantrange
74*9880d681SAndroid Build Coastguard Worker     /// is used instead.)
75*9880d681SAndroid Build Coastguard Worker     constant,
76*9880d681SAndroid Build Coastguard Worker 
77*9880d681SAndroid Build Coastguard Worker     /// This Value is known to not have the specified value.  (For integers,
78*9880d681SAndroid Build Coastguard Worker     /// constantrange is used instead.)
79*9880d681SAndroid Build Coastguard Worker     notconstant,
80*9880d681SAndroid Build Coastguard Worker 
81*9880d681SAndroid Build Coastguard Worker     /// The Value falls within this range. (Used only for integer typed values.)
82*9880d681SAndroid Build Coastguard Worker     constantrange,
83*9880d681SAndroid Build Coastguard Worker 
84*9880d681SAndroid Build Coastguard Worker     /// We can not precisely model the dynamic values this value might take.
85*9880d681SAndroid Build Coastguard Worker     overdefined
86*9880d681SAndroid Build Coastguard Worker   };
87*9880d681SAndroid Build Coastguard Worker 
88*9880d681SAndroid Build Coastguard Worker   /// Val: This stores the current lattice value along with the Constant* for
89*9880d681SAndroid Build Coastguard Worker   /// the constant if this is a 'constant' or 'notconstant' value.
90*9880d681SAndroid Build Coastguard Worker   LatticeValueTy Tag;
91*9880d681SAndroid Build Coastguard Worker   Constant *Val;
92*9880d681SAndroid Build Coastguard Worker   ConstantRange Range;
93*9880d681SAndroid Build Coastguard Worker 
94*9880d681SAndroid Build Coastguard Worker public:
LVILatticeVal()95*9880d681SAndroid Build Coastguard Worker   LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
96*9880d681SAndroid Build Coastguard Worker 
get(Constant * C)97*9880d681SAndroid Build Coastguard Worker   static LVILatticeVal get(Constant *C) {
98*9880d681SAndroid Build Coastguard Worker     LVILatticeVal Res;
99*9880d681SAndroid Build Coastguard Worker     if (!isa<UndefValue>(C))
100*9880d681SAndroid Build Coastguard Worker       Res.markConstant(C);
101*9880d681SAndroid Build Coastguard Worker     return Res;
102*9880d681SAndroid Build Coastguard Worker   }
getNot(Constant * C)103*9880d681SAndroid Build Coastguard Worker   static LVILatticeVal getNot(Constant *C) {
104*9880d681SAndroid Build Coastguard Worker     LVILatticeVal Res;
105*9880d681SAndroid Build Coastguard Worker     if (!isa<UndefValue>(C))
106*9880d681SAndroid Build Coastguard Worker       Res.markNotConstant(C);
107*9880d681SAndroid Build Coastguard Worker     return Res;
108*9880d681SAndroid Build Coastguard Worker   }
getRange(ConstantRange CR)109*9880d681SAndroid Build Coastguard Worker   static LVILatticeVal getRange(ConstantRange CR) {
110*9880d681SAndroid Build Coastguard Worker     LVILatticeVal Res;
111*9880d681SAndroid Build Coastguard Worker     Res.markConstantRange(std::move(CR));
112*9880d681SAndroid Build Coastguard Worker     return Res;
113*9880d681SAndroid Build Coastguard Worker   }
getOverdefined()114*9880d681SAndroid Build Coastguard Worker   static LVILatticeVal getOverdefined() {
115*9880d681SAndroid Build Coastguard Worker     LVILatticeVal Res;
116*9880d681SAndroid Build Coastguard Worker     Res.markOverdefined();
117*9880d681SAndroid Build Coastguard Worker     return Res;
118*9880d681SAndroid Build Coastguard Worker   }
119*9880d681SAndroid Build Coastguard Worker 
isUndefined() const120*9880d681SAndroid Build Coastguard Worker   bool isUndefined() const     { return Tag == undefined; }
isConstant() const121*9880d681SAndroid Build Coastguard Worker   bool isConstant() const      { return Tag == constant; }
isNotConstant() const122*9880d681SAndroid Build Coastguard Worker   bool isNotConstant() const   { return Tag == notconstant; }
isConstantRange() const123*9880d681SAndroid Build Coastguard Worker   bool isConstantRange() const { return Tag == constantrange; }
isOverdefined() const124*9880d681SAndroid Build Coastguard Worker   bool isOverdefined() const   { return Tag == overdefined; }
125*9880d681SAndroid Build Coastguard Worker 
getConstant() const126*9880d681SAndroid Build Coastguard Worker   Constant *getConstant() const {
127*9880d681SAndroid Build Coastguard Worker     assert(isConstant() && "Cannot get the constant of a non-constant!");
128*9880d681SAndroid Build Coastguard Worker     return Val;
129*9880d681SAndroid Build Coastguard Worker   }
130*9880d681SAndroid Build Coastguard Worker 
getNotConstant() const131*9880d681SAndroid Build Coastguard Worker   Constant *getNotConstant() const {
132*9880d681SAndroid Build Coastguard Worker     assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
133*9880d681SAndroid Build Coastguard Worker     return Val;
134*9880d681SAndroid Build Coastguard Worker   }
135*9880d681SAndroid Build Coastguard Worker 
getConstantRange() const136*9880d681SAndroid Build Coastguard Worker   ConstantRange getConstantRange() const {
137*9880d681SAndroid Build Coastguard Worker     assert(isConstantRange() &&
138*9880d681SAndroid Build Coastguard Worker            "Cannot get the constant-range of a non-constant-range!");
139*9880d681SAndroid Build Coastguard Worker     return Range;
140*9880d681SAndroid Build Coastguard Worker   }
141*9880d681SAndroid Build Coastguard Worker 
142*9880d681SAndroid Build Coastguard Worker   /// Return true if this is a change in status.
markOverdefined()143*9880d681SAndroid Build Coastguard Worker   bool markOverdefined() {
144*9880d681SAndroid Build Coastguard Worker     if (isOverdefined())
145*9880d681SAndroid Build Coastguard Worker       return false;
146*9880d681SAndroid Build Coastguard Worker     Tag = overdefined;
147*9880d681SAndroid Build Coastguard Worker     return true;
148*9880d681SAndroid Build Coastguard Worker   }
149*9880d681SAndroid Build Coastguard Worker 
150*9880d681SAndroid Build Coastguard Worker   /// Return true if this is a change in status.
markConstant(Constant * V)151*9880d681SAndroid Build Coastguard Worker   bool markConstant(Constant *V) {
152*9880d681SAndroid Build Coastguard Worker     assert(V && "Marking constant with NULL");
153*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154*9880d681SAndroid Build Coastguard Worker       return markConstantRange(ConstantRange(CI->getValue()));
155*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(V))
156*9880d681SAndroid Build Coastguard Worker       return false;
157*9880d681SAndroid Build Coastguard Worker 
158*9880d681SAndroid Build Coastguard Worker     assert((!isConstant() || getConstant() == V) &&
159*9880d681SAndroid Build Coastguard Worker            "Marking constant with different value");
160*9880d681SAndroid Build Coastguard Worker     assert(isUndefined());
161*9880d681SAndroid Build Coastguard Worker     Tag = constant;
162*9880d681SAndroid Build Coastguard Worker     Val = V;
163*9880d681SAndroid Build Coastguard Worker     return true;
164*9880d681SAndroid Build Coastguard Worker   }
165*9880d681SAndroid Build Coastguard Worker 
166*9880d681SAndroid Build Coastguard Worker   /// Return true if this is a change in status.
markNotConstant(Constant * V)167*9880d681SAndroid Build Coastguard Worker   bool markNotConstant(Constant *V) {
168*9880d681SAndroid Build Coastguard Worker     assert(V && "Marking constant with NULL");
169*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
170*9880d681SAndroid Build Coastguard Worker       return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
171*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(V))
172*9880d681SAndroid Build Coastguard Worker       return false;
173*9880d681SAndroid Build Coastguard Worker 
174*9880d681SAndroid Build Coastguard Worker     assert((!isConstant() || getConstant() != V) &&
175*9880d681SAndroid Build Coastguard Worker            "Marking constant !constant with same value");
176*9880d681SAndroid Build Coastguard Worker     assert((!isNotConstant() || getNotConstant() == V) &&
177*9880d681SAndroid Build Coastguard Worker            "Marking !constant with different value");
178*9880d681SAndroid Build Coastguard Worker     assert(isUndefined() || isConstant());
179*9880d681SAndroid Build Coastguard Worker     Tag = notconstant;
180*9880d681SAndroid Build Coastguard Worker     Val = V;
181*9880d681SAndroid Build Coastguard Worker     return true;
182*9880d681SAndroid Build Coastguard Worker   }
183*9880d681SAndroid Build Coastguard Worker 
184*9880d681SAndroid Build Coastguard Worker   /// Return true if this is a change in status.
markConstantRange(ConstantRange NewR)185*9880d681SAndroid Build Coastguard Worker   bool markConstantRange(ConstantRange NewR) {
186*9880d681SAndroid Build Coastguard Worker     if (isConstantRange()) {
187*9880d681SAndroid Build Coastguard Worker       if (NewR.isEmptySet())
188*9880d681SAndroid Build Coastguard Worker         return markOverdefined();
189*9880d681SAndroid Build Coastguard Worker 
190*9880d681SAndroid Build Coastguard Worker       bool changed = Range != NewR;
191*9880d681SAndroid Build Coastguard Worker       Range = std::move(NewR);
192*9880d681SAndroid Build Coastguard Worker       return changed;
193*9880d681SAndroid Build Coastguard Worker     }
194*9880d681SAndroid Build Coastguard Worker 
195*9880d681SAndroid Build Coastguard Worker     assert(isUndefined());
196*9880d681SAndroid Build Coastguard Worker     if (NewR.isEmptySet())
197*9880d681SAndroid Build Coastguard Worker       return markOverdefined();
198*9880d681SAndroid Build Coastguard Worker 
199*9880d681SAndroid Build Coastguard Worker     Tag = constantrange;
200*9880d681SAndroid Build Coastguard Worker     Range = std::move(NewR);
201*9880d681SAndroid Build Coastguard Worker     return true;
202*9880d681SAndroid Build Coastguard Worker   }
203*9880d681SAndroid Build Coastguard Worker 
204*9880d681SAndroid Build Coastguard Worker   /// Merge the specified lattice value into this one, updating this
205*9880d681SAndroid Build Coastguard Worker   /// one and returning true if anything changed.
mergeIn(const LVILatticeVal & RHS,const DataLayout & DL)206*9880d681SAndroid Build Coastguard Worker   bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
207*9880d681SAndroid Build Coastguard Worker     if (RHS.isUndefined() || isOverdefined()) return false;
208*9880d681SAndroid Build Coastguard Worker     if (RHS.isOverdefined()) return markOverdefined();
209*9880d681SAndroid Build Coastguard Worker 
210*9880d681SAndroid Build Coastguard Worker     if (isUndefined()) {
211*9880d681SAndroid Build Coastguard Worker       Tag = RHS.Tag;
212*9880d681SAndroid Build Coastguard Worker       Val = RHS.Val;
213*9880d681SAndroid Build Coastguard Worker       Range = RHS.Range;
214*9880d681SAndroid Build Coastguard Worker       return true;
215*9880d681SAndroid Build Coastguard Worker     }
216*9880d681SAndroid Build Coastguard Worker 
217*9880d681SAndroid Build Coastguard Worker     if (isConstant()) {
218*9880d681SAndroid Build Coastguard Worker       if (RHS.isConstant()) {
219*9880d681SAndroid Build Coastguard Worker         if (Val == RHS.Val)
220*9880d681SAndroid Build Coastguard Worker           return false;
221*9880d681SAndroid Build Coastguard Worker         return markOverdefined();
222*9880d681SAndroid Build Coastguard Worker       }
223*9880d681SAndroid Build Coastguard Worker 
224*9880d681SAndroid Build Coastguard Worker       if (RHS.isNotConstant()) {
225*9880d681SAndroid Build Coastguard Worker         if (Val == RHS.Val)
226*9880d681SAndroid Build Coastguard Worker           return markOverdefined();
227*9880d681SAndroid Build Coastguard Worker 
228*9880d681SAndroid Build Coastguard Worker         // Unless we can prove that the two Constants are different, we must
229*9880d681SAndroid Build Coastguard Worker         // move to overdefined.
230*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *Res =
231*9880d681SAndroid Build Coastguard Worker                 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
232*9880d681SAndroid Build Coastguard Worker                     CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
233*9880d681SAndroid Build Coastguard Worker           if (Res->isOne())
234*9880d681SAndroid Build Coastguard Worker             return markNotConstant(RHS.getNotConstant());
235*9880d681SAndroid Build Coastguard Worker 
236*9880d681SAndroid Build Coastguard Worker         return markOverdefined();
237*9880d681SAndroid Build Coastguard Worker       }
238*9880d681SAndroid Build Coastguard Worker 
239*9880d681SAndroid Build Coastguard Worker       return markOverdefined();
240*9880d681SAndroid Build Coastguard Worker     }
241*9880d681SAndroid Build Coastguard Worker 
242*9880d681SAndroid Build Coastguard Worker     if (isNotConstant()) {
243*9880d681SAndroid Build Coastguard Worker       if (RHS.isConstant()) {
244*9880d681SAndroid Build Coastguard Worker         if (Val == RHS.Val)
245*9880d681SAndroid Build Coastguard Worker           return markOverdefined();
246*9880d681SAndroid Build Coastguard Worker 
247*9880d681SAndroid Build Coastguard Worker         // Unless we can prove that the two Constants are different, we must
248*9880d681SAndroid Build Coastguard Worker         // move to overdefined.
249*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *Res =
250*9880d681SAndroid Build Coastguard Worker                 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
251*9880d681SAndroid Build Coastguard Worker                     CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
252*9880d681SAndroid Build Coastguard Worker           if (Res->isOne())
253*9880d681SAndroid Build Coastguard Worker             return false;
254*9880d681SAndroid Build Coastguard Worker 
255*9880d681SAndroid Build Coastguard Worker         return markOverdefined();
256*9880d681SAndroid Build Coastguard Worker       }
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker       if (RHS.isNotConstant()) {
259*9880d681SAndroid Build Coastguard Worker         if (Val == RHS.Val)
260*9880d681SAndroid Build Coastguard Worker           return false;
261*9880d681SAndroid Build Coastguard Worker         return markOverdefined();
262*9880d681SAndroid Build Coastguard Worker       }
263*9880d681SAndroid Build Coastguard Worker 
264*9880d681SAndroid Build Coastguard Worker       return markOverdefined();
265*9880d681SAndroid Build Coastguard Worker     }
266*9880d681SAndroid Build Coastguard Worker 
267*9880d681SAndroid Build Coastguard Worker     assert(isConstantRange() && "New LVILattice type?");
268*9880d681SAndroid Build Coastguard Worker     if (!RHS.isConstantRange())
269*9880d681SAndroid Build Coastguard Worker       return markOverdefined();
270*9880d681SAndroid Build Coastguard Worker 
271*9880d681SAndroid Build Coastguard Worker     ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
272*9880d681SAndroid Build Coastguard Worker     if (NewR.isFullSet())
273*9880d681SAndroid Build Coastguard Worker       return markOverdefined();
274*9880d681SAndroid Build Coastguard Worker     return markConstantRange(NewR);
275*9880d681SAndroid Build Coastguard Worker   }
276*9880d681SAndroid Build Coastguard Worker };
277*9880d681SAndroid Build Coastguard Worker 
278*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace.
279*9880d681SAndroid Build Coastguard Worker 
280*9880d681SAndroid Build Coastguard Worker namespace llvm {
281*9880d681SAndroid Build Coastguard Worker raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
282*9880d681SAndroid Build Coastguard Worker     LLVM_ATTRIBUTE_USED;
operator <<(raw_ostream & OS,const LVILatticeVal & Val)283*9880d681SAndroid Build Coastguard Worker raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
284*9880d681SAndroid Build Coastguard Worker   if (Val.isUndefined())
285*9880d681SAndroid Build Coastguard Worker     return OS << "undefined";
286*9880d681SAndroid Build Coastguard Worker   if (Val.isOverdefined())
287*9880d681SAndroid Build Coastguard Worker     return OS << "overdefined";
288*9880d681SAndroid Build Coastguard Worker 
289*9880d681SAndroid Build Coastguard Worker   if (Val.isNotConstant())
290*9880d681SAndroid Build Coastguard Worker     return OS << "notconstant<" << *Val.getNotConstant() << '>';
291*9880d681SAndroid Build Coastguard Worker   if (Val.isConstantRange())
292*9880d681SAndroid Build Coastguard Worker     return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
293*9880d681SAndroid Build Coastguard Worker               << Val.getConstantRange().getUpper() << '>';
294*9880d681SAndroid Build Coastguard Worker   return OS << "constant<" << *Val.getConstant() << '>';
295*9880d681SAndroid Build Coastguard Worker }
296*9880d681SAndroid Build Coastguard Worker }
297*9880d681SAndroid Build Coastguard Worker 
298*9880d681SAndroid Build Coastguard Worker /// Returns true if this lattice value represents at most one possible value.
299*9880d681SAndroid Build Coastguard Worker /// This is as precise as any lattice value can get while still representing
300*9880d681SAndroid Build Coastguard Worker /// reachable code.
hasSingleValue(const LVILatticeVal & Val)301*9880d681SAndroid Build Coastguard Worker static bool hasSingleValue(const LVILatticeVal &Val) {
302*9880d681SAndroid Build Coastguard Worker   if (Val.isConstantRange() &&
303*9880d681SAndroid Build Coastguard Worker       Val.getConstantRange().isSingleElement())
304*9880d681SAndroid Build Coastguard Worker     // Integer constants are single element ranges
305*9880d681SAndroid Build Coastguard Worker     return true;
306*9880d681SAndroid Build Coastguard Worker   if (Val.isConstant())
307*9880d681SAndroid Build Coastguard Worker     // Non integer constants
308*9880d681SAndroid Build Coastguard Worker     return true;
309*9880d681SAndroid Build Coastguard Worker   return false;
310*9880d681SAndroid Build Coastguard Worker }
311*9880d681SAndroid Build Coastguard Worker 
312*9880d681SAndroid Build Coastguard Worker /// Combine two sets of facts about the same value into a single set of
313*9880d681SAndroid Build Coastguard Worker /// facts.  Note that this method is not suitable for merging facts along
314*9880d681SAndroid Build Coastguard Worker /// different paths in a CFG; that's what the mergeIn function is for.  This
315*9880d681SAndroid Build Coastguard Worker /// is for merging facts gathered about the same value at the same location
316*9880d681SAndroid Build Coastguard Worker /// through two independent means.
317*9880d681SAndroid Build Coastguard Worker /// Notes:
318*9880d681SAndroid Build Coastguard Worker /// * This method does not promise to return the most precise possible lattice
319*9880d681SAndroid Build Coastguard Worker ///   value implied by A and B.  It is allowed to return any lattice element
320*9880d681SAndroid Build Coastguard Worker ///   which is at least as strong as *either* A or B (unless our facts
321*9880d681SAndroid Build Coastguard Worker ///   conflict, see below).
322*9880d681SAndroid Build Coastguard Worker /// * Due to unreachable code, the intersection of two lattice values could be
323*9880d681SAndroid Build Coastguard Worker ///   contradictory.  If this happens, we return some valid lattice value so as
324*9880d681SAndroid Build Coastguard Worker ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
325*9880d681SAndroid Build Coastguard Worker ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
intersect(LVILatticeVal A,LVILatticeVal B)326*9880d681SAndroid Build Coastguard Worker static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
327*9880d681SAndroid Build Coastguard Worker   // Undefined is the strongest state.  It means the value is known to be along
328*9880d681SAndroid Build Coastguard Worker   // an unreachable path.
329*9880d681SAndroid Build Coastguard Worker   if (A.isUndefined())
330*9880d681SAndroid Build Coastguard Worker     return A;
331*9880d681SAndroid Build Coastguard Worker   if (B.isUndefined())
332*9880d681SAndroid Build Coastguard Worker     return B;
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker   // If we gave up for one, but got a useable fact from the other, use it.
335*9880d681SAndroid Build Coastguard Worker   if (A.isOverdefined())
336*9880d681SAndroid Build Coastguard Worker     return B;
337*9880d681SAndroid Build Coastguard Worker   if (B.isOverdefined())
338*9880d681SAndroid Build Coastguard Worker     return A;
339*9880d681SAndroid Build Coastguard Worker 
340*9880d681SAndroid Build Coastguard Worker   // Can't get any more precise than constants.
341*9880d681SAndroid Build Coastguard Worker   if (hasSingleValue(A))
342*9880d681SAndroid Build Coastguard Worker     return A;
343*9880d681SAndroid Build Coastguard Worker   if (hasSingleValue(B))
344*9880d681SAndroid Build Coastguard Worker     return B;
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker   // Could be either constant range or not constant here.
347*9880d681SAndroid Build Coastguard Worker   if (!A.isConstantRange() || !B.isConstantRange()) {
348*9880d681SAndroid Build Coastguard Worker     // TODO: Arbitrary choice, could be improved
349*9880d681SAndroid Build Coastguard Worker     return A;
350*9880d681SAndroid Build Coastguard Worker   }
351*9880d681SAndroid Build Coastguard Worker 
352*9880d681SAndroid Build Coastguard Worker   // Intersect two constant ranges
353*9880d681SAndroid Build Coastguard Worker   ConstantRange Range =
354*9880d681SAndroid Build Coastguard Worker     A.getConstantRange().intersectWith(B.getConstantRange());
355*9880d681SAndroid Build Coastguard Worker   // Note: An empty range is implicitly converted to overdefined internally.
356*9880d681SAndroid Build Coastguard Worker   // TODO: We could instead use Undefined here since we've proven a conflict
357*9880d681SAndroid Build Coastguard Worker   // and thus know this path must be unreachable.
358*9880d681SAndroid Build Coastguard Worker   return LVILatticeVal::getRange(std::move(Range));
359*9880d681SAndroid Build Coastguard Worker }
360*9880d681SAndroid Build Coastguard Worker 
361*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
362*9880d681SAndroid Build Coastguard Worker //                          LazyValueInfoCache Decl
363*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
364*9880d681SAndroid Build Coastguard Worker 
365*9880d681SAndroid Build Coastguard Worker namespace {
366*9880d681SAndroid Build Coastguard Worker   /// A callback value handle updates the cache when values are erased.
367*9880d681SAndroid Build Coastguard Worker   class LazyValueInfoCache;
368*9880d681SAndroid Build Coastguard Worker   struct LVIValueHandle final : public CallbackVH {
369*9880d681SAndroid Build Coastguard Worker     LazyValueInfoCache *Parent;
370*9880d681SAndroid Build Coastguard Worker 
LVIValueHandle__anon4b4364240211::LVIValueHandle371*9880d681SAndroid Build Coastguard Worker     LVIValueHandle(Value *V, LazyValueInfoCache *P)
372*9880d681SAndroid Build Coastguard Worker       : CallbackVH(V), Parent(P) { }
373*9880d681SAndroid Build Coastguard Worker 
374*9880d681SAndroid Build Coastguard Worker     void deleted() override;
allUsesReplacedWith__anon4b4364240211::LVIValueHandle375*9880d681SAndroid Build Coastguard Worker     void allUsesReplacedWith(Value *V) override {
376*9880d681SAndroid Build Coastguard Worker       deleted();
377*9880d681SAndroid Build Coastguard Worker     }
378*9880d681SAndroid Build Coastguard Worker   };
379*9880d681SAndroid Build Coastguard Worker }
380*9880d681SAndroid Build Coastguard Worker 
381*9880d681SAndroid Build Coastguard Worker namespace {
382*9880d681SAndroid Build Coastguard Worker   /// This is the cache kept by LazyValueInfo which
383*9880d681SAndroid Build Coastguard Worker   /// maintains information about queries across the clients' queries.
384*9880d681SAndroid Build Coastguard Worker   class LazyValueInfoCache {
385*9880d681SAndroid Build Coastguard Worker     /// This is all of the cached block information for exactly one Value*.
386*9880d681SAndroid Build Coastguard Worker     /// The entries are sorted by the BasicBlock* of the
387*9880d681SAndroid Build Coastguard Worker     /// entries, allowing us to do a lookup with a binary search.
388*9880d681SAndroid Build Coastguard Worker     /// Over-defined lattice values are recorded in OverDefinedCache to reduce
389*9880d681SAndroid Build Coastguard Worker     /// memory overhead.
390*9880d681SAndroid Build Coastguard Worker     typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
391*9880d681SAndroid Build Coastguard Worker         ValueCacheEntryTy;
392*9880d681SAndroid Build Coastguard Worker 
393*9880d681SAndroid Build Coastguard Worker     /// This is all of the cached information for all values,
394*9880d681SAndroid Build Coastguard Worker     /// mapped from Value* to key information.
395*9880d681SAndroid Build Coastguard Worker     std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
396*9880d681SAndroid Build Coastguard Worker 
397*9880d681SAndroid Build Coastguard Worker     /// This tracks, on a per-block basis, the set of values that are
398*9880d681SAndroid Build Coastguard Worker     /// over-defined at the end of that block.
399*9880d681SAndroid Build Coastguard Worker     typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
400*9880d681SAndroid Build Coastguard Worker         OverDefinedCacheTy;
401*9880d681SAndroid Build Coastguard Worker     OverDefinedCacheTy OverDefinedCache;
402*9880d681SAndroid Build Coastguard Worker 
403*9880d681SAndroid Build Coastguard Worker     /// Keep track of all blocks that we have ever seen, so we
404*9880d681SAndroid Build Coastguard Worker     /// don't spend time removing unused blocks from our caches.
405*9880d681SAndroid Build Coastguard Worker     DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
406*9880d681SAndroid Build Coastguard Worker 
407*9880d681SAndroid Build Coastguard Worker     /// This stack holds the state of the value solver during a query.
408*9880d681SAndroid Build Coastguard Worker     /// It basically emulates the callstack of the naive
409*9880d681SAndroid Build Coastguard Worker     /// recursive value lookup process.
410*9880d681SAndroid Build Coastguard Worker     std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
411*9880d681SAndroid Build Coastguard Worker 
412*9880d681SAndroid Build Coastguard Worker     /// Keeps track of which block-value pairs are in BlockValueStack.
413*9880d681SAndroid Build Coastguard Worker     DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
414*9880d681SAndroid Build Coastguard Worker 
415*9880d681SAndroid Build Coastguard Worker     /// Push BV onto BlockValueStack unless it's already in there.
416*9880d681SAndroid Build Coastguard Worker     /// Returns true on success.
pushBlockValue(const std::pair<BasicBlock *,Value * > & BV)417*9880d681SAndroid Build Coastguard Worker     bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
418*9880d681SAndroid Build Coastguard Worker       if (!BlockValueSet.insert(BV).second)
419*9880d681SAndroid Build Coastguard Worker         return false;  // It's already in the stack.
420*9880d681SAndroid Build Coastguard Worker 
421*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
422*9880d681SAndroid Build Coastguard Worker                    << "\n");
423*9880d681SAndroid Build Coastguard Worker       BlockValueStack.push(BV);
424*9880d681SAndroid Build Coastguard Worker       return true;
425*9880d681SAndroid Build Coastguard Worker     }
426*9880d681SAndroid Build Coastguard Worker 
427*9880d681SAndroid Build Coastguard Worker     AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
428*9880d681SAndroid Build Coastguard Worker     const DataLayout &DL; ///< A mandatory DataLayout
429*9880d681SAndroid Build Coastguard Worker     DominatorTree *DT;    ///< An optional DT pointer.
430*9880d681SAndroid Build Coastguard Worker 
431*9880d681SAndroid Build Coastguard Worker     friend struct LVIValueHandle;
432*9880d681SAndroid Build Coastguard Worker 
insertResult(Value * Val,BasicBlock * BB,const LVILatticeVal & Result)433*9880d681SAndroid Build Coastguard Worker     void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
434*9880d681SAndroid Build Coastguard Worker       SeenBlocks.insert(BB);
435*9880d681SAndroid Build Coastguard Worker 
436*9880d681SAndroid Build Coastguard Worker       // Insert over-defined values into their own cache to reduce memory
437*9880d681SAndroid Build Coastguard Worker       // overhead.
438*9880d681SAndroid Build Coastguard Worker       if (Result.isOverdefined())
439*9880d681SAndroid Build Coastguard Worker         OverDefinedCache[BB].insert(Val);
440*9880d681SAndroid Build Coastguard Worker       else
441*9880d681SAndroid Build Coastguard Worker         lookup(Val)[BB] = Result;
442*9880d681SAndroid Build Coastguard Worker     }
443*9880d681SAndroid Build Coastguard Worker 
444*9880d681SAndroid Build Coastguard Worker   LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
445*9880d681SAndroid Build Coastguard Worker   bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
446*9880d681SAndroid Build Coastguard Worker                     LVILatticeVal &Result, Instruction *CxtI = nullptr);
447*9880d681SAndroid Build Coastguard Worker   bool hasBlockValue(Value *Val, BasicBlock *BB);
448*9880d681SAndroid Build Coastguard Worker 
449*9880d681SAndroid Build Coastguard Worker   // These methods process one work item and may add more. A false value
450*9880d681SAndroid Build Coastguard Worker   // returned means that the work item was not completely processed and must
451*9880d681SAndroid Build Coastguard Worker   // be revisited after going through the new items.
452*9880d681SAndroid Build Coastguard Worker   bool solveBlockValue(Value *Val, BasicBlock *BB);
453*9880d681SAndroid Build Coastguard Worker   bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
454*9880d681SAndroid Build Coastguard Worker   bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
455*9880d681SAndroid Build Coastguard Worker   bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
456*9880d681SAndroid Build Coastguard Worker                              BasicBlock *BB);
457*9880d681SAndroid Build Coastguard Worker   bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
458*9880d681SAndroid Build Coastguard Worker                                BasicBlock *BB);
459*9880d681SAndroid Build Coastguard Worker   bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
460*9880d681SAndroid Build Coastguard Worker                            BasicBlock *BB);
461*9880d681SAndroid Build Coastguard Worker   void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
462*9880d681SAndroid Build Coastguard Worker                                               Instruction *BBI);
463*9880d681SAndroid Build Coastguard Worker 
464*9880d681SAndroid Build Coastguard Worker   void solve();
465*9880d681SAndroid Build Coastguard Worker 
lookup(Value * V)466*9880d681SAndroid Build Coastguard Worker   ValueCacheEntryTy &lookup(Value *V) {
467*9880d681SAndroid Build Coastguard Worker     return ValueCache[LVIValueHandle(V, this)];
468*9880d681SAndroid Build Coastguard Worker   }
469*9880d681SAndroid Build Coastguard Worker 
isOverdefined(Value * V,BasicBlock * BB) const470*9880d681SAndroid Build Coastguard Worker     bool isOverdefined(Value *V, BasicBlock *BB) const {
471*9880d681SAndroid Build Coastguard Worker       auto ODI = OverDefinedCache.find(BB);
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker       if (ODI == OverDefinedCache.end())
474*9880d681SAndroid Build Coastguard Worker         return false;
475*9880d681SAndroid Build Coastguard Worker 
476*9880d681SAndroid Build Coastguard Worker       return ODI->second.count(V);
477*9880d681SAndroid Build Coastguard Worker     }
478*9880d681SAndroid Build Coastguard Worker 
hasCachedValueInfo(Value * V,BasicBlock * BB)479*9880d681SAndroid Build Coastguard Worker     bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
480*9880d681SAndroid Build Coastguard Worker       if (isOverdefined(V, BB))
481*9880d681SAndroid Build Coastguard Worker         return true;
482*9880d681SAndroid Build Coastguard Worker 
483*9880d681SAndroid Build Coastguard Worker       LVIValueHandle ValHandle(V, this);
484*9880d681SAndroid Build Coastguard Worker       auto I = ValueCache.find(ValHandle);
485*9880d681SAndroid Build Coastguard Worker       if (I == ValueCache.end())
486*9880d681SAndroid Build Coastguard Worker         return false;
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker       return I->second.count(BB);
489*9880d681SAndroid Build Coastguard Worker     }
490*9880d681SAndroid Build Coastguard Worker 
getCachedValueInfo(Value * V,BasicBlock * BB)491*9880d681SAndroid Build Coastguard Worker     LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
492*9880d681SAndroid Build Coastguard Worker       if (isOverdefined(V, BB))
493*9880d681SAndroid Build Coastguard Worker         return LVILatticeVal::getOverdefined();
494*9880d681SAndroid Build Coastguard Worker 
495*9880d681SAndroid Build Coastguard Worker       return lookup(V)[BB];
496*9880d681SAndroid Build Coastguard Worker     }
497*9880d681SAndroid Build Coastguard Worker 
498*9880d681SAndroid Build Coastguard Worker   public:
499*9880d681SAndroid Build Coastguard Worker     /// This is the query interface to determine the lattice
500*9880d681SAndroid Build Coastguard Worker     /// value for the specified Value* at the end of the specified block.
501*9880d681SAndroid Build Coastguard Worker     LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
502*9880d681SAndroid Build Coastguard Worker                                   Instruction *CxtI = nullptr);
503*9880d681SAndroid Build Coastguard Worker 
504*9880d681SAndroid Build Coastguard Worker     /// This is the query interface to determine the lattice
505*9880d681SAndroid Build Coastguard Worker     /// value for the specified Value* at the specified instruction (generally
506*9880d681SAndroid Build Coastguard Worker     /// from an assume intrinsic).
507*9880d681SAndroid Build Coastguard Worker     LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
508*9880d681SAndroid Build Coastguard Worker 
509*9880d681SAndroid Build Coastguard Worker     /// This is the query interface to determine the lattice
510*9880d681SAndroid Build Coastguard Worker     /// value for the specified Value* that is true on the specified edge.
511*9880d681SAndroid Build Coastguard Worker     LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
512*9880d681SAndroid Build Coastguard Worker                                  Instruction *CxtI = nullptr);
513*9880d681SAndroid Build Coastguard Worker 
514*9880d681SAndroid Build Coastguard Worker     /// This is the update interface to inform the cache that an edge from
515*9880d681SAndroid Build Coastguard Worker     /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
516*9880d681SAndroid Build Coastguard Worker     void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
517*9880d681SAndroid Build Coastguard Worker 
518*9880d681SAndroid Build Coastguard Worker     /// This is part of the update interface to inform the cache
519*9880d681SAndroid Build Coastguard Worker     /// that a block has been deleted.
520*9880d681SAndroid Build Coastguard Worker     void eraseBlock(BasicBlock *BB);
521*9880d681SAndroid Build Coastguard Worker 
522*9880d681SAndroid Build Coastguard Worker     /// clear - Empty the cache.
clear()523*9880d681SAndroid Build Coastguard Worker     void clear() {
524*9880d681SAndroid Build Coastguard Worker       SeenBlocks.clear();
525*9880d681SAndroid Build Coastguard Worker       ValueCache.clear();
526*9880d681SAndroid Build Coastguard Worker       OverDefinedCache.clear();
527*9880d681SAndroid Build Coastguard Worker     }
528*9880d681SAndroid Build Coastguard Worker 
LazyValueInfoCache(AssumptionCache * AC,const DataLayout & DL,DominatorTree * DT=nullptr)529*9880d681SAndroid Build Coastguard Worker     LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
530*9880d681SAndroid Build Coastguard Worker                        DominatorTree *DT = nullptr)
531*9880d681SAndroid Build Coastguard Worker         : AC(AC), DL(DL), DT(DT) {}
532*9880d681SAndroid Build Coastguard Worker   };
533*9880d681SAndroid Build Coastguard Worker } // end anonymous namespace
534*9880d681SAndroid Build Coastguard Worker 
deleted()535*9880d681SAndroid Build Coastguard Worker void LVIValueHandle::deleted() {
536*9880d681SAndroid Build Coastguard Worker   SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
537*9880d681SAndroid Build Coastguard Worker   for (auto &I : Parent->OverDefinedCache) {
538*9880d681SAndroid Build Coastguard Worker     SmallPtrSetImpl<Value *> &ValueSet = I.second;
539*9880d681SAndroid Build Coastguard Worker     if (ValueSet.count(getValPtr()))
540*9880d681SAndroid Build Coastguard Worker       ValueSet.erase(getValPtr());
541*9880d681SAndroid Build Coastguard Worker     if (ValueSet.empty())
542*9880d681SAndroid Build Coastguard Worker       ToErase.push_back(I.first);
543*9880d681SAndroid Build Coastguard Worker   }
544*9880d681SAndroid Build Coastguard Worker   for (auto &BB : ToErase)
545*9880d681SAndroid Build Coastguard Worker     Parent->OverDefinedCache.erase(BB);
546*9880d681SAndroid Build Coastguard Worker 
547*9880d681SAndroid Build Coastguard Worker   // This erasure deallocates *this, so it MUST happen after we're done
548*9880d681SAndroid Build Coastguard Worker   // using any and all members of *this.
549*9880d681SAndroid Build Coastguard Worker   Parent->ValueCache.erase(*this);
550*9880d681SAndroid Build Coastguard Worker }
551*9880d681SAndroid Build Coastguard Worker 
eraseBlock(BasicBlock * BB)552*9880d681SAndroid Build Coastguard Worker void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
553*9880d681SAndroid Build Coastguard Worker   // Shortcut if we have never seen this block.
554*9880d681SAndroid Build Coastguard Worker   DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
555*9880d681SAndroid Build Coastguard Worker   if (I == SeenBlocks.end())
556*9880d681SAndroid Build Coastguard Worker     return;
557*9880d681SAndroid Build Coastguard Worker   SeenBlocks.erase(I);
558*9880d681SAndroid Build Coastguard Worker 
559*9880d681SAndroid Build Coastguard Worker   auto ODI = OverDefinedCache.find(BB);
560*9880d681SAndroid Build Coastguard Worker   if (ODI != OverDefinedCache.end())
561*9880d681SAndroid Build Coastguard Worker     OverDefinedCache.erase(ODI);
562*9880d681SAndroid Build Coastguard Worker 
563*9880d681SAndroid Build Coastguard Worker   for (auto &I : ValueCache)
564*9880d681SAndroid Build Coastguard Worker     I.second.erase(BB);
565*9880d681SAndroid Build Coastguard Worker }
566*9880d681SAndroid Build Coastguard Worker 
solve()567*9880d681SAndroid Build Coastguard Worker void LazyValueInfoCache::solve() {
568*9880d681SAndroid Build Coastguard Worker   while (!BlockValueStack.empty()) {
569*9880d681SAndroid Build Coastguard Worker     std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
570*9880d681SAndroid Build Coastguard Worker     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
571*9880d681SAndroid Build Coastguard Worker 
572*9880d681SAndroid Build Coastguard Worker     if (solveBlockValue(e.second, e.first)) {
573*9880d681SAndroid Build Coastguard Worker       // The work item was completely processed.
574*9880d681SAndroid Build Coastguard Worker       assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
575*9880d681SAndroid Build Coastguard Worker       assert(hasCachedValueInfo(e.second, e.first) &&
576*9880d681SAndroid Build Coastguard Worker              "Result should be in cache!");
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
579*9880d681SAndroid Build Coastguard Worker                    << " = " << getCachedValueInfo(e.second, e.first) << "\n");
580*9880d681SAndroid Build Coastguard Worker 
581*9880d681SAndroid Build Coastguard Worker       BlockValueStack.pop();
582*9880d681SAndroid Build Coastguard Worker       BlockValueSet.erase(e);
583*9880d681SAndroid Build Coastguard Worker     } else {
584*9880d681SAndroid Build Coastguard Worker       // More work needs to be done before revisiting.
585*9880d681SAndroid Build Coastguard Worker       assert(BlockValueStack.top() != e && "Stack should have been pushed!");
586*9880d681SAndroid Build Coastguard Worker     }
587*9880d681SAndroid Build Coastguard Worker   }
588*9880d681SAndroid Build Coastguard Worker }
589*9880d681SAndroid Build Coastguard Worker 
hasBlockValue(Value * Val,BasicBlock * BB)590*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
591*9880d681SAndroid Build Coastguard Worker   // If already a constant, there is nothing to compute.
592*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(Val))
593*9880d681SAndroid Build Coastguard Worker     return true;
594*9880d681SAndroid Build Coastguard Worker 
595*9880d681SAndroid Build Coastguard Worker   return hasCachedValueInfo(Val, BB);
596*9880d681SAndroid Build Coastguard Worker }
597*9880d681SAndroid Build Coastguard Worker 
getBlockValue(Value * Val,BasicBlock * BB)598*9880d681SAndroid Build Coastguard Worker LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
599*9880d681SAndroid Build Coastguard Worker   // If already a constant, there is nothing to compute.
600*9880d681SAndroid Build Coastguard Worker   if (Constant *VC = dyn_cast<Constant>(Val))
601*9880d681SAndroid Build Coastguard Worker     return LVILatticeVal::get(VC);
602*9880d681SAndroid Build Coastguard Worker 
603*9880d681SAndroid Build Coastguard Worker   SeenBlocks.insert(BB);
604*9880d681SAndroid Build Coastguard Worker   return getCachedValueInfo(Val, BB);
605*9880d681SAndroid Build Coastguard Worker }
606*9880d681SAndroid Build Coastguard Worker 
getFromRangeMetadata(Instruction * BBI)607*9880d681SAndroid Build Coastguard Worker static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
608*9880d681SAndroid Build Coastguard Worker   switch (BBI->getOpcode()) {
609*9880d681SAndroid Build Coastguard Worker   default: break;
610*9880d681SAndroid Build Coastguard Worker   case Instruction::Load:
611*9880d681SAndroid Build Coastguard Worker   case Instruction::Call:
612*9880d681SAndroid Build Coastguard Worker   case Instruction::Invoke:
613*9880d681SAndroid Build Coastguard Worker     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
614*9880d681SAndroid Build Coastguard Worker       if (isa<IntegerType>(BBI->getType())) {
615*9880d681SAndroid Build Coastguard Worker         return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
616*9880d681SAndroid Build Coastguard Worker       }
617*9880d681SAndroid Build Coastguard Worker     break;
618*9880d681SAndroid Build Coastguard Worker   };
619*9880d681SAndroid Build Coastguard Worker   // Nothing known - will be intersected with other facts
620*9880d681SAndroid Build Coastguard Worker   return LVILatticeVal::getOverdefined();
621*9880d681SAndroid Build Coastguard Worker }
622*9880d681SAndroid Build Coastguard Worker 
solveBlockValue(Value * Val,BasicBlock * BB)623*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
624*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(Val))
625*9880d681SAndroid Build Coastguard Worker     return true;
626*9880d681SAndroid Build Coastguard Worker 
627*9880d681SAndroid Build Coastguard Worker   if (hasCachedValueInfo(Val, BB)) {
628*9880d681SAndroid Build Coastguard Worker     // If we have a cached value, use that.
629*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  reuse BB '" << BB->getName()
630*9880d681SAndroid Build Coastguard Worker                  << "' val=" << getCachedValueInfo(Val, BB) << '\n');
631*9880d681SAndroid Build Coastguard Worker 
632*9880d681SAndroid Build Coastguard Worker     // Since we're reusing a cached value, we don't need to update the
633*9880d681SAndroid Build Coastguard Worker     // OverDefinedCache. The cache will have been properly updated whenever the
634*9880d681SAndroid Build Coastguard Worker     // cached value was inserted.
635*9880d681SAndroid Build Coastguard Worker     return true;
636*9880d681SAndroid Build Coastguard Worker   }
637*9880d681SAndroid Build Coastguard Worker 
638*9880d681SAndroid Build Coastguard Worker   // Hold off inserting this value into the Cache in case we have to return
639*9880d681SAndroid Build Coastguard Worker   // false and come back later.
640*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Res;
641*9880d681SAndroid Build Coastguard Worker 
642*9880d681SAndroid Build Coastguard Worker   Instruction *BBI = dyn_cast<Instruction>(Val);
643*9880d681SAndroid Build Coastguard Worker   if (!BBI || BBI->getParent() != BB) {
644*9880d681SAndroid Build Coastguard Worker     if (!solveBlockValueNonLocal(Res, Val, BB))
645*9880d681SAndroid Build Coastguard Worker       return false;
646*9880d681SAndroid Build Coastguard Worker    insertResult(Val, BB, Res);
647*9880d681SAndroid Build Coastguard Worker    return true;
648*9880d681SAndroid Build Coastguard Worker   }
649*9880d681SAndroid Build Coastguard Worker 
650*9880d681SAndroid Build Coastguard Worker   if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
651*9880d681SAndroid Build Coastguard Worker     if (!solveBlockValuePHINode(Res, PN, BB))
652*9880d681SAndroid Build Coastguard Worker       return false;
653*9880d681SAndroid Build Coastguard Worker     insertResult(Val, BB, Res);
654*9880d681SAndroid Build Coastguard Worker     return true;
655*9880d681SAndroid Build Coastguard Worker   }
656*9880d681SAndroid Build Coastguard Worker 
657*9880d681SAndroid Build Coastguard Worker   if (auto *SI = dyn_cast<SelectInst>(BBI)) {
658*9880d681SAndroid Build Coastguard Worker     if (!solveBlockValueSelect(Res, SI, BB))
659*9880d681SAndroid Build Coastguard Worker       return false;
660*9880d681SAndroid Build Coastguard Worker     insertResult(Val, BB, Res);
661*9880d681SAndroid Build Coastguard Worker     return true;
662*9880d681SAndroid Build Coastguard Worker   }
663*9880d681SAndroid Build Coastguard Worker 
664*9880d681SAndroid Build Coastguard Worker   // If this value is a nonnull pointer, record it's range and bailout.  Note
665*9880d681SAndroid Build Coastguard Worker   // that for all other pointer typed values, we terminate the search at the
666*9880d681SAndroid Build Coastguard Worker   // definition.  We could easily extend this to look through geps, bitcasts,
667*9880d681SAndroid Build Coastguard Worker   // and the like to prove non-nullness, but it's not clear that's worth it
668*9880d681SAndroid Build Coastguard Worker   // compile time wise.  The context-insensative value walk done inside
669*9880d681SAndroid Build Coastguard Worker   // isKnownNonNull gets most of the profitable cases at much less expense.
670*9880d681SAndroid Build Coastguard Worker   // This does mean that we have a sensativity to where the defining
671*9880d681SAndroid Build Coastguard Worker   // instruction is placed, even if it could legally be hoisted much higher.
672*9880d681SAndroid Build Coastguard Worker   // That is unfortunate.
673*9880d681SAndroid Build Coastguard Worker   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
674*9880d681SAndroid Build Coastguard Worker   if (PT && isKnownNonNull(BBI)) {
675*9880d681SAndroid Build Coastguard Worker     Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
676*9880d681SAndroid Build Coastguard Worker     insertResult(Val, BB, Res);
677*9880d681SAndroid Build Coastguard Worker     return true;
678*9880d681SAndroid Build Coastguard Worker   }
679*9880d681SAndroid Build Coastguard Worker   if (BBI->getType()->isIntegerTy()) {
680*9880d681SAndroid Build Coastguard Worker     if (isa<CastInst>(BBI)) {
681*9880d681SAndroid Build Coastguard Worker       if (!solveBlockValueCast(Res, BBI, BB))
682*9880d681SAndroid Build Coastguard Worker         return false;
683*9880d681SAndroid Build Coastguard Worker       insertResult(Val, BB, Res);
684*9880d681SAndroid Build Coastguard Worker       return true;
685*9880d681SAndroid Build Coastguard Worker     }
686*9880d681SAndroid Build Coastguard Worker     BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
687*9880d681SAndroid Build Coastguard Worker     if (BO && isa<ConstantInt>(BO->getOperand(1))) {
688*9880d681SAndroid Build Coastguard Worker       if (!solveBlockValueBinaryOp(Res, BBI, BB))
689*9880d681SAndroid Build Coastguard Worker         return false;
690*9880d681SAndroid Build Coastguard Worker       insertResult(Val, BB, Res);
691*9880d681SAndroid Build Coastguard Worker       return true;
692*9880d681SAndroid Build Coastguard Worker     }
693*9880d681SAndroid Build Coastguard Worker   }
694*9880d681SAndroid Build Coastguard Worker 
695*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << " compute BB '" << BB->getName()
696*9880d681SAndroid Build Coastguard Worker                  << "' - unknown inst def found.\n");
697*9880d681SAndroid Build Coastguard Worker   Res = getFromRangeMetadata(BBI);
698*9880d681SAndroid Build Coastguard Worker   insertResult(Val, BB, Res);
699*9880d681SAndroid Build Coastguard Worker   return true;
700*9880d681SAndroid Build Coastguard Worker }
701*9880d681SAndroid Build Coastguard Worker 
InstructionDereferencesPointer(Instruction * I,Value * Ptr)702*9880d681SAndroid Build Coastguard Worker static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
703*9880d681SAndroid Build Coastguard Worker   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
704*9880d681SAndroid Build Coastguard Worker     return L->getPointerAddressSpace() == 0 &&
705*9880d681SAndroid Build Coastguard Worker            GetUnderlyingObject(L->getPointerOperand(),
706*9880d681SAndroid Build Coastguard Worker                                L->getModule()->getDataLayout()) == Ptr;
707*9880d681SAndroid Build Coastguard Worker   }
708*9880d681SAndroid Build Coastguard Worker   if (StoreInst *S = dyn_cast<StoreInst>(I)) {
709*9880d681SAndroid Build Coastguard Worker     return S->getPointerAddressSpace() == 0 &&
710*9880d681SAndroid Build Coastguard Worker            GetUnderlyingObject(S->getPointerOperand(),
711*9880d681SAndroid Build Coastguard Worker                                S->getModule()->getDataLayout()) == Ptr;
712*9880d681SAndroid Build Coastguard Worker   }
713*9880d681SAndroid Build Coastguard Worker   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
714*9880d681SAndroid Build Coastguard Worker     if (MI->isVolatile()) return false;
715*9880d681SAndroid Build Coastguard Worker 
716*9880d681SAndroid Build Coastguard Worker     // FIXME: check whether it has a valuerange that excludes zero?
717*9880d681SAndroid Build Coastguard Worker     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
718*9880d681SAndroid Build Coastguard Worker     if (!Len || Len->isZero()) return false;
719*9880d681SAndroid Build Coastguard Worker 
720*9880d681SAndroid Build Coastguard Worker     if (MI->getDestAddressSpace() == 0)
721*9880d681SAndroid Build Coastguard Worker       if (GetUnderlyingObject(MI->getRawDest(),
722*9880d681SAndroid Build Coastguard Worker                               MI->getModule()->getDataLayout()) == Ptr)
723*9880d681SAndroid Build Coastguard Worker         return true;
724*9880d681SAndroid Build Coastguard Worker     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
725*9880d681SAndroid Build Coastguard Worker       if (MTI->getSourceAddressSpace() == 0)
726*9880d681SAndroid Build Coastguard Worker         if (GetUnderlyingObject(MTI->getRawSource(),
727*9880d681SAndroid Build Coastguard Worker                                 MTI->getModule()->getDataLayout()) == Ptr)
728*9880d681SAndroid Build Coastguard Worker           return true;
729*9880d681SAndroid Build Coastguard Worker   }
730*9880d681SAndroid Build Coastguard Worker   return false;
731*9880d681SAndroid Build Coastguard Worker }
732*9880d681SAndroid Build Coastguard Worker 
733*9880d681SAndroid Build Coastguard Worker /// Return true if the allocation associated with Val is ever dereferenced
734*9880d681SAndroid Build Coastguard Worker /// within the given basic block.  This establishes the fact Val is not null,
735*9880d681SAndroid Build Coastguard Worker /// but does not imply that the memory at Val is dereferenceable.  (Val may
736*9880d681SAndroid Build Coastguard Worker /// point off the end of the dereferenceable part of the object.)
isObjectDereferencedInBlock(Value * Val,BasicBlock * BB)737*9880d681SAndroid Build Coastguard Worker static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
738*9880d681SAndroid Build Coastguard Worker   assert(Val->getType()->isPointerTy());
739*9880d681SAndroid Build Coastguard Worker 
740*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = BB->getModule()->getDataLayout();
741*9880d681SAndroid Build Coastguard Worker   Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
742*9880d681SAndroid Build Coastguard Worker   // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
743*9880d681SAndroid Build Coastguard Worker   // inside InstructionDereferencesPointer either.
744*9880d681SAndroid Build Coastguard Worker   if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
745*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *BB)
746*9880d681SAndroid Build Coastguard Worker       if (InstructionDereferencesPointer(&I, UnderlyingVal))
747*9880d681SAndroid Build Coastguard Worker         return true;
748*9880d681SAndroid Build Coastguard Worker   return false;
749*9880d681SAndroid Build Coastguard Worker }
750*9880d681SAndroid Build Coastguard Worker 
solveBlockValueNonLocal(LVILatticeVal & BBLV,Value * Val,BasicBlock * BB)751*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
752*9880d681SAndroid Build Coastguard Worker                                                  Value *Val, BasicBlock *BB) {
753*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;  // Start Undefined.
754*9880d681SAndroid Build Coastguard Worker 
755*9880d681SAndroid Build Coastguard Worker   // If this is the entry block, we must be asking about an argument.  The
756*9880d681SAndroid Build Coastguard Worker   // value is overdefined.
757*9880d681SAndroid Build Coastguard Worker   if (BB == &BB->getParent()->getEntryBlock()) {
758*9880d681SAndroid Build Coastguard Worker     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
759*9880d681SAndroid Build Coastguard Worker     // Bofore giving up, see if we can prove the pointer non-null local to
760*9880d681SAndroid Build Coastguard Worker     // this particular block.
761*9880d681SAndroid Build Coastguard Worker     if (Val->getType()->isPointerTy() &&
762*9880d681SAndroid Build Coastguard Worker         (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
763*9880d681SAndroid Build Coastguard Worker       PointerType *PTy = cast<PointerType>(Val->getType());
764*9880d681SAndroid Build Coastguard Worker       Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
765*9880d681SAndroid Build Coastguard Worker     } else {
766*9880d681SAndroid Build Coastguard Worker       Result.markOverdefined();
767*9880d681SAndroid Build Coastguard Worker     }
768*9880d681SAndroid Build Coastguard Worker     BBLV = Result;
769*9880d681SAndroid Build Coastguard Worker     return true;
770*9880d681SAndroid Build Coastguard Worker   }
771*9880d681SAndroid Build Coastguard Worker 
772*9880d681SAndroid Build Coastguard Worker   // Loop over all of our predecessors, merging what we know from them into
773*9880d681SAndroid Build Coastguard Worker   // result.
774*9880d681SAndroid Build Coastguard Worker   bool EdgesMissing = false;
775*9880d681SAndroid Build Coastguard Worker   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
776*9880d681SAndroid Build Coastguard Worker     LVILatticeVal EdgeResult;
777*9880d681SAndroid Build Coastguard Worker     EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
778*9880d681SAndroid Build Coastguard Worker     if (EdgesMissing)
779*9880d681SAndroid Build Coastguard Worker       continue;
780*9880d681SAndroid Build Coastguard Worker 
781*9880d681SAndroid Build Coastguard Worker     Result.mergeIn(EdgeResult, DL);
782*9880d681SAndroid Build Coastguard Worker 
783*9880d681SAndroid Build Coastguard Worker     // If we hit overdefined, exit early.  The BlockVals entry is already set
784*9880d681SAndroid Build Coastguard Worker     // to overdefined.
785*9880d681SAndroid Build Coastguard Worker     if (Result.isOverdefined()) {
786*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << " compute BB '" << BB->getName()
787*9880d681SAndroid Build Coastguard Worker             << "' - overdefined because of pred (non local).\n");
788*9880d681SAndroid Build Coastguard Worker       // Bofore giving up, see if we can prove the pointer non-null local to
789*9880d681SAndroid Build Coastguard Worker       // this particular block.
790*9880d681SAndroid Build Coastguard Worker       if (Val->getType()->isPointerTy() &&
791*9880d681SAndroid Build Coastguard Worker           isObjectDereferencedInBlock(Val, BB)) {
792*9880d681SAndroid Build Coastguard Worker         PointerType *PTy = cast<PointerType>(Val->getType());
793*9880d681SAndroid Build Coastguard Worker         Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
794*9880d681SAndroid Build Coastguard Worker       }
795*9880d681SAndroid Build Coastguard Worker 
796*9880d681SAndroid Build Coastguard Worker       BBLV = Result;
797*9880d681SAndroid Build Coastguard Worker       return true;
798*9880d681SAndroid Build Coastguard Worker     }
799*9880d681SAndroid Build Coastguard Worker   }
800*9880d681SAndroid Build Coastguard Worker   if (EdgesMissing)
801*9880d681SAndroid Build Coastguard Worker     return false;
802*9880d681SAndroid Build Coastguard Worker 
803*9880d681SAndroid Build Coastguard Worker   // Return the merged value, which is more precise than 'overdefined'.
804*9880d681SAndroid Build Coastguard Worker   assert(!Result.isOverdefined());
805*9880d681SAndroid Build Coastguard Worker   BBLV = Result;
806*9880d681SAndroid Build Coastguard Worker   return true;
807*9880d681SAndroid Build Coastguard Worker }
808*9880d681SAndroid Build Coastguard Worker 
solveBlockValuePHINode(LVILatticeVal & BBLV,PHINode * PN,BasicBlock * BB)809*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
810*9880d681SAndroid Build Coastguard Worker                                                 PHINode *PN, BasicBlock *BB) {
811*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;  // Start Undefined.
812*9880d681SAndroid Build Coastguard Worker 
813*9880d681SAndroid Build Coastguard Worker   // Loop over all of our predecessors, merging what we know from them into
814*9880d681SAndroid Build Coastguard Worker   // result.
815*9880d681SAndroid Build Coastguard Worker   bool EdgesMissing = false;
816*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
817*9880d681SAndroid Build Coastguard Worker     BasicBlock *PhiBB = PN->getIncomingBlock(i);
818*9880d681SAndroid Build Coastguard Worker     Value *PhiVal = PN->getIncomingValue(i);
819*9880d681SAndroid Build Coastguard Worker     LVILatticeVal EdgeResult;
820*9880d681SAndroid Build Coastguard Worker     // Note that we can provide PN as the context value to getEdgeValue, even
821*9880d681SAndroid Build Coastguard Worker     // though the results will be cached, because PN is the value being used as
822*9880d681SAndroid Build Coastguard Worker     // the cache key in the caller.
823*9880d681SAndroid Build Coastguard Worker     EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
824*9880d681SAndroid Build Coastguard Worker     if (EdgesMissing)
825*9880d681SAndroid Build Coastguard Worker       continue;
826*9880d681SAndroid Build Coastguard Worker 
827*9880d681SAndroid Build Coastguard Worker     Result.mergeIn(EdgeResult, DL);
828*9880d681SAndroid Build Coastguard Worker 
829*9880d681SAndroid Build Coastguard Worker     // If we hit overdefined, exit early.  The BlockVals entry is already set
830*9880d681SAndroid Build Coastguard Worker     // to overdefined.
831*9880d681SAndroid Build Coastguard Worker     if (Result.isOverdefined()) {
832*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << " compute BB '" << BB->getName()
833*9880d681SAndroid Build Coastguard Worker             << "' - overdefined because of pred (local).\n");
834*9880d681SAndroid Build Coastguard Worker 
835*9880d681SAndroid Build Coastguard Worker       BBLV = Result;
836*9880d681SAndroid Build Coastguard Worker       return true;
837*9880d681SAndroid Build Coastguard Worker     }
838*9880d681SAndroid Build Coastguard Worker   }
839*9880d681SAndroid Build Coastguard Worker   if (EdgesMissing)
840*9880d681SAndroid Build Coastguard Worker     return false;
841*9880d681SAndroid Build Coastguard Worker 
842*9880d681SAndroid Build Coastguard Worker   // Return the merged value, which is more precise than 'overdefined'.
843*9880d681SAndroid Build Coastguard Worker   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
844*9880d681SAndroid Build Coastguard Worker   BBLV = Result;
845*9880d681SAndroid Build Coastguard Worker   return true;
846*9880d681SAndroid Build Coastguard Worker }
847*9880d681SAndroid Build Coastguard Worker 
848*9880d681SAndroid Build Coastguard Worker static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
849*9880d681SAndroid Build Coastguard Worker                                       LVILatticeVal &Result,
850*9880d681SAndroid Build Coastguard Worker                                       bool isTrueDest = true);
851*9880d681SAndroid Build Coastguard Worker 
852*9880d681SAndroid Build Coastguard Worker // If we can determine a constraint on the value given conditions assumed by
853*9880d681SAndroid Build Coastguard Worker // the program, intersect those constraints with BBLV
intersectAssumeBlockValueConstantRange(Value * Val,LVILatticeVal & BBLV,Instruction * BBI)854*9880d681SAndroid Build Coastguard Worker void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
855*9880d681SAndroid Build Coastguard Worker                                                             LVILatticeVal &BBLV,
856*9880d681SAndroid Build Coastguard Worker                                                             Instruction *BBI) {
857*9880d681SAndroid Build Coastguard Worker   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
858*9880d681SAndroid Build Coastguard Worker   if (!BBI)
859*9880d681SAndroid Build Coastguard Worker     return;
860*9880d681SAndroid Build Coastguard Worker 
861*9880d681SAndroid Build Coastguard Worker   for (auto &AssumeVH : AC->assumptions()) {
862*9880d681SAndroid Build Coastguard Worker     if (!AssumeVH)
863*9880d681SAndroid Build Coastguard Worker       continue;
864*9880d681SAndroid Build Coastguard Worker     auto *I = cast<CallInst>(AssumeVH);
865*9880d681SAndroid Build Coastguard Worker     if (!isValidAssumeForContext(I, BBI, DT))
866*9880d681SAndroid Build Coastguard Worker       continue;
867*9880d681SAndroid Build Coastguard Worker 
868*9880d681SAndroid Build Coastguard Worker     Value *C = I->getArgOperand(0);
869*9880d681SAndroid Build Coastguard Worker     if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
870*9880d681SAndroid Build Coastguard Worker       LVILatticeVal Result;
871*9880d681SAndroid Build Coastguard Worker       if (getValueFromFromCondition(Val, ICI, Result))
872*9880d681SAndroid Build Coastguard Worker         BBLV = intersect(BBLV, Result);
873*9880d681SAndroid Build Coastguard Worker     }
874*9880d681SAndroid Build Coastguard Worker   }
875*9880d681SAndroid Build Coastguard Worker }
876*9880d681SAndroid Build Coastguard Worker 
solveBlockValueSelect(LVILatticeVal & BBLV,SelectInst * SI,BasicBlock * BB)877*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
878*9880d681SAndroid Build Coastguard Worker                                                SelectInst *SI, BasicBlock *BB) {
879*9880d681SAndroid Build Coastguard Worker 
880*9880d681SAndroid Build Coastguard Worker   // Recurse on our inputs if needed
881*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(SI->getTrueValue(), BB)) {
882*9880d681SAndroid Build Coastguard Worker     if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
883*9880d681SAndroid Build Coastguard Worker       return false;
884*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
885*9880d681SAndroid Build Coastguard Worker     return true;
886*9880d681SAndroid Build Coastguard Worker   }
887*9880d681SAndroid Build Coastguard Worker   LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
888*9880d681SAndroid Build Coastguard Worker   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
889*9880d681SAndroid Build Coastguard Worker   // extra slots in the table if we can.
890*9880d681SAndroid Build Coastguard Worker   if (TrueVal.isOverdefined()) {
891*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
892*9880d681SAndroid Build Coastguard Worker     return true;
893*9880d681SAndroid Build Coastguard Worker   }
894*9880d681SAndroid Build Coastguard Worker 
895*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(SI->getFalseValue(), BB)) {
896*9880d681SAndroid Build Coastguard Worker     if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
897*9880d681SAndroid Build Coastguard Worker       return false;
898*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
899*9880d681SAndroid Build Coastguard Worker     return true;
900*9880d681SAndroid Build Coastguard Worker   }
901*9880d681SAndroid Build Coastguard Worker   LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
902*9880d681SAndroid Build Coastguard Worker   // If we hit overdefined, don't ask more queries.  We want to avoid poisoning
903*9880d681SAndroid Build Coastguard Worker   // extra slots in the table if we can.
904*9880d681SAndroid Build Coastguard Worker   if (FalseVal.isOverdefined()) {
905*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
906*9880d681SAndroid Build Coastguard Worker     return true;
907*9880d681SAndroid Build Coastguard Worker   }
908*9880d681SAndroid Build Coastguard Worker 
909*9880d681SAndroid Build Coastguard Worker   if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
910*9880d681SAndroid Build Coastguard Worker     ConstantRange TrueCR = TrueVal.getConstantRange();
911*9880d681SAndroid Build Coastguard Worker     ConstantRange FalseCR = FalseVal.getConstantRange();
912*9880d681SAndroid Build Coastguard Worker     Value *LHS = nullptr;
913*9880d681SAndroid Build Coastguard Worker     Value *RHS = nullptr;
914*9880d681SAndroid Build Coastguard Worker     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
915*9880d681SAndroid Build Coastguard Worker     // Is this a min specifically of our two inputs?  (Avoid the risk of
916*9880d681SAndroid Build Coastguard Worker     // ValueTracking getting smarter looking back past our immediate inputs.)
917*9880d681SAndroid Build Coastguard Worker     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
918*9880d681SAndroid Build Coastguard Worker         LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
919*9880d681SAndroid Build Coastguard Worker       switch (SPR.Flavor) {
920*9880d681SAndroid Build Coastguard Worker       default:
921*9880d681SAndroid Build Coastguard Worker         llvm_unreachable("unexpected minmax type!");
922*9880d681SAndroid Build Coastguard Worker       case SPF_SMIN:                   /// Signed minimum
923*9880d681SAndroid Build Coastguard Worker         BBLV.markConstantRange(TrueCR.smin(FalseCR));
924*9880d681SAndroid Build Coastguard Worker         return true;
925*9880d681SAndroid Build Coastguard Worker       case SPF_UMIN:                   /// Unsigned minimum
926*9880d681SAndroid Build Coastguard Worker         BBLV.markConstantRange(TrueCR.umin(FalseCR));
927*9880d681SAndroid Build Coastguard Worker         return true;
928*9880d681SAndroid Build Coastguard Worker       case SPF_SMAX:                   /// Signed maximum
929*9880d681SAndroid Build Coastguard Worker         BBLV.markConstantRange(TrueCR.smax(FalseCR));
930*9880d681SAndroid Build Coastguard Worker         return true;
931*9880d681SAndroid Build Coastguard Worker       case SPF_UMAX:                   /// Unsigned maximum
932*9880d681SAndroid Build Coastguard Worker         BBLV.markConstantRange(TrueCR.umax(FalseCR));
933*9880d681SAndroid Build Coastguard Worker         return true;
934*9880d681SAndroid Build Coastguard Worker       };
935*9880d681SAndroid Build Coastguard Worker     }
936*9880d681SAndroid Build Coastguard Worker 
937*9880d681SAndroid Build Coastguard Worker     // TODO: ABS, NABS from the SelectPatternResult
938*9880d681SAndroid Build Coastguard Worker   }
939*9880d681SAndroid Build Coastguard Worker 
940*9880d681SAndroid Build Coastguard Worker   // Can we constrain the facts about the true and false values by using the
941*9880d681SAndroid Build Coastguard Worker   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
942*9880d681SAndroid Build Coastguard Worker   // TODO: We could potentially refine an overdefined true value above.
943*9880d681SAndroid Build Coastguard Worker   if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
944*9880d681SAndroid Build Coastguard Worker     LVILatticeVal TrueValTaken, FalseValTaken;
945*9880d681SAndroid Build Coastguard Worker     if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
946*9880d681SAndroid Build Coastguard Worker                                    TrueValTaken, true))
947*9880d681SAndroid Build Coastguard Worker       TrueValTaken.markOverdefined();
948*9880d681SAndroid Build Coastguard Worker     if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
949*9880d681SAndroid Build Coastguard Worker                                    FalseValTaken, false))
950*9880d681SAndroid Build Coastguard Worker       FalseValTaken.markOverdefined();
951*9880d681SAndroid Build Coastguard Worker 
952*9880d681SAndroid Build Coastguard Worker     TrueVal = intersect(TrueVal, TrueValTaken);
953*9880d681SAndroid Build Coastguard Worker     FalseVal = intersect(FalseVal, FalseValTaken);
954*9880d681SAndroid Build Coastguard Worker 
955*9880d681SAndroid Build Coastguard Worker 
956*9880d681SAndroid Build Coastguard Worker     // Handle clamp idioms such as:
957*9880d681SAndroid Build Coastguard Worker     //   %24 = constantrange<0, 17>
958*9880d681SAndroid Build Coastguard Worker     //   %39 = icmp eq i32 %24, 0
959*9880d681SAndroid Build Coastguard Worker     //   %40 = add i32 %24, -1
960*9880d681SAndroid Build Coastguard Worker     //   %siv.next = select i1 %39, i32 16, i32 %40
961*9880d681SAndroid Build Coastguard Worker     //   %siv.next = constantrange<0, 17> not <-1, 17>
962*9880d681SAndroid Build Coastguard Worker     // In general, this can handle any clamp idiom which tests the edge
963*9880d681SAndroid Build Coastguard Worker     // condition via an equality or inequality.
964*9880d681SAndroid Build Coastguard Worker     ICmpInst::Predicate Pred = ICI->getPredicate();
965*9880d681SAndroid Build Coastguard Worker     Value *A = ICI->getOperand(0);
966*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
967*9880d681SAndroid Build Coastguard Worker       auto addConstants = [](ConstantInt *A, ConstantInt *B) {
968*9880d681SAndroid Build Coastguard Worker         assert(A->getType() == B->getType());
969*9880d681SAndroid Build Coastguard Worker         return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
970*9880d681SAndroid Build Coastguard Worker       };
971*9880d681SAndroid Build Coastguard Worker       // See if either input is A + C2, subject to the constraint from the
972*9880d681SAndroid Build Coastguard Worker       // condition that A != C when that input is used.  We can assume that
973*9880d681SAndroid Build Coastguard Worker       // that input doesn't include C + C2.
974*9880d681SAndroid Build Coastguard Worker       ConstantInt *CIAdded;
975*9880d681SAndroid Build Coastguard Worker       switch (Pred) {
976*9880d681SAndroid Build Coastguard Worker       default: break;
977*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_EQ:
978*9880d681SAndroid Build Coastguard Worker         if (match(SI->getFalseValue(), m_Add(m_Specific(A),
979*9880d681SAndroid Build Coastguard Worker                                              m_ConstantInt(CIAdded)))) {
980*9880d681SAndroid Build Coastguard Worker           auto ResNot = addConstants(CIBase, CIAdded);
981*9880d681SAndroid Build Coastguard Worker           FalseVal = intersect(FalseVal,
982*9880d681SAndroid Build Coastguard Worker                                LVILatticeVal::getNot(ResNot));
983*9880d681SAndroid Build Coastguard Worker         }
984*9880d681SAndroid Build Coastguard Worker         break;
985*9880d681SAndroid Build Coastguard Worker       case ICmpInst::ICMP_NE:
986*9880d681SAndroid Build Coastguard Worker         if (match(SI->getTrueValue(), m_Add(m_Specific(A),
987*9880d681SAndroid Build Coastguard Worker                                             m_ConstantInt(CIAdded)))) {
988*9880d681SAndroid Build Coastguard Worker           auto ResNot = addConstants(CIBase, CIAdded);
989*9880d681SAndroid Build Coastguard Worker           TrueVal = intersect(TrueVal,
990*9880d681SAndroid Build Coastguard Worker                               LVILatticeVal::getNot(ResNot));
991*9880d681SAndroid Build Coastguard Worker         }
992*9880d681SAndroid Build Coastguard Worker         break;
993*9880d681SAndroid Build Coastguard Worker       };
994*9880d681SAndroid Build Coastguard Worker     }
995*9880d681SAndroid Build Coastguard Worker   }
996*9880d681SAndroid Build Coastguard Worker 
997*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;  // Start Undefined.
998*9880d681SAndroid Build Coastguard Worker   Result.mergeIn(TrueVal, DL);
999*9880d681SAndroid Build Coastguard Worker   Result.mergeIn(FalseVal, DL);
1000*9880d681SAndroid Build Coastguard Worker   BBLV = Result;
1001*9880d681SAndroid Build Coastguard Worker   return true;
1002*9880d681SAndroid Build Coastguard Worker }
1003*9880d681SAndroid Build Coastguard Worker 
solveBlockValueCast(LVILatticeVal & BBLV,Instruction * BBI,BasicBlock * BB)1004*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValueCast(LVILatticeVal &BBLV,
1005*9880d681SAndroid Build Coastguard Worker                                              Instruction *BBI,
1006*9880d681SAndroid Build Coastguard Worker                                              BasicBlock *BB) {
1007*9880d681SAndroid Build Coastguard Worker   if (!BBI->getOperand(0)->getType()->isSized()) {
1008*9880d681SAndroid Build Coastguard Worker     // Without knowing how wide the input is, we can't analyze it in any useful
1009*9880d681SAndroid Build Coastguard Worker     // way.
1010*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
1011*9880d681SAndroid Build Coastguard Worker     return true;
1012*9880d681SAndroid Build Coastguard Worker   }
1013*9880d681SAndroid Build Coastguard Worker 
1014*9880d681SAndroid Build Coastguard Worker   // Filter out casts we don't know how to reason about before attempting to
1015*9880d681SAndroid Build Coastguard Worker   // recurse on our operand.  This can cut a long search short if we know we're
1016*9880d681SAndroid Build Coastguard Worker   // not going to be able to get any useful information anways.
1017*9880d681SAndroid Build Coastguard Worker   switch (BBI->getOpcode()) {
1018*9880d681SAndroid Build Coastguard Worker   case Instruction::Trunc:
1019*9880d681SAndroid Build Coastguard Worker   case Instruction::SExt:
1020*9880d681SAndroid Build Coastguard Worker   case Instruction::ZExt:
1021*9880d681SAndroid Build Coastguard Worker   case Instruction::BitCast:
1022*9880d681SAndroid Build Coastguard Worker     break;
1023*9880d681SAndroid Build Coastguard Worker   default:
1024*9880d681SAndroid Build Coastguard Worker     // Unhandled instructions are overdefined.
1025*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << " compute BB '" << BB->getName()
1026*9880d681SAndroid Build Coastguard Worker                  << "' - overdefined (unknown cast).\n");
1027*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
1028*9880d681SAndroid Build Coastguard Worker     return true;
1029*9880d681SAndroid Build Coastguard Worker   }
1030*9880d681SAndroid Build Coastguard Worker 
1031*9880d681SAndroid Build Coastguard Worker   // Figure out the range of the LHS.  If that fails, we still apply the
1032*9880d681SAndroid Build Coastguard Worker   // transfer rule on the full set since we may be able to locally infer
1033*9880d681SAndroid Build Coastguard Worker   // interesting facts.
1034*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(BBI->getOperand(0), BB))
1035*9880d681SAndroid Build Coastguard Worker     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1036*9880d681SAndroid Build Coastguard Worker       // More work to do before applying this transfer rule.
1037*9880d681SAndroid Build Coastguard Worker       return false;
1038*9880d681SAndroid Build Coastguard Worker 
1039*9880d681SAndroid Build Coastguard Worker   const unsigned OperandBitWidth =
1040*9880d681SAndroid Build Coastguard Worker     DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1041*9880d681SAndroid Build Coastguard Worker   ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1042*9880d681SAndroid Build Coastguard Worker   if (hasBlockValue(BBI->getOperand(0), BB)) {
1043*9880d681SAndroid Build Coastguard Worker     LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1044*9880d681SAndroid Build Coastguard Worker     intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1045*9880d681SAndroid Build Coastguard Worker     if (LHSVal.isConstantRange())
1046*9880d681SAndroid Build Coastguard Worker       LHSRange = LHSVal.getConstantRange();
1047*9880d681SAndroid Build Coastguard Worker   }
1048*9880d681SAndroid Build Coastguard Worker 
1049*9880d681SAndroid Build Coastguard Worker   const unsigned ResultBitWidth =
1050*9880d681SAndroid Build Coastguard Worker     cast<IntegerType>(BBI->getType())->getBitWidth();
1051*9880d681SAndroid Build Coastguard Worker 
1052*9880d681SAndroid Build Coastguard Worker   // NOTE: We're currently limited by the set of operations that ConstantRange
1053*9880d681SAndroid Build Coastguard Worker   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1054*9880d681SAndroid Build Coastguard Worker   // more definitions.
1055*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;
1056*9880d681SAndroid Build Coastguard Worker   switch (BBI->getOpcode()) {
1057*9880d681SAndroid Build Coastguard Worker   case Instruction::Trunc:
1058*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.truncate(ResultBitWidth));
1059*9880d681SAndroid Build Coastguard Worker     break;
1060*9880d681SAndroid Build Coastguard Worker   case Instruction::SExt:
1061*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.signExtend(ResultBitWidth));
1062*9880d681SAndroid Build Coastguard Worker     break;
1063*9880d681SAndroid Build Coastguard Worker   case Instruction::ZExt:
1064*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.zeroExtend(ResultBitWidth));
1065*9880d681SAndroid Build Coastguard Worker     break;
1066*9880d681SAndroid Build Coastguard Worker   case Instruction::BitCast:
1067*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange);
1068*9880d681SAndroid Build Coastguard Worker     break;
1069*9880d681SAndroid Build Coastguard Worker   default:
1070*9880d681SAndroid Build Coastguard Worker     // Should be dead if the code above is correct
1071*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("inconsistent with above");
1072*9880d681SAndroid Build Coastguard Worker     break;
1073*9880d681SAndroid Build Coastguard Worker   }
1074*9880d681SAndroid Build Coastguard Worker 
1075*9880d681SAndroid Build Coastguard Worker   BBLV = Result;
1076*9880d681SAndroid Build Coastguard Worker   return true;
1077*9880d681SAndroid Build Coastguard Worker }
1078*9880d681SAndroid Build Coastguard Worker 
solveBlockValueBinaryOp(LVILatticeVal & BBLV,Instruction * BBI,BasicBlock * BB)1079*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
1080*9880d681SAndroid Build Coastguard Worker                                                  Instruction *BBI,
1081*9880d681SAndroid Build Coastguard Worker                                                  BasicBlock *BB) {
1082*9880d681SAndroid Build Coastguard Worker 
1083*9880d681SAndroid Build Coastguard Worker   assert(BBI->getOperand(0)->getType()->isSized() &&
1084*9880d681SAndroid Build Coastguard Worker          "all operands to binary operators are sized");
1085*9880d681SAndroid Build Coastguard Worker 
1086*9880d681SAndroid Build Coastguard Worker   // Filter out operators we don't know how to reason about before attempting to
1087*9880d681SAndroid Build Coastguard Worker   // recurse on our operand(s).  This can cut a long search short if we know
1088*9880d681SAndroid Build Coastguard Worker   // we're not going to be able to get any useful information anways.
1089*9880d681SAndroid Build Coastguard Worker   switch (BBI->getOpcode()) {
1090*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
1091*9880d681SAndroid Build Coastguard Worker   case Instruction::Sub:
1092*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
1093*9880d681SAndroid Build Coastguard Worker   case Instruction::UDiv:
1094*9880d681SAndroid Build Coastguard Worker   case Instruction::Shl:
1095*9880d681SAndroid Build Coastguard Worker   case Instruction::LShr:
1096*9880d681SAndroid Build Coastguard Worker   case Instruction::And:
1097*9880d681SAndroid Build Coastguard Worker   case Instruction::Or:
1098*9880d681SAndroid Build Coastguard Worker     // continue into the code below
1099*9880d681SAndroid Build Coastguard Worker     break;
1100*9880d681SAndroid Build Coastguard Worker   default:
1101*9880d681SAndroid Build Coastguard Worker     // Unhandled instructions are overdefined.
1102*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << " compute BB '" << BB->getName()
1103*9880d681SAndroid Build Coastguard Worker                  << "' - overdefined (unknown binary operator).\n");
1104*9880d681SAndroid Build Coastguard Worker     BBLV.markOverdefined();
1105*9880d681SAndroid Build Coastguard Worker     return true;
1106*9880d681SAndroid Build Coastguard Worker   };
1107*9880d681SAndroid Build Coastguard Worker 
1108*9880d681SAndroid Build Coastguard Worker   // Figure out the range of the LHS.  If that fails, use a conservative range,
1109*9880d681SAndroid Build Coastguard Worker   // but apply the transfer rule anyways.  This lets us pick up facts from
1110*9880d681SAndroid Build Coastguard Worker   // expressions like "and i32 (call i32 @foo()), 32"
1111*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(BBI->getOperand(0), BB))
1112*9880d681SAndroid Build Coastguard Worker     if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1113*9880d681SAndroid Build Coastguard Worker       // More work to do before applying this transfer rule.
1114*9880d681SAndroid Build Coastguard Worker       return false;
1115*9880d681SAndroid Build Coastguard Worker 
1116*9880d681SAndroid Build Coastguard Worker   const unsigned OperandBitWidth =
1117*9880d681SAndroid Build Coastguard Worker     DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1118*9880d681SAndroid Build Coastguard Worker   ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1119*9880d681SAndroid Build Coastguard Worker   if (hasBlockValue(BBI->getOperand(0), BB)) {
1120*9880d681SAndroid Build Coastguard Worker     LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
1121*9880d681SAndroid Build Coastguard Worker     intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
1122*9880d681SAndroid Build Coastguard Worker     if (LHSVal.isConstantRange())
1123*9880d681SAndroid Build Coastguard Worker       LHSRange = LHSVal.getConstantRange();
1124*9880d681SAndroid Build Coastguard Worker   }
1125*9880d681SAndroid Build Coastguard Worker 
1126*9880d681SAndroid Build Coastguard Worker   ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1127*9880d681SAndroid Build Coastguard Worker   ConstantRange RHSRange = ConstantRange(RHS->getValue());
1128*9880d681SAndroid Build Coastguard Worker 
1129*9880d681SAndroid Build Coastguard Worker   // NOTE: We're currently limited by the set of operations that ConstantRange
1130*9880d681SAndroid Build Coastguard Worker   // can evaluate symbolically.  Enhancing that set will allows us to analyze
1131*9880d681SAndroid Build Coastguard Worker   // more definitions.
1132*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;
1133*9880d681SAndroid Build Coastguard Worker   switch (BBI->getOpcode()) {
1134*9880d681SAndroid Build Coastguard Worker   case Instruction::Add:
1135*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.add(RHSRange));
1136*9880d681SAndroid Build Coastguard Worker     break;
1137*9880d681SAndroid Build Coastguard Worker   case Instruction::Sub:
1138*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.sub(RHSRange));
1139*9880d681SAndroid Build Coastguard Worker     break;
1140*9880d681SAndroid Build Coastguard Worker   case Instruction::Mul:
1141*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.multiply(RHSRange));
1142*9880d681SAndroid Build Coastguard Worker     break;
1143*9880d681SAndroid Build Coastguard Worker   case Instruction::UDiv:
1144*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.udiv(RHSRange));
1145*9880d681SAndroid Build Coastguard Worker     break;
1146*9880d681SAndroid Build Coastguard Worker   case Instruction::Shl:
1147*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.shl(RHSRange));
1148*9880d681SAndroid Build Coastguard Worker     break;
1149*9880d681SAndroid Build Coastguard Worker   case Instruction::LShr:
1150*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.lshr(RHSRange));
1151*9880d681SAndroid Build Coastguard Worker     break;
1152*9880d681SAndroid Build Coastguard Worker   case Instruction::And:
1153*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
1154*9880d681SAndroid Build Coastguard Worker     break;
1155*9880d681SAndroid Build Coastguard Worker   case Instruction::Or:
1156*9880d681SAndroid Build Coastguard Worker     Result.markConstantRange(LHSRange.binaryOr(RHSRange));
1157*9880d681SAndroid Build Coastguard Worker     break;
1158*9880d681SAndroid Build Coastguard Worker   default:
1159*9880d681SAndroid Build Coastguard Worker     // Should be dead if the code above is correct
1160*9880d681SAndroid Build Coastguard Worker     llvm_unreachable("inconsistent with above");
1161*9880d681SAndroid Build Coastguard Worker     break;
1162*9880d681SAndroid Build Coastguard Worker   }
1163*9880d681SAndroid Build Coastguard Worker 
1164*9880d681SAndroid Build Coastguard Worker   BBLV = Result;
1165*9880d681SAndroid Build Coastguard Worker   return true;
1166*9880d681SAndroid Build Coastguard Worker }
1167*9880d681SAndroid Build Coastguard Worker 
getValueFromFromCondition(Value * Val,ICmpInst * ICI,LVILatticeVal & Result,bool isTrueDest)1168*9880d681SAndroid Build Coastguard Worker bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
1169*9880d681SAndroid Build Coastguard Worker                                LVILatticeVal &Result, bool isTrueDest) {
1170*9880d681SAndroid Build Coastguard Worker   assert(ICI && "precondition");
1171*9880d681SAndroid Build Coastguard Worker   if (isa<Constant>(ICI->getOperand(1))) {
1172*9880d681SAndroid Build Coastguard Worker     if (ICI->isEquality() && ICI->getOperand(0) == Val) {
1173*9880d681SAndroid Build Coastguard Worker       // We know that V has the RHS constant if this is a true SETEQ or
1174*9880d681SAndroid Build Coastguard Worker       // false SETNE.
1175*9880d681SAndroid Build Coastguard Worker       if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
1176*9880d681SAndroid Build Coastguard Worker         Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
1177*9880d681SAndroid Build Coastguard Worker       else
1178*9880d681SAndroid Build Coastguard Worker         Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
1179*9880d681SAndroid Build Coastguard Worker       return true;
1180*9880d681SAndroid Build Coastguard Worker     }
1181*9880d681SAndroid Build Coastguard Worker 
1182*9880d681SAndroid Build Coastguard Worker     // Recognize the range checking idiom that InstCombine produces.
1183*9880d681SAndroid Build Coastguard Worker     // (X-C1) u< C2 --> [C1, C1+C2)
1184*9880d681SAndroid Build Coastguard Worker     ConstantInt *NegOffset = nullptr;
1185*9880d681SAndroid Build Coastguard Worker     if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
1186*9880d681SAndroid Build Coastguard Worker       match(ICI->getOperand(0), m_Add(m_Specific(Val),
1187*9880d681SAndroid Build Coastguard Worker                                       m_ConstantInt(NegOffset)));
1188*9880d681SAndroid Build Coastguard Worker 
1189*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
1190*9880d681SAndroid Build Coastguard Worker     if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
1191*9880d681SAndroid Build Coastguard Worker       // Calculate the range of values that are allowed by the comparison
1192*9880d681SAndroid Build Coastguard Worker       ConstantRange CmpRange(CI->getValue());
1193*9880d681SAndroid Build Coastguard Worker       ConstantRange TrueValues =
1194*9880d681SAndroid Build Coastguard Worker           ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
1195*9880d681SAndroid Build Coastguard Worker 
1196*9880d681SAndroid Build Coastguard Worker       if (NegOffset) // Apply the offset from above.
1197*9880d681SAndroid Build Coastguard Worker         TrueValues = TrueValues.subtract(NegOffset->getValue());
1198*9880d681SAndroid Build Coastguard Worker 
1199*9880d681SAndroid Build Coastguard Worker       // If we're interested in the false dest, invert the condition.
1200*9880d681SAndroid Build Coastguard Worker       if (!isTrueDest) TrueValues = TrueValues.inverse();
1201*9880d681SAndroid Build Coastguard Worker 
1202*9880d681SAndroid Build Coastguard Worker       Result = LVILatticeVal::getRange(std::move(TrueValues));
1203*9880d681SAndroid Build Coastguard Worker       return true;
1204*9880d681SAndroid Build Coastguard Worker     }
1205*9880d681SAndroid Build Coastguard Worker   }
1206*9880d681SAndroid Build Coastguard Worker 
1207*9880d681SAndroid Build Coastguard Worker   return false;
1208*9880d681SAndroid Build Coastguard Worker }
1209*9880d681SAndroid Build Coastguard Worker 
1210*9880d681SAndroid Build Coastguard Worker /// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1211*9880d681SAndroid Build Coastguard Worker /// Val is not constrained on the edge.  Result is unspecified if return value
1212*9880d681SAndroid Build Coastguard Worker /// is false.
getEdgeValueLocal(Value * Val,BasicBlock * BBFrom,BasicBlock * BBTo,LVILatticeVal & Result)1213*9880d681SAndroid Build Coastguard Worker static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1214*9880d681SAndroid Build Coastguard Worker                               BasicBlock *BBTo, LVILatticeVal &Result) {
1215*9880d681SAndroid Build Coastguard Worker   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1216*9880d681SAndroid Build Coastguard Worker   // know that v != 0.
1217*9880d681SAndroid Build Coastguard Worker   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1218*9880d681SAndroid Build Coastguard Worker     // If this is a conditional branch and only one successor goes to BBTo, then
1219*9880d681SAndroid Build Coastguard Worker     // we may be able to infer something from the condition.
1220*9880d681SAndroid Build Coastguard Worker     if (BI->isConditional() &&
1221*9880d681SAndroid Build Coastguard Worker         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1222*9880d681SAndroid Build Coastguard Worker       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1223*9880d681SAndroid Build Coastguard Worker       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1224*9880d681SAndroid Build Coastguard Worker              "BBTo isn't a successor of BBFrom");
1225*9880d681SAndroid Build Coastguard Worker 
1226*9880d681SAndroid Build Coastguard Worker       // If V is the condition of the branch itself, then we know exactly what
1227*9880d681SAndroid Build Coastguard Worker       // it is.
1228*9880d681SAndroid Build Coastguard Worker       if (BI->getCondition() == Val) {
1229*9880d681SAndroid Build Coastguard Worker         Result = LVILatticeVal::get(ConstantInt::get(
1230*9880d681SAndroid Build Coastguard Worker                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1231*9880d681SAndroid Build Coastguard Worker         return true;
1232*9880d681SAndroid Build Coastguard Worker       }
1233*9880d681SAndroid Build Coastguard Worker 
1234*9880d681SAndroid Build Coastguard Worker       // If the condition of the branch is an equality comparison, we may be
1235*9880d681SAndroid Build Coastguard Worker       // able to infer the value.
1236*9880d681SAndroid Build Coastguard Worker       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1237*9880d681SAndroid Build Coastguard Worker         if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1238*9880d681SAndroid Build Coastguard Worker           return true;
1239*9880d681SAndroid Build Coastguard Worker     }
1240*9880d681SAndroid Build Coastguard Worker   }
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker   // If the edge was formed by a switch on the value, then we may know exactly
1243*9880d681SAndroid Build Coastguard Worker   // what it is.
1244*9880d681SAndroid Build Coastguard Worker   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1245*9880d681SAndroid Build Coastguard Worker     if (SI->getCondition() != Val)
1246*9880d681SAndroid Build Coastguard Worker       return false;
1247*9880d681SAndroid Build Coastguard Worker 
1248*9880d681SAndroid Build Coastguard Worker     bool DefaultCase = SI->getDefaultDest() == BBTo;
1249*9880d681SAndroid Build Coastguard Worker     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1250*9880d681SAndroid Build Coastguard Worker     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1251*9880d681SAndroid Build Coastguard Worker 
1252*9880d681SAndroid Build Coastguard Worker     for (SwitchInst::CaseIt i : SI->cases()) {
1253*9880d681SAndroid Build Coastguard Worker       ConstantRange EdgeVal(i.getCaseValue()->getValue());
1254*9880d681SAndroid Build Coastguard Worker       if (DefaultCase) {
1255*9880d681SAndroid Build Coastguard Worker         // It is possible that the default destination is the destination of
1256*9880d681SAndroid Build Coastguard Worker         // some cases. There is no need to perform difference for those cases.
1257*9880d681SAndroid Build Coastguard Worker         if (i.getCaseSuccessor() != BBTo)
1258*9880d681SAndroid Build Coastguard Worker           EdgesVals = EdgesVals.difference(EdgeVal);
1259*9880d681SAndroid Build Coastguard Worker       } else if (i.getCaseSuccessor() == BBTo)
1260*9880d681SAndroid Build Coastguard Worker         EdgesVals = EdgesVals.unionWith(EdgeVal);
1261*9880d681SAndroid Build Coastguard Worker     }
1262*9880d681SAndroid Build Coastguard Worker     Result = LVILatticeVal::getRange(std::move(EdgesVals));
1263*9880d681SAndroid Build Coastguard Worker     return true;
1264*9880d681SAndroid Build Coastguard Worker   }
1265*9880d681SAndroid Build Coastguard Worker   return false;
1266*9880d681SAndroid Build Coastguard Worker }
1267*9880d681SAndroid Build Coastguard Worker 
1268*9880d681SAndroid Build Coastguard Worker /// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1269*9880d681SAndroid Build Coastguard Worker /// the basic block if the edge does not constrain Val.
getEdgeValue(Value * Val,BasicBlock * BBFrom,BasicBlock * BBTo,LVILatticeVal & Result,Instruction * CxtI)1270*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1271*9880d681SAndroid Build Coastguard Worker                                       BasicBlock *BBTo, LVILatticeVal &Result,
1272*9880d681SAndroid Build Coastguard Worker                                       Instruction *CxtI) {
1273*9880d681SAndroid Build Coastguard Worker   // If already a constant, there is nothing to compute.
1274*9880d681SAndroid Build Coastguard Worker   if (Constant *VC = dyn_cast<Constant>(Val)) {
1275*9880d681SAndroid Build Coastguard Worker     Result = LVILatticeVal::get(VC);
1276*9880d681SAndroid Build Coastguard Worker     return true;
1277*9880d681SAndroid Build Coastguard Worker   }
1278*9880d681SAndroid Build Coastguard Worker 
1279*9880d681SAndroid Build Coastguard Worker   LVILatticeVal LocalResult;
1280*9880d681SAndroid Build Coastguard Worker   if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1281*9880d681SAndroid Build Coastguard Worker     // If we couldn't constrain the value on the edge, LocalResult doesn't
1282*9880d681SAndroid Build Coastguard Worker     // provide any information.
1283*9880d681SAndroid Build Coastguard Worker     LocalResult.markOverdefined();
1284*9880d681SAndroid Build Coastguard Worker 
1285*9880d681SAndroid Build Coastguard Worker   if (hasSingleValue(LocalResult)) {
1286*9880d681SAndroid Build Coastguard Worker     // Can't get any more precise here
1287*9880d681SAndroid Build Coastguard Worker     Result = LocalResult;
1288*9880d681SAndroid Build Coastguard Worker     return true;
1289*9880d681SAndroid Build Coastguard Worker   }
1290*9880d681SAndroid Build Coastguard Worker 
1291*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(Val, BBFrom)) {
1292*9880d681SAndroid Build Coastguard Worker     if (pushBlockValue(std::make_pair(BBFrom, Val)))
1293*9880d681SAndroid Build Coastguard Worker       return false;
1294*9880d681SAndroid Build Coastguard Worker     // No new information.
1295*9880d681SAndroid Build Coastguard Worker     Result = LocalResult;
1296*9880d681SAndroid Build Coastguard Worker     return true;
1297*9880d681SAndroid Build Coastguard Worker   }
1298*9880d681SAndroid Build Coastguard Worker 
1299*9880d681SAndroid Build Coastguard Worker   // Try to intersect ranges of the BB and the constraint on the edge.
1300*9880d681SAndroid Build Coastguard Worker   LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
1301*9880d681SAndroid Build Coastguard Worker   intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
1302*9880d681SAndroid Build Coastguard Worker   // We can use the context instruction (generically the ultimate instruction
1303*9880d681SAndroid Build Coastguard Worker   // the calling pass is trying to simplify) here, even though the result of
1304*9880d681SAndroid Build Coastguard Worker   // this function is generally cached when called from the solve* functions
1305*9880d681SAndroid Build Coastguard Worker   // (and that cached result might be used with queries using a different
1306*9880d681SAndroid Build Coastguard Worker   // context instruction), because when this function is called from the solve*
1307*9880d681SAndroid Build Coastguard Worker   // functions, the context instruction is not provided. When called from
1308*9880d681SAndroid Build Coastguard Worker   // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1309*9880d681SAndroid Build Coastguard Worker   // but then the result is not cached.
1310*9880d681SAndroid Build Coastguard Worker   intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
1311*9880d681SAndroid Build Coastguard Worker 
1312*9880d681SAndroid Build Coastguard Worker   Result = intersect(LocalResult, InBlock);
1313*9880d681SAndroid Build Coastguard Worker   return true;
1314*9880d681SAndroid Build Coastguard Worker }
1315*9880d681SAndroid Build Coastguard Worker 
getValueInBlock(Value * V,BasicBlock * BB,Instruction * CxtI)1316*9880d681SAndroid Build Coastguard Worker LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1317*9880d681SAndroid Build Coastguard Worker                                                   Instruction *CxtI) {
1318*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1319*9880d681SAndroid Build Coastguard Worker         << BB->getName() << "'\n");
1320*9880d681SAndroid Build Coastguard Worker 
1321*9880d681SAndroid Build Coastguard Worker   assert(BlockValueStack.empty() && BlockValueSet.empty());
1322*9880d681SAndroid Build Coastguard Worker   if (!hasBlockValue(V, BB)) {
1323*9880d681SAndroid Build Coastguard Worker     pushBlockValue(std::make_pair(BB, V));
1324*9880d681SAndroid Build Coastguard Worker     solve();
1325*9880d681SAndroid Build Coastguard Worker   }
1326*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result = getBlockValue(V, BB);
1327*9880d681SAndroid Build Coastguard Worker   intersectAssumeBlockValueConstantRange(V, Result, CxtI);
1328*9880d681SAndroid Build Coastguard Worker 
1329*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Result = " << Result << "\n");
1330*9880d681SAndroid Build Coastguard Worker   return Result;
1331*9880d681SAndroid Build Coastguard Worker }
1332*9880d681SAndroid Build Coastguard Worker 
getValueAt(Value * V,Instruction * CxtI)1333*9880d681SAndroid Build Coastguard Worker LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1334*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1335*9880d681SAndroid Build Coastguard Worker         << CxtI->getName() << "'\n");
1336*9880d681SAndroid Build Coastguard Worker 
1337*9880d681SAndroid Build Coastguard Worker   if (auto *C = dyn_cast<Constant>(V))
1338*9880d681SAndroid Build Coastguard Worker     return LVILatticeVal::get(C);
1339*9880d681SAndroid Build Coastguard Worker 
1340*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result = LVILatticeVal::getOverdefined();
1341*9880d681SAndroid Build Coastguard Worker   if (auto *I = dyn_cast<Instruction>(V))
1342*9880d681SAndroid Build Coastguard Worker     Result = getFromRangeMetadata(I);
1343*9880d681SAndroid Build Coastguard Worker   intersectAssumeBlockValueConstantRange(V, Result, CxtI);
1344*9880d681SAndroid Build Coastguard Worker 
1345*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Result = " << Result << "\n");
1346*9880d681SAndroid Build Coastguard Worker   return Result;
1347*9880d681SAndroid Build Coastguard Worker }
1348*9880d681SAndroid Build Coastguard Worker 
1349*9880d681SAndroid Build Coastguard Worker LVILatticeVal LazyValueInfoCache::
getValueOnEdge(Value * V,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)1350*9880d681SAndroid Build Coastguard Worker getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1351*9880d681SAndroid Build Coastguard Worker                Instruction *CxtI) {
1352*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1353*9880d681SAndroid Build Coastguard Worker         << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
1354*9880d681SAndroid Build Coastguard Worker 
1355*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result;
1356*9880d681SAndroid Build Coastguard Worker   if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
1357*9880d681SAndroid Build Coastguard Worker     solve();
1358*9880d681SAndroid Build Coastguard Worker     bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
1359*9880d681SAndroid Build Coastguard Worker     (void)WasFastQuery;
1360*9880d681SAndroid Build Coastguard Worker     assert(WasFastQuery && "More work to do after problem solved?");
1361*9880d681SAndroid Build Coastguard Worker   }
1362*9880d681SAndroid Build Coastguard Worker 
1363*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Result = " << Result << "\n");
1364*9880d681SAndroid Build Coastguard Worker   return Result;
1365*9880d681SAndroid Build Coastguard Worker }
1366*9880d681SAndroid Build Coastguard Worker 
threadEdge(BasicBlock * PredBB,BasicBlock * OldSucc,BasicBlock * NewSucc)1367*9880d681SAndroid Build Coastguard Worker void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1368*9880d681SAndroid Build Coastguard Worker                                     BasicBlock *NewSucc) {
1369*9880d681SAndroid Build Coastguard Worker   // When an edge in the graph has been threaded, values that we could not
1370*9880d681SAndroid Build Coastguard Worker   // determine a value for before (i.e. were marked overdefined) may be
1371*9880d681SAndroid Build Coastguard Worker   // possible to solve now. We do NOT try to proactively update these values.
1372*9880d681SAndroid Build Coastguard Worker   // Instead, we clear their entries from the cache, and allow lazy updating to
1373*9880d681SAndroid Build Coastguard Worker   // recompute them when needed.
1374*9880d681SAndroid Build Coastguard Worker 
1375*9880d681SAndroid Build Coastguard Worker   // The updating process is fairly simple: we need to drop cached info
1376*9880d681SAndroid Build Coastguard Worker   // for all values that were marked overdefined in OldSucc, and for those same
1377*9880d681SAndroid Build Coastguard Worker   // values in any successor of OldSucc (except NewSucc) in which they were
1378*9880d681SAndroid Build Coastguard Worker   // also marked overdefined.
1379*9880d681SAndroid Build Coastguard Worker   std::vector<BasicBlock*> worklist;
1380*9880d681SAndroid Build Coastguard Worker   worklist.push_back(OldSucc);
1381*9880d681SAndroid Build Coastguard Worker 
1382*9880d681SAndroid Build Coastguard Worker   auto I = OverDefinedCache.find(OldSucc);
1383*9880d681SAndroid Build Coastguard Worker   if (I == OverDefinedCache.end())
1384*9880d681SAndroid Build Coastguard Worker     return; // Nothing to process here.
1385*9880d681SAndroid Build Coastguard Worker   SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
1386*9880d681SAndroid Build Coastguard Worker 
1387*9880d681SAndroid Build Coastguard Worker   // Use a worklist to perform a depth-first search of OldSucc's successors.
1388*9880d681SAndroid Build Coastguard Worker   // NOTE: We do not need a visited list since any blocks we have already
1389*9880d681SAndroid Build Coastguard Worker   // visited will have had their overdefined markers cleared already, and we
1390*9880d681SAndroid Build Coastguard Worker   // thus won't loop to their successors.
1391*9880d681SAndroid Build Coastguard Worker   while (!worklist.empty()) {
1392*9880d681SAndroid Build Coastguard Worker     BasicBlock *ToUpdate = worklist.back();
1393*9880d681SAndroid Build Coastguard Worker     worklist.pop_back();
1394*9880d681SAndroid Build Coastguard Worker 
1395*9880d681SAndroid Build Coastguard Worker     // Skip blocks only accessible through NewSucc.
1396*9880d681SAndroid Build Coastguard Worker     if (ToUpdate == NewSucc) continue;
1397*9880d681SAndroid Build Coastguard Worker 
1398*9880d681SAndroid Build Coastguard Worker     bool changed = false;
1399*9880d681SAndroid Build Coastguard Worker     for (Value *V : ValsToClear) {
1400*9880d681SAndroid Build Coastguard Worker       // If a value was marked overdefined in OldSucc, and is here too...
1401*9880d681SAndroid Build Coastguard Worker       auto OI = OverDefinedCache.find(ToUpdate);
1402*9880d681SAndroid Build Coastguard Worker       if (OI == OverDefinedCache.end())
1403*9880d681SAndroid Build Coastguard Worker         continue;
1404*9880d681SAndroid Build Coastguard Worker       SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1405*9880d681SAndroid Build Coastguard Worker       if (!ValueSet.count(V))
1406*9880d681SAndroid Build Coastguard Worker         continue;
1407*9880d681SAndroid Build Coastguard Worker 
1408*9880d681SAndroid Build Coastguard Worker       ValueSet.erase(V);
1409*9880d681SAndroid Build Coastguard Worker       if (ValueSet.empty())
1410*9880d681SAndroid Build Coastguard Worker         OverDefinedCache.erase(OI);
1411*9880d681SAndroid Build Coastguard Worker 
1412*9880d681SAndroid Build Coastguard Worker       // If we removed anything, then we potentially need to update
1413*9880d681SAndroid Build Coastguard Worker       // blocks successors too.
1414*9880d681SAndroid Build Coastguard Worker       changed = true;
1415*9880d681SAndroid Build Coastguard Worker     }
1416*9880d681SAndroid Build Coastguard Worker 
1417*9880d681SAndroid Build Coastguard Worker     if (!changed) continue;
1418*9880d681SAndroid Build Coastguard Worker 
1419*9880d681SAndroid Build Coastguard Worker     worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1420*9880d681SAndroid Build Coastguard Worker   }
1421*9880d681SAndroid Build Coastguard Worker }
1422*9880d681SAndroid Build Coastguard Worker 
1423*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1424*9880d681SAndroid Build Coastguard Worker //                            LazyValueInfo Impl
1425*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
1426*9880d681SAndroid Build Coastguard Worker 
1427*9880d681SAndroid Build Coastguard Worker /// This lazily constructs the LazyValueInfoCache.
getCache(void * & PImpl,AssumptionCache * AC,const DataLayout * DL,DominatorTree * DT=nullptr)1428*9880d681SAndroid Build Coastguard Worker static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
1429*9880d681SAndroid Build Coastguard Worker                                     const DataLayout *DL,
1430*9880d681SAndroid Build Coastguard Worker                                     DominatorTree *DT = nullptr) {
1431*9880d681SAndroid Build Coastguard Worker   if (!PImpl) {
1432*9880d681SAndroid Build Coastguard Worker     assert(DL && "getCache() called with a null DataLayout");
1433*9880d681SAndroid Build Coastguard Worker     PImpl = new LazyValueInfoCache(AC, *DL, DT);
1434*9880d681SAndroid Build Coastguard Worker   }
1435*9880d681SAndroid Build Coastguard Worker   return *static_cast<LazyValueInfoCache*>(PImpl);
1436*9880d681SAndroid Build Coastguard Worker }
1437*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)1438*9880d681SAndroid Build Coastguard Worker bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1439*9880d681SAndroid Build Coastguard Worker   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1440*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = F.getParent()->getDataLayout();
1441*9880d681SAndroid Build Coastguard Worker 
1442*9880d681SAndroid Build Coastguard Worker   DominatorTreeWrapperPass *DTWP =
1443*9880d681SAndroid Build Coastguard Worker       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1444*9880d681SAndroid Build Coastguard Worker   Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1445*9880d681SAndroid Build Coastguard Worker   Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1446*9880d681SAndroid Build Coastguard Worker 
1447*9880d681SAndroid Build Coastguard Worker   if (Info.PImpl)
1448*9880d681SAndroid Build Coastguard Worker     getCache(Info.PImpl, Info.AC, &DL, Info.DT).clear();
1449*9880d681SAndroid Build Coastguard Worker 
1450*9880d681SAndroid Build Coastguard Worker   // Fully lazy.
1451*9880d681SAndroid Build Coastguard Worker   return false;
1452*9880d681SAndroid Build Coastguard Worker }
1453*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const1454*9880d681SAndroid Build Coastguard Worker void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1455*9880d681SAndroid Build Coastguard Worker   AU.setPreservesAll();
1456*9880d681SAndroid Build Coastguard Worker   AU.addRequired<AssumptionCacheTracker>();
1457*9880d681SAndroid Build Coastguard Worker   AU.addRequired<TargetLibraryInfoWrapperPass>();
1458*9880d681SAndroid Build Coastguard Worker }
1459*9880d681SAndroid Build Coastguard Worker 
getLVI()1460*9880d681SAndroid Build Coastguard Worker LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1461*9880d681SAndroid Build Coastguard Worker 
~LazyValueInfo()1462*9880d681SAndroid Build Coastguard Worker LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1463*9880d681SAndroid Build Coastguard Worker 
releaseMemory()1464*9880d681SAndroid Build Coastguard Worker void LazyValueInfo::releaseMemory() {
1465*9880d681SAndroid Build Coastguard Worker   // If the cache was allocated, free it.
1466*9880d681SAndroid Build Coastguard Worker   if (PImpl) {
1467*9880d681SAndroid Build Coastguard Worker     delete &getCache(PImpl, AC, nullptr);
1468*9880d681SAndroid Build Coastguard Worker     PImpl = nullptr;
1469*9880d681SAndroid Build Coastguard Worker   }
1470*9880d681SAndroid Build Coastguard Worker }
1471*9880d681SAndroid Build Coastguard Worker 
releaseMemory()1472*9880d681SAndroid Build Coastguard Worker void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1473*9880d681SAndroid Build Coastguard Worker 
run(Function & F,FunctionAnalysisManager & FAM)1474*9880d681SAndroid Build Coastguard Worker LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1475*9880d681SAndroid Build Coastguard Worker   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1476*9880d681SAndroid Build Coastguard Worker   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1477*9880d681SAndroid Build Coastguard Worker   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1478*9880d681SAndroid Build Coastguard Worker 
1479*9880d681SAndroid Build Coastguard Worker   return LazyValueInfo(&AC, &TLI, DT);
1480*9880d681SAndroid Build Coastguard Worker }
1481*9880d681SAndroid Build Coastguard Worker 
getConstant(Value * V,BasicBlock * BB,Instruction * CxtI)1482*9880d681SAndroid Build Coastguard Worker Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1483*9880d681SAndroid Build Coastguard Worker                                      Instruction *CxtI) {
1484*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = BB->getModule()->getDataLayout();
1485*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result =
1486*9880d681SAndroid Build Coastguard Worker       getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1487*9880d681SAndroid Build Coastguard Worker 
1488*9880d681SAndroid Build Coastguard Worker   if (Result.isConstant())
1489*9880d681SAndroid Build Coastguard Worker     return Result.getConstant();
1490*9880d681SAndroid Build Coastguard Worker   if (Result.isConstantRange()) {
1491*9880d681SAndroid Build Coastguard Worker     ConstantRange CR = Result.getConstantRange();
1492*9880d681SAndroid Build Coastguard Worker     if (const APInt *SingleVal = CR.getSingleElement())
1493*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(V->getContext(), *SingleVal);
1494*9880d681SAndroid Build Coastguard Worker   }
1495*9880d681SAndroid Build Coastguard Worker   return nullptr;
1496*9880d681SAndroid Build Coastguard Worker }
1497*9880d681SAndroid Build Coastguard Worker 
getConstantRange(Value * V,BasicBlock * BB,Instruction * CxtI)1498*9880d681SAndroid Build Coastguard Worker ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
1499*9880d681SAndroid Build Coastguard Worker                                               Instruction *CxtI) {
1500*9880d681SAndroid Build Coastguard Worker   assert(V->getType()->isIntegerTy());
1501*9880d681SAndroid Build Coastguard Worker   unsigned Width = V->getType()->getIntegerBitWidth();
1502*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = BB->getModule()->getDataLayout();
1503*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result =
1504*9880d681SAndroid Build Coastguard Worker       getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
1505*9880d681SAndroid Build Coastguard Worker   assert(!Result.isConstant());
1506*9880d681SAndroid Build Coastguard Worker   if (Result.isUndefined())
1507*9880d681SAndroid Build Coastguard Worker     return ConstantRange(Width, /*isFullSet=*/false);
1508*9880d681SAndroid Build Coastguard Worker   if (Result.isConstantRange())
1509*9880d681SAndroid Build Coastguard Worker     return Result.getConstantRange();
1510*9880d681SAndroid Build Coastguard Worker   return ConstantRange(Width, /*isFullSet=*/true);
1511*9880d681SAndroid Build Coastguard Worker }
1512*9880d681SAndroid Build Coastguard Worker 
1513*9880d681SAndroid Build Coastguard Worker /// Determine whether the specified value is known to be a
1514*9880d681SAndroid Build Coastguard Worker /// constant on the specified edge. Return null if not.
getConstantOnEdge(Value * V,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)1515*9880d681SAndroid Build Coastguard Worker Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1516*9880d681SAndroid Build Coastguard Worker                                            BasicBlock *ToBB,
1517*9880d681SAndroid Build Coastguard Worker                                            Instruction *CxtI) {
1518*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1519*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result =
1520*9880d681SAndroid Build Coastguard Worker       getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1521*9880d681SAndroid Build Coastguard Worker 
1522*9880d681SAndroid Build Coastguard Worker   if (Result.isConstant())
1523*9880d681SAndroid Build Coastguard Worker     return Result.getConstant();
1524*9880d681SAndroid Build Coastguard Worker   if (Result.isConstantRange()) {
1525*9880d681SAndroid Build Coastguard Worker     ConstantRange CR = Result.getConstantRange();
1526*9880d681SAndroid Build Coastguard Worker     if (const APInt *SingleVal = CR.getSingleElement())
1527*9880d681SAndroid Build Coastguard Worker       return ConstantInt::get(V->getContext(), *SingleVal);
1528*9880d681SAndroid Build Coastguard Worker   }
1529*9880d681SAndroid Build Coastguard Worker   return nullptr;
1530*9880d681SAndroid Build Coastguard Worker }
1531*9880d681SAndroid Build Coastguard Worker 
getPredicateResult(unsigned Pred,Constant * C,LVILatticeVal & Result,const DataLayout & DL,TargetLibraryInfo * TLI)1532*9880d681SAndroid Build Coastguard Worker static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1533*9880d681SAndroid Build Coastguard Worker                                                   LVILatticeVal &Result,
1534*9880d681SAndroid Build Coastguard Worker                                                   const DataLayout &DL,
1535*9880d681SAndroid Build Coastguard Worker                                                   TargetLibraryInfo *TLI) {
1536*9880d681SAndroid Build Coastguard Worker 
1537*9880d681SAndroid Build Coastguard Worker   // If we know the value is a constant, evaluate the conditional.
1538*9880d681SAndroid Build Coastguard Worker   Constant *Res = nullptr;
1539*9880d681SAndroid Build Coastguard Worker   if (Result.isConstant()) {
1540*9880d681SAndroid Build Coastguard Worker     Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
1541*9880d681SAndroid Build Coastguard Worker                                           TLI);
1542*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1543*9880d681SAndroid Build Coastguard Worker       return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1544*9880d681SAndroid Build Coastguard Worker     return LazyValueInfo::Unknown;
1545*9880d681SAndroid Build Coastguard Worker   }
1546*9880d681SAndroid Build Coastguard Worker 
1547*9880d681SAndroid Build Coastguard Worker   if (Result.isConstantRange()) {
1548*9880d681SAndroid Build Coastguard Worker     ConstantInt *CI = dyn_cast<ConstantInt>(C);
1549*9880d681SAndroid Build Coastguard Worker     if (!CI) return LazyValueInfo::Unknown;
1550*9880d681SAndroid Build Coastguard Worker 
1551*9880d681SAndroid Build Coastguard Worker     ConstantRange CR = Result.getConstantRange();
1552*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_EQ) {
1553*9880d681SAndroid Build Coastguard Worker       if (!CR.contains(CI->getValue()))
1554*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::False;
1555*9880d681SAndroid Build Coastguard Worker 
1556*9880d681SAndroid Build Coastguard Worker       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1557*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::True;
1558*9880d681SAndroid Build Coastguard Worker     } else if (Pred == ICmpInst::ICMP_NE) {
1559*9880d681SAndroid Build Coastguard Worker       if (!CR.contains(CI->getValue()))
1560*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::True;
1561*9880d681SAndroid Build Coastguard Worker 
1562*9880d681SAndroid Build Coastguard Worker       if (CR.isSingleElement() && CR.contains(CI->getValue()))
1563*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::False;
1564*9880d681SAndroid Build Coastguard Worker     }
1565*9880d681SAndroid Build Coastguard Worker 
1566*9880d681SAndroid Build Coastguard Worker     // Handle more complex predicates.
1567*9880d681SAndroid Build Coastguard Worker     ConstantRange TrueValues =
1568*9880d681SAndroid Build Coastguard Worker         ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1569*9880d681SAndroid Build Coastguard Worker     if (TrueValues.contains(CR))
1570*9880d681SAndroid Build Coastguard Worker       return LazyValueInfo::True;
1571*9880d681SAndroid Build Coastguard Worker     if (TrueValues.inverse().contains(CR))
1572*9880d681SAndroid Build Coastguard Worker       return LazyValueInfo::False;
1573*9880d681SAndroid Build Coastguard Worker     return LazyValueInfo::Unknown;
1574*9880d681SAndroid Build Coastguard Worker   }
1575*9880d681SAndroid Build Coastguard Worker 
1576*9880d681SAndroid Build Coastguard Worker   if (Result.isNotConstant()) {
1577*9880d681SAndroid Build Coastguard Worker     // If this is an equality comparison, we can try to fold it knowing that
1578*9880d681SAndroid Build Coastguard Worker     // "V != C1".
1579*9880d681SAndroid Build Coastguard Worker     if (Pred == ICmpInst::ICMP_EQ) {
1580*9880d681SAndroid Build Coastguard Worker       // !C1 == C -> false iff C1 == C.
1581*9880d681SAndroid Build Coastguard Worker       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1582*9880d681SAndroid Build Coastguard Worker                                             Result.getNotConstant(), C, DL,
1583*9880d681SAndroid Build Coastguard Worker                                             TLI);
1584*9880d681SAndroid Build Coastguard Worker       if (Res->isNullValue())
1585*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::False;
1586*9880d681SAndroid Build Coastguard Worker     } else if (Pred == ICmpInst::ICMP_NE) {
1587*9880d681SAndroid Build Coastguard Worker       // !C1 != C -> true iff C1 == C.
1588*9880d681SAndroid Build Coastguard Worker       Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1589*9880d681SAndroid Build Coastguard Worker                                             Result.getNotConstant(), C, DL,
1590*9880d681SAndroid Build Coastguard Worker                                             TLI);
1591*9880d681SAndroid Build Coastguard Worker       if (Res->isNullValue())
1592*9880d681SAndroid Build Coastguard Worker         return LazyValueInfo::True;
1593*9880d681SAndroid Build Coastguard Worker     }
1594*9880d681SAndroid Build Coastguard Worker     return LazyValueInfo::Unknown;
1595*9880d681SAndroid Build Coastguard Worker   }
1596*9880d681SAndroid Build Coastguard Worker 
1597*9880d681SAndroid Build Coastguard Worker   return LazyValueInfo::Unknown;
1598*9880d681SAndroid Build Coastguard Worker }
1599*9880d681SAndroid Build Coastguard Worker 
1600*9880d681SAndroid Build Coastguard Worker /// Determine whether the specified value comparison with a constant is known to
1601*9880d681SAndroid Build Coastguard Worker /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1602*9880d681SAndroid Build Coastguard Worker LazyValueInfo::Tristate
getPredicateOnEdge(unsigned Pred,Value * V,Constant * C,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)1603*9880d681SAndroid Build Coastguard Worker LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1604*9880d681SAndroid Build Coastguard Worker                                   BasicBlock *FromBB, BasicBlock *ToBB,
1605*9880d681SAndroid Build Coastguard Worker                                   Instruction *CxtI) {
1606*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = FromBB->getModule()->getDataLayout();
1607*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result =
1608*9880d681SAndroid Build Coastguard Worker       getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1609*9880d681SAndroid Build Coastguard Worker 
1610*9880d681SAndroid Build Coastguard Worker   return getPredicateResult(Pred, C, Result, DL, TLI);
1611*9880d681SAndroid Build Coastguard Worker }
1612*9880d681SAndroid Build Coastguard Worker 
1613*9880d681SAndroid Build Coastguard Worker LazyValueInfo::Tristate
getPredicateAt(unsigned Pred,Value * V,Constant * C,Instruction * CxtI)1614*9880d681SAndroid Build Coastguard Worker LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1615*9880d681SAndroid Build Coastguard Worker                               Instruction *CxtI) {
1616*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = CxtI->getModule()->getDataLayout();
1617*9880d681SAndroid Build Coastguard Worker   LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
1618*9880d681SAndroid Build Coastguard Worker   Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1619*9880d681SAndroid Build Coastguard Worker   if (Ret != Unknown)
1620*9880d681SAndroid Build Coastguard Worker     return Ret;
1621*9880d681SAndroid Build Coastguard Worker 
1622*9880d681SAndroid Build Coastguard Worker   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1623*9880d681SAndroid Build Coastguard Worker   // LVI as a whole tries to compute a lattice value which is conservatively
1624*9880d681SAndroid Build Coastguard Worker   // correct at a given location.  In this case, we have a predicate which we
1625*9880d681SAndroid Build Coastguard Worker   // weren't able to prove about the merged result, and we're pushing that
1626*9880d681SAndroid Build Coastguard Worker   // predicate back along each incoming edge to see if we can prove it
1627*9880d681SAndroid Build Coastguard Worker   // separately for each input.  As a motivating example, consider:
1628*9880d681SAndroid Build Coastguard Worker   // bb1:
1629*9880d681SAndroid Build Coastguard Worker   //   %v1 = ... ; constantrange<1, 5>
1630*9880d681SAndroid Build Coastguard Worker   //   br label %merge
1631*9880d681SAndroid Build Coastguard Worker   // bb2:
1632*9880d681SAndroid Build Coastguard Worker   //   %v2 = ... ; constantrange<10, 20>
1633*9880d681SAndroid Build Coastguard Worker   //   br label %merge
1634*9880d681SAndroid Build Coastguard Worker   // merge:
1635*9880d681SAndroid Build Coastguard Worker   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1636*9880d681SAndroid Build Coastguard Worker   //   %pred = icmp eq i32 %phi, 8
1637*9880d681SAndroid Build Coastguard Worker   // We can't tell from the lattice value for '%phi' that '%pred' is false
1638*9880d681SAndroid Build Coastguard Worker   // along each path, but by checking the predicate over each input separately,
1639*9880d681SAndroid Build Coastguard Worker   // we can.
1640*9880d681SAndroid Build Coastguard Worker   // We limit the search to one step backwards from the current BB and value.
1641*9880d681SAndroid Build Coastguard Worker   // We could consider extending this to search further backwards through the
1642*9880d681SAndroid Build Coastguard Worker   // CFG and/or value graph, but there are non-obvious compile time vs quality
1643*9880d681SAndroid Build Coastguard Worker   // tradeoffs.
1644*9880d681SAndroid Build Coastguard Worker   if (CxtI) {
1645*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = CxtI->getParent();
1646*9880d681SAndroid Build Coastguard Worker 
1647*9880d681SAndroid Build Coastguard Worker     // Function entry or an unreachable block.  Bail to avoid confusing
1648*9880d681SAndroid Build Coastguard Worker     // analysis below.
1649*9880d681SAndroid Build Coastguard Worker     pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1650*9880d681SAndroid Build Coastguard Worker     if (PI == PE)
1651*9880d681SAndroid Build Coastguard Worker       return Unknown;
1652*9880d681SAndroid Build Coastguard Worker 
1653*9880d681SAndroid Build Coastguard Worker     // If V is a PHI node in the same block as the context, we need to ask
1654*9880d681SAndroid Build Coastguard Worker     // questions about the predicate as applied to the incoming value along
1655*9880d681SAndroid Build Coastguard Worker     // each edge. This is useful for eliminating cases where the predicate is
1656*9880d681SAndroid Build Coastguard Worker     // known along all incoming edges.
1657*9880d681SAndroid Build Coastguard Worker     if (auto *PHI = dyn_cast<PHINode>(V))
1658*9880d681SAndroid Build Coastguard Worker       if (PHI->getParent() == BB) {
1659*9880d681SAndroid Build Coastguard Worker         Tristate Baseline = Unknown;
1660*9880d681SAndroid Build Coastguard Worker         for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1661*9880d681SAndroid Build Coastguard Worker           Value *Incoming = PHI->getIncomingValue(i);
1662*9880d681SAndroid Build Coastguard Worker           BasicBlock *PredBB = PHI->getIncomingBlock(i);
1663*9880d681SAndroid Build Coastguard Worker           // Note that PredBB may be BB itself.
1664*9880d681SAndroid Build Coastguard Worker           Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1665*9880d681SAndroid Build Coastguard Worker                                                CxtI);
1666*9880d681SAndroid Build Coastguard Worker 
1667*9880d681SAndroid Build Coastguard Worker           // Keep going as long as we've seen a consistent known result for
1668*9880d681SAndroid Build Coastguard Worker           // all inputs.
1669*9880d681SAndroid Build Coastguard Worker           Baseline = (i == 0) ? Result /* First iteration */
1670*9880d681SAndroid Build Coastguard Worker             : (Baseline == Result ? Baseline : Unknown); /* All others */
1671*9880d681SAndroid Build Coastguard Worker           if (Baseline == Unknown)
1672*9880d681SAndroid Build Coastguard Worker             break;
1673*9880d681SAndroid Build Coastguard Worker         }
1674*9880d681SAndroid Build Coastguard Worker         if (Baseline != Unknown)
1675*9880d681SAndroid Build Coastguard Worker           return Baseline;
1676*9880d681SAndroid Build Coastguard Worker       }
1677*9880d681SAndroid Build Coastguard Worker 
1678*9880d681SAndroid Build Coastguard Worker     // For a comparison where the V is outside this block, it's possible
1679*9880d681SAndroid Build Coastguard Worker     // that we've branched on it before. Look to see if the value is known
1680*9880d681SAndroid Build Coastguard Worker     // on all incoming edges.
1681*9880d681SAndroid Build Coastguard Worker     if (!isa<Instruction>(V) ||
1682*9880d681SAndroid Build Coastguard Worker         cast<Instruction>(V)->getParent() != BB) {
1683*9880d681SAndroid Build Coastguard Worker       // For predecessor edge, determine if the comparison is true or false
1684*9880d681SAndroid Build Coastguard Worker       // on that edge. If they're all true or all false, we can conclude
1685*9880d681SAndroid Build Coastguard Worker       // the value of the comparison in this block.
1686*9880d681SAndroid Build Coastguard Worker       Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1687*9880d681SAndroid Build Coastguard Worker       if (Baseline != Unknown) {
1688*9880d681SAndroid Build Coastguard Worker         // Check that all remaining incoming values match the first one.
1689*9880d681SAndroid Build Coastguard Worker         while (++PI != PE) {
1690*9880d681SAndroid Build Coastguard Worker           Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1691*9880d681SAndroid Build Coastguard Worker           if (Ret != Baseline) break;
1692*9880d681SAndroid Build Coastguard Worker         }
1693*9880d681SAndroid Build Coastguard Worker         // If we terminated early, then one of the values didn't match.
1694*9880d681SAndroid Build Coastguard Worker         if (PI == PE) {
1695*9880d681SAndroid Build Coastguard Worker           return Baseline;
1696*9880d681SAndroid Build Coastguard Worker         }
1697*9880d681SAndroid Build Coastguard Worker       }
1698*9880d681SAndroid Build Coastguard Worker     }
1699*9880d681SAndroid Build Coastguard Worker   }
1700*9880d681SAndroid Build Coastguard Worker   return Unknown;
1701*9880d681SAndroid Build Coastguard Worker }
1702*9880d681SAndroid Build Coastguard Worker 
threadEdge(BasicBlock * PredBB,BasicBlock * OldSucc,BasicBlock * NewSucc)1703*9880d681SAndroid Build Coastguard Worker void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1704*9880d681SAndroid Build Coastguard Worker                                BasicBlock *NewSucc) {
1705*9880d681SAndroid Build Coastguard Worker   if (PImpl) {
1706*9880d681SAndroid Build Coastguard Worker     const DataLayout &DL = PredBB->getModule()->getDataLayout();
1707*9880d681SAndroid Build Coastguard Worker     getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1708*9880d681SAndroid Build Coastguard Worker   }
1709*9880d681SAndroid Build Coastguard Worker }
1710*9880d681SAndroid Build Coastguard Worker 
eraseBlock(BasicBlock * BB)1711*9880d681SAndroid Build Coastguard Worker void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1712*9880d681SAndroid Build Coastguard Worker   if (PImpl) {
1713*9880d681SAndroid Build Coastguard Worker     const DataLayout &DL = BB->getModule()->getDataLayout();
1714*9880d681SAndroid Build Coastguard Worker     getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1715*9880d681SAndroid Build Coastguard Worker   }
1716*9880d681SAndroid Build Coastguard Worker }
1717