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