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