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