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