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