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