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