1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/MemoryBuiltins.h"
21 #include "llvm/Analysis/Loads.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/CallSite.h"
24 #include "llvm/IR/ConstantRange.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/GlobalAlias.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/IR/Statepoint.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/MathExtras.h"
40 #include <algorithm>
41 #include <array>
42 #include <cstring>
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
45 
46 const unsigned MaxDepth = 6;
47 
48 /// Enable an experimental feature to leverage information about dominating
49 /// conditions to compute known bits.  The individual options below control how
50 /// hard we search.  The defaults are chosen to be fairly aggressive.  If you
51 /// run into compile time problems when testing, scale them back and report
52 /// your findings.
53 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
54                                          cl::Hidden, cl::init(false));
55 
56 // This is expensive, so we only do it for the top level query value.
57 // (TODO: evaluate cost vs profit, consider higher thresholds)
58 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
59                                                cl::Hidden, cl::init(1));
60 
61 /// How many dominating blocks should be scanned looking for dominating
62 /// conditions?
63 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
64                                                    cl::Hidden,
65                                                    cl::init(20));
66 
67 // Controls the number of uses of the value searched for possible
68 // dominating comparisons.
69 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
70                                               cl::Hidden, cl::init(20));
71 
72 // If true, don't consider only compares whose only use is a branch.
73 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
74                                                cl::Hidden, cl::init(false));
75 
76 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
77 /// 0). For vector types, returns the element type's bitwidth.
78 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
79   if (unsigned BitWidth = Ty->getScalarSizeInBits())
80     return BitWidth;
81 
82   return DL.getPointerTypeSizeInBits(Ty);
83 }
84 
85 namespace {
86 // Simplifying using an assume can only be done in a particular control-flow
87 // context (the context instruction provides that context). If an assume and
88 // the context instruction are not in the same block then the DT helps in
89 // figuring out if we can use it.
90 struct Query {
91   const DataLayout &DL;
92   AssumptionCache *AC;
93   const Instruction *CxtI;
94   const DominatorTree *DT;
95 
96   /// Set of assumptions that should be excluded from further queries.
97   /// This is because of the potential for mutual recursion to cause
98   /// computeKnownBits to repeatedly visit the same assume intrinsic. The
99   /// classic case of this is assume(x = y), which will attempt to determine
100   /// bits in x from bits in y, which will attempt to determine bits in y from
101   /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
102   /// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
103   /// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so
104   /// on.
105   std::array<const Value*, MaxDepth> Excluded;
106   unsigned NumExcluded;
107 
108   Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
109         const DominatorTree *DT)
110       : DL(DL), AC(AC), CxtI(CxtI), DT(DT), NumExcluded(0) {}
111 
112   Query(const Query &Q, const Value *NewExcl)
113       : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), NumExcluded(Q.NumExcluded) {
114     Excluded = Q.Excluded;
115     Excluded[NumExcluded++] = NewExcl;
116     assert(NumExcluded <= Excluded.size());
117   }
118 
119   bool isExcluded(const Value *Value) const {
120     if (NumExcluded == 0)
121       return false;
122     auto End = Excluded.begin() + NumExcluded;
123     return std::find(Excluded.begin(), End, Value) != End;
124   }
125 };
126 } // end anonymous namespace
127 
128 // Given the provided Value and, potentially, a context instruction, return
129 // the preferred context instruction (if any).
130 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
131   // If we've been provided with a context instruction, then use that (provided
132   // it has been inserted).
133   if (CxtI && CxtI->getParent())
134     return CxtI;
135 
136   // If the value is really an already-inserted instruction, then use that.
137   CxtI = dyn_cast<Instruction>(V);
138   if (CxtI && CxtI->getParent())
139     return CxtI;
140 
141   return nullptr;
142 }
143 
144 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
145                              unsigned Depth, const Query &Q);
146 
147 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
148                             const DataLayout &DL, unsigned Depth,
149                             AssumptionCache *AC, const Instruction *CxtI,
150                             const DominatorTree *DT) {
151   ::computeKnownBits(V, KnownZero, KnownOne, Depth,
152                      Query(DL, AC, safeCxtI(V, CxtI), DT));
153 }
154 
155 bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
156                                AssumptionCache *AC, const Instruction *CxtI,
157                                const DominatorTree *DT) {
158   assert(LHS->getType() == RHS->getType() &&
159          "LHS and RHS should have the same type");
160   assert(LHS->getType()->isIntOrIntVectorTy() &&
161          "LHS and RHS should be integers");
162   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
163   APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
164   APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
165   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
166   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
167   return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
168 }
169 
170 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
171                            unsigned Depth, const Query &Q);
172 
173 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
174                           const DataLayout &DL, unsigned Depth,
175                           AssumptionCache *AC, const Instruction *CxtI,
176                           const DominatorTree *DT) {
177   ::ComputeSignBit(V, KnownZero, KnownOne, Depth,
178                    Query(DL, AC, safeCxtI(V, CxtI), DT));
179 }
180 
181 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
182                                    const Query &Q);
183 
184 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
185                                   unsigned Depth, AssumptionCache *AC,
186                                   const Instruction *CxtI,
187                                   const DominatorTree *DT) {
188   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
189                                   Query(DL, AC, safeCxtI(V, CxtI), DT));
190 }
191 
192 static bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q);
193 
194 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
195                           AssumptionCache *AC, const Instruction *CxtI,
196                           const DominatorTree *DT) {
197   return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
198 }
199 
200 bool llvm::isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth,
201                               AssumptionCache *AC, const Instruction *CxtI,
202                               const DominatorTree *DT) {
203   bool NonNegative, Negative;
204   ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
205   return NonNegative;
206 }
207 
208 static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q);
209 
210 bool llvm::isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
211                           AssumptionCache *AC, const Instruction *CxtI,
212                           const DominatorTree *DT) {
213   return ::isKnownNonEqual(V1, V2, Query(DL, AC,
214                                          safeCxtI(V1, safeCxtI(V2, CxtI)),
215                                          DT));
216 }
217 
218 static bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
219                               const Query &Q);
220 
221 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
222                              unsigned Depth, AssumptionCache *AC,
223                              const Instruction *CxtI, const DominatorTree *DT) {
224   return ::MaskedValueIsZero(V, Mask, Depth,
225                              Query(DL, AC, safeCxtI(V, CxtI), DT));
226 }
227 
228 static unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q);
229 
230 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
231                                   unsigned Depth, AssumptionCache *AC,
232                                   const Instruction *CxtI,
233                                   const DominatorTree *DT) {
234   return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
235 }
236 
237 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
238                                    APInt &KnownZero, APInt &KnownOne,
239                                    APInt &KnownZero2, APInt &KnownOne2,
240                                    unsigned Depth, const Query &Q) {
241   if (!Add) {
242     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
243       // We know that the top bits of C-X are clear if X contains less bits
244       // than C (i.e. no wrap-around can happen).  For example, 20-X is
245       // positive if we can prove that X is >= 0 and < 16.
246       if (!CLHS->getValue().isNegative()) {
247         unsigned BitWidth = KnownZero.getBitWidth();
248         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
249         // NLZ can't be BitWidth with no sign bit
250         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
251         computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
252 
253         // If all of the MaskV bits are known to be zero, then we know the
254         // output top bits are zero, because we now know that the output is
255         // from [0-C].
256         if ((KnownZero2 & MaskV) == MaskV) {
257           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
258           // Top bits known zero.
259           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
260         }
261       }
262     }
263   }
264 
265   unsigned BitWidth = KnownZero.getBitWidth();
266 
267   // If an initial sequence of bits in the result is not needed, the
268   // corresponding bits in the operands are not needed.
269   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
270   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, Depth + 1, Q);
271   computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
272 
273   // Carry in a 1 for a subtract, rather than a 0.
274   APInt CarryIn(BitWidth, 0);
275   if (!Add) {
276     // Sum = LHS + ~RHS + 1
277     std::swap(KnownZero2, KnownOne2);
278     CarryIn.setBit(0);
279   }
280 
281   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
282   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
283 
284   // Compute known bits of the carry.
285   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
286   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
287 
288   // Compute set of known bits (where all three relevant bits are known).
289   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
290   APInt RHSKnown = KnownZero2 | KnownOne2;
291   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
292   APInt Known = LHSKnown & RHSKnown & CarryKnown;
293 
294   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
295          "known bits of sum differ");
296 
297   // Compute known bits of the result.
298   KnownZero = ~PossibleSumOne & Known;
299   KnownOne = PossibleSumOne & Known;
300 
301   // Are we still trying to solve for the sign bit?
302   if (!Known.isNegative()) {
303     if (NSW) {
304       // Adding two non-negative numbers, or subtracting a negative number from
305       // a non-negative one, can't wrap into negative.
306       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
307         KnownZero |= APInt::getSignBit(BitWidth);
308       // Adding two negative numbers, or subtracting a non-negative number from
309       // a negative one, can't wrap into non-negative.
310       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
311         KnownOne |= APInt::getSignBit(BitWidth);
312     }
313   }
314 }
315 
316 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
317                                 APInt &KnownZero, APInt &KnownOne,
318                                 APInt &KnownZero2, APInt &KnownOne2,
319                                 unsigned Depth, const Query &Q) {
320   unsigned BitWidth = KnownZero.getBitWidth();
321   computeKnownBits(Op1, KnownZero, KnownOne, Depth + 1, Q);
322   computeKnownBits(Op0, KnownZero2, KnownOne2, Depth + 1, Q);
323 
324   bool isKnownNegative = false;
325   bool isKnownNonNegative = false;
326   // If the multiplication is known not to overflow, compute the sign bit.
327   if (NSW) {
328     if (Op0 == Op1) {
329       // The product of a number with itself is non-negative.
330       isKnownNonNegative = true;
331     } else {
332       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
333       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
334       bool isKnownNegativeOp1 = KnownOne.isNegative();
335       bool isKnownNegativeOp0 = KnownOne2.isNegative();
336       // The product of two numbers with the same sign is non-negative.
337       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
338         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
339       // The product of a negative number and a non-negative number is either
340       // negative or zero.
341       if (!isKnownNonNegative)
342         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
343                            isKnownNonZero(Op0, Depth, Q)) ||
344                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
345                            isKnownNonZero(Op1, Depth, Q));
346     }
347   }
348 
349   // If low bits are zero in either operand, output low known-0 bits.
350   // Also compute a conservative estimate for high known-0 bits.
351   // More trickiness is possible, but this is sufficient for the
352   // interesting case of alignment computation.
353   KnownOne.clearAllBits();
354   unsigned TrailZ = KnownZero.countTrailingOnes() +
355                     KnownZero2.countTrailingOnes();
356   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
357                              KnownZero2.countLeadingOnes(),
358                              BitWidth) - BitWidth;
359 
360   TrailZ = std::min(TrailZ, BitWidth);
361   LeadZ = std::min(LeadZ, BitWidth);
362   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
363               APInt::getHighBitsSet(BitWidth, LeadZ);
364 
365   // Only make use of no-wrap flags if we failed to compute the sign bit
366   // directly.  This matters if the multiplication always overflows, in
367   // which case we prefer to follow the result of the direct computation,
368   // though as the program is invoking undefined behaviour we can choose
369   // whatever we like here.
370   if (isKnownNonNegative && !KnownOne.isNegative())
371     KnownZero.setBit(BitWidth - 1);
372   else if (isKnownNegative && !KnownZero.isNegative())
373     KnownOne.setBit(BitWidth - 1);
374 }
375 
376 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
377                                              APInt &KnownZero,
378                                              APInt &KnownOne) {
379   unsigned BitWidth = KnownZero.getBitWidth();
380   unsigned NumRanges = Ranges.getNumOperands() / 2;
381   assert(NumRanges >= 1);
382 
383   KnownZero.setAllBits();
384   KnownOne.setAllBits();
385 
386   for (unsigned i = 0; i < NumRanges; ++i) {
387     ConstantInt *Lower =
388         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
389     ConstantInt *Upper =
390         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
391     ConstantRange Range(Lower->getValue(), Upper->getValue());
392 
393     // The first CommonPrefixBits of all values in Range are equal.
394     unsigned CommonPrefixBits =
395         (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
396 
397     APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
398     KnownOne &= Range.getUnsignedMax() & Mask;
399     KnownZero &= ~Range.getUnsignedMax() & Mask;
400   }
401 }
402 
403 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
404   SmallVector<const Value *, 16> WorkSet(1, I);
405   SmallPtrSet<const Value *, 32> Visited;
406   SmallPtrSet<const Value *, 16> EphValues;
407 
408   // The instruction defining an assumption's condition itself is always
409   // considered ephemeral to that assumption (even if it has other
410   // non-ephemeral users). See r246696's test case for an example.
411   if (std::find(I->op_begin(), I->op_end(), E) != I->op_end())
412     return true;
413 
414   while (!WorkSet.empty()) {
415     const Value *V = WorkSet.pop_back_val();
416     if (!Visited.insert(V).second)
417       continue;
418 
419     // If all uses of this value are ephemeral, then so is this value.
420     if (std::all_of(V->user_begin(), V->user_end(),
421                     [&](const User *U) { return EphValues.count(U); })) {
422       if (V == E)
423         return true;
424 
425       EphValues.insert(V);
426       if (const User *U = dyn_cast<User>(V))
427         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
428              J != JE; ++J) {
429           if (isSafeToSpeculativelyExecute(*J))
430             WorkSet.push_back(*J);
431         }
432     }
433   }
434 
435   return false;
436 }
437 
438 // Is this an intrinsic that cannot be speculated but also cannot trap?
439 static bool isAssumeLikeIntrinsic(const Instruction *I) {
440   if (const CallInst *CI = dyn_cast<CallInst>(I))
441     if (Function *F = CI->getCalledFunction())
442       switch (F->getIntrinsicID()) {
443       default: break;
444       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
445       case Intrinsic::assume:
446       case Intrinsic::dbg_declare:
447       case Intrinsic::dbg_value:
448       case Intrinsic::invariant_start:
449       case Intrinsic::invariant_end:
450       case Intrinsic::lifetime_start:
451       case Intrinsic::lifetime_end:
452       case Intrinsic::objectsize:
453       case Intrinsic::ptr_annotation:
454       case Intrinsic::var_annotation:
455         return true;
456       }
457 
458   return false;
459 }
460 
461 static bool isValidAssumeForContext(Value *V, const Instruction *CxtI,
462                                     const DominatorTree *DT) {
463   Instruction *Inv = cast<Instruction>(V);
464 
465   // There are two restrictions on the use of an assume:
466   //  1. The assume must dominate the context (or the control flow must
467   //     reach the assume whenever it reaches the context).
468   //  2. The context must not be in the assume's set of ephemeral values
469   //     (otherwise we will use the assume to prove that the condition
470   //     feeding the assume is trivially true, thus causing the removal of
471   //     the assume).
472 
473   if (DT) {
474     if (DT->dominates(Inv, CxtI)) {
475       return true;
476     } else if (Inv->getParent() == CxtI->getParent()) {
477       // The context comes first, but they're both in the same block. Make sure
478       // there is nothing in between that might interrupt the control flow.
479       for (BasicBlock::const_iterator I =
480              std::next(BasicBlock::const_iterator(CxtI)),
481                                       IE(Inv); I != IE; ++I)
482         if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
483           return false;
484 
485       return !isEphemeralValueOf(Inv, CxtI);
486     }
487 
488     return false;
489   }
490 
491   // When we don't have a DT, we do a limited search...
492   if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
493     return true;
494   } else if (Inv->getParent() == CxtI->getParent()) {
495     // Search forward from the assume until we reach the context (or the end
496     // of the block); the common case is that the assume will come first.
497     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
498          IE = Inv->getParent()->end(); I != IE; ++I)
499       if (&*I == CxtI)
500         return true;
501 
502     // The context must come first...
503     for (BasicBlock::const_iterator I =
504            std::next(BasicBlock::const_iterator(CxtI)),
505                                     IE(Inv); I != IE; ++I)
506       if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
507         return false;
508 
509     return !isEphemeralValueOf(Inv, CxtI);
510   }
511 
512   return false;
513 }
514 
515 bool llvm::isValidAssumeForContext(const Instruction *I,
516                                    const Instruction *CxtI,
517                                    const DominatorTree *DT) {
518   return ::isValidAssumeForContext(const_cast<Instruction *>(I), CxtI, DT);
519 }
520 
521 template<typename LHS, typename RHS>
522 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
523                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
524 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
525   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
526 }
527 
528 template<typename LHS, typename RHS>
529 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
530                         BinaryOp_match<RHS, LHS, Instruction::And>>
531 m_c_And(const LHS &L, const RHS &R) {
532   return m_CombineOr(m_And(L, R), m_And(R, L));
533 }
534 
535 template<typename LHS, typename RHS>
536 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
537                         BinaryOp_match<RHS, LHS, Instruction::Or>>
538 m_c_Or(const LHS &L, const RHS &R) {
539   return m_CombineOr(m_Or(L, R), m_Or(R, L));
540 }
541 
542 template<typename LHS, typename RHS>
543 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
544                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
545 m_c_Xor(const LHS &L, const RHS &R) {
546   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
547 }
548 
549 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
550 /// true (at the context instruction.)  This is mostly a utility function for
551 /// the prototype dominating conditions reasoning below.
552 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
553                                               APInt &KnownZero,
554                                               APInt &KnownOne,
555                                               unsigned Depth, const Query &Q) {
556   Value *LHS = Cmp->getOperand(0);
557   Value *RHS = Cmp->getOperand(1);
558   // TODO: We could potentially be more aggressive here.  This would be worth
559   // evaluating.  If we can, explore commoning this code with the assume
560   // handling logic.
561   if (LHS != V && RHS != V)
562     return;
563 
564   const unsigned BitWidth = KnownZero.getBitWidth();
565 
566   switch (Cmp->getPredicate()) {
567   default:
568     // We know nothing from this condition
569     break;
570   // TODO: implement unsigned bound from below (known one bits)
571   // TODO: common condition check implementations with assumes
572   // TODO: implement other patterns from assume (e.g. V & B == A)
573   case ICmpInst::ICMP_SGT:
574     if (LHS == V) {
575       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
576       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
577       if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
578         // We know that the sign bit is zero.
579         KnownZero |= APInt::getSignBit(BitWidth);
580       }
581     }
582     break;
583   case ICmpInst::ICMP_EQ:
584     {
585       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
586       if (LHS == V)
587         computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
588       else if (RHS == V)
589         computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
590       else
591         llvm_unreachable("missing use?");
592       KnownZero |= KnownZeroTemp;
593       KnownOne |= KnownOneTemp;
594     }
595     break;
596   case ICmpInst::ICMP_ULE:
597     if (LHS == V) {
598       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
599       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
600       // The known zero bits carry over
601       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
602       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
603     }
604     break;
605   case ICmpInst::ICMP_ULT:
606     if (LHS == V) {
607       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
608       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
609       // Whatever high bits in rhs are zero are known to be zero (if rhs is a
610       // power of 2, then one more).
611       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
612       if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp)))
613         SignBits++;
614       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
615     }
616     break;
617   };
618 }
619 
620 /// Compute known bits in 'V' from conditions which are known to be true along
621 /// all paths leading to the context instruction.  In particular, look for
622 /// cases where one branch of an interesting condition dominates the context
623 /// instruction.  This does not do general dataflow.
624 /// NOTE: This code is EXPERIMENTAL and currently off by default.
625 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
626                                                     APInt &KnownOne,
627                                                     unsigned Depth,
628                                                     const Query &Q) {
629   // Need both the dominator tree and the query location to do anything useful
630   if (!Q.DT || !Q.CxtI)
631     return;
632   Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
633   // The context instruction might be in a statically unreachable block.  If
634   // so, asking dominator queries may yield suprising results.  (e.g. the block
635   // may not have a dom tree node)
636   if (!Q.DT->isReachableFromEntry(Cxt->getParent()))
637     return;
638 
639   // Avoid useless work
640   if (auto VI = dyn_cast<Instruction>(V))
641     if (VI->getParent() == Cxt->getParent())
642       return;
643 
644   // Note: We currently implement two options.  It's not clear which of these
645   // will survive long term, we need data for that.
646   // Option 1 - Try walking the dominator tree looking for conditions which
647   // might apply.  This works well for local conditions (loop guards, etc..),
648   // but not as well for things far from the context instruction (presuming a
649   // low max blocks explored).  If we can set an high enough limit, this would
650   // be all we need.
651   // Option 2 - We restrict out search to those conditions which are uses of
652   // the value we're interested in.  This is independent of dom structure,
653   // but is slightly less powerful without looking through lots of use chains.
654   // It does handle conditions far from the context instruction (e.g. early
655   // function exits on entry) really well though.
656 
657   // Option 1 - Search the dom tree
658   unsigned NumBlocksExplored = 0;
659   BasicBlock *Current = Cxt->getParent();
660   while (true) {
661     // Stop searching if we've gone too far up the chain
662     if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
663       break;
664     NumBlocksExplored++;
665 
666     if (!Q.DT->getNode(Current)->getIDom())
667       break;
668     Current = Q.DT->getNode(Current)->getIDom()->getBlock();
669     if (!Current)
670       // found function entry
671       break;
672 
673     BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
674     if (!BI || BI->isUnconditional())
675       continue;
676     ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
677     if (!Cmp)
678       continue;
679 
680     // We're looking for conditions that are guaranteed to hold at the context
681     // instruction.  Finding a condition where one path dominates the context
682     // isn't enough because both the true and false cases could merge before
683     // the context instruction we're actually interested in.  Instead, we need
684     // to ensure that the taken *edge* dominates the context instruction.  We
685     // know that the edge must be reachable since we started from a reachable
686     // block.
687     BasicBlock *BB0 = BI->getSuccessor(0);
688     BasicBlockEdge Edge(BI->getParent(), BB0);
689     if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
690       continue;
691 
692     computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
693   }
694 
695   // Option 2 - Search the other uses of V
696   unsigned NumUsesExplored = 0;
697   for (auto U : V->users()) {
698     // Avoid massive lists
699     if (NumUsesExplored >= DomConditionsMaxUses)
700       break;
701     NumUsesExplored++;
702     // Consider only compare instructions uniquely controlling a branch
703     ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
704     if (!Cmp)
705       continue;
706 
707     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
708       continue;
709 
710     for (auto *CmpU : Cmp->users()) {
711       BranchInst *BI = dyn_cast<BranchInst>(CmpU);
712       if (!BI || BI->isUnconditional())
713         continue;
714       // We're looking for conditions that are guaranteed to hold at the
715       // context instruction.  Finding a condition where one path dominates
716       // the context isn't enough because both the true and false cases could
717       // merge before the context instruction we're actually interested in.
718       // Instead, we need to ensure that the taken *edge* dominates the context
719       // instruction.
720       BasicBlock *BB0 = BI->getSuccessor(0);
721       BasicBlockEdge Edge(BI->getParent(), BB0);
722       if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
723         continue;
724 
725       computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
726     }
727   }
728 }
729 
730 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
731                                        APInt &KnownOne, unsigned Depth,
732                                        const Query &Q) {
733   // Use of assumptions is context-sensitive. If we don't have a context, we
734   // cannot use them!
735   if (!Q.AC || !Q.CxtI)
736     return;
737 
738   unsigned BitWidth = KnownZero.getBitWidth();
739 
740   for (auto &AssumeVH : Q.AC->assumptions()) {
741     if (!AssumeVH)
742       continue;
743     CallInst *I = cast<CallInst>(AssumeVH);
744     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
745            "Got assumption for the wrong function!");
746     if (Q.isExcluded(I))
747       continue;
748 
749     // Warning: This loop can end up being somewhat performance sensetive.
750     // We're running this loop for once for each value queried resulting in a
751     // runtime of ~O(#assumes * #values).
752 
753     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
754            "must be an assume intrinsic");
755 
756     Value *Arg = I->getArgOperand(0);
757 
758     if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
759       assert(BitWidth == 1 && "assume operand is not i1?");
760       KnownZero.clearAllBits();
761       KnownOne.setAllBits();
762       return;
763     }
764 
765     // The remaining tests are all recursive, so bail out if we hit the limit.
766     if (Depth == MaxDepth)
767       continue;
768 
769     Value *A, *B;
770     auto m_V = m_CombineOr(m_Specific(V),
771                            m_CombineOr(m_PtrToInt(m_Specific(V)),
772                            m_BitCast(m_Specific(V))));
773 
774     CmpInst::Predicate Pred;
775     ConstantInt *C;
776     // assume(v = a)
777     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
778         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
779       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
780       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
781       KnownZero |= RHSKnownZero;
782       KnownOne  |= RHSKnownOne;
783     // assume(v & b = a)
784     } else if (match(Arg,
785                      m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
786                Pred == ICmpInst::ICMP_EQ &&
787                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
788       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
789       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
790       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
791       computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
792 
793       // For those bits in the mask that are known to be one, we can propagate
794       // known bits from the RHS to V.
795       KnownZero |= RHSKnownZero & MaskKnownOne;
796       KnownOne  |= RHSKnownOne  & MaskKnownOne;
797     // assume(~(v & b) = a)
798     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
799                                    m_Value(A))) &&
800                Pred == ICmpInst::ICMP_EQ &&
801                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
802       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
803       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
804       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
805       computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
806 
807       // For those bits in the mask that are known to be one, we can propagate
808       // inverted known bits from the RHS to V.
809       KnownZero |= RHSKnownOne  & MaskKnownOne;
810       KnownOne  |= RHSKnownZero & MaskKnownOne;
811     // assume(v | b = a)
812     } else if (match(Arg,
813                      m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
814                Pred == ICmpInst::ICMP_EQ &&
815                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
816       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
817       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
818       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
819       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
820 
821       // For those bits in B that are known to be zero, we can propagate known
822       // bits from the RHS to V.
823       KnownZero |= RHSKnownZero & BKnownZero;
824       KnownOne  |= RHSKnownOne  & BKnownZero;
825     // assume(~(v | b) = a)
826     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
827                                    m_Value(A))) &&
828                Pred == ICmpInst::ICMP_EQ &&
829                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
830       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
831       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
832       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
833       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
834 
835       // For those bits in B that are known to be zero, we can propagate
836       // inverted known bits from the RHS to V.
837       KnownZero |= RHSKnownOne  & BKnownZero;
838       KnownOne  |= RHSKnownZero & BKnownZero;
839     // assume(v ^ b = a)
840     } else if (match(Arg,
841                      m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
842                Pred == ICmpInst::ICMP_EQ &&
843                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
844       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
845       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
846       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
847       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
848 
849       // For those bits in B that are known to be zero, we can propagate known
850       // bits from the RHS to V. For those bits in B that are known to be one,
851       // we can propagate inverted known bits from the RHS to V.
852       KnownZero |= RHSKnownZero & BKnownZero;
853       KnownOne  |= RHSKnownOne  & BKnownZero;
854       KnownZero |= RHSKnownOne  & BKnownOne;
855       KnownOne  |= RHSKnownZero & BKnownOne;
856     // assume(~(v ^ b) = a)
857     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
858                                    m_Value(A))) &&
859                Pred == ICmpInst::ICMP_EQ &&
860                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
861       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
862       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
863       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
864       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
865 
866       // For those bits in B that are known to be zero, we can propagate
867       // inverted known bits from the RHS to V. For those bits in B that are
868       // known to be one, we can propagate known bits from the RHS to V.
869       KnownZero |= RHSKnownOne  & BKnownZero;
870       KnownOne  |= RHSKnownZero & BKnownZero;
871       KnownZero |= RHSKnownZero & BKnownOne;
872       KnownOne  |= RHSKnownOne  & BKnownOne;
873     // assume(v << c = a)
874     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
875                                    m_Value(A))) &&
876                Pred == ICmpInst::ICMP_EQ &&
877                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
878       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
879       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
880       // For those bits in RHS that are known, we can propagate them to known
881       // bits in V shifted to the right by C.
882       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
883       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
884     // assume(~(v << c) = a)
885     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
886                                    m_Value(A))) &&
887                Pred == ICmpInst::ICMP_EQ &&
888                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
889       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
890       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
891       // For those bits in RHS that are known, we can propagate them inverted
892       // to known bits in V shifted to the right by C.
893       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
894       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
895     // assume(v >> c = a)
896     } else if (match(Arg,
897                      m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
898                                                 m_AShr(m_V, m_ConstantInt(C))),
899                               m_Value(A))) &&
900                Pred == ICmpInst::ICMP_EQ &&
901                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
902       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
903       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
904       // For those bits in RHS that are known, we can propagate them to known
905       // bits in V shifted to the right by C.
906       KnownZero |= RHSKnownZero << C->getZExtValue();
907       KnownOne  |= RHSKnownOne  << C->getZExtValue();
908     // assume(~(v >> c) = a)
909     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
910                                              m_LShr(m_V, m_ConstantInt(C)),
911                                              m_AShr(m_V, m_ConstantInt(C)))),
912                                    m_Value(A))) &&
913                Pred == ICmpInst::ICMP_EQ &&
914                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
915       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
916       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
917       // For those bits in RHS that are known, we can propagate them inverted
918       // to known bits in V shifted to the right by C.
919       KnownZero |= RHSKnownOne  << C->getZExtValue();
920       KnownOne  |= RHSKnownZero << C->getZExtValue();
921     // assume(v >=_s c) where c is non-negative
922     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
923                Pred == ICmpInst::ICMP_SGE &&
924                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
925       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
926       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
927 
928       if (RHSKnownZero.isNegative()) {
929         // We know that the sign bit is zero.
930         KnownZero |= APInt::getSignBit(BitWidth);
931       }
932     // assume(v >_s c) where c is at least -1.
933     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
934                Pred == ICmpInst::ICMP_SGT &&
935                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
936       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
937       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
938 
939       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
940         // We know that the sign bit is zero.
941         KnownZero |= APInt::getSignBit(BitWidth);
942       }
943     // assume(v <=_s c) where c is negative
944     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
945                Pred == ICmpInst::ICMP_SLE &&
946                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
947       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
948       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
949 
950       if (RHSKnownOne.isNegative()) {
951         // We know that the sign bit is one.
952         KnownOne |= APInt::getSignBit(BitWidth);
953       }
954     // assume(v <_s c) where c is non-positive
955     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
956                Pred == ICmpInst::ICMP_SLT &&
957                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
958       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
959       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
960 
961       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
962         // We know that the sign bit is one.
963         KnownOne |= APInt::getSignBit(BitWidth);
964       }
965     // assume(v <=_u c)
966     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
967                Pred == ICmpInst::ICMP_ULE &&
968                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
969       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
970       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
971 
972       // Whatever high bits in c are zero are known to be zero.
973       KnownZero |=
974         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
975     // assume(v <_u c)
976     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
977                Pred == ICmpInst::ICMP_ULT &&
978                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
979       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
980       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
981 
982       // Whatever high bits in c are zero are known to be zero (if c is a power
983       // of 2, then one more).
984       if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
985         KnownZero |=
986           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
987       else
988         KnownZero |=
989           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
990     }
991   }
992 }
993 
994 // Compute known bits from a shift operator, including those with a
995 // non-constant shift amount. KnownZero and KnownOne are the outputs of this
996 // function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the
997 // same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific
998 // functors that, given the known-zero or known-one bits respectively, and a
999 // shift amount, compute the implied known-zero or known-one bits of the shift
1000 // operator's result respectively for that shift amount. The results from calling
1001 // KZF and KOF are conservatively combined for all permitted shift amounts.
1002 template <typename KZFunctor, typename KOFunctor>
1003 static void computeKnownBitsFromShiftOperator(Operator *I,
1004               APInt &KnownZero, APInt &KnownOne,
1005               APInt &KnownZero2, APInt &KnownOne2,
1006               unsigned Depth, const Query &Q, KZFunctor KZF, KOFunctor KOF) {
1007   unsigned BitWidth = KnownZero.getBitWidth();
1008 
1009   if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1010     unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
1011 
1012     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1013     KnownZero = KZF(KnownZero, ShiftAmt);
1014     KnownOne  = KOF(KnownOne, ShiftAmt);
1015     return;
1016   }
1017 
1018   computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1019 
1020   // Note: We cannot use KnownZero.getLimitedValue() here, because if
1021   // BitWidth > 64 and any upper bits are known, we'll end up returning the
1022   // limit value (which implies all bits are known).
1023   uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue();
1024   uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue();
1025 
1026   // It would be more-clearly correct to use the two temporaries for this
1027   // calculation. Reusing the APInts here to prevent unnecessary allocations.
1028   KnownZero.clearAllBits();
1029   KnownOne.clearAllBits();
1030 
1031   // If we know the shifter operand is nonzero, we can sometimes infer more
1032   // known bits. However this is expensive to compute, so be lazy about it and
1033   // only compute it when absolutely necessary.
1034   Optional<bool> ShifterOperandIsNonZero;
1035 
1036   // Early exit if we can't constrain any well-defined shift amount.
1037   if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
1038     ShifterOperandIsNonZero =
1039         isKnownNonZero(I->getOperand(1), Depth + 1, Q);
1040     if (!*ShifterOperandIsNonZero)
1041       return;
1042   }
1043 
1044   computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1045 
1046   KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
1047   for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
1048     // Combine the shifted known input bits only for those shift amounts
1049     // compatible with its known constraints.
1050     if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
1051       continue;
1052     if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
1053       continue;
1054     // If we know the shifter is nonzero, we may be able to infer more known
1055     // bits. This check is sunk down as far as possible to avoid the expensive
1056     // call to isKnownNonZero if the cheaper checks above fail.
1057     if (ShiftAmt == 0) {
1058       if (!ShifterOperandIsNonZero.hasValue())
1059         ShifterOperandIsNonZero =
1060             isKnownNonZero(I->getOperand(1), Depth + 1, Q);
1061       if (*ShifterOperandIsNonZero)
1062         continue;
1063     }
1064 
1065     KnownZero &= KZF(KnownZero2, ShiftAmt);
1066     KnownOne  &= KOF(KnownOne2, ShiftAmt);
1067   }
1068 
1069   // If there are no compatible shift amounts, then we've proven that the shift
1070   // amount must be >= the BitWidth, and the result is undefined. We could
1071   // return anything we'd like, but we need to make sure the sets of known bits
1072   // stay disjoint (it should be better for some other code to actually
1073   // propagate the undef than to pick a value here using known bits).
1074   if ((KnownZero & KnownOne) != 0) {
1075     KnownZero.clearAllBits();
1076     KnownOne.clearAllBits();
1077   }
1078 }
1079 
1080 static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
1081                                          APInt &KnownOne, unsigned Depth,
1082                                          const Query &Q) {
1083   unsigned BitWidth = KnownZero.getBitWidth();
1084 
1085   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
1086   switch (I->getOpcode()) {
1087   default: break;
1088   case Instruction::Load:
1089     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
1090       computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
1091     break;
1092   case Instruction::And: {
1093     // If either the LHS or the RHS are Zero, the result is zero.
1094     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1095     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1096 
1097     // Output known-1 bits are only known if set in both the LHS & RHS.
1098     KnownOne &= KnownOne2;
1099     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1100     KnownZero |= KnownZero2;
1101 
1102     // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1103     // here we handle the more general case of adding any odd number by
1104     // matching the form add(x, add(x, y)) where y is odd.
1105     // TODO: This could be generalized to clearing any bit set in y where the
1106     // following bit is known to be unset in y.
1107     Value *Y = nullptr;
1108     if (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
1109                                       m_Value(Y))) ||
1110         match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
1111                                       m_Value(Y)))) {
1112       APInt KnownZero3(BitWidth, 0), KnownOne3(BitWidth, 0);
1113       computeKnownBits(Y, KnownZero3, KnownOne3, Depth + 1, Q);
1114       if (KnownOne3.countTrailingOnes() > 0)
1115         KnownZero |= APInt::getLowBitsSet(BitWidth, 1);
1116     }
1117     break;
1118   }
1119   case Instruction::Or: {
1120     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1121     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1122 
1123     // Output known-0 bits are only known if clear in both the LHS & RHS.
1124     KnownZero &= KnownZero2;
1125     // Output known-1 are known to be set if set in either the LHS | RHS.
1126     KnownOne |= KnownOne2;
1127     break;
1128   }
1129   case Instruction::Xor: {
1130     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
1131     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1132 
1133     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1134     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1135     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1136     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1137     KnownZero = KnownZeroOut;
1138     break;
1139   }
1140   case Instruction::Mul: {
1141     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1142     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1143                         KnownOne, KnownZero2, KnownOne2, Depth, Q);
1144     break;
1145   }
1146   case Instruction::UDiv: {
1147     // For the purposes of computing leading zeros we can conservatively
1148     // treat a udiv as a logical right shift by the power of 2 known to
1149     // be less than the denominator.
1150     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1151     unsigned LeadZ = KnownZero2.countLeadingOnes();
1152 
1153     KnownOne2.clearAllBits();
1154     KnownZero2.clearAllBits();
1155     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
1156     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1157     if (RHSUnknownLeadingOnes != BitWidth)
1158       LeadZ = std::min(BitWidth,
1159                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1160 
1161     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1162     break;
1163   }
1164   case Instruction::Select:
1165     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q);
1166     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
1167 
1168     // Only known if known in both the LHS and RHS.
1169     KnownOne &= KnownOne2;
1170     KnownZero &= KnownZero2;
1171     break;
1172   case Instruction::FPTrunc:
1173   case Instruction::FPExt:
1174   case Instruction::FPToUI:
1175   case Instruction::FPToSI:
1176   case Instruction::SIToFP:
1177   case Instruction::UIToFP:
1178     break; // Can't work with floating point.
1179   case Instruction::PtrToInt:
1180   case Instruction::IntToPtr:
1181   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
1182     // FALL THROUGH and handle them the same as zext/trunc.
1183   case Instruction::ZExt:
1184   case Instruction::Trunc: {
1185     Type *SrcTy = I->getOperand(0)->getType();
1186 
1187     unsigned SrcBitWidth;
1188     // Note that we handle pointer operands here because of inttoptr/ptrtoint
1189     // which fall through here.
1190     SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
1191 
1192     assert(SrcBitWidth && "SrcBitWidth can't be zero");
1193     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1194     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1195     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1196     KnownZero = KnownZero.zextOrTrunc(BitWidth);
1197     KnownOne = KnownOne.zextOrTrunc(BitWidth);
1198     // Any top bits are known to be zero.
1199     if (BitWidth > SrcBitWidth)
1200       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1201     break;
1202   }
1203   case Instruction::BitCast: {
1204     Type *SrcTy = I->getOperand(0)->getType();
1205     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy() ||
1206          SrcTy->isFloatingPointTy()) &&
1207         // TODO: For now, not handling conversions like:
1208         // (bitcast i64 %x to <2 x i32>)
1209         !I->getType()->isVectorTy()) {
1210       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1211       break;
1212     }
1213     break;
1214   }
1215   case Instruction::SExt: {
1216     // Compute the bits in the result that are not present in the input.
1217     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1218 
1219     KnownZero = KnownZero.trunc(SrcBitWidth);
1220     KnownOne = KnownOne.trunc(SrcBitWidth);
1221     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1222     KnownZero = KnownZero.zext(BitWidth);
1223     KnownOne = KnownOne.zext(BitWidth);
1224 
1225     // If the sign bit of the input is known set or clear, then we know the
1226     // top bits of the result.
1227     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
1228       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1229     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
1230       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1231     break;
1232   }
1233   case Instruction::Shl: {
1234     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1235     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1236       return (KnownZero << ShiftAmt) |
1237              APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0.
1238     };
1239 
1240     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1241       return KnownOne << ShiftAmt;
1242     };
1243 
1244     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1245                                       KnownZero2, KnownOne2, Depth, Q, KZF,
1246                                       KOF);
1247     break;
1248   }
1249   case Instruction::LShr: {
1250     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1251     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1252       return APIntOps::lshr(KnownZero, ShiftAmt) |
1253              // High bits known zero.
1254              APInt::getHighBitsSet(BitWidth, ShiftAmt);
1255     };
1256 
1257     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1258       return APIntOps::lshr(KnownOne, ShiftAmt);
1259     };
1260 
1261     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1262                                       KnownZero2, KnownOne2, Depth, Q, KZF,
1263                                       KOF);
1264     break;
1265   }
1266   case Instruction::AShr: {
1267     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1268     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1269       return APIntOps::ashr(KnownZero, ShiftAmt);
1270     };
1271 
1272     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1273       return APIntOps::ashr(KnownOne, ShiftAmt);
1274     };
1275 
1276     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1277                                       KnownZero2, KnownOne2, Depth, Q, KZF,
1278                                       KOF);
1279     break;
1280   }
1281   case Instruction::Sub: {
1282     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1283     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1284                            KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1285                            Q);
1286     break;
1287   }
1288   case Instruction::Add: {
1289     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1290     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1291                            KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1292                            Q);
1293     break;
1294   }
1295   case Instruction::SRem:
1296     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1297       APInt RA = Rem->getValue().abs();
1298       if (RA.isPowerOf2()) {
1299         APInt LowBits = RA - 1;
1300         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1,
1301                          Q);
1302 
1303         // The low bits of the first operand are unchanged by the srem.
1304         KnownZero = KnownZero2 & LowBits;
1305         KnownOne = KnownOne2 & LowBits;
1306 
1307         // If the first operand is non-negative or has all low bits zero, then
1308         // the upper bits are all zero.
1309         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1310           KnownZero |= ~LowBits;
1311 
1312         // If the first operand is negative and not all low bits are zero, then
1313         // the upper bits are all one.
1314         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1315           KnownOne |= ~LowBits;
1316 
1317         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1318       }
1319     }
1320 
1321     // The sign bit is the LHS's sign bit, except when the result of the
1322     // remainder is zero.
1323     if (KnownZero.isNonNegative()) {
1324       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1325       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
1326                        Q);
1327       // If it's known zero, our sign bit is also zero.
1328       if (LHSKnownZero.isNegative())
1329         KnownZero.setBit(BitWidth - 1);
1330     }
1331 
1332     break;
1333   case Instruction::URem: {
1334     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1335       APInt RA = Rem->getValue();
1336       if (RA.isPowerOf2()) {
1337         APInt LowBits = (RA - 1);
1338         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1339         KnownZero |= ~LowBits;
1340         KnownOne &= LowBits;
1341         break;
1342       }
1343     }
1344 
1345     // Since the result is less than or equal to either operand, any leading
1346     // zero bits in either operand must also exist in the result.
1347     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1348     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
1349 
1350     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1351                                 KnownZero2.countLeadingOnes());
1352     KnownOne.clearAllBits();
1353     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1354     break;
1355   }
1356 
1357   case Instruction::Alloca: {
1358     AllocaInst *AI = cast<AllocaInst>(I);
1359     unsigned Align = AI->getAlignment();
1360     if (Align == 0)
1361       Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
1362 
1363     if (Align > 0)
1364       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1365     break;
1366   }
1367   case Instruction::GetElementPtr: {
1368     // Analyze all of the subscripts of this getelementptr instruction
1369     // to determine if we can prove known low zero bits.
1370     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1371     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, Depth + 1,
1372                      Q);
1373     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1374 
1375     gep_type_iterator GTI = gep_type_begin(I);
1376     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1377       Value *Index = I->getOperand(i);
1378       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1379         // Handle struct member offset arithmetic.
1380 
1381         // Handle case when index is vector zeroinitializer
1382         Constant *CIndex = cast<Constant>(Index);
1383         if (CIndex->isZeroValue())
1384           continue;
1385 
1386         if (CIndex->getType()->isVectorTy())
1387           Index = CIndex->getSplatValue();
1388 
1389         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1390         const StructLayout *SL = Q.DL.getStructLayout(STy);
1391         uint64_t Offset = SL->getElementOffset(Idx);
1392         TrailZ = std::min<unsigned>(TrailZ,
1393                                     countTrailingZeros(Offset));
1394       } else {
1395         // Handle array index arithmetic.
1396         Type *IndexedTy = GTI.getIndexedType();
1397         if (!IndexedTy->isSized()) {
1398           TrailZ = 0;
1399           break;
1400         }
1401         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1402         uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1403         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1404         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, Depth + 1, Q);
1405         TrailZ = std::min(TrailZ,
1406                           unsigned(countTrailingZeros(TypeSize) +
1407                                    LocalKnownZero.countTrailingOnes()));
1408       }
1409     }
1410 
1411     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1412     break;
1413   }
1414   case Instruction::PHI: {
1415     PHINode *P = cast<PHINode>(I);
1416     // Handle the case of a simple two-predecessor recurrence PHI.
1417     // There's a lot more that could theoretically be done here, but
1418     // this is sufficient to catch some interesting cases.
1419     if (P->getNumIncomingValues() == 2) {
1420       for (unsigned i = 0; i != 2; ++i) {
1421         Value *L = P->getIncomingValue(i);
1422         Value *R = P->getIncomingValue(!i);
1423         Operator *LU = dyn_cast<Operator>(L);
1424         if (!LU)
1425           continue;
1426         unsigned Opcode = LU->getOpcode();
1427         // Check for operations that have the property that if
1428         // both their operands have low zero bits, the result
1429         // will have low zero bits.
1430         if (Opcode == Instruction::Add ||
1431             Opcode == Instruction::Sub ||
1432             Opcode == Instruction::And ||
1433             Opcode == Instruction::Or ||
1434             Opcode == Instruction::Mul) {
1435           Value *LL = LU->getOperand(0);
1436           Value *LR = LU->getOperand(1);
1437           // Find a recurrence.
1438           if (LL == I)
1439             L = LR;
1440           else if (LR == I)
1441             L = LL;
1442           else
1443             break;
1444           // Ok, we have a PHI of the form L op= R. Check for low
1445           // zero bits.
1446           computeKnownBits(R, KnownZero2, KnownOne2, Depth + 1, Q);
1447 
1448           // We need to take the minimum number of known bits
1449           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1450           computeKnownBits(L, KnownZero3, KnownOne3, Depth + 1, Q);
1451 
1452           KnownZero = APInt::getLowBitsSet(BitWidth,
1453                                            std::min(KnownZero2.countTrailingOnes(),
1454                                                     KnownZero3.countTrailingOnes()));
1455           break;
1456         }
1457       }
1458     }
1459 
1460     // Unreachable blocks may have zero-operand PHI nodes.
1461     if (P->getNumIncomingValues() == 0)
1462       break;
1463 
1464     // Otherwise take the unions of the known bit sets of the operands,
1465     // taking conservative care to avoid excessive recursion.
1466     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1467       // Skip if every incoming value references to ourself.
1468       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1469         break;
1470 
1471       KnownZero = APInt::getAllOnesValue(BitWidth);
1472       KnownOne = APInt::getAllOnesValue(BitWidth);
1473       for (Value *IncValue : P->incoming_values()) {
1474         // Skip direct self references.
1475         if (IncValue == P) continue;
1476 
1477         KnownZero2 = APInt(BitWidth, 0);
1478         KnownOne2 = APInt(BitWidth, 0);
1479         // Recurse, but cap the recursion to one level, because we don't
1480         // want to waste time spinning around in loops.
1481         computeKnownBits(IncValue, KnownZero2, KnownOne2, MaxDepth - 1, Q);
1482         KnownZero &= KnownZero2;
1483         KnownOne &= KnownOne2;
1484         // If all bits have been ruled out, there's no need to check
1485         // more operands.
1486         if (!KnownZero && !KnownOne)
1487           break;
1488       }
1489     }
1490     break;
1491   }
1492   case Instruction::Call:
1493   case Instruction::Invoke:
1494     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1495       computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
1496     // If a range metadata is attached to this IntrinsicInst, intersect the
1497     // explicit range specified by the metadata and the implicit range of
1498     // the intrinsic.
1499     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1500       switch (II->getIntrinsicID()) {
1501       default: break;
1502       case Intrinsic::bswap:
1503         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1504         KnownZero |= KnownZero2.byteSwap();
1505         KnownOne |= KnownOne2.byteSwap();
1506         break;
1507       case Intrinsic::ctlz:
1508       case Intrinsic::cttz: {
1509         unsigned LowBits = Log2_32(BitWidth)+1;
1510         // If this call is undefined for 0, the result will be less than 2^n.
1511         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1512           LowBits -= 1;
1513         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1514         break;
1515       }
1516       case Intrinsic::ctpop: {
1517         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1518         // We can bound the space the count needs.  Also, bits known to be zero
1519         // can't contribute to the population.
1520         unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation();
1521         unsigned LeadingZeros =
1522           APInt(BitWidth, BitsPossiblySet).countLeadingZeros();
1523         assert(LeadingZeros <= BitWidth);
1524         KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros);
1525         KnownOne &= ~KnownZero;
1526         // TODO: we could bound KnownOne using the lower bound on the number
1527         // of bits which might be set provided by popcnt KnownOne2.
1528         break;
1529       }
1530       case Intrinsic::fabs: {
1531         Type *Ty = II->getType();
1532         APInt SignBit = APInt::getSignBit(Ty->getScalarSizeInBits());
1533         KnownZero |= APInt::getSplat(Ty->getPrimitiveSizeInBits(), SignBit);
1534         break;
1535       }
1536       case Intrinsic::x86_sse42_crc32_64_64:
1537         KnownZero |= APInt::getHighBitsSet(64, 32);
1538         break;
1539       }
1540     }
1541     break;
1542   case Instruction::ExtractValue:
1543     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1544       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1545       if (EVI->getNumIndices() != 1) break;
1546       if (EVI->getIndices()[0] == 0) {
1547         switch (II->getIntrinsicID()) {
1548         default: break;
1549         case Intrinsic::uadd_with_overflow:
1550         case Intrinsic::sadd_with_overflow:
1551           computeKnownBitsAddSub(true, II->getArgOperand(0),
1552                                  II->getArgOperand(1), false, KnownZero,
1553                                  KnownOne, KnownZero2, KnownOne2, Depth, Q);
1554           break;
1555         case Intrinsic::usub_with_overflow:
1556         case Intrinsic::ssub_with_overflow:
1557           computeKnownBitsAddSub(false, II->getArgOperand(0),
1558                                  II->getArgOperand(1), false, KnownZero,
1559                                  KnownOne, KnownZero2, KnownOne2, Depth, Q);
1560           break;
1561         case Intrinsic::umul_with_overflow:
1562         case Intrinsic::smul_with_overflow:
1563           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1564                               KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1565                               Q);
1566           break;
1567         }
1568       }
1569     }
1570   }
1571 }
1572 
1573 /// Determine which bits of V are known to be either zero or one and return
1574 /// them in the KnownZero/KnownOne bit sets.
1575 ///
1576 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
1577 /// we cannot optimize based on the assumption that it is zero without changing
1578 /// it to be an explicit zero.  If we don't change it to zero, other code could
1579 /// optimized based on the contradictory assumption that it is non-zero.
1580 /// Because instcombine aggressively folds operations with undef args anyway,
1581 /// this won't lose us code quality.
1582 ///
1583 /// This function is defined on values with integer type, values with pointer
1584 /// type, and vectors of integers.  In the case
1585 /// where V is a vector, known zero, and known one values are the
1586 /// same width as the vector element, and the bit is set only if it is true
1587 /// for all of the elements in the vector.
1588 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
1589                       unsigned Depth, const Query &Q) {
1590   assert(V && "No Value?");
1591   assert(Depth <= MaxDepth && "Limit Search Depth");
1592   unsigned BitWidth = KnownZero.getBitWidth();
1593 
1594   assert((V->getType()->isIntOrIntVectorTy() ||
1595           V->getType()->isFPOrFPVectorTy() ||
1596           V->getType()->getScalarType()->isPointerTy()) &&
1597          "Not integer, floating point, or pointer type!");
1598   assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
1599          (!V->getType()->isIntOrIntVectorTy() ||
1600           V->getType()->getScalarSizeInBits() == BitWidth) &&
1601          KnownZero.getBitWidth() == BitWidth &&
1602          KnownOne.getBitWidth() == BitWidth &&
1603          "V, KnownOne and KnownZero should have same BitWidth");
1604 
1605   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1606     // We know all of the bits for a constant!
1607     KnownOne = CI->getValue();
1608     KnownZero = ~KnownOne;
1609     return;
1610   }
1611   // Null and aggregate-zero are all-zeros.
1612   if (isa<ConstantPointerNull>(V) ||
1613       isa<ConstantAggregateZero>(V)) {
1614     KnownOne.clearAllBits();
1615     KnownZero = APInt::getAllOnesValue(BitWidth);
1616     return;
1617   }
1618   // Handle a constant vector by taking the intersection of the known bits of
1619   // each element.  There is no real need to handle ConstantVector here, because
1620   // we don't handle undef in any particularly useful way.
1621   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1622     // We know that CDS must be a vector of integers. Take the intersection of
1623     // each element.
1624     KnownZero.setAllBits(); KnownOne.setAllBits();
1625     APInt Elt(KnownZero.getBitWidth(), 0);
1626     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1627       Elt = CDS->getElementAsInteger(i);
1628       KnownZero &= ~Elt;
1629       KnownOne &= Elt;
1630     }
1631     return;
1632   }
1633 
1634   // Start out not knowing anything.
1635   KnownZero.clearAllBits(); KnownOne.clearAllBits();
1636 
1637   // Limit search depth.
1638   // All recursive calls that increase depth must come after this.
1639   if (Depth == MaxDepth)
1640     return;
1641 
1642   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1643   // the bits of its aliasee.
1644   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1645     if (!GA->mayBeOverridden())
1646       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, Depth + 1, Q);
1647     return;
1648   }
1649 
1650   if (Operator *I = dyn_cast<Operator>(V))
1651     computeKnownBitsFromOperator(I, KnownZero, KnownOne, Depth, Q);
1652 
1653   // Aligned pointers have trailing zeros - refine KnownZero set
1654   if (V->getType()->isPointerTy()) {
1655     unsigned Align = V->getPointerAlignment(Q.DL);
1656     if (Align)
1657       KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1658   }
1659 
1660   // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
1661   // strictly refines KnownZero and KnownOne. Therefore, we run them after
1662   // computeKnownBitsFromOperator.
1663 
1664   // Check whether a nearby assume intrinsic can determine some known bits.
1665   computeKnownBitsFromAssume(V, KnownZero, KnownOne, Depth, Q);
1666 
1667   // Check whether there's a dominating condition which implies something about
1668   // this value at the given context.
1669   if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1670     computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, Depth, Q);
1671 
1672   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1673 }
1674 
1675 /// Determine whether the sign bit is known to be zero or one.
1676 /// Convenience wrapper around computeKnownBits.
1677 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1678                     unsigned Depth, const Query &Q) {
1679   unsigned BitWidth = getBitWidth(V->getType(), Q.DL);
1680   if (!BitWidth) {
1681     KnownZero = false;
1682     KnownOne = false;
1683     return;
1684   }
1685   APInt ZeroBits(BitWidth, 0);
1686   APInt OneBits(BitWidth, 0);
1687   computeKnownBits(V, ZeroBits, OneBits, Depth, Q);
1688   KnownOne = OneBits[BitWidth - 1];
1689   KnownZero = ZeroBits[BitWidth - 1];
1690 }
1691 
1692 /// Return true if the given value is known to have exactly one
1693 /// bit set when defined. For vectors return true if every element is known to
1694 /// be a power of two when defined. Supports values with integer or pointer
1695 /// types and vectors of integers.
1696 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1697                             const Query &Q) {
1698   if (Constant *C = dyn_cast<Constant>(V)) {
1699     if (C->isNullValue())
1700       return OrZero;
1701     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1702       return CI->getValue().isPowerOf2();
1703     // TODO: Handle vector constants.
1704   }
1705 
1706   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1707   // it is shifted off the end then the result is undefined.
1708   if (match(V, m_Shl(m_One(), m_Value())))
1709     return true;
1710 
1711   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1712   // bottom.  If it is shifted off the bottom then the result is undefined.
1713   if (match(V, m_LShr(m_SignBit(), m_Value())))
1714     return true;
1715 
1716   // The remaining tests are all recursive, so bail out if we hit the limit.
1717   if (Depth++ == MaxDepth)
1718     return false;
1719 
1720   Value *X = nullptr, *Y = nullptr;
1721   // A shift left or a logical shift right of a power of two is a power of two
1722   // or zero.
1723   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1724                  match(V, m_LShr(m_Value(X), m_Value()))))
1725     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
1726 
1727   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1728     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1729 
1730   if (SelectInst *SI = dyn_cast<SelectInst>(V))
1731     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1732            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1733 
1734   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1735     // A power of two and'd with anything is a power of two or zero.
1736     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1737         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
1738       return true;
1739     // X & (-X) is always a power of two or zero.
1740     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1741       return true;
1742     return false;
1743   }
1744 
1745   // Adding a power-of-two or zero to the same power-of-two or zero yields
1746   // either the original power-of-two, a larger power-of-two or zero.
1747   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1748     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1749     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1750       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1751           match(X, m_And(m_Value(), m_Specific(Y))))
1752         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1753           return true;
1754       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1755           match(Y, m_And(m_Value(), m_Specific(X))))
1756         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1757           return true;
1758 
1759       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1760       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1761       computeKnownBits(X, LHSZeroBits, LHSOneBits, Depth, Q);
1762 
1763       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1764       computeKnownBits(Y, RHSZeroBits, RHSOneBits, Depth, Q);
1765       // If i8 V is a power of two or zero:
1766       //  ZeroBits: 1 1 1 0 1 1 1 1
1767       // ~ZeroBits: 0 0 0 1 0 0 0 0
1768       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1769         // If OrZero isn't set, we cannot give back a zero result.
1770         // Make sure either the LHS or RHS has a bit set.
1771         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1772           return true;
1773     }
1774   }
1775 
1776   // An exact divide or right shift can only shift off zero bits, so the result
1777   // is a power of two only if the first operand is a power of two and not
1778   // copying a sign bit (sdiv int_min, 2).
1779   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1780       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1781     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1782                                   Depth, Q);
1783   }
1784 
1785   return false;
1786 }
1787 
1788 /// \brief Test whether a GEP's result is known to be non-null.
1789 ///
1790 /// Uses properties inherent in a GEP to try to determine whether it is known
1791 /// to be non-null.
1792 ///
1793 /// Currently this routine does not support vector GEPs.
1794 static bool isGEPKnownNonNull(GEPOperator *GEP, unsigned Depth,
1795                               const Query &Q) {
1796   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1797     return false;
1798 
1799   // FIXME: Support vector-GEPs.
1800   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1801 
1802   // If the base pointer is non-null, we cannot walk to a null address with an
1803   // inbounds GEP in address space zero.
1804   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
1805     return true;
1806 
1807   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1808   // If so, then the GEP cannot produce a null pointer, as doing so would
1809   // inherently violate the inbounds contract within address space zero.
1810   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1811        GTI != GTE; ++GTI) {
1812     // Struct types are easy -- they must always be indexed by a constant.
1813     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1814       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1815       unsigned ElementIdx = OpC->getZExtValue();
1816       const StructLayout *SL = Q.DL.getStructLayout(STy);
1817       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1818       if (ElementOffset > 0)
1819         return true;
1820       continue;
1821     }
1822 
1823     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1824     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1825       continue;
1826 
1827     // Fast path the constant operand case both for efficiency and so we don't
1828     // increment Depth when just zipping down an all-constant GEP.
1829     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1830       if (!OpC->isZero())
1831         return true;
1832       continue;
1833     }
1834 
1835     // We post-increment Depth here because while isKnownNonZero increments it
1836     // as well, when we pop back up that increment won't persist. We don't want
1837     // to recurse 10k times just because we have 10k GEP operands. We don't
1838     // bail completely out because we want to handle constant GEPs regardless
1839     // of depth.
1840     if (Depth++ >= MaxDepth)
1841       continue;
1842 
1843     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
1844       return true;
1845   }
1846 
1847   return false;
1848 }
1849 
1850 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1851 /// ensure that the value it's attached to is never Value?  'RangeType' is
1852 /// is the type of the value described by the range.
1853 static bool rangeMetadataExcludesValue(MDNode* Ranges,
1854                                        const APInt& Value) {
1855   const unsigned NumRanges = Ranges->getNumOperands() / 2;
1856   assert(NumRanges >= 1);
1857   for (unsigned i = 0; i < NumRanges; ++i) {
1858     ConstantInt *Lower =
1859         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1860     ConstantInt *Upper =
1861         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1862     ConstantRange Range(Lower->getValue(), Upper->getValue());
1863     if (Range.contains(Value))
1864       return false;
1865   }
1866   return true;
1867 }
1868 
1869 /// Return true if the given value is known to be non-zero when defined.
1870 /// For vectors return true if every element is known to be non-zero when
1871 /// defined. Supports values with integer or pointer type and vectors of
1872 /// integers.
1873 bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q) {
1874   if (Constant *C = dyn_cast<Constant>(V)) {
1875     if (C->isNullValue())
1876       return false;
1877     if (isa<ConstantInt>(C))
1878       // Must be non-zero due to null test above.
1879       return true;
1880     // TODO: Handle vectors
1881     return false;
1882   }
1883 
1884   if (Instruction* I = dyn_cast<Instruction>(V)) {
1885     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1886       // If the possible ranges don't contain zero, then the value is
1887       // definitely non-zero.
1888       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1889         const APInt ZeroValue(Ty->getBitWidth(), 0);
1890         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1891           return true;
1892       }
1893     }
1894   }
1895 
1896   // The remaining tests are all recursive, so bail out if we hit the limit.
1897   if (Depth++ >= MaxDepth)
1898     return false;
1899 
1900   // Check for pointer simplifications.
1901   if (V->getType()->isPointerTy()) {
1902     if (isKnownNonNull(V))
1903       return true;
1904     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1905       if (isGEPKnownNonNull(GEP, Depth, Q))
1906         return true;
1907   }
1908 
1909   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
1910 
1911   // X | Y != 0 if X != 0 or Y != 0.
1912   Value *X = nullptr, *Y = nullptr;
1913   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1914     return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
1915 
1916   // ext X != 0 if X != 0.
1917   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1918     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
1919 
1920   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1921   // if the lowest bit is shifted off the end.
1922   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1923     // shl nuw can't remove any non-zero bits.
1924     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1925     if (BO->hasNoUnsignedWrap())
1926       return isKnownNonZero(X, Depth, Q);
1927 
1928     APInt KnownZero(BitWidth, 0);
1929     APInt KnownOne(BitWidth, 0);
1930     computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1931     if (KnownOne[0])
1932       return true;
1933   }
1934   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1935   // defined if the sign bit is shifted off the end.
1936   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1937     // shr exact can only shift out zero bits.
1938     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1939     if (BO->isExact())
1940       return isKnownNonZero(X, Depth, Q);
1941 
1942     bool XKnownNonNegative, XKnownNegative;
1943     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1944     if (XKnownNegative)
1945       return true;
1946 
1947     // If the shifter operand is a constant, and all of the bits shifted
1948     // out are known to be zero, and X is known non-zero then at least one
1949     // non-zero bit must remain.
1950     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
1951       APInt KnownZero(BitWidth, 0);
1952       APInt KnownOne(BitWidth, 0);
1953       computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1954 
1955       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1956       // Is there a known one in the portion not shifted out?
1957       if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal)
1958         return true;
1959       // Are all the bits to be shifted out known zero?
1960       if (KnownZero.countTrailingOnes() >= ShiftVal)
1961         return isKnownNonZero(X, Depth, Q);
1962     }
1963   }
1964   // div exact can only produce a zero if the dividend is zero.
1965   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1966     return isKnownNonZero(X, Depth, Q);
1967   }
1968   // X + Y.
1969   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1970     bool XKnownNonNegative, XKnownNegative;
1971     bool YKnownNonNegative, YKnownNegative;
1972     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1973     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q);
1974 
1975     // If X and Y are both non-negative (as signed values) then their sum is not
1976     // zero unless both X and Y are zero.
1977     if (XKnownNonNegative && YKnownNonNegative)
1978       if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
1979         return true;
1980 
1981     // If X and Y are both negative (as signed values) then their sum is not
1982     // zero unless both X and Y equal INT_MIN.
1983     if (BitWidth && XKnownNegative && YKnownNegative) {
1984       APInt KnownZero(BitWidth, 0);
1985       APInt KnownOne(BitWidth, 0);
1986       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1987       // The sign bit of X is set.  If some other bit is set then X is not equal
1988       // to INT_MIN.
1989       computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1990       if ((KnownOne & Mask) != 0)
1991         return true;
1992       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1993       // to INT_MIN.
1994       computeKnownBits(Y, KnownZero, KnownOne, Depth, Q);
1995       if ((KnownOne & Mask) != 0)
1996         return true;
1997     }
1998 
1999     // The sum of a non-negative number and a power of two is not zero.
2000     if (XKnownNonNegative &&
2001         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2002       return true;
2003     if (YKnownNonNegative &&
2004         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2005       return true;
2006   }
2007   // X * Y.
2008   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
2009     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2010     // If X and Y are non-zero then so is X * Y as long as the multiplication
2011     // does not overflow.
2012     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
2013         isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
2014       return true;
2015   }
2016   // (C ? X : Y) != 0 if X != 0 and Y != 0.
2017   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2018     if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2019         isKnownNonZero(SI->getFalseValue(), Depth, Q))
2020       return true;
2021   }
2022   // PHI
2023   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2024     // Try and detect a recurrence that monotonically increases from a
2025     // starting value, as these are common as induction variables.
2026     if (PN->getNumIncomingValues() == 2) {
2027       Value *Start = PN->getIncomingValue(0);
2028       Value *Induction = PN->getIncomingValue(1);
2029       if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2030         std::swap(Start, Induction);
2031       if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2032         if (!C->isZero() && !C->isNegative()) {
2033           ConstantInt *X;
2034           if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2035                match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2036               !X->isNegative())
2037             return true;
2038         }
2039       }
2040     }
2041     // Check if all incoming values are non-zero constant.
2042     bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
2043       return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
2044     });
2045     if (AllNonZeroConstants)
2046       return true;
2047   }
2048 
2049   if (!BitWidth) return false;
2050   APInt KnownZero(BitWidth, 0);
2051   APInt KnownOne(BitWidth, 0);
2052   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2053   return KnownOne != 0;
2054 }
2055 
2056 /// Return true if V2 == V1 + X, where X is known non-zero.
2057 static bool isAddOfNonZero(Value *V1, Value *V2, const Query &Q) {
2058   BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2059   if (!BO || BO->getOpcode() != Instruction::Add)
2060     return false;
2061   Value *Op = nullptr;
2062   if (V2 == BO->getOperand(0))
2063     Op = BO->getOperand(1);
2064   else if (V2 == BO->getOperand(1))
2065     Op = BO->getOperand(0);
2066   else
2067     return false;
2068   return isKnownNonZero(Op, 0, Q);
2069 }
2070 
2071 /// Return true if it is known that V1 != V2.
2072 static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q) {
2073   if (V1->getType()->isVectorTy() || V1 == V2)
2074     return false;
2075   if (V1->getType() != V2->getType())
2076     // We can't look through casts yet.
2077     return false;
2078   if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
2079     return true;
2080 
2081   if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
2082     // Are any known bits in V1 contradictory to known bits in V2? If V1
2083     // has a known zero where V2 has a known one, they must not be equal.
2084     auto BitWidth = Ty->getBitWidth();
2085     APInt KnownZero1(BitWidth, 0);
2086     APInt KnownOne1(BitWidth, 0);
2087     computeKnownBits(V1, KnownZero1, KnownOne1, 0, Q);
2088     APInt KnownZero2(BitWidth, 0);
2089     APInt KnownOne2(BitWidth, 0);
2090     computeKnownBits(V2, KnownZero2, KnownOne2, 0, Q);
2091 
2092     auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1);
2093     if (OppositeBits.getBoolValue())
2094       return true;
2095   }
2096   return false;
2097 }
2098 
2099 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
2100 /// simplify operations downstream. Mask is known to be zero for bits that V
2101 /// cannot have.
2102 ///
2103 /// This function is defined on values with integer type, values with pointer
2104 /// type, and vectors of integers.  In the case
2105 /// where V is a vector, the mask, known zero, and known one values are the
2106 /// same width as the vector element, and the bit is set only if it is true
2107 /// for all of the elements in the vector.
2108 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
2109                        const Query &Q) {
2110   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
2111   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2112   return (KnownZero & Mask) == Mask;
2113 }
2114 
2115 
2116 
2117 /// Return the number of times the sign bit of the register is replicated into
2118 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2119 /// (itself), but other cases can give us information. For example, immediately
2120 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2121 /// other, so we return 3.
2122 ///
2123 /// 'Op' must have a scalar integer type.
2124 ///
2125 unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q) {
2126   unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
2127   unsigned Tmp, Tmp2;
2128   unsigned FirstAnswer = 1;
2129 
2130   // Note that ConstantInt is handled by the general computeKnownBits case
2131   // below.
2132 
2133   if (Depth == 6)
2134     return 1;  // Limit search depth.
2135 
2136   Operator *U = dyn_cast<Operator>(V);
2137   switch (Operator::getOpcode(V)) {
2138   default: break;
2139   case Instruction::SExt:
2140     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2141     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2142 
2143   case Instruction::SDiv: {
2144     const APInt *Denominator;
2145     // sdiv X, C -> adds log(C) sign bits.
2146     if (match(U->getOperand(1), m_APInt(Denominator))) {
2147 
2148       // Ignore non-positive denominator.
2149       if (!Denominator->isStrictlyPositive())
2150         break;
2151 
2152       // Calculate the incoming numerator bits.
2153       unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2154 
2155       // Add floor(log(C)) bits to the numerator bits.
2156       return std::min(TyBits, NumBits + Denominator->logBase2());
2157     }
2158     break;
2159   }
2160 
2161   case Instruction::SRem: {
2162     const APInt *Denominator;
2163     // srem X, C -> we know that the result is within [-C+1,C) when C is a
2164     // positive constant.  This let us put a lower bound on the number of sign
2165     // bits.
2166     if (match(U->getOperand(1), m_APInt(Denominator))) {
2167 
2168       // Ignore non-positive denominator.
2169       if (!Denominator->isStrictlyPositive())
2170         break;
2171 
2172       // Calculate the incoming numerator bits. SRem by a positive constant
2173       // can't lower the number of sign bits.
2174       unsigned NumrBits =
2175           ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2176 
2177       // Calculate the leading sign bit constraints by examining the
2178       // denominator.  Given that the denominator is positive, there are two
2179       // cases:
2180       //
2181       //  1. the numerator is positive.  The result range is [0,C) and [0,C) u<
2182       //     (1 << ceilLogBase2(C)).
2183       //
2184       //  2. the numerator is negative.  Then the result range is (-C,0] and
2185       //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2186       //
2187       // Thus a lower bound on the number of sign bits is `TyBits -
2188       // ceilLogBase2(C)`.
2189 
2190       unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2191       return std::max(NumrBits, ResBits);
2192     }
2193     break;
2194   }
2195 
2196   case Instruction::AShr: {
2197     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2198     // ashr X, C   -> adds C sign bits.  Vectors too.
2199     const APInt *ShAmt;
2200     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2201       Tmp += ShAmt->getZExtValue();
2202       if (Tmp > TyBits) Tmp = TyBits;
2203     }
2204     return Tmp;
2205   }
2206   case Instruction::Shl: {
2207     const APInt *ShAmt;
2208     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2209       // shl destroys sign bits.
2210       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2211       Tmp2 = ShAmt->getZExtValue();
2212       if (Tmp2 >= TyBits ||      // Bad shift.
2213           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
2214       return Tmp - Tmp2;
2215     }
2216     break;
2217   }
2218   case Instruction::And:
2219   case Instruction::Or:
2220   case Instruction::Xor:    // NOT is handled here.
2221     // Logical binary ops preserve the number of sign bits at the worst.
2222     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2223     if (Tmp != 1) {
2224       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2225       FirstAnswer = std::min(Tmp, Tmp2);
2226       // We computed what we know about the sign bits as our first
2227       // answer. Now proceed to the generic code that uses
2228       // computeKnownBits, and pick whichever answer is better.
2229     }
2230     break;
2231 
2232   case Instruction::Select:
2233     Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2234     if (Tmp == 1) return 1;  // Early out.
2235     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
2236     return std::min(Tmp, Tmp2);
2237 
2238   case Instruction::Add:
2239     // Add can have at most one carry bit.  Thus we know that the output
2240     // is, at worst, one more bit than the inputs.
2241     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2242     if (Tmp == 1) return 1;  // Early out.
2243 
2244     // Special case decrementing a value (ADD X, -1):
2245     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2246       if (CRHS->isAllOnesValue()) {
2247         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2248         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
2249 
2250         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2251         // sign bits set.
2252         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2253           return TyBits;
2254 
2255         // If we are subtracting one from a positive number, there is no carry
2256         // out of the result.
2257         if (KnownZero.isNegative())
2258           return Tmp;
2259       }
2260 
2261     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2262     if (Tmp2 == 1) return 1;
2263     return std::min(Tmp, Tmp2)-1;
2264 
2265   case Instruction::Sub:
2266     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2267     if (Tmp2 == 1) return 1;
2268 
2269     // Handle NEG.
2270     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2271       if (CLHS->isNullValue()) {
2272         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2273         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
2274         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2275         // sign bits set.
2276         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2277           return TyBits;
2278 
2279         // If the input is known to be positive (the sign bit is known clear),
2280         // the output of the NEG has the same number of sign bits as the input.
2281         if (KnownZero.isNegative())
2282           return Tmp2;
2283 
2284         // Otherwise, we treat this like a SUB.
2285       }
2286 
2287     // Sub can have at most one carry bit.  Thus we know that the output
2288     // is, at worst, one more bit than the inputs.
2289     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2290     if (Tmp == 1) return 1;  // Early out.
2291     return std::min(Tmp, Tmp2)-1;
2292 
2293   case Instruction::PHI: {
2294     PHINode *PN = cast<PHINode>(U);
2295     unsigned NumIncomingValues = PN->getNumIncomingValues();
2296     // Don't analyze large in-degree PHIs.
2297     if (NumIncomingValues > 4) break;
2298     // Unreachable blocks may have zero-operand PHI nodes.
2299     if (NumIncomingValues == 0) break;
2300 
2301     // Take the minimum of all incoming values.  This can't infinitely loop
2302     // because of our depth threshold.
2303     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
2304     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2305       if (Tmp == 1) return Tmp;
2306       Tmp = std::min(
2307           Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
2308     }
2309     return Tmp;
2310   }
2311 
2312   case Instruction::Trunc:
2313     // FIXME: it's tricky to do anything useful for this, but it is an important
2314     // case for targets like X86.
2315     break;
2316   }
2317 
2318   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2319   // use this information.
2320   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2321   APInt Mask;
2322   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2323 
2324   if (KnownZero.isNegative()) {        // sign bit is 0
2325     Mask = KnownZero;
2326   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2327     Mask = KnownOne;
2328   } else {
2329     // Nothing known.
2330     return FirstAnswer;
2331   }
2332 
2333   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2334   // the number of identical bits in the top of the input value.
2335   Mask = ~Mask;
2336   Mask <<= Mask.getBitWidth()-TyBits;
2337   // Return # leading zeros.  We use 'min' here in case Val was zero before
2338   // shifting.  We don't want to return '64' as for an i32 "0".
2339   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2340 }
2341 
2342 /// This function computes the integer multiple of Base that equals V.
2343 /// If successful, it returns true and returns the multiple in
2344 /// Multiple. If unsuccessful, it returns false. It looks
2345 /// through SExt instructions only if LookThroughSExt is true.
2346 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2347                            bool LookThroughSExt, unsigned Depth) {
2348   const unsigned MaxDepth = 6;
2349 
2350   assert(V && "No Value?");
2351   assert(Depth <= MaxDepth && "Limit Search Depth");
2352   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2353 
2354   Type *T = V->getType();
2355 
2356   ConstantInt *CI = dyn_cast<ConstantInt>(V);
2357 
2358   if (Base == 0)
2359     return false;
2360 
2361   if (Base == 1) {
2362     Multiple = V;
2363     return true;
2364   }
2365 
2366   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2367   Constant *BaseVal = ConstantInt::get(T, Base);
2368   if (CO && CO == BaseVal) {
2369     // Multiple is 1.
2370     Multiple = ConstantInt::get(T, 1);
2371     return true;
2372   }
2373 
2374   if (CI && CI->getZExtValue() % Base == 0) {
2375     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2376     return true;
2377   }
2378 
2379   if (Depth == MaxDepth) return false;  // Limit search depth.
2380 
2381   Operator *I = dyn_cast<Operator>(V);
2382   if (!I) return false;
2383 
2384   switch (I->getOpcode()) {
2385   default: break;
2386   case Instruction::SExt:
2387     if (!LookThroughSExt) return false;
2388     // otherwise fall through to ZExt
2389   case Instruction::ZExt:
2390     return ComputeMultiple(I->getOperand(0), Base, Multiple,
2391                            LookThroughSExt, Depth+1);
2392   case Instruction::Shl:
2393   case Instruction::Mul: {
2394     Value *Op0 = I->getOperand(0);
2395     Value *Op1 = I->getOperand(1);
2396 
2397     if (I->getOpcode() == Instruction::Shl) {
2398       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2399       if (!Op1CI) return false;
2400       // Turn Op0 << Op1 into Op0 * 2^Op1
2401       APInt Op1Int = Op1CI->getValue();
2402       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2403       APInt API(Op1Int.getBitWidth(), 0);
2404       API.setBit(BitToSet);
2405       Op1 = ConstantInt::get(V->getContext(), API);
2406     }
2407 
2408     Value *Mul0 = nullptr;
2409     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2410       if (Constant *Op1C = dyn_cast<Constant>(Op1))
2411         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2412           if (Op1C->getType()->getPrimitiveSizeInBits() <
2413               MulC->getType()->getPrimitiveSizeInBits())
2414             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2415           if (Op1C->getType()->getPrimitiveSizeInBits() >
2416               MulC->getType()->getPrimitiveSizeInBits())
2417             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2418 
2419           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2420           Multiple = ConstantExpr::getMul(MulC, Op1C);
2421           return true;
2422         }
2423 
2424       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2425         if (Mul0CI->getValue() == 1) {
2426           // V == Base * Op1, so return Op1
2427           Multiple = Op1;
2428           return true;
2429         }
2430     }
2431 
2432     Value *Mul1 = nullptr;
2433     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2434       if (Constant *Op0C = dyn_cast<Constant>(Op0))
2435         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2436           if (Op0C->getType()->getPrimitiveSizeInBits() <
2437               MulC->getType()->getPrimitiveSizeInBits())
2438             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2439           if (Op0C->getType()->getPrimitiveSizeInBits() >
2440               MulC->getType()->getPrimitiveSizeInBits())
2441             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2442 
2443           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2444           Multiple = ConstantExpr::getMul(MulC, Op0C);
2445           return true;
2446         }
2447 
2448       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2449         if (Mul1CI->getValue() == 1) {
2450           // V == Base * Op0, so return Op0
2451           Multiple = Op0;
2452           return true;
2453         }
2454     }
2455   }
2456   }
2457 
2458   // We could not determine if V is a multiple of Base.
2459   return false;
2460 }
2461 
2462 /// Return true if we can prove that the specified FP value is never equal to
2463 /// -0.0.
2464 ///
2465 /// NOTE: this function will need to be revisited when we support non-default
2466 /// rounding modes!
2467 ///
2468 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2469   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2470     return !CFP->getValueAPF().isNegZero();
2471 
2472   // FIXME: Magic number! At the least, this should be given a name because it's
2473   // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2474   // expose it as a parameter, so it can be used for testing / experimenting.
2475   if (Depth == 6)
2476     return false;  // Limit search depth.
2477 
2478   const Operator *I = dyn_cast<Operator>(V);
2479   if (!I) return false;
2480 
2481   // Check if the nsz fast-math flag is set
2482   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2483     if (FPO->hasNoSignedZeros())
2484       return true;
2485 
2486   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2487   if (I->getOpcode() == Instruction::FAdd)
2488     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2489       if (CFP->isNullValue())
2490         return true;
2491 
2492   // sitofp and uitofp turn into +0.0 for zero.
2493   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2494     return true;
2495 
2496   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2497     // sqrt(-0.0) = -0.0, no other negative results are possible.
2498     if (II->getIntrinsicID() == Intrinsic::sqrt)
2499       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
2500 
2501   if (const CallInst *CI = dyn_cast<CallInst>(I))
2502     if (const Function *F = CI->getCalledFunction()) {
2503       if (F->isDeclaration()) {
2504         // abs(x) != -0.0
2505         if (F->getName() == "abs") return true;
2506         // fabs[lf](x) != -0.0
2507         if (F->getName() == "fabs") return true;
2508         if (F->getName() == "fabsf") return true;
2509         if (F->getName() == "fabsl") return true;
2510         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2511             F->getName() == "sqrtl")
2512           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2513       }
2514     }
2515 
2516   return false;
2517 }
2518 
2519 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2520   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2521     return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2522 
2523   // FIXME: Magic number! At the least, this should be given a name because it's
2524   // used similarly in CannotBeNegativeZero(). A better fix may be to
2525   // expose it as a parameter, so it can be used for testing / experimenting.
2526   if (Depth == 6)
2527     return false;  // Limit search depth.
2528 
2529   const Operator *I = dyn_cast<Operator>(V);
2530   if (!I) return false;
2531 
2532   switch (I->getOpcode()) {
2533   default: break;
2534   // Unsigned integers are always nonnegative.
2535   case Instruction::UIToFP:
2536     return true;
2537   case Instruction::FMul:
2538     // x*x is always non-negative or a NaN.
2539     if (I->getOperand(0) == I->getOperand(1))
2540       return true;
2541     // Fall through
2542   case Instruction::FAdd:
2543   case Instruction::FDiv:
2544   case Instruction::FRem:
2545     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2546            CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2547   case Instruction::Select:
2548     return CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1) &&
2549            CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2550   case Instruction::FPExt:
2551   case Instruction::FPTrunc:
2552     // Widening/narrowing never change sign.
2553     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2554   case Instruction::Call:
2555     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2556       switch (II->getIntrinsicID()) {
2557       default: break;
2558       case Intrinsic::maxnum:
2559         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) ||
2560                CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2561       case Intrinsic::minnum:
2562         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2563                CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2564       case Intrinsic::exp:
2565       case Intrinsic::exp2:
2566       case Intrinsic::fabs:
2567       case Intrinsic::sqrt:
2568         return true;
2569       case Intrinsic::powi:
2570         if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2571           // powi(x,n) is non-negative if n is even.
2572           if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2573             return true;
2574         }
2575         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2576       case Intrinsic::fma:
2577       case Intrinsic::fmuladd:
2578         // x*x+y is non-negative if y is non-negative.
2579         return I->getOperand(0) == I->getOperand(1) &&
2580                CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2581       }
2582     break;
2583   }
2584   return false;
2585 }
2586 
2587 /// If the specified value can be set by repeating the same byte in memory,
2588 /// return the i8 value that it is represented with.  This is
2589 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2590 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
2591 /// byte store (e.g. i16 0x1234), return null.
2592 Value *llvm::isBytewiseValue(Value *V) {
2593   // All byte-wide stores are splatable, even of arbitrary variables.
2594   if (V->getType()->isIntegerTy(8)) return V;
2595 
2596   // Handle 'null' ConstantArrayZero etc.
2597   if (Constant *C = dyn_cast<Constant>(V))
2598     if (C->isNullValue())
2599       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2600 
2601   // Constant float and double values can be handled as integer values if the
2602   // corresponding integer value is "byteable".  An important case is 0.0.
2603   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2604     if (CFP->getType()->isFloatTy())
2605       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2606     if (CFP->getType()->isDoubleTy())
2607       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2608     // Don't handle long double formats, which have strange constraints.
2609   }
2610 
2611   // We can handle constant integers that are multiple of 8 bits.
2612   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2613     if (CI->getBitWidth() % 8 == 0) {
2614       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2615 
2616       if (!CI->getValue().isSplat(8))
2617         return nullptr;
2618       return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2619     }
2620   }
2621 
2622   // A ConstantDataArray/Vector is splatable if all its members are equal and
2623   // also splatable.
2624   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2625     Value *Elt = CA->getElementAsConstant(0);
2626     Value *Val = isBytewiseValue(Elt);
2627     if (!Val)
2628       return nullptr;
2629 
2630     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2631       if (CA->getElementAsConstant(I) != Elt)
2632         return nullptr;
2633 
2634     return Val;
2635   }
2636 
2637   // Conceptually, we could handle things like:
2638   //   %a = zext i8 %X to i16
2639   //   %b = shl i16 %a, 8
2640   //   %c = or i16 %a, %b
2641   // but until there is an example that actually needs this, it doesn't seem
2642   // worth worrying about.
2643   return nullptr;
2644 }
2645 
2646 
2647 // This is the recursive version of BuildSubAggregate. It takes a few different
2648 // arguments. Idxs is the index within the nested struct From that we are
2649 // looking at now (which is of type IndexedType). IdxSkip is the number of
2650 // indices from Idxs that should be left out when inserting into the resulting
2651 // struct. To is the result struct built so far, new insertvalue instructions
2652 // build on that.
2653 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2654                                 SmallVectorImpl<unsigned> &Idxs,
2655                                 unsigned IdxSkip,
2656                                 Instruction *InsertBefore) {
2657   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2658   if (STy) {
2659     // Save the original To argument so we can modify it
2660     Value *OrigTo = To;
2661     // General case, the type indexed by Idxs is a struct
2662     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2663       // Process each struct element recursively
2664       Idxs.push_back(i);
2665       Value *PrevTo = To;
2666       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2667                              InsertBefore);
2668       Idxs.pop_back();
2669       if (!To) {
2670         // Couldn't find any inserted value for this index? Cleanup
2671         while (PrevTo != OrigTo) {
2672           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2673           PrevTo = Del->getAggregateOperand();
2674           Del->eraseFromParent();
2675         }
2676         // Stop processing elements
2677         break;
2678       }
2679     }
2680     // If we successfully found a value for each of our subaggregates
2681     if (To)
2682       return To;
2683   }
2684   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2685   // the struct's elements had a value that was inserted directly. In the latter
2686   // case, perhaps we can't determine each of the subelements individually, but
2687   // we might be able to find the complete struct somewhere.
2688 
2689   // Find the value that is at that particular spot
2690   Value *V = FindInsertedValue(From, Idxs);
2691 
2692   if (!V)
2693     return nullptr;
2694 
2695   // Insert the value in the new (sub) aggregrate
2696   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2697                                        "tmp", InsertBefore);
2698 }
2699 
2700 // This helper takes a nested struct and extracts a part of it (which is again a
2701 // struct) into a new value. For example, given the struct:
2702 // { a, { b, { c, d }, e } }
2703 // and the indices "1, 1" this returns
2704 // { c, d }.
2705 //
2706 // It does this by inserting an insertvalue for each element in the resulting
2707 // struct, as opposed to just inserting a single struct. This will only work if
2708 // each of the elements of the substruct are known (ie, inserted into From by an
2709 // insertvalue instruction somewhere).
2710 //
2711 // All inserted insertvalue instructions are inserted before InsertBefore
2712 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2713                                 Instruction *InsertBefore) {
2714   assert(InsertBefore && "Must have someplace to insert!");
2715   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2716                                                              idx_range);
2717   Value *To = UndefValue::get(IndexedType);
2718   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2719   unsigned IdxSkip = Idxs.size();
2720 
2721   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2722 }
2723 
2724 /// Given an aggregrate and an sequence of indices, see if
2725 /// the scalar value indexed is already around as a register, for example if it
2726 /// were inserted directly into the aggregrate.
2727 ///
2728 /// If InsertBefore is not null, this function will duplicate (modified)
2729 /// insertvalues when a part of a nested struct is extracted.
2730 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2731                                Instruction *InsertBefore) {
2732   // Nothing to index? Just return V then (this is useful at the end of our
2733   // recursion).
2734   if (idx_range.empty())
2735     return V;
2736   // We have indices, so V should have an indexable type.
2737   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2738          "Not looking at a struct or array?");
2739   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2740          "Invalid indices for type?");
2741 
2742   if (Constant *C = dyn_cast<Constant>(V)) {
2743     C = C->getAggregateElement(idx_range[0]);
2744     if (!C) return nullptr;
2745     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2746   }
2747 
2748   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2749     // Loop the indices for the insertvalue instruction in parallel with the
2750     // requested indices
2751     const unsigned *req_idx = idx_range.begin();
2752     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2753          i != e; ++i, ++req_idx) {
2754       if (req_idx == idx_range.end()) {
2755         // We can't handle this without inserting insertvalues
2756         if (!InsertBefore)
2757           return nullptr;
2758 
2759         // The requested index identifies a part of a nested aggregate. Handle
2760         // this specially. For example,
2761         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2762         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2763         // %C = extractvalue {i32, { i32, i32 } } %B, 1
2764         // This can be changed into
2765         // %A = insertvalue {i32, i32 } undef, i32 10, 0
2766         // %C = insertvalue {i32, i32 } %A, i32 11, 1
2767         // which allows the unused 0,0 element from the nested struct to be
2768         // removed.
2769         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2770                                  InsertBefore);
2771       }
2772 
2773       // This insert value inserts something else than what we are looking for.
2774       // See if the (aggregate) value inserted into has the value we are
2775       // looking for, then.
2776       if (*req_idx != *i)
2777         return FindInsertedValue(I->getAggregateOperand(), idx_range,
2778                                  InsertBefore);
2779     }
2780     // If we end up here, the indices of the insertvalue match with those
2781     // requested (though possibly only partially). Now we recursively look at
2782     // the inserted value, passing any remaining indices.
2783     return FindInsertedValue(I->getInsertedValueOperand(),
2784                              makeArrayRef(req_idx, idx_range.end()),
2785                              InsertBefore);
2786   }
2787 
2788   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2789     // If we're extracting a value from an aggregate that was extracted from
2790     // something else, we can extract from that something else directly instead.
2791     // However, we will need to chain I's indices with the requested indices.
2792 
2793     // Calculate the number of indices required
2794     unsigned size = I->getNumIndices() + idx_range.size();
2795     // Allocate some space to put the new indices in
2796     SmallVector<unsigned, 5> Idxs;
2797     Idxs.reserve(size);
2798     // Add indices from the extract value instruction
2799     Idxs.append(I->idx_begin(), I->idx_end());
2800 
2801     // Add requested indices
2802     Idxs.append(idx_range.begin(), idx_range.end());
2803 
2804     assert(Idxs.size() == size
2805            && "Number of indices added not correct?");
2806 
2807     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2808   }
2809   // Otherwise, we don't know (such as, extracting from a function return value
2810   // or load instruction)
2811   return nullptr;
2812 }
2813 
2814 /// Analyze the specified pointer to see if it can be expressed as a base
2815 /// pointer plus a constant offset. Return the base and offset to the caller.
2816 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2817                                               const DataLayout &DL) {
2818   unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2819   APInt ByteOffset(BitWidth, 0);
2820 
2821   // We walk up the defs but use a visited set to handle unreachable code. In
2822   // that case, we stop after accumulating the cycle once (not that it
2823   // matters).
2824   SmallPtrSet<Value *, 16> Visited;
2825   while (Visited.insert(Ptr).second) {
2826     if (Ptr->getType()->isVectorTy())
2827       break;
2828 
2829     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2830       APInt GEPOffset(BitWidth, 0);
2831       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2832         break;
2833 
2834       ByteOffset += GEPOffset;
2835 
2836       Ptr = GEP->getPointerOperand();
2837     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2838                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2839       Ptr = cast<Operator>(Ptr)->getOperand(0);
2840     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2841       if (GA->mayBeOverridden())
2842         break;
2843       Ptr = GA->getAliasee();
2844     } else {
2845       break;
2846     }
2847   }
2848   Offset = ByteOffset.getSExtValue();
2849   return Ptr;
2850 }
2851 
2852 
2853 /// This function computes the length of a null-terminated C string pointed to
2854 /// by V. If successful, it returns true and returns the string in Str.
2855 /// If unsuccessful, it returns false.
2856 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2857                                  uint64_t Offset, bool TrimAtNul) {
2858   assert(V);
2859 
2860   // Look through bitcast instructions and geps.
2861   V = V->stripPointerCasts();
2862 
2863   // If the value is a GEP instruction or constant expression, treat it as an
2864   // offset.
2865   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2866     // Make sure the GEP has exactly three arguments.
2867     if (GEP->getNumOperands() != 3)
2868       return false;
2869 
2870     // Make sure the index-ee is a pointer to array of i8.
2871     ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2872     if (!AT || !AT->getElementType()->isIntegerTy(8))
2873       return false;
2874 
2875     // Check to make sure that the first operand of the GEP is an integer and
2876     // has value 0 so that we are sure we're indexing into the initializer.
2877     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2878     if (!FirstIdx || !FirstIdx->isZero())
2879       return false;
2880 
2881     // If the second index isn't a ConstantInt, then this is a variable index
2882     // into the array.  If this occurs, we can't say anything meaningful about
2883     // the string.
2884     uint64_t StartIdx = 0;
2885     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2886       StartIdx = CI->getZExtValue();
2887     else
2888       return false;
2889     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2890                                  TrimAtNul);
2891   }
2892 
2893   // The GEP instruction, constant or instruction, must reference a global
2894   // variable that is a constant and is initialized. The referenced constant
2895   // initializer is the array that we'll use for optimization.
2896   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2897   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2898     return false;
2899 
2900   // Handle the all-zeros case
2901   if (GV->getInitializer()->isNullValue()) {
2902     // This is a degenerate case. The initializer is constant zero so the
2903     // length of the string must be zero.
2904     Str = "";
2905     return true;
2906   }
2907 
2908   // Must be a Constant Array
2909   const ConstantDataArray *Array =
2910     dyn_cast<ConstantDataArray>(GV->getInitializer());
2911   if (!Array || !Array->isString())
2912     return false;
2913 
2914   // Get the number of elements in the array
2915   uint64_t NumElts = Array->getType()->getArrayNumElements();
2916 
2917   // Start out with the entire array in the StringRef.
2918   Str = Array->getAsString();
2919 
2920   if (Offset > NumElts)
2921     return false;
2922 
2923   // Skip over 'offset' bytes.
2924   Str = Str.substr(Offset);
2925 
2926   if (TrimAtNul) {
2927     // Trim off the \0 and anything after it.  If the array is not nul
2928     // terminated, we just return the whole end of string.  The client may know
2929     // some other way that the string is length-bound.
2930     Str = Str.substr(0, Str.find('\0'));
2931   }
2932   return true;
2933 }
2934 
2935 // These next two are very similar to the above, but also look through PHI
2936 // nodes.
2937 // TODO: See if we can integrate these two together.
2938 
2939 /// If we can compute the length of the string pointed to by
2940 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2941 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2942   // Look through noop bitcast instructions.
2943   V = V->stripPointerCasts();
2944 
2945   // If this is a PHI node, there are two cases: either we have already seen it
2946   // or we haven't.
2947   if (PHINode *PN = dyn_cast<PHINode>(V)) {
2948     if (!PHIs.insert(PN).second)
2949       return ~0ULL;  // already in the set.
2950 
2951     // If it was new, see if all the input strings are the same length.
2952     uint64_t LenSoFar = ~0ULL;
2953     for (Value *IncValue : PN->incoming_values()) {
2954       uint64_t Len = GetStringLengthH(IncValue, PHIs);
2955       if (Len == 0) return 0; // Unknown length -> unknown.
2956 
2957       if (Len == ~0ULL) continue;
2958 
2959       if (Len != LenSoFar && LenSoFar != ~0ULL)
2960         return 0;    // Disagree -> unknown.
2961       LenSoFar = Len;
2962     }
2963 
2964     // Success, all agree.
2965     return LenSoFar;
2966   }
2967 
2968   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2969   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2970     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2971     if (Len1 == 0) return 0;
2972     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2973     if (Len2 == 0) return 0;
2974     if (Len1 == ~0ULL) return Len2;
2975     if (Len2 == ~0ULL) return Len1;
2976     if (Len1 != Len2) return 0;
2977     return Len1;
2978   }
2979 
2980   // Otherwise, see if we can read the string.
2981   StringRef StrData;
2982   if (!getConstantStringInfo(V, StrData))
2983     return 0;
2984 
2985   return StrData.size()+1;
2986 }
2987 
2988 /// If we can compute the length of the string pointed to by
2989 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2990 uint64_t llvm::GetStringLength(Value *V) {
2991   if (!V->getType()->isPointerTy()) return 0;
2992 
2993   SmallPtrSet<PHINode*, 32> PHIs;
2994   uint64_t Len = GetStringLengthH(V, PHIs);
2995   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2996   // an empty string as a length.
2997   return Len == ~0ULL ? 1 : Len;
2998 }
2999 
3000 /// \brief \p PN defines a loop-variant pointer to an object.  Check if the
3001 /// previous iteration of the loop was referring to the same object as \p PN.
3002 static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
3003   // Find the loop-defined value.
3004   Loop *L = LI->getLoopFor(PN->getParent());
3005   if (PN->getNumIncomingValues() != 2)
3006     return true;
3007 
3008   // Find the value from previous iteration.
3009   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3010   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3011     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3012   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3013     return true;
3014 
3015   // If a new pointer is loaded in the loop, the pointer references a different
3016   // object in every iteration.  E.g.:
3017   //    for (i)
3018   //       int *p = a[i];
3019   //       ...
3020   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3021     if (!L->isLoopInvariant(Load->getPointerOperand()))
3022       return false;
3023   return true;
3024 }
3025 
3026 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3027                                  unsigned MaxLookup) {
3028   if (!V->getType()->isPointerTy())
3029     return V;
3030   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3031     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3032       V = GEP->getPointerOperand();
3033     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3034                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3035       V = cast<Operator>(V)->getOperand(0);
3036     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3037       if (GA->mayBeOverridden())
3038         return V;
3039       V = GA->getAliasee();
3040     } else {
3041       // See if InstructionSimplify knows any relevant tricks.
3042       if (Instruction *I = dyn_cast<Instruction>(V))
3043         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3044         if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
3045           V = Simplified;
3046           continue;
3047         }
3048 
3049       return V;
3050     }
3051     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3052   }
3053   return V;
3054 }
3055 
3056 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
3057                                 const DataLayout &DL, LoopInfo *LI,
3058                                 unsigned MaxLookup) {
3059   SmallPtrSet<Value *, 4> Visited;
3060   SmallVector<Value *, 4> Worklist;
3061   Worklist.push_back(V);
3062   do {
3063     Value *P = Worklist.pop_back_val();
3064     P = GetUnderlyingObject(P, DL, MaxLookup);
3065 
3066     if (!Visited.insert(P).second)
3067       continue;
3068 
3069     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3070       Worklist.push_back(SI->getTrueValue());
3071       Worklist.push_back(SI->getFalseValue());
3072       continue;
3073     }
3074 
3075     if (PHINode *PN = dyn_cast<PHINode>(P)) {
3076       // If this PHI changes the underlying object in every iteration of the
3077       // loop, don't look through it.  Consider:
3078       //   int **A;
3079       //   for (i) {
3080       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
3081       //     Curr = A[i];
3082       //     *Prev, *Curr;
3083       //
3084       // Prev is tracking Curr one iteration behind so they refer to different
3085       // underlying objects.
3086       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3087           isSameUnderlyingObjectInLoop(PN, LI))
3088         for (Value *IncValue : PN->incoming_values())
3089           Worklist.push_back(IncValue);
3090       continue;
3091     }
3092 
3093     Objects.push_back(P);
3094   } while (!Worklist.empty());
3095 }
3096 
3097 /// Return true if the only users of this pointer are lifetime markers.
3098 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3099   for (const User *U : V->users()) {
3100     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3101     if (!II) return false;
3102 
3103     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3104         II->getIntrinsicID() != Intrinsic::lifetime_end)
3105       return false;
3106   }
3107   return true;
3108 }
3109 
3110 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3111                                         const Instruction *CtxI,
3112                                         const DominatorTree *DT,
3113                                         const TargetLibraryInfo *TLI) {
3114   const Operator *Inst = dyn_cast<Operator>(V);
3115   if (!Inst)
3116     return false;
3117 
3118   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3119     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3120       if (C->canTrap())
3121         return false;
3122 
3123   switch (Inst->getOpcode()) {
3124   default:
3125     return true;
3126   case Instruction::UDiv:
3127   case Instruction::URem: {
3128     // x / y is undefined if y == 0.
3129     const APInt *V;
3130     if (match(Inst->getOperand(1), m_APInt(V)))
3131       return *V != 0;
3132     return false;
3133   }
3134   case Instruction::SDiv:
3135   case Instruction::SRem: {
3136     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3137     const APInt *Numerator, *Denominator;
3138     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3139       return false;
3140     // We cannot hoist this division if the denominator is 0.
3141     if (*Denominator == 0)
3142       return false;
3143     // It's safe to hoist if the denominator is not 0 or -1.
3144     if (*Denominator != -1)
3145       return true;
3146     // At this point we know that the denominator is -1.  It is safe to hoist as
3147     // long we know that the numerator is not INT_MIN.
3148     if (match(Inst->getOperand(0), m_APInt(Numerator)))
3149       return !Numerator->isMinSignedValue();
3150     // The numerator *might* be MinSignedValue.
3151     return false;
3152   }
3153   case Instruction::Load: {
3154     const LoadInst *LI = cast<LoadInst>(Inst);
3155     if (!LI->isUnordered() ||
3156         // Speculative load may create a race that did not exist in the source.
3157         LI->getParent()->getParent()->hasFnAttribute(
3158             Attribute::SanitizeThread) ||
3159         // Speculative load may load data from dirty regions.
3160         LI->getParent()->getParent()->hasFnAttribute(
3161             Attribute::SanitizeAddress))
3162       return false;
3163     const DataLayout &DL = LI->getModule()->getDataLayout();
3164     return isDereferenceableAndAlignedPointer(
3165         LI->getPointerOperand(), LI->getAlignment(), DL, CtxI, DT, TLI);
3166   }
3167   case Instruction::Call: {
3168     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3169       switch (II->getIntrinsicID()) {
3170       // These synthetic intrinsics have no side-effects and just mark
3171       // information about their operands.
3172       // FIXME: There are other no-op synthetic instructions that potentially
3173       // should be considered at least *safe* to speculate...
3174       case Intrinsic::dbg_declare:
3175       case Intrinsic::dbg_value:
3176         return true;
3177 
3178       case Intrinsic::bswap:
3179       case Intrinsic::ctlz:
3180       case Intrinsic::ctpop:
3181       case Intrinsic::cttz:
3182       case Intrinsic::objectsize:
3183       case Intrinsic::sadd_with_overflow:
3184       case Intrinsic::smul_with_overflow:
3185       case Intrinsic::ssub_with_overflow:
3186       case Intrinsic::uadd_with_overflow:
3187       case Intrinsic::umul_with_overflow:
3188       case Intrinsic::usub_with_overflow:
3189         return true;
3190       // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3191       // errno like libm sqrt would.
3192       case Intrinsic::sqrt:
3193       case Intrinsic::fma:
3194       case Intrinsic::fmuladd:
3195       case Intrinsic::fabs:
3196       case Intrinsic::minnum:
3197       case Intrinsic::maxnum:
3198         return true;
3199       // TODO: some fp intrinsics are marked as having the same error handling
3200       // as libm. They're safe to speculate when they won't error.
3201       // TODO: are convert_{from,to}_fp16 safe?
3202       // TODO: can we list target-specific intrinsics here?
3203       default: break;
3204       }
3205     }
3206     return false; // The called function could have undefined behavior or
3207                   // side-effects, even if marked readnone nounwind.
3208   }
3209   case Instruction::VAArg:
3210   case Instruction::Alloca:
3211   case Instruction::Invoke:
3212   case Instruction::PHI:
3213   case Instruction::Store:
3214   case Instruction::Ret:
3215   case Instruction::Br:
3216   case Instruction::IndirectBr:
3217   case Instruction::Switch:
3218   case Instruction::Unreachable:
3219   case Instruction::Fence:
3220   case Instruction::AtomicRMW:
3221   case Instruction::AtomicCmpXchg:
3222   case Instruction::LandingPad:
3223   case Instruction::Resume:
3224   case Instruction::CatchSwitch:
3225   case Instruction::CatchPad:
3226   case Instruction::CatchRet:
3227   case Instruction::CleanupPad:
3228   case Instruction::CleanupRet:
3229     return false; // Misc instructions which have effects
3230   }
3231 }
3232 
3233 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3234   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3235 }
3236 
3237 /// Return true if we know that the specified value is never null.
3238 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
3239   assert(V->getType()->isPointerTy() && "V must be pointer type");
3240 
3241   // Alloca never returns null, malloc might.
3242   if (isa<AllocaInst>(V)) return true;
3243 
3244   // A byval, inalloca, or nonnull argument is never null.
3245   if (const Argument *A = dyn_cast<Argument>(V))
3246     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3247 
3248   // A global variable in address space 0 is non null unless extern weak.
3249   // Other address spaces may have null as a valid address for a global,
3250   // so we can't assume anything.
3251   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3252     return !GV->hasExternalWeakLinkage() &&
3253            GV->getType()->getAddressSpace() == 0;
3254 
3255   // A Load tagged w/nonnull metadata is never null.
3256   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3257     return LI->getMetadata(LLVMContext::MD_nonnull);
3258 
3259   if (auto CS = ImmutableCallSite(V))
3260     if (CS.isReturnNonNull())
3261       return true;
3262 
3263   return false;
3264 }
3265 
3266 static bool isKnownNonNullFromDominatingCondition(const Value *V,
3267                                                   const Instruction *CtxI,
3268                                                   const DominatorTree *DT) {
3269   assert(V->getType()->isPointerTy() && "V must be pointer type");
3270 
3271   unsigned NumUsesExplored = 0;
3272   for (auto U : V->users()) {
3273     // Avoid massive lists
3274     if (NumUsesExplored >= DomConditionsMaxUses)
3275       break;
3276     NumUsesExplored++;
3277     // Consider only compare instructions uniquely controlling a branch
3278     const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
3279     if (!Cmp)
3280       continue;
3281 
3282     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
3283       continue;
3284 
3285     for (auto *CmpU : Cmp->users()) {
3286       const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
3287       if (!BI)
3288         continue;
3289 
3290       assert(BI->isConditional() && "uses a comparison!");
3291 
3292       BasicBlock *NonNullSuccessor = nullptr;
3293       CmpInst::Predicate Pred;
3294 
3295       if (match(const_cast<ICmpInst*>(Cmp),
3296                 m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
3297         if (Pred == ICmpInst::ICMP_EQ)
3298           NonNullSuccessor = BI->getSuccessor(1);
3299         else if (Pred == ICmpInst::ICMP_NE)
3300           NonNullSuccessor = BI->getSuccessor(0);
3301       }
3302 
3303       if (NonNullSuccessor) {
3304         BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3305         if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3306           return true;
3307       }
3308     }
3309   }
3310 
3311   return false;
3312 }
3313 
3314 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3315                    const DominatorTree *DT, const TargetLibraryInfo *TLI) {
3316   if (isKnownNonNull(V, TLI))
3317     return true;
3318 
3319   return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
3320 }
3321 
3322 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
3323                                                    const DataLayout &DL,
3324                                                    AssumptionCache *AC,
3325                                                    const Instruction *CxtI,
3326                                                    const DominatorTree *DT) {
3327   // Multiplying n * m significant bits yields a result of n + m significant
3328   // bits. If the total number of significant bits does not exceed the
3329   // result bit width (minus 1), there is no overflow.
3330   // This means if we have enough leading zero bits in the operands
3331   // we can guarantee that the result does not overflow.
3332   // Ref: "Hacker's Delight" by Henry Warren
3333   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3334   APInt LHSKnownZero(BitWidth, 0);
3335   APInt LHSKnownOne(BitWidth, 0);
3336   APInt RHSKnownZero(BitWidth, 0);
3337   APInt RHSKnownOne(BitWidth, 0);
3338   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3339                    DT);
3340   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3341                    DT);
3342   // Note that underestimating the number of zero bits gives a more
3343   // conservative answer.
3344   unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3345                       RHSKnownZero.countLeadingOnes();
3346   // First handle the easy case: if we have enough zero bits there's
3347   // definitely no overflow.
3348   if (ZeroBits >= BitWidth)
3349     return OverflowResult::NeverOverflows;
3350 
3351   // Get the largest possible values for each operand.
3352   APInt LHSMax = ~LHSKnownZero;
3353   APInt RHSMax = ~RHSKnownZero;
3354 
3355   // We know the multiply operation doesn't overflow if the maximum values for
3356   // each operand will not overflow after we multiply them together.
3357   bool MaxOverflow;
3358   LHSMax.umul_ov(RHSMax, MaxOverflow);
3359   if (!MaxOverflow)
3360     return OverflowResult::NeverOverflows;
3361 
3362   // We know it always overflows if multiplying the smallest possible values for
3363   // the operands also results in overflow.
3364   bool MinOverflow;
3365   LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3366   if (MinOverflow)
3367     return OverflowResult::AlwaysOverflows;
3368 
3369   return OverflowResult::MayOverflow;
3370 }
3371 
3372 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
3373                                                    const DataLayout &DL,
3374                                                    AssumptionCache *AC,
3375                                                    const Instruction *CxtI,
3376                                                    const DominatorTree *DT) {
3377   bool LHSKnownNonNegative, LHSKnownNegative;
3378   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3379                  AC, CxtI, DT);
3380   if (LHSKnownNonNegative || LHSKnownNegative) {
3381     bool RHSKnownNonNegative, RHSKnownNegative;
3382     ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3383                    AC, CxtI, DT);
3384 
3385     if (LHSKnownNegative && RHSKnownNegative) {
3386       // The sign bit is set in both cases: this MUST overflow.
3387       // Create a simple add instruction, and insert it into the struct.
3388       return OverflowResult::AlwaysOverflows;
3389     }
3390 
3391     if (LHSKnownNonNegative && RHSKnownNonNegative) {
3392       // The sign bit is clear in both cases: this CANNOT overflow.
3393       // Create a simple add instruction, and insert it into the struct.
3394       return OverflowResult::NeverOverflows;
3395     }
3396   }
3397 
3398   return OverflowResult::MayOverflow;
3399 }
3400 
3401 static OverflowResult computeOverflowForSignedAdd(
3402     Value *LHS, Value *RHS, AddOperator *Add, const DataLayout &DL,
3403     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) {
3404   if (Add && Add->hasNoSignedWrap()) {
3405     return OverflowResult::NeverOverflows;
3406   }
3407 
3408   bool LHSKnownNonNegative, LHSKnownNegative;
3409   bool RHSKnownNonNegative, RHSKnownNegative;
3410   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3411                  AC, CxtI, DT);
3412   ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3413                  AC, CxtI, DT);
3414 
3415   if ((LHSKnownNonNegative && RHSKnownNegative) ||
3416       (LHSKnownNegative && RHSKnownNonNegative)) {
3417     // The sign bits are opposite: this CANNOT overflow.
3418     return OverflowResult::NeverOverflows;
3419   }
3420 
3421   // The remaining code needs Add to be available. Early returns if not so.
3422   if (!Add)
3423     return OverflowResult::MayOverflow;
3424 
3425   // If the sign of Add is the same as at least one of the operands, this add
3426   // CANNOT overflow. This is particularly useful when the sum is
3427   // @llvm.assume'ed non-negative rather than proved so from analyzing its
3428   // operands.
3429   bool LHSOrRHSKnownNonNegative =
3430       (LHSKnownNonNegative || RHSKnownNonNegative);
3431   bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3432   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3433     bool AddKnownNonNegative, AddKnownNegative;
3434     ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
3435                    /*Depth=*/0, AC, CxtI, DT);
3436     if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3437         (AddKnownNegative && LHSOrRHSKnownNegative)) {
3438       return OverflowResult::NeverOverflows;
3439     }
3440   }
3441 
3442   return OverflowResult::MayOverflow;
3443 }
3444 
3445 OverflowResult llvm::computeOverflowForSignedAdd(AddOperator *Add,
3446                                                  const DataLayout &DL,
3447                                                  AssumptionCache *AC,
3448                                                  const Instruction *CxtI,
3449                                                  const DominatorTree *DT) {
3450   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3451                                        Add, DL, AC, CxtI, DT);
3452 }
3453 
3454 OverflowResult llvm::computeOverflowForSignedAdd(Value *LHS, Value *RHS,
3455                                                  const DataLayout &DL,
3456                                                  AssumptionCache *AC,
3457                                                  const Instruction *CxtI,
3458                                                  const DominatorTree *DT) {
3459   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3460 }
3461 
3462 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3463   // FIXME: This conservative implementation can be relaxed. E.g. most
3464   // atomic operations are guaranteed to terminate on most platforms
3465   // and most functions terminate.
3466 
3467   return !I->isAtomic() &&       // atomics may never succeed on some platforms
3468          !isa<CallInst>(I) &&    // could throw and might not terminate
3469          !isa<InvokeInst>(I) &&  // might not terminate and could throw to
3470                                  //   non-successor (see bug 24185 for details).
3471          !isa<ResumeInst>(I) &&  // has no successors
3472          !isa<ReturnInst>(I);    // has no successors
3473 }
3474 
3475 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3476                                                   const Loop *L) {
3477   // The loop header is guaranteed to be executed for every iteration.
3478   //
3479   // FIXME: Relax this constraint to cover all basic blocks that are
3480   // guaranteed to be executed at every iteration.
3481   if (I->getParent() != L->getHeader()) return false;
3482 
3483   for (const Instruction &LI : *L->getHeader()) {
3484     if (&LI == I) return true;
3485     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3486   }
3487   llvm_unreachable("Instruction not contained in its own parent basic block.");
3488 }
3489 
3490 bool llvm::propagatesFullPoison(const Instruction *I) {
3491   switch (I->getOpcode()) {
3492     case Instruction::Add:
3493     case Instruction::Sub:
3494     case Instruction::Xor:
3495     case Instruction::Trunc:
3496     case Instruction::BitCast:
3497     case Instruction::AddrSpaceCast:
3498       // These operations all propagate poison unconditionally. Note that poison
3499       // is not any particular value, so xor or subtraction of poison with
3500       // itself still yields poison, not zero.
3501       return true;
3502 
3503     case Instruction::AShr:
3504     case Instruction::SExt:
3505       // For these operations, one bit of the input is replicated across
3506       // multiple output bits. A replicated poison bit is still poison.
3507       return true;
3508 
3509     case Instruction::Shl: {
3510       // Left shift *by* a poison value is poison. The number of
3511       // positions to shift is unsigned, so no negative values are
3512       // possible there. Left shift by zero places preserves poison. So
3513       // it only remains to consider left shift of poison by a positive
3514       // number of places.
3515       //
3516       // A left shift by a positive number of places leaves the lowest order bit
3517       // non-poisoned. However, if such a shift has a no-wrap flag, then we can
3518       // make the poison operand violate that flag, yielding a fresh full-poison
3519       // value.
3520       auto *OBO = cast<OverflowingBinaryOperator>(I);
3521       return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
3522     }
3523 
3524     case Instruction::Mul: {
3525       // A multiplication by zero yields a non-poison zero result, so we need to
3526       // rule out zero as an operand. Conservatively, multiplication by a
3527       // non-zero constant is not multiplication by zero.
3528       //
3529       // Multiplication by a non-zero constant can leave some bits
3530       // non-poisoned. For example, a multiplication by 2 leaves the lowest
3531       // order bit unpoisoned. So we need to consider that.
3532       //
3533       // Multiplication by 1 preserves poison. If the multiplication has a
3534       // no-wrap flag, then we can make the poison operand violate that flag
3535       // when multiplied by any integer other than 0 and 1.
3536       auto *OBO = cast<OverflowingBinaryOperator>(I);
3537       if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
3538         for (Value *V : OBO->operands()) {
3539           if (auto *CI = dyn_cast<ConstantInt>(V)) {
3540             // A ConstantInt cannot yield poison, so we can assume that it is
3541             // the other operand that is poison.
3542             return !CI->isZero();
3543           }
3544         }
3545       }
3546       return false;
3547     }
3548 
3549     case Instruction::GetElementPtr:
3550       // A GEP implicitly represents a sequence of additions, subtractions,
3551       // truncations, sign extensions and multiplications. The multiplications
3552       // are by the non-zero sizes of some set of types, so we do not have to be
3553       // concerned with multiplication by zero. If the GEP is in-bounds, then
3554       // these operations are implicitly no-signed-wrap so poison is propagated
3555       // by the arguments above for Add, Sub, Trunc, SExt and Mul.
3556       return cast<GEPOperator>(I)->isInBounds();
3557 
3558     default:
3559       return false;
3560   }
3561 }
3562 
3563 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3564   switch (I->getOpcode()) {
3565     case Instruction::Store:
3566       return cast<StoreInst>(I)->getPointerOperand();
3567 
3568     case Instruction::Load:
3569       return cast<LoadInst>(I)->getPointerOperand();
3570 
3571     case Instruction::AtomicCmpXchg:
3572       return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3573 
3574     case Instruction::AtomicRMW:
3575       return cast<AtomicRMWInst>(I)->getPointerOperand();
3576 
3577     case Instruction::UDiv:
3578     case Instruction::SDiv:
3579     case Instruction::URem:
3580     case Instruction::SRem:
3581       return I->getOperand(1);
3582 
3583     default:
3584       return nullptr;
3585   }
3586 }
3587 
3588 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3589   // We currently only look for uses of poison values within the same basic
3590   // block, as that makes it easier to guarantee that the uses will be
3591   // executed given that PoisonI is executed.
3592   //
3593   // FIXME: Expand this to consider uses beyond the same basic block. To do
3594   // this, look out for the distinction between post-dominance and strong
3595   // post-dominance.
3596   const BasicBlock *BB = PoisonI->getParent();
3597 
3598   // Set of instructions that we have proved will yield poison if PoisonI
3599   // does.
3600   SmallSet<const Value *, 16> YieldsPoison;
3601   YieldsPoison.insert(PoisonI);
3602 
3603   for (BasicBlock::const_iterator I = PoisonI->getIterator(), E = BB->end();
3604        I != E; ++I) {
3605     if (&*I != PoisonI) {
3606       const Value *NotPoison = getGuaranteedNonFullPoisonOp(&*I);
3607       if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) return true;
3608       if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
3609         return false;
3610     }
3611 
3612     // Mark poison that propagates from I through uses of I.
3613     if (YieldsPoison.count(&*I)) {
3614       for (const User *User : I->users()) {
3615         const Instruction *UserI = cast<Instruction>(User);
3616         if (UserI->getParent() == BB && propagatesFullPoison(UserI))
3617           YieldsPoison.insert(User);
3618       }
3619     }
3620   }
3621   return false;
3622 }
3623 
3624 static bool isKnownNonNaN(Value *V, FastMathFlags FMF) {
3625   if (FMF.noNaNs())
3626     return true;
3627 
3628   if (auto *C = dyn_cast<ConstantFP>(V))
3629     return !C->isNaN();
3630   return false;
3631 }
3632 
3633 static bool isKnownNonZero(Value *V) {
3634   if (auto *C = dyn_cast<ConstantFP>(V))
3635     return !C->isZero();
3636   return false;
3637 }
3638 
3639 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3640                                               FastMathFlags FMF,
3641                                               Value *CmpLHS, Value *CmpRHS,
3642                                               Value *TrueVal, Value *FalseVal,
3643                                               Value *&LHS, Value *&RHS) {
3644   LHS = CmpLHS;
3645   RHS = CmpRHS;
3646 
3647   // If the predicate is an "or-equal"  (FP) predicate, then signed zeroes may
3648   // return inconsistent results between implementations.
3649   //   (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3650   //   minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3651   // Therefore we behave conservatively and only proceed if at least one of the
3652   // operands is known to not be zero, or if we don't care about signed zeroes.
3653   switch (Pred) {
3654   default: break;
3655   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3656   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3657     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3658         !isKnownNonZero(CmpRHS))
3659       return {SPF_UNKNOWN, SPNB_NA, false};
3660   }
3661 
3662   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3663   bool Ordered = false;
3664 
3665   // When given one NaN and one non-NaN input:
3666   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3667   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3668   //     ordered comparison fails), which could be NaN or non-NaN.
3669   // so here we discover exactly what NaN behavior is required/accepted.
3670   if (CmpInst::isFPPredicate(Pred)) {
3671     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3672     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3673 
3674     if (LHSSafe && RHSSafe) {
3675       // Both operands are known non-NaN.
3676       NaNBehavior = SPNB_RETURNS_ANY;
3677     } else if (CmpInst::isOrdered(Pred)) {
3678       // An ordered comparison will return false when given a NaN, so it
3679       // returns the RHS.
3680       Ordered = true;
3681       if (LHSSafe)
3682         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
3683         NaNBehavior = SPNB_RETURNS_NAN;
3684       else if (RHSSafe)
3685         NaNBehavior = SPNB_RETURNS_OTHER;
3686       else
3687         // Completely unsafe.
3688         return {SPF_UNKNOWN, SPNB_NA, false};
3689     } else {
3690       Ordered = false;
3691       // An unordered comparison will return true when given a NaN, so it
3692       // returns the LHS.
3693       if (LHSSafe)
3694         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
3695         NaNBehavior = SPNB_RETURNS_OTHER;
3696       else if (RHSSafe)
3697         NaNBehavior = SPNB_RETURNS_NAN;
3698       else
3699         // Completely unsafe.
3700         return {SPF_UNKNOWN, SPNB_NA, false};
3701     }
3702   }
3703 
3704   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
3705     std::swap(CmpLHS, CmpRHS);
3706     Pred = CmpInst::getSwappedPredicate(Pred);
3707     if (NaNBehavior == SPNB_RETURNS_NAN)
3708       NaNBehavior = SPNB_RETURNS_OTHER;
3709     else if (NaNBehavior == SPNB_RETURNS_OTHER)
3710       NaNBehavior = SPNB_RETURNS_NAN;
3711     Ordered = !Ordered;
3712   }
3713 
3714   // ([if]cmp X, Y) ? X : Y
3715   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
3716     switch (Pred) {
3717     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
3718     case ICmpInst::ICMP_UGT:
3719     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
3720     case ICmpInst::ICMP_SGT:
3721     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
3722     case ICmpInst::ICMP_ULT:
3723     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
3724     case ICmpInst::ICMP_SLT:
3725     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
3726     case FCmpInst::FCMP_UGT:
3727     case FCmpInst::FCMP_UGE:
3728     case FCmpInst::FCMP_OGT:
3729     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
3730     case FCmpInst::FCMP_ULT:
3731     case FCmpInst::FCMP_ULE:
3732     case FCmpInst::FCMP_OLT:
3733     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
3734     }
3735   }
3736 
3737   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
3738     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
3739         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
3740 
3741       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
3742       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
3743       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
3744         return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3745       }
3746 
3747       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
3748       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
3749       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
3750         return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
3751       }
3752     }
3753 
3754     // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
3755     if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
3756       if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
3757           (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
3758            match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
3759         LHS = TrueVal;
3760         RHS = FalseVal;
3761         return {SPF_SMIN, SPNB_NA, false};
3762       }
3763     }
3764   }
3765 
3766   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
3767 
3768   return {SPF_UNKNOWN, SPNB_NA, false};
3769 }
3770 
3771 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
3772                               Instruction::CastOps *CastOp) {
3773   CastInst *CI = dyn_cast<CastInst>(V1);
3774   Constant *C = dyn_cast<Constant>(V2);
3775   CastInst *CI2 = dyn_cast<CastInst>(V2);
3776   if (!CI)
3777     return nullptr;
3778   *CastOp = CI->getOpcode();
3779 
3780   if (CI2) {
3781     // If V1 and V2 are both the same cast from the same type, we can look
3782     // through V1.
3783     if (CI2->getOpcode() == CI->getOpcode() &&
3784         CI2->getSrcTy() == CI->getSrcTy())
3785       return CI2->getOperand(0);
3786     return nullptr;
3787   } else if (!C) {
3788     return nullptr;
3789   }
3790 
3791   if (isa<SExtInst>(CI) && CmpI->isSigned()) {
3792     Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
3793     // This is only valid if the truncated value can be sign-extended
3794     // back to the original value.
3795     if (ConstantExpr::getSExt(T, C->getType()) == C)
3796       return T;
3797     return nullptr;
3798   }
3799   if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
3800     return ConstantExpr::getTrunc(C, CI->getSrcTy());
3801 
3802   if (isa<TruncInst>(CI))
3803     return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
3804 
3805   if (isa<FPToUIInst>(CI))
3806     return ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
3807 
3808   if (isa<FPToSIInst>(CI))
3809     return ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
3810 
3811   if (isa<UIToFPInst>(CI))
3812     return ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
3813 
3814   if (isa<SIToFPInst>(CI))
3815     return ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
3816 
3817   if (isa<FPTruncInst>(CI))
3818     return ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
3819 
3820   if (isa<FPExtInst>(CI))
3821     return ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
3822 
3823   return nullptr;
3824 }
3825 
3826 SelectPatternResult llvm::matchSelectPattern(Value *V,
3827                                              Value *&LHS, Value *&RHS,
3828                                              Instruction::CastOps *CastOp) {
3829   SelectInst *SI = dyn_cast<SelectInst>(V);
3830   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
3831 
3832   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
3833   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
3834 
3835   CmpInst::Predicate Pred = CmpI->getPredicate();
3836   Value *CmpLHS = CmpI->getOperand(0);
3837   Value *CmpRHS = CmpI->getOperand(1);
3838   Value *TrueVal = SI->getTrueValue();
3839   Value *FalseVal = SI->getFalseValue();
3840   FastMathFlags FMF;
3841   if (isa<FPMathOperator>(CmpI))
3842     FMF = CmpI->getFastMathFlags();
3843 
3844   // Bail out early.
3845   if (CmpI->isEquality())
3846     return {SPF_UNKNOWN, SPNB_NA, false};
3847 
3848   // Deal with type mismatches.
3849   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
3850     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
3851       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
3852                                   cast<CastInst>(TrueVal)->getOperand(0), C,
3853                                   LHS, RHS);
3854     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
3855       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
3856                                   C, cast<CastInst>(FalseVal)->getOperand(0),
3857                                   LHS, RHS);
3858   }
3859   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
3860                               LHS, RHS);
3861 }
3862 
3863 ConstantRange llvm::getConstantRangeFromMetadata(MDNode &Ranges) {
3864   const unsigned NumRanges = Ranges.getNumOperands() / 2;
3865   assert(NumRanges >= 1 && "Must have at least one range!");
3866   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
3867 
3868   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
3869   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
3870 
3871   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
3872 
3873   for (unsigned i = 1; i < NumRanges; ++i) {
3874     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
3875     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
3876 
3877     // Note: unionWith will potentially create a range that contains values not
3878     // contained in any of the original N ranges.
3879     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
3880   }
3881 
3882   return CR;
3883 }
3884 
3885 /// Return true if "icmp Pred LHS RHS" is always true.
3886 static bool isTruePredicate(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
3887                             const DataLayout &DL, unsigned Depth,
3888                             AssumptionCache *AC, const Instruction *CxtI,
3889                             const DominatorTree *DT) {
3890   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
3891   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
3892     return true;
3893 
3894   switch (Pred) {
3895   default:
3896     return false;
3897 
3898   case CmpInst::ICMP_SLE: {
3899     const APInt *C;
3900 
3901     // LHS s<= LHS +_{nsw} C   if C >= 0
3902     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
3903       return !C->isNegative();
3904     return false;
3905   }
3906 
3907   case CmpInst::ICMP_ULE: {
3908     const APInt *C;
3909 
3910     // LHS u<= LHS +_{nuw} C   for any C
3911     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
3912       return true;
3913 
3914     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
3915     auto MatchNUWAddsToSameValue = [&](Value *A, Value *B, Value *&X,
3916                                        const APInt *&CA, const APInt *&CB) {
3917       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
3918           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
3919         return true;
3920 
3921       // If X & C == 0 then (X | C) == X +_{nuw} C
3922       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
3923           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
3924         unsigned BitWidth = CA->getBitWidth();
3925         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3926         computeKnownBits(X, KnownZero, KnownOne, DL, Depth + 1, AC, CxtI, DT);
3927 
3928         if ((KnownZero & *CA) == *CA && (KnownZero & *CB) == *CB)
3929           return true;
3930       }
3931 
3932       return false;
3933     };
3934 
3935     Value *X;
3936     const APInt *CLHS, *CRHS;
3937     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
3938       return CLHS->ule(*CRHS);
3939 
3940     return false;
3941   }
3942   }
3943 }
3944 
3945 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
3946 /// ALHS ARHS" is true.
3947 static bool isImpliedCondOperands(CmpInst::Predicate Pred, Value *ALHS,
3948                                   Value *ARHS, Value *BLHS, Value *BRHS,
3949                                   const DataLayout &DL, unsigned Depth,
3950                                   AssumptionCache *AC, const Instruction *CxtI,
3951                                   const DominatorTree *DT) {
3952   switch (Pred) {
3953   default:
3954     return false;
3955 
3956   case CmpInst::ICMP_SLT:
3957   case CmpInst::ICMP_SLE:
3958     return isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
3959                            DT) &&
3960            isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI,
3961                            DT);
3962 
3963   case CmpInst::ICMP_ULT:
3964   case CmpInst::ICMP_ULE:
3965     return isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
3966                            DT) &&
3967            isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI,
3968                            DT);
3969   }
3970 }
3971 
3972 bool llvm::isImpliedCondition(Value *LHS, Value *RHS, const DataLayout &DL,
3973                               unsigned Depth, AssumptionCache *AC,
3974                               const Instruction *CxtI,
3975                               const DominatorTree *DT) {
3976   assert(LHS->getType() == RHS->getType() && "mismatched type");
3977   Type *OpTy = LHS->getType();
3978   assert(OpTy->getScalarType()->isIntegerTy(1));
3979 
3980   // LHS ==> RHS by definition
3981   if (LHS == RHS) return true;
3982 
3983   if (OpTy->isVectorTy())
3984     // TODO: extending the code below to handle vectors
3985     return false;
3986   assert(OpTy->isIntegerTy(1) && "implied by above");
3987 
3988   ICmpInst::Predicate APred, BPred;
3989   Value *ALHS, *ARHS;
3990   Value *BLHS, *BRHS;
3991 
3992   if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
3993       !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
3994     return false;
3995 
3996   if (APred == BPred)
3997     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
3998                                  CxtI, DT);
3999 
4000   return false;
4001 }
4002