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