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