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