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