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