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