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