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