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