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