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