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