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::mayHaveNonDefUseDependency(const Instruction &I) {
4647   if (I.mayReadOrWriteMemory())
4648     // Memory dependency possible
4649     return true;
4650   if (!isSafeToSpeculativelyExecute(&I))
4651     // Can't move above a maythrow call or infinite loop.  Or if an
4652     // inalloca alloca, above a stacksave call.
4653     return true;
4654   if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4655     // 1) Can't reorder two inf-loop calls, even if readonly
4656     // 2) Also can't reorder an inf-loop call below a instruction which isn't
4657     //    safe to speculative execute.  (Inverse of above)
4658     return true;
4659   return false;
4660 }
4661 
4662 /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
4663 static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
4664   switch (OR) {
4665     case ConstantRange::OverflowResult::MayOverflow:
4666       return OverflowResult::MayOverflow;
4667     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
4668       return OverflowResult::AlwaysOverflowsLow;
4669     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
4670       return OverflowResult::AlwaysOverflowsHigh;
4671     case ConstantRange::OverflowResult::NeverOverflows:
4672       return OverflowResult::NeverOverflows;
4673   }
4674   llvm_unreachable("Unknown OverflowResult");
4675 }
4676 
4677 /// Combine constant ranges from computeConstantRange() and computeKnownBits().
4678 static ConstantRange computeConstantRangeIncludingKnownBits(
4679     const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4680     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4681     OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4682   KnownBits Known = computeKnownBits(
4683       V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4684   ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4685   ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4686   ConstantRange::PreferredRangeType RangeType =
4687       ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
4688   return CR1.intersectWith(CR2, RangeType);
4689 }
4690 
4691 OverflowResult llvm::computeOverflowForUnsignedMul(
4692     const Value *LHS, const Value *RHS, const DataLayout &DL,
4693     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4694     bool UseInstrInfo) {
4695   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4696                                         nullptr, UseInstrInfo);
4697   KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4698                                         nullptr, UseInstrInfo);
4699   ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4700   ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4701   return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
4702 }
4703 
4704 OverflowResult
4705 llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4706                                   const DataLayout &DL, AssumptionCache *AC,
4707                                   const Instruction *CxtI,
4708                                   const DominatorTree *DT, bool UseInstrInfo) {
4709   // Multiplying n * m significant bits yields a result of n + m significant
4710   // bits. If the total number of significant bits does not exceed the
4711   // result bit width (minus 1), there is no overflow.
4712   // This means if we have enough leading sign bits in the operands
4713   // we can guarantee that the result does not overflow.
4714   // Ref: "Hacker's Delight" by Henry Warren
4715   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4716 
4717   // Note that underestimating the number of sign bits gives a more
4718   // conservative answer.
4719   unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4720                       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4721 
4722   // First handle the easy case: if we have enough sign bits there's
4723   // definitely no overflow.
4724   if (SignBits > BitWidth + 1)
4725     return OverflowResult::NeverOverflows;
4726 
4727   // There are two ambiguous cases where there can be no overflow:
4728   //   SignBits == BitWidth + 1    and
4729   //   SignBits == BitWidth
4730   // The second case is difficult to check, therefore we only handle the
4731   // first case.
4732   if (SignBits == BitWidth + 1) {
4733     // It overflows only when both arguments are negative and the true
4734     // product is exactly the minimum negative number.
4735     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4736     // For simplicity we just check if at least one side is not negative.
4737     KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4738                                           nullptr, UseInstrInfo);
4739     KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4740                                           nullptr, UseInstrInfo);
4741     if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4742       return OverflowResult::NeverOverflows;
4743   }
4744   return OverflowResult::MayOverflow;
4745 }
4746 
4747 OverflowResult llvm::computeOverflowForUnsignedAdd(
4748     const Value *LHS, const Value *RHS, const DataLayout &DL,
4749     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4750     bool UseInstrInfo) {
4751   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4752       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4753       nullptr, UseInstrInfo);
4754   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4755       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4756       nullptr, UseInstrInfo);
4757   return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
4758 }
4759 
4760 static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4761                                                   const Value *RHS,
4762                                                   const AddOperator *Add,
4763                                                   const DataLayout &DL,
4764                                                   AssumptionCache *AC,
4765                                                   const Instruction *CxtI,
4766                                                   const DominatorTree *DT) {
4767   if (Add && Add->hasNoSignedWrap()) {
4768     return OverflowResult::NeverOverflows;
4769   }
4770 
4771   // If LHS and RHS each have at least two sign bits, the addition will look
4772   // like
4773   //
4774   // XX..... +
4775   // YY.....
4776   //
4777   // If the carry into the most significant position is 0, X and Y can't both
4778   // be 1 and therefore the carry out of the addition is also 0.
4779   //
4780   // If the carry into the most significant position is 1, X and Y can't both
4781   // be 0 and therefore the carry out of the addition is also 1.
4782   //
4783   // Since the carry into the most significant position is always equal to
4784   // the carry out of the addition, there is no signed overflow.
4785   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4786       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4787     return OverflowResult::NeverOverflows;
4788 
4789   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4790       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4791   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4792       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4793   OverflowResult OR =
4794       mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4795   if (OR != OverflowResult::MayOverflow)
4796     return OR;
4797 
4798   // The remaining code needs Add to be available. Early returns if not so.
4799   if (!Add)
4800     return OverflowResult::MayOverflow;
4801 
4802   // If the sign of Add is the same as at least one of the operands, this add
4803   // CANNOT overflow. If this can be determined from the known bits of the
4804   // operands the above signedAddMayOverflow() check will have already done so.
4805   // The only other way to improve on the known bits is from an assumption, so
4806   // call computeKnownBitsFromAssume() directly.
4807   bool LHSOrRHSKnownNonNegative =
4808       (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
4809   bool LHSOrRHSKnownNegative =
4810       (LHSRange.isAllNegative() || RHSRange.isAllNegative());
4811   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4812     KnownBits AddKnown(LHSRange.getBitWidth());
4813     computeKnownBitsFromAssume(
4814         Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
4815     if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4816         (AddKnown.isNegative() && LHSOrRHSKnownNegative))
4817       return OverflowResult::NeverOverflows;
4818   }
4819 
4820   return OverflowResult::MayOverflow;
4821 }
4822 
4823 OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
4824                                                    const Value *RHS,
4825                                                    const DataLayout &DL,
4826                                                    AssumptionCache *AC,
4827                                                    const Instruction *CxtI,
4828                                                    const DominatorTree *DT) {
4829   // Checking for conditions implied by dominating conditions may be expensive.
4830   // Limit it to usub_with_overflow calls for now.
4831   if (match(CxtI,
4832             m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value())))
4833     if (auto C =
4834             isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) {
4835       if (*C)
4836         return OverflowResult::NeverOverflows;
4837       return OverflowResult::AlwaysOverflowsLow;
4838     }
4839   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4840       LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4841   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4842       RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
4843   return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
4844 }
4845 
4846 OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
4847                                                  const Value *RHS,
4848                                                  const DataLayout &DL,
4849                                                  AssumptionCache *AC,
4850                                                  const Instruction *CxtI,
4851                                                  const DominatorTree *DT) {
4852   // If LHS and RHS each have at least two sign bits, the subtraction
4853   // cannot overflow.
4854   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4855       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4856     return OverflowResult::NeverOverflows;
4857 
4858   ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4859       LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4860   ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4861       RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4862   return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
4863 }
4864 
4865 bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
4866                                      const DominatorTree &DT) {
4867   SmallVector<const BranchInst *, 2> GuardingBranches;
4868   SmallVector<const ExtractValueInst *, 2> Results;
4869 
4870   for (const User *U : WO->users()) {
4871     if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4872       assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
4873 
4874       if (EVI->getIndices()[0] == 0)
4875         Results.push_back(EVI);
4876       else {
4877         assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
4878 
4879         for (const auto *U : EVI->users())
4880           if (const auto *B = dyn_cast<BranchInst>(U)) {
4881             assert(B->isConditional() && "How else is it using an i1?");
4882             GuardingBranches.push_back(B);
4883           }
4884       }
4885     } else {
4886       // We are using the aggregate directly in a way we don't want to analyze
4887       // here (storing it to a global, say).
4888       return false;
4889     }
4890   }
4891 
4892   auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
4893     BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
4894     if (!NoWrapEdge.isSingleEdge())
4895       return false;
4896 
4897     // Check if all users of the add are provably no-wrap.
4898     for (const auto *Result : Results) {
4899       // If the extractvalue itself is not executed on overflow, the we don't
4900       // need to check each use separately, since domination is transitive.
4901       if (DT.dominates(NoWrapEdge, Result->getParent()))
4902         continue;
4903 
4904       for (auto &RU : Result->uses())
4905         if (!DT.dominates(NoWrapEdge, RU))
4906           return false;
4907     }
4908 
4909     return true;
4910   };
4911 
4912   return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
4913 }
4914 
4915 static bool canCreateUndefOrPoison(const Operator *Op, bool PoisonOnly,
4916                                    bool ConsiderFlags) {
4917 
4918   if (ConsiderFlags && Op->hasPoisonGeneratingFlags())
4919     return true;
4920 
4921   unsigned Opcode = Op->getOpcode();
4922 
4923   // Check whether opcode is a poison/undef-generating operation
4924   switch (Opcode) {
4925   case Instruction::Shl:
4926   case Instruction::AShr:
4927   case Instruction::LShr: {
4928     // Shifts return poison if shiftwidth is larger than the bitwidth.
4929     if (auto *C = dyn_cast<Constant>(Op->getOperand(1))) {
4930       SmallVector<Constant *, 4> ShiftAmounts;
4931       if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
4932         unsigned NumElts = FVTy->getNumElements();
4933         for (unsigned i = 0; i < NumElts; ++i)
4934           ShiftAmounts.push_back(C->getAggregateElement(i));
4935       } else if (isa<ScalableVectorType>(C->getType()))
4936         return true; // Can't tell, just return true to be safe
4937       else
4938         ShiftAmounts.push_back(C);
4939 
4940       bool Safe = llvm::all_of(ShiftAmounts, [](Constant *C) {
4941         auto *CI = dyn_cast_or_null<ConstantInt>(C);
4942         return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
4943       });
4944       return !Safe;
4945     }
4946     return true;
4947   }
4948   case Instruction::FPToSI:
4949   case Instruction::FPToUI:
4950     // fptosi/ui yields poison if the resulting value does not fit in the
4951     // destination type.
4952     return true;
4953   case Instruction::Call:
4954     if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
4955       switch (II->getIntrinsicID()) {
4956       // TODO: Add more intrinsics.
4957       case Intrinsic::ctpop:
4958       case Intrinsic::sadd_with_overflow:
4959       case Intrinsic::ssub_with_overflow:
4960       case Intrinsic::smul_with_overflow:
4961       case Intrinsic::uadd_with_overflow:
4962       case Intrinsic::usub_with_overflow:
4963       case Intrinsic::umul_with_overflow:
4964         return false;
4965       }
4966     }
4967     LLVM_FALLTHROUGH;
4968   case Instruction::CallBr:
4969   case Instruction::Invoke: {
4970     const auto *CB = cast<CallBase>(Op);
4971     return !CB->hasRetAttr(Attribute::NoUndef);
4972   }
4973   case Instruction::InsertElement:
4974   case Instruction::ExtractElement: {
4975     // If index exceeds the length of the vector, it returns poison
4976     auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
4977     unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
4978     auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
4979     if (!Idx || Idx->getValue().uge(VTy->getElementCount().getKnownMinValue()))
4980       return true;
4981     return false;
4982   }
4983   case Instruction::ShuffleVector: {
4984     // shufflevector may return undef.
4985     if (PoisonOnly)
4986       return false;
4987     ArrayRef<int> Mask = isa<ConstantExpr>(Op)
4988                              ? cast<ConstantExpr>(Op)->getShuffleMask()
4989                              : cast<ShuffleVectorInst>(Op)->getShuffleMask();
4990     return is_contained(Mask, UndefMaskElem);
4991   }
4992   case Instruction::FNeg:
4993   case Instruction::PHI:
4994   case Instruction::Select:
4995   case Instruction::URem:
4996   case Instruction::SRem:
4997   case Instruction::ExtractValue:
4998   case Instruction::InsertValue:
4999   case Instruction::Freeze:
5000   case Instruction::ICmp:
5001   case Instruction::FCmp:
5002     return false;
5003   case Instruction::GetElementPtr:
5004     // inbounds is handled above
5005     // TODO: what about inrange on constexpr?
5006     return false;
5007   default: {
5008     const auto *CE = dyn_cast<ConstantExpr>(Op);
5009     if (isa<CastInst>(Op) || (CE && CE->isCast()))
5010       return false;
5011     else if (Instruction::isBinaryOp(Opcode))
5012       return false;
5013     // Be conservative and return true.
5014     return true;
5015   }
5016   }
5017 }
5018 
5019 bool llvm::canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlags) {
5020   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/false, ConsiderFlags);
5021 }
5022 
5023 bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlags) {
5024   return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/true, ConsiderFlags);
5025 }
5026 
5027 static bool directlyImpliesPoison(const Value *ValAssumedPoison,
5028                                   const Value *V, unsigned Depth) {
5029   if (ValAssumedPoison == V)
5030     return true;
5031 
5032   const unsigned MaxDepth = 2;
5033   if (Depth >= MaxDepth)
5034     return false;
5035 
5036   if (const auto *I = dyn_cast<Instruction>(V)) {
5037     if (propagatesPoison(cast<Operator>(I)))
5038       return any_of(I->operands(), [=](const Value *Op) {
5039         return directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
5040       });
5041 
5042     // 'select ValAssumedPoison, _, _' is poison.
5043     if (const auto *SI = dyn_cast<SelectInst>(I))
5044       return directlyImpliesPoison(ValAssumedPoison, SI->getCondition(),
5045                                    Depth + 1);
5046     // V  = extractvalue V0, idx
5047     // V2 = extractvalue V0, idx2
5048     // V0's elements are all poison or not. (e.g., add_with_overflow)
5049     const WithOverflowInst *II;
5050     if (match(I, m_ExtractValue(m_WithOverflowInst(II))) &&
5051         (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
5052          llvm::is_contained(II->args(), ValAssumedPoison)))
5053       return true;
5054   }
5055   return false;
5056 }
5057 
5058 static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
5059                           unsigned Depth) {
5060   if (isGuaranteedNotToBeUndefOrPoison(ValAssumedPoison))
5061     return true;
5062 
5063   if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
5064     return true;
5065 
5066   const unsigned MaxDepth = 2;
5067   if (Depth >= MaxDepth)
5068     return false;
5069 
5070   const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
5071   if (I && !canCreatePoison(cast<Operator>(I))) {
5072     return all_of(I->operands(), [=](const Value *Op) {
5073       return impliesPoison(Op, V, Depth + 1);
5074     });
5075   }
5076   return false;
5077 }
5078 
5079 bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
5080   return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
5081 }
5082 
5083 static bool programUndefinedIfUndefOrPoison(const Value *V,
5084                                             bool PoisonOnly);
5085 
5086 static bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
5087                                              AssumptionCache *AC,
5088                                              const Instruction *CtxI,
5089                                              const DominatorTree *DT,
5090                                              unsigned Depth, bool PoisonOnly) {
5091   if (Depth >= MaxAnalysisRecursionDepth)
5092     return false;
5093 
5094   if (isa<MetadataAsValue>(V))
5095     return false;
5096 
5097   if (const auto *A = dyn_cast<Argument>(V)) {
5098     if (A->hasAttribute(Attribute::NoUndef))
5099       return true;
5100   }
5101 
5102   if (auto *C = dyn_cast<Constant>(V)) {
5103     if (isa<UndefValue>(C))
5104       return PoisonOnly && !isa<PoisonValue>(C);
5105 
5106     if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(V) ||
5107         isa<ConstantPointerNull>(C) || isa<Function>(C))
5108       return true;
5109 
5110     if (C->getType()->isVectorTy() && !isa<ConstantExpr>(C))
5111       return (PoisonOnly ? !C->containsPoisonElement()
5112                          : !C->containsUndefOrPoisonElement()) &&
5113              !C->containsConstantExpression();
5114   }
5115 
5116   // Strip cast operations from a pointer value.
5117   // Note that stripPointerCastsSameRepresentation can strip off getelementptr
5118   // inbounds with zero offset. To guarantee that the result isn't poison, the
5119   // stripped pointer is checked as it has to be pointing into an allocated
5120   // object or be null `null` to ensure `inbounds` getelement pointers with a
5121   // zero offset could not produce poison.
5122   // It can strip off addrspacecast that do not change bit representation as
5123   // well. We believe that such addrspacecast is equivalent to no-op.
5124   auto *StrippedV = V->stripPointerCastsSameRepresentation();
5125   if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
5126       isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
5127     return true;
5128 
5129   auto OpCheck = [&](const Value *V) {
5130     return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1,
5131                                             PoisonOnly);
5132   };
5133 
5134   if (auto *Opr = dyn_cast<Operator>(V)) {
5135     // If the value is a freeze instruction, then it can never
5136     // be undef or poison.
5137     if (isa<FreezeInst>(V))
5138       return true;
5139 
5140     if (const auto *CB = dyn_cast<CallBase>(V)) {
5141       if (CB->hasRetAttr(Attribute::NoUndef))
5142         return true;
5143     }
5144 
5145     if (const auto *PN = dyn_cast<PHINode>(V)) {
5146       unsigned Num = PN->getNumIncomingValues();
5147       bool IsWellDefined = true;
5148       for (unsigned i = 0; i < Num; ++i) {
5149         auto *TI = PN->getIncomingBlock(i)->getTerminator();
5150         if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
5151                                               DT, Depth + 1, PoisonOnly)) {
5152           IsWellDefined = false;
5153           break;
5154         }
5155       }
5156       if (IsWellDefined)
5157         return true;
5158     } else if (!canCreateUndefOrPoison(Opr) && all_of(Opr->operands(), OpCheck))
5159       return true;
5160   }
5161 
5162   if (auto *I = dyn_cast<LoadInst>(V))
5163     if (I->getMetadata(LLVMContext::MD_noundef))
5164       return true;
5165 
5166   if (programUndefinedIfUndefOrPoison(V, PoisonOnly))
5167     return true;
5168 
5169   // CxtI may be null or a cloned instruction.
5170   if (!CtxI || !CtxI->getParent() || !DT)
5171     return false;
5172 
5173   auto *DNode = DT->getNode(CtxI->getParent());
5174   if (!DNode)
5175     // Unreachable block
5176     return false;
5177 
5178   // If V is used as a branch condition before reaching CtxI, V cannot be
5179   // undef or poison.
5180   //   br V, BB1, BB2
5181   // BB1:
5182   //   CtxI ; V cannot be undef or poison here
5183   auto *Dominator = DNode->getIDom();
5184   while (Dominator) {
5185     auto *TI = Dominator->getBlock()->getTerminator();
5186 
5187     Value *Cond = nullptr;
5188     if (auto BI = dyn_cast_or_null<BranchInst>(TI)) {
5189       if (BI->isConditional())
5190         Cond = BI->getCondition();
5191     } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
5192       Cond = SI->getCondition();
5193     }
5194 
5195     if (Cond) {
5196       if (Cond == V)
5197         return true;
5198       else if (PoisonOnly && isa<Operator>(Cond)) {
5199         // For poison, we can analyze further
5200         auto *Opr = cast<Operator>(Cond);
5201         if (propagatesPoison(Opr) && is_contained(Opr->operand_values(), V))
5202           return true;
5203       }
5204     }
5205 
5206     Dominator = Dominator->getIDom();
5207   }
5208 
5209   if (getKnowledgeValidInContext(V, {Attribute::NoUndef}, CtxI, DT, AC))
5210     return true;
5211 
5212   return false;
5213 }
5214 
5215 bool llvm::isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC,
5216                                             const Instruction *CtxI,
5217                                             const DominatorTree *DT,
5218                                             unsigned Depth) {
5219   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, false);
5220 }
5221 
5222 bool llvm::isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC,
5223                                      const Instruction *CtxI,
5224                                      const DominatorTree *DT, unsigned Depth) {
5225   return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, true);
5226 }
5227 
5228 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
5229                                                  const DataLayout &DL,
5230                                                  AssumptionCache *AC,
5231                                                  const Instruction *CxtI,
5232                                                  const DominatorTree *DT) {
5233   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
5234                                        Add, DL, AC, CxtI, DT);
5235 }
5236 
5237 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
5238                                                  const Value *RHS,
5239                                                  const DataLayout &DL,
5240                                                  AssumptionCache *AC,
5241                                                  const Instruction *CxtI,
5242                                                  const DominatorTree *DT) {
5243   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
5244 }
5245 
5246 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
5247   // Note: An atomic operation isn't guaranteed to return in a reasonable amount
5248   // of time because it's possible for another thread to interfere with it for an
5249   // arbitrary length of time, but programs aren't allowed to rely on that.
5250 
5251   // If there is no successor, then execution can't transfer to it.
5252   if (isa<ReturnInst>(I))
5253     return false;
5254   if (isa<UnreachableInst>(I))
5255     return false;
5256 
5257   // Note: Do not add new checks here; instead, change Instruction::mayThrow or
5258   // Instruction::willReturn.
5259   //
5260   // FIXME: Move this check into Instruction::willReturn.
5261   if (isa<CatchPadInst>(I)) {
5262     switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
5263     default:
5264       // A catchpad may invoke exception object constructors and such, which
5265       // in some languages can be arbitrary code, so be conservative by default.
5266       return false;
5267     case EHPersonality::CoreCLR:
5268       // For CoreCLR, it just involves a type test.
5269       return true;
5270     }
5271   }
5272 
5273   // An instruction that returns without throwing must transfer control flow
5274   // to a successor.
5275   return !I->mayThrow() && I->willReturn();
5276 }
5277 
5278 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
5279   // TODO: This is slightly conservative for invoke instruction since exiting
5280   // via an exception *is* normal control for them.
5281   for (const Instruction &I : *BB)
5282     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5283       return false;
5284   return true;
5285 }
5286 
5287 bool llvm::isGuaranteedToTransferExecutionToSuccessor(
5288    BasicBlock::const_iterator Begin, BasicBlock::const_iterator End,
5289    unsigned ScanLimit) {
5290   return isGuaranteedToTransferExecutionToSuccessor(make_range(Begin, End),
5291                                                     ScanLimit);
5292 }
5293 
5294 bool llvm::isGuaranteedToTransferExecutionToSuccessor(
5295    iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit) {
5296   assert(ScanLimit && "scan limit must be non-zero");
5297   for (const Instruction &I : Range) {
5298     if (isa<DbgInfoIntrinsic>(I))
5299         continue;
5300     if (--ScanLimit == 0)
5301       return false;
5302     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5303       return false;
5304   }
5305   return true;
5306 }
5307 
5308 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
5309                                                   const Loop *L) {
5310   // The loop header is guaranteed to be executed for every iteration.
5311   //
5312   // FIXME: Relax this constraint to cover all basic blocks that are
5313   // guaranteed to be executed at every iteration.
5314   if (I->getParent() != L->getHeader()) return false;
5315 
5316   for (const Instruction &LI : *L->getHeader()) {
5317     if (&LI == I) return true;
5318     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
5319   }
5320   llvm_unreachable("Instruction not contained in its own parent basic block.");
5321 }
5322 
5323 bool llvm::propagatesPoison(const Operator *I) {
5324   switch (I->getOpcode()) {
5325   case Instruction::Freeze:
5326   case Instruction::Select:
5327   case Instruction::PHI:
5328   case Instruction::Invoke:
5329     return false;
5330   case Instruction::Call:
5331     if (auto *II = dyn_cast<IntrinsicInst>(I)) {
5332       switch (II->getIntrinsicID()) {
5333       // TODO: Add more intrinsics.
5334       case Intrinsic::sadd_with_overflow:
5335       case Intrinsic::ssub_with_overflow:
5336       case Intrinsic::smul_with_overflow:
5337       case Intrinsic::uadd_with_overflow:
5338       case Intrinsic::usub_with_overflow:
5339       case Intrinsic::umul_with_overflow:
5340         // If an input is a vector containing a poison element, the
5341         // two output vectors (calculated results, overflow bits)'
5342         // corresponding lanes are poison.
5343         return true;
5344       case Intrinsic::ctpop:
5345         return true;
5346       }
5347     }
5348     return false;
5349   case Instruction::ICmp:
5350   case Instruction::FCmp:
5351   case Instruction::GetElementPtr:
5352     return true;
5353   default:
5354     if (isa<BinaryOperator>(I) || isa<UnaryOperator>(I) || isa<CastInst>(I))
5355       return true;
5356 
5357     // Be conservative and return false.
5358     return false;
5359   }
5360 }
5361 
5362 void llvm::getGuaranteedWellDefinedOps(
5363     const Instruction *I, SmallPtrSetImpl<const Value *> &Operands) {
5364   switch (I->getOpcode()) {
5365     case Instruction::Store:
5366       Operands.insert(cast<StoreInst>(I)->getPointerOperand());
5367       break;
5368 
5369     case Instruction::Load:
5370       Operands.insert(cast<LoadInst>(I)->getPointerOperand());
5371       break;
5372 
5373     // Since dereferenceable attribute imply noundef, atomic operations
5374     // also implicitly have noundef pointers too
5375     case Instruction::AtomicCmpXchg:
5376       Operands.insert(cast<AtomicCmpXchgInst>(I)->getPointerOperand());
5377       break;
5378 
5379     case Instruction::AtomicRMW:
5380       Operands.insert(cast<AtomicRMWInst>(I)->getPointerOperand());
5381       break;
5382 
5383     case Instruction::Call:
5384     case Instruction::Invoke: {
5385       const CallBase *CB = cast<CallBase>(I);
5386       if (CB->isIndirectCall())
5387         Operands.insert(CB->getCalledOperand());
5388       for (unsigned i = 0; i < CB->arg_size(); ++i) {
5389         if (CB->paramHasAttr(i, Attribute::NoUndef) ||
5390             CB->paramHasAttr(i, Attribute::Dereferenceable))
5391           Operands.insert(CB->getArgOperand(i));
5392       }
5393       break;
5394     }
5395     case Instruction::Ret:
5396       if (I->getFunction()->hasRetAttribute(Attribute::NoUndef))
5397         Operands.insert(I->getOperand(0));
5398       break;
5399     default:
5400       break;
5401   }
5402 }
5403 
5404 void llvm::getGuaranteedNonPoisonOps(const Instruction *I,
5405                                      SmallPtrSetImpl<const Value *> &Operands) {
5406   getGuaranteedWellDefinedOps(I, Operands);
5407   switch (I->getOpcode()) {
5408   // Divisors of these operations are allowed to be partially undef.
5409   case Instruction::UDiv:
5410   case Instruction::SDiv:
5411   case Instruction::URem:
5412   case Instruction::SRem:
5413     Operands.insert(I->getOperand(1));
5414     break;
5415   case Instruction::Switch:
5416     if (BranchOnPoisonAsUB)
5417       Operands.insert(cast<SwitchInst>(I)->getCondition());
5418     break;
5419   case Instruction::Br: {
5420     auto *BR = cast<BranchInst>(I);
5421     if (BranchOnPoisonAsUB && BR->isConditional())
5422       Operands.insert(BR->getCondition());
5423     break;
5424   }
5425   default:
5426     break;
5427   }
5428 }
5429 
5430 bool llvm::mustTriggerUB(const Instruction *I,
5431                          const SmallSet<const Value *, 16>& KnownPoison) {
5432   SmallPtrSet<const Value *, 4> NonPoisonOps;
5433   getGuaranteedNonPoisonOps(I, NonPoisonOps);
5434 
5435   for (const auto *V : NonPoisonOps)
5436     if (KnownPoison.count(V))
5437       return true;
5438 
5439   return false;
5440 }
5441 
5442 static bool programUndefinedIfUndefOrPoison(const Value *V,
5443                                             bool PoisonOnly) {
5444   // We currently only look for uses of values within the same basic
5445   // block, as that makes it easier to guarantee that the uses will be
5446   // executed given that Inst is executed.
5447   //
5448   // FIXME: Expand this to consider uses beyond the same basic block. To do
5449   // this, look out for the distinction between post-dominance and strong
5450   // post-dominance.
5451   const BasicBlock *BB = nullptr;
5452   BasicBlock::const_iterator Begin;
5453   if (const auto *Inst = dyn_cast<Instruction>(V)) {
5454     BB = Inst->getParent();
5455     Begin = Inst->getIterator();
5456     Begin++;
5457   } else if (const auto *Arg = dyn_cast<Argument>(V)) {
5458     BB = &Arg->getParent()->getEntryBlock();
5459     Begin = BB->begin();
5460   } else {
5461     return false;
5462   }
5463 
5464   // Limit number of instructions we look at, to avoid scanning through large
5465   // blocks. The current limit is chosen arbitrarily.
5466   unsigned ScanLimit = 32;
5467   BasicBlock::const_iterator End = BB->end();
5468 
5469   if (!PoisonOnly) {
5470     // Since undef does not propagate eagerly, be conservative & just check
5471     // whether a value is directly passed to an instruction that must take
5472     // well-defined operands.
5473 
5474     for (auto &I : make_range(Begin, End)) {
5475       if (isa<DbgInfoIntrinsic>(I))
5476         continue;
5477       if (--ScanLimit == 0)
5478         break;
5479 
5480       SmallPtrSet<const Value *, 4> WellDefinedOps;
5481       getGuaranteedWellDefinedOps(&I, WellDefinedOps);
5482       if (WellDefinedOps.contains(V))
5483         return true;
5484 
5485       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5486         break;
5487     }
5488     return false;
5489   }
5490 
5491   // Set of instructions that we have proved will yield poison if Inst
5492   // does.
5493   SmallSet<const Value *, 16> YieldsPoison;
5494   SmallSet<const BasicBlock *, 4> Visited;
5495 
5496   YieldsPoison.insert(V);
5497   auto Propagate = [&](const User *User) {
5498     if (propagatesPoison(cast<Operator>(User)))
5499       YieldsPoison.insert(User);
5500   };
5501   for_each(V->users(), Propagate);
5502   Visited.insert(BB);
5503 
5504   while (true) {
5505     for (auto &I : make_range(Begin, End)) {
5506       if (isa<DbgInfoIntrinsic>(I))
5507         continue;
5508       if (--ScanLimit == 0)
5509         return false;
5510       if (mustTriggerUB(&I, YieldsPoison))
5511         return true;
5512       if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5513         return false;
5514 
5515       // Mark poison that propagates from I through uses of I.
5516       if (YieldsPoison.count(&I))
5517         for_each(I.users(), Propagate);
5518     }
5519 
5520     BB = BB->getSingleSuccessor();
5521     if (!BB || !Visited.insert(BB).second)
5522       break;
5523 
5524     Begin = BB->getFirstNonPHI()->getIterator();
5525     End = BB->end();
5526   }
5527   return false;
5528 }
5529 
5530 bool llvm::programUndefinedIfUndefOrPoison(const Instruction *Inst) {
5531   return ::programUndefinedIfUndefOrPoison(Inst, false);
5532 }
5533 
5534 bool llvm::programUndefinedIfPoison(const Instruction *Inst) {
5535   return ::programUndefinedIfUndefOrPoison(Inst, true);
5536 }
5537 
5538 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
5539   if (FMF.noNaNs())
5540     return true;
5541 
5542   if (auto *C = dyn_cast<ConstantFP>(V))
5543     return !C->isNaN();
5544 
5545   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
5546     if (!C->getElementType()->isFloatingPointTy())
5547       return false;
5548     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
5549       if (C->getElementAsAPFloat(I).isNaN())
5550         return false;
5551     }
5552     return true;
5553   }
5554 
5555   if (isa<ConstantAggregateZero>(V))
5556     return true;
5557 
5558   return false;
5559 }
5560 
5561 static bool isKnownNonZero(const Value *V) {
5562   if (auto *C = dyn_cast<ConstantFP>(V))
5563     return !C->isZero();
5564 
5565   if (auto *C = dyn_cast<ConstantDataVector>(V)) {
5566     if (!C->getElementType()->isFloatingPointTy())
5567       return false;
5568     for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
5569       if (C->getElementAsAPFloat(I).isZero())
5570         return false;
5571     }
5572     return true;
5573   }
5574 
5575   return false;
5576 }
5577 
5578 /// Match clamp pattern for float types without care about NaNs or signed zeros.
5579 /// Given non-min/max outer cmp/select from the clamp pattern this
5580 /// function recognizes if it can be substitued by a "canonical" min/max
5581 /// pattern.
5582 static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
5583                                                Value *CmpLHS, Value *CmpRHS,
5584                                                Value *TrueVal, Value *FalseVal,
5585                                                Value *&LHS, Value *&RHS) {
5586   // Try to match
5587   //   X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
5588   //   X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
5589   // and return description of the outer Max/Min.
5590 
5591   // First, check if select has inverse order:
5592   if (CmpRHS == FalseVal) {
5593     std::swap(TrueVal, FalseVal);
5594     Pred = CmpInst::getInversePredicate(Pred);
5595   }
5596 
5597   // Assume success now. If there's no match, callers should not use these anyway.
5598   LHS = TrueVal;
5599   RHS = FalseVal;
5600 
5601   const APFloat *FC1;
5602   if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
5603     return {SPF_UNKNOWN, SPNB_NA, false};
5604 
5605   const APFloat *FC2;
5606   switch (Pred) {
5607   case CmpInst::FCMP_OLT:
5608   case CmpInst::FCMP_OLE:
5609   case CmpInst::FCMP_ULT:
5610   case CmpInst::FCMP_ULE:
5611     if (match(FalseVal,
5612               m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
5613                           m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5614         *FC1 < *FC2)
5615       return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
5616     break;
5617   case CmpInst::FCMP_OGT:
5618   case CmpInst::FCMP_OGE:
5619   case CmpInst::FCMP_UGT:
5620   case CmpInst::FCMP_UGE:
5621     if (match(FalseVal,
5622               m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
5623                           m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
5624         *FC1 > *FC2)
5625       return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
5626     break;
5627   default:
5628     break;
5629   }
5630 
5631   return {SPF_UNKNOWN, SPNB_NA, false};
5632 }
5633 
5634 /// Recognize variations of:
5635 ///   CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
5636 static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
5637                                       Value *CmpLHS, Value *CmpRHS,
5638                                       Value *TrueVal, Value *FalseVal) {
5639   // Swap the select operands and predicate to match the patterns below.
5640   if (CmpRHS != TrueVal) {
5641     Pred = ICmpInst::getSwappedPredicate(Pred);
5642     std::swap(TrueVal, FalseVal);
5643   }
5644   const APInt *C1;
5645   if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
5646     const APInt *C2;
5647     // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
5648     if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
5649         C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
5650       return {SPF_SMAX, SPNB_NA, false};
5651 
5652     // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
5653     if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
5654         C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
5655       return {SPF_SMIN, SPNB_NA, false};
5656 
5657     // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
5658     if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
5659         C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
5660       return {SPF_UMAX, SPNB_NA, false};
5661 
5662     // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
5663     if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
5664         C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
5665       return {SPF_UMIN, SPNB_NA, false};
5666   }
5667   return {SPF_UNKNOWN, SPNB_NA, false};
5668 }
5669 
5670 /// Recognize variations of:
5671 ///   a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
5672 static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
5673                                                Value *CmpLHS, Value *CmpRHS,
5674                                                Value *TVal, Value *FVal,
5675                                                unsigned Depth) {
5676   // TODO: Allow FP min/max with nnan/nsz.
5677   assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
5678 
5679   Value *A = nullptr, *B = nullptr;
5680   SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
5681   if (!SelectPatternResult::isMinOrMax(L.Flavor))
5682     return {SPF_UNKNOWN, SPNB_NA, false};
5683 
5684   Value *C = nullptr, *D = nullptr;
5685   SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
5686   if (L.Flavor != R.Flavor)
5687     return {SPF_UNKNOWN, SPNB_NA, false};
5688 
5689   // We have something like: x Pred y ? min(a, b) : min(c, d).
5690   // Try to match the compare to the min/max operations of the select operands.
5691   // First, make sure we have the right compare predicate.
5692   switch (L.Flavor) {
5693   case SPF_SMIN:
5694     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
5695       Pred = ICmpInst::getSwappedPredicate(Pred);
5696       std::swap(CmpLHS, CmpRHS);
5697     }
5698     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5699       break;
5700     return {SPF_UNKNOWN, SPNB_NA, false};
5701   case SPF_SMAX:
5702     if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
5703       Pred = ICmpInst::getSwappedPredicate(Pred);
5704       std::swap(CmpLHS, CmpRHS);
5705     }
5706     if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5707       break;
5708     return {SPF_UNKNOWN, SPNB_NA, false};
5709   case SPF_UMIN:
5710     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
5711       Pred = ICmpInst::getSwappedPredicate(Pred);
5712       std::swap(CmpLHS, CmpRHS);
5713     }
5714     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
5715       break;
5716     return {SPF_UNKNOWN, SPNB_NA, false};
5717   case SPF_UMAX:
5718     if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
5719       Pred = ICmpInst::getSwappedPredicate(Pred);
5720       std::swap(CmpLHS, CmpRHS);
5721     }
5722     if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
5723       break;
5724     return {SPF_UNKNOWN, SPNB_NA, false};
5725   default:
5726     return {SPF_UNKNOWN, SPNB_NA, false};
5727   }
5728 
5729   // If there is a common operand in the already matched min/max and the other
5730   // min/max operands match the compare operands (either directly or inverted),
5731   // then this is min/max of the same flavor.
5732 
5733   // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
5734   // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
5735   if (D == B) {
5736     if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
5737                                          match(A, m_Not(m_Specific(CmpRHS)))))
5738       return {L.Flavor, SPNB_NA, false};
5739   }
5740   // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
5741   // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
5742   if (C == B) {
5743     if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
5744                                          match(A, m_Not(m_Specific(CmpRHS)))))
5745       return {L.Flavor, SPNB_NA, false};
5746   }
5747   // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
5748   // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
5749   if (D == A) {
5750     if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
5751                                          match(B, m_Not(m_Specific(CmpRHS)))))
5752       return {L.Flavor, SPNB_NA, false};
5753   }
5754   // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
5755   // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
5756   if (C == A) {
5757     if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
5758                                          match(B, m_Not(m_Specific(CmpRHS)))))
5759       return {L.Flavor, SPNB_NA, false};
5760   }
5761 
5762   return {SPF_UNKNOWN, SPNB_NA, false};
5763 }
5764 
5765 /// If the input value is the result of a 'not' op, constant integer, or vector
5766 /// splat of a constant integer, return the bitwise-not source value.
5767 /// TODO: This could be extended to handle non-splat vector integer constants.
5768 static Value *getNotValue(Value *V) {
5769   Value *NotV;
5770   if (match(V, m_Not(m_Value(NotV))))
5771     return NotV;
5772 
5773   const APInt *C;
5774   if (match(V, m_APInt(C)))
5775     return ConstantInt::get(V->getType(), ~(*C));
5776 
5777   return nullptr;
5778 }
5779 
5780 /// Match non-obvious integer minimum and maximum sequences.
5781 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
5782                                        Value *CmpLHS, Value *CmpRHS,
5783                                        Value *TrueVal, Value *FalseVal,
5784                                        Value *&LHS, Value *&RHS,
5785                                        unsigned Depth) {
5786   // Assume success. If there's no match, callers should not use these anyway.
5787   LHS = TrueVal;
5788   RHS = FalseVal;
5789 
5790   SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
5791   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
5792     return SPR;
5793 
5794   SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
5795   if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
5796     return SPR;
5797 
5798   // Look through 'not' ops to find disguised min/max.
5799   // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
5800   // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
5801   if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
5802     switch (Pred) {
5803     case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
5804     case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
5805     case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
5806     case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
5807     default: break;
5808     }
5809   }
5810 
5811   // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
5812   // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
5813   if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
5814     switch (Pred) {
5815     case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
5816     case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
5817     case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
5818     case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
5819     default: break;
5820     }
5821   }
5822 
5823   if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
5824     return {SPF_UNKNOWN, SPNB_NA, false};
5825 
5826   const APInt *C1;
5827   if (!match(CmpRHS, m_APInt(C1)))
5828     return {SPF_UNKNOWN, SPNB_NA, false};
5829 
5830   // An unsigned min/max can be written with a signed compare.
5831   const APInt *C2;
5832   if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
5833       (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
5834     // Is the sign bit set?
5835     // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
5836     // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
5837     if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
5838       return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
5839 
5840     // Is the sign bit clear?
5841     // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
5842     // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
5843     if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
5844       return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
5845   }
5846 
5847   return {SPF_UNKNOWN, SPNB_NA, false};
5848 }
5849 
5850 bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) {
5851   assert(X && Y && "Invalid operand");
5852 
5853   // X = sub (0, Y) || X = sub nsw (0, Y)
5854   if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) ||
5855       (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y)))))
5856     return true;
5857 
5858   // Y = sub (0, X) || Y = sub nsw (0, X)
5859   if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) ||
5860       (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X)))))
5861     return true;
5862 
5863   // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
5864   Value *A, *B;
5865   return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
5866                         match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
5867          (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
5868                        match(Y, m_NSWSub(m_Specific(B), m_Specific(A)))));
5869 }
5870 
5871 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
5872                                               FastMathFlags FMF,
5873                                               Value *CmpLHS, Value *CmpRHS,
5874                                               Value *TrueVal, Value *FalseVal,
5875                                               Value *&LHS, Value *&RHS,
5876                                               unsigned Depth) {
5877   if (CmpInst::isFPPredicate(Pred)) {
5878     // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
5879     // 0.0 operand, set the compare's 0.0 operands to that same value for the
5880     // purpose of identifying min/max. Disregard vector constants with undefined
5881     // elements because those can not be back-propagated for analysis.
5882     Value *OutputZeroVal = nullptr;
5883     if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
5884         !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
5885       OutputZeroVal = TrueVal;
5886     else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
5887              !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
5888       OutputZeroVal = FalseVal;
5889 
5890     if (OutputZeroVal) {
5891       if (match(CmpLHS, m_AnyZeroFP()))
5892         CmpLHS = OutputZeroVal;
5893       if (match(CmpRHS, m_AnyZeroFP()))
5894         CmpRHS = OutputZeroVal;
5895     }
5896   }
5897 
5898   LHS = CmpLHS;
5899   RHS = CmpRHS;
5900 
5901   // Signed zero may return inconsistent results between implementations.
5902   //  (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
5903   //  minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
5904   // Therefore, we behave conservatively and only proceed if at least one of the
5905   // operands is known to not be zero or if we don't care about signed zero.
5906   switch (Pred) {
5907   default: break;
5908   // FIXME: Include OGT/OLT/UGT/ULT.
5909   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
5910   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
5911     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
5912         !isKnownNonZero(CmpRHS))
5913       return {SPF_UNKNOWN, SPNB_NA, false};
5914   }
5915 
5916   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
5917   bool Ordered = false;
5918 
5919   // When given one NaN and one non-NaN input:
5920   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
5921   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
5922   //     ordered comparison fails), which could be NaN or non-NaN.
5923   // so here we discover exactly what NaN behavior is required/accepted.
5924   if (CmpInst::isFPPredicate(Pred)) {
5925     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
5926     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
5927 
5928     if (LHSSafe && RHSSafe) {
5929       // Both operands are known non-NaN.
5930       NaNBehavior = SPNB_RETURNS_ANY;
5931     } else if (CmpInst::isOrdered(Pred)) {
5932       // An ordered comparison will return false when given a NaN, so it
5933       // returns the RHS.
5934       Ordered = true;
5935       if (LHSSafe)
5936         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
5937         NaNBehavior = SPNB_RETURNS_NAN;
5938       else if (RHSSafe)
5939         NaNBehavior = SPNB_RETURNS_OTHER;
5940       else
5941         // Completely unsafe.
5942         return {SPF_UNKNOWN, SPNB_NA, false};
5943     } else {
5944       Ordered = false;
5945       // An unordered comparison will return true when given a NaN, so it
5946       // returns the LHS.
5947       if (LHSSafe)
5948         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
5949         NaNBehavior = SPNB_RETURNS_OTHER;
5950       else if (RHSSafe)
5951         NaNBehavior = SPNB_RETURNS_NAN;
5952       else
5953         // Completely unsafe.
5954         return {SPF_UNKNOWN, SPNB_NA, false};
5955     }
5956   }
5957 
5958   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
5959     std::swap(CmpLHS, CmpRHS);
5960     Pred = CmpInst::getSwappedPredicate(Pred);
5961     if (NaNBehavior == SPNB_RETURNS_NAN)
5962       NaNBehavior = SPNB_RETURNS_OTHER;
5963     else if (NaNBehavior == SPNB_RETURNS_OTHER)
5964       NaNBehavior = SPNB_RETURNS_NAN;
5965     Ordered = !Ordered;
5966   }
5967 
5968   // ([if]cmp X, Y) ? X : Y
5969   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
5970     switch (Pred) {
5971     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
5972     case ICmpInst::ICMP_UGT:
5973     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
5974     case ICmpInst::ICMP_SGT:
5975     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
5976     case ICmpInst::ICMP_ULT:
5977     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
5978     case ICmpInst::ICMP_SLT:
5979     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
5980     case FCmpInst::FCMP_UGT:
5981     case FCmpInst::FCMP_UGE:
5982     case FCmpInst::FCMP_OGT:
5983     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
5984     case FCmpInst::FCMP_ULT:
5985     case FCmpInst::FCMP_ULE:
5986     case FCmpInst::FCMP_OLT:
5987     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
5988     }
5989   }
5990 
5991   if (isKnownNegation(TrueVal, FalseVal)) {
5992     // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
5993     // match against either LHS or sext(LHS).
5994     auto MaybeSExtCmpLHS =
5995         m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
5996     auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
5997     auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
5998     if (match(TrueVal, MaybeSExtCmpLHS)) {
5999       // Set the return values. If the compare uses the negated value (-X >s 0),
6000       // swap the return values because the negated value is always 'RHS'.
6001       LHS = TrueVal;
6002       RHS = FalseVal;
6003       if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
6004         std::swap(LHS, RHS);
6005 
6006       // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
6007       // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
6008       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
6009         return {SPF_ABS, SPNB_NA, false};
6010 
6011       // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
6012       if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
6013         return {SPF_ABS, SPNB_NA, false};
6014 
6015       // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
6016       // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
6017       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
6018         return {SPF_NABS, SPNB_NA, false};
6019     }
6020     else if (match(FalseVal, MaybeSExtCmpLHS)) {
6021       // Set the return values. If the compare uses the negated value (-X >s 0),
6022       // swap the return values because the negated value is always 'RHS'.
6023       LHS = FalseVal;
6024       RHS = TrueVal;
6025       if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
6026         std::swap(LHS, RHS);
6027 
6028       // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
6029       // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
6030       if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
6031         return {SPF_NABS, SPNB_NA, false};
6032 
6033       // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
6034       // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
6035       if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
6036         return {SPF_ABS, SPNB_NA, false};
6037     }
6038   }
6039 
6040   if (CmpInst::isIntPredicate(Pred))
6041     return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
6042 
6043   // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
6044   // may return either -0.0 or 0.0, so fcmp/select pair has stricter
6045   // semantics than minNum. Be conservative in such case.
6046   if (NaNBehavior != SPNB_RETURNS_ANY ||
6047       (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
6048        !isKnownNonZero(CmpRHS)))
6049     return {SPF_UNKNOWN, SPNB_NA, false};
6050 
6051   return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
6052 }
6053 
6054 /// Helps to match a select pattern in case of a type mismatch.
6055 ///
6056 /// The function processes the case when type of true and false values of a
6057 /// select instruction differs from type of the cmp instruction operands because
6058 /// of a cast instruction. The function checks if it is legal to move the cast
6059 /// operation after "select". If yes, it returns the new second value of
6060 /// "select" (with the assumption that cast is moved):
6061 /// 1. As operand of cast instruction when both values of "select" are same cast
6062 /// instructions.
6063 /// 2. As restored constant (by applying reverse cast operation) when the first
6064 /// value of the "select" is a cast operation and the second value is a
6065 /// constant.
6066 /// NOTE: We return only the new second value because the first value could be
6067 /// accessed as operand of cast instruction.
6068 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
6069                               Instruction::CastOps *CastOp) {
6070   auto *Cast1 = dyn_cast<CastInst>(V1);
6071   if (!Cast1)
6072     return nullptr;
6073 
6074   *CastOp = Cast1->getOpcode();
6075   Type *SrcTy = Cast1->getSrcTy();
6076   if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
6077     // If V1 and V2 are both the same cast from the same type, look through V1.
6078     if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
6079       return Cast2->getOperand(0);
6080     return nullptr;
6081   }
6082 
6083   auto *C = dyn_cast<Constant>(V2);
6084   if (!C)
6085     return nullptr;
6086 
6087   Constant *CastedTo = nullptr;
6088   switch (*CastOp) {
6089   case Instruction::ZExt:
6090     if (CmpI->isUnsigned())
6091       CastedTo = ConstantExpr::getTrunc(C, SrcTy);
6092     break;
6093   case Instruction::SExt:
6094     if (CmpI->isSigned())
6095       CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
6096     break;
6097   case Instruction::Trunc:
6098     Constant *CmpConst;
6099     if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
6100         CmpConst->getType() == SrcTy) {
6101       // Here we have the following case:
6102       //
6103       //   %cond = cmp iN %x, CmpConst
6104       //   %tr = trunc iN %x to iK
6105       //   %narrowsel = select i1 %cond, iK %t, iK C
6106       //
6107       // We can always move trunc after select operation:
6108       //
6109       //   %cond = cmp iN %x, CmpConst
6110       //   %widesel = select i1 %cond, iN %x, iN CmpConst
6111       //   %tr = trunc iN %widesel to iK
6112       //
6113       // Note that C could be extended in any way because we don't care about
6114       // upper bits after truncation. It can't be abs pattern, because it would
6115       // look like:
6116       //
6117       //   select i1 %cond, x, -x.
6118       //
6119       // So only min/max pattern could be matched. Such match requires widened C
6120       // == CmpConst. That is why set widened C = CmpConst, condition trunc
6121       // CmpConst == C is checked below.
6122       CastedTo = CmpConst;
6123     } else {
6124       CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
6125     }
6126     break;
6127   case Instruction::FPTrunc:
6128     CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
6129     break;
6130   case Instruction::FPExt:
6131     CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
6132     break;
6133   case Instruction::FPToUI:
6134     CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
6135     break;
6136   case Instruction::FPToSI:
6137     CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
6138     break;
6139   case Instruction::UIToFP:
6140     CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
6141     break;
6142   case Instruction::SIToFP:
6143     CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
6144     break;
6145   default:
6146     break;
6147   }
6148 
6149   if (!CastedTo)
6150     return nullptr;
6151 
6152   // Make sure the cast doesn't lose any information.
6153   Constant *CastedBack =
6154       ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
6155   if (CastedBack != C)
6156     return nullptr;
6157 
6158   return CastedTo;
6159 }
6160 
6161 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
6162                                              Instruction::CastOps *CastOp,
6163                                              unsigned Depth) {
6164   if (Depth >= MaxAnalysisRecursionDepth)
6165     return {SPF_UNKNOWN, SPNB_NA, false};
6166 
6167   SelectInst *SI = dyn_cast<SelectInst>(V);
6168   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
6169 
6170   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
6171   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
6172 
6173   Value *TrueVal = SI->getTrueValue();
6174   Value *FalseVal = SI->getFalseValue();
6175 
6176   return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
6177                                             CastOp, Depth);
6178 }
6179 
6180 SelectPatternResult llvm::matchDecomposedSelectPattern(
6181     CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
6182     Instruction::CastOps *CastOp, unsigned Depth) {
6183   CmpInst::Predicate Pred = CmpI->getPredicate();
6184   Value *CmpLHS = CmpI->getOperand(0);
6185   Value *CmpRHS = CmpI->getOperand(1);
6186   FastMathFlags FMF;
6187   if (isa<FPMathOperator>(CmpI))
6188     FMF = CmpI->getFastMathFlags();
6189 
6190   // Bail out early.
6191   if (CmpI->isEquality())
6192     return {SPF_UNKNOWN, SPNB_NA, false};
6193 
6194   // Deal with type mismatches.
6195   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
6196     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
6197       // If this is a potential fmin/fmax with a cast to integer, then ignore
6198       // -0.0 because there is no corresponding integer value.
6199       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
6200         FMF.setNoSignedZeros();
6201       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
6202                                   cast<CastInst>(TrueVal)->getOperand(0), C,
6203                                   LHS, RHS, Depth);
6204     }
6205     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
6206       // If this is a potential fmin/fmax with a cast to integer, then ignore
6207       // -0.0 because there is no corresponding integer value.
6208       if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
6209         FMF.setNoSignedZeros();
6210       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
6211                                   C, cast<CastInst>(FalseVal)->getOperand(0),
6212                                   LHS, RHS, Depth);
6213     }
6214   }
6215   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
6216                               LHS, RHS, Depth);
6217 }
6218 
6219 CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) {
6220   if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
6221   if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
6222   if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
6223   if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
6224   if (SPF == SPF_FMINNUM)
6225     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
6226   if (SPF == SPF_FMAXNUM)
6227     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
6228   llvm_unreachable("unhandled!");
6229 }
6230 
6231 SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) {
6232   if (SPF == SPF_SMIN) return SPF_SMAX;
6233   if (SPF == SPF_UMIN) return SPF_UMAX;
6234   if (SPF == SPF_SMAX) return SPF_SMIN;
6235   if (SPF == SPF_UMAX) return SPF_UMIN;
6236   llvm_unreachable("unhandled!");
6237 }
6238 
6239 Intrinsic::ID llvm::getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID) {
6240   switch (MinMaxID) {
6241   case Intrinsic::smax: return Intrinsic::smin;
6242   case Intrinsic::smin: return Intrinsic::smax;
6243   case Intrinsic::umax: return Intrinsic::umin;
6244   case Intrinsic::umin: return Intrinsic::umax;
6245   default: llvm_unreachable("Unexpected intrinsic");
6246   }
6247 }
6248 
6249 CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) {
6250   return getMinMaxPred(getInverseMinMaxFlavor(SPF));
6251 }
6252 
6253 APInt llvm::getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth) {
6254   switch (SPF) {
6255   case SPF_SMAX: return APInt::getSignedMaxValue(BitWidth);
6256   case SPF_SMIN: return APInt::getSignedMinValue(BitWidth);
6257   case SPF_UMAX: return APInt::getMaxValue(BitWidth);
6258   case SPF_UMIN: return APInt::getMinValue(BitWidth);
6259   default: llvm_unreachable("Unexpected flavor");
6260   }
6261 }
6262 
6263 std::pair<Intrinsic::ID, bool>
6264 llvm::canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL) {
6265   // Check if VL contains select instructions that can be folded into a min/max
6266   // vector intrinsic and return the intrinsic if it is possible.
6267   // TODO: Support floating point min/max.
6268   bool AllCmpSingleUse = true;
6269   SelectPatternResult SelectPattern;
6270   SelectPattern.Flavor = SPF_UNKNOWN;
6271   if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
6272         Value *LHS, *RHS;
6273         auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
6274         if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor) ||
6275             CurrentPattern.Flavor == SPF_FMINNUM ||
6276             CurrentPattern.Flavor == SPF_FMAXNUM ||
6277             !I->getType()->isIntOrIntVectorTy())
6278           return false;
6279         if (SelectPattern.Flavor != SPF_UNKNOWN &&
6280             SelectPattern.Flavor != CurrentPattern.Flavor)
6281           return false;
6282         SelectPattern = CurrentPattern;
6283         AllCmpSingleUse &=
6284             match(I, m_Select(m_OneUse(m_Value()), m_Value(), m_Value()));
6285         return true;
6286       })) {
6287     switch (SelectPattern.Flavor) {
6288     case SPF_SMIN:
6289       return {Intrinsic::smin, AllCmpSingleUse};
6290     case SPF_UMIN:
6291       return {Intrinsic::umin, AllCmpSingleUse};
6292     case SPF_SMAX:
6293       return {Intrinsic::smax, AllCmpSingleUse};
6294     case SPF_UMAX:
6295       return {Intrinsic::umax, AllCmpSingleUse};
6296     default:
6297       llvm_unreachable("unexpected select pattern flavor");
6298     }
6299   }
6300   return {Intrinsic::not_intrinsic, false};
6301 }
6302 
6303 bool llvm::matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
6304                                  Value *&Start, Value *&Step) {
6305   // Handle the case of a simple two-predecessor recurrence PHI.
6306   // There's a lot more that could theoretically be done here, but
6307   // this is sufficient to catch some interesting cases.
6308   if (P->getNumIncomingValues() != 2)
6309     return false;
6310 
6311   for (unsigned i = 0; i != 2; ++i) {
6312     Value *L = P->getIncomingValue(i);
6313     Value *R = P->getIncomingValue(!i);
6314     Operator *LU = dyn_cast<Operator>(L);
6315     if (!LU)
6316       continue;
6317     unsigned Opcode = LU->getOpcode();
6318 
6319     switch (Opcode) {
6320     default:
6321       continue;
6322     // TODO: Expand list -- xor, div, gep, uaddo, etc..
6323     case Instruction::LShr:
6324     case Instruction::AShr:
6325     case Instruction::Shl:
6326     case Instruction::Add:
6327     case Instruction::Sub:
6328     case Instruction::And:
6329     case Instruction::Or:
6330     case Instruction::Mul: {
6331       Value *LL = LU->getOperand(0);
6332       Value *LR = LU->getOperand(1);
6333       // Find a recurrence.
6334       if (LL == P)
6335         L = LR;
6336       else if (LR == P)
6337         L = LL;
6338       else
6339         continue; // Check for recurrence with L and R flipped.
6340 
6341       break; // Match!
6342     }
6343     };
6344 
6345     // We have matched a recurrence of the form:
6346     //   %iv = [R, %entry], [%iv.next, %backedge]
6347     //   %iv.next = binop %iv, L
6348     // OR
6349     //   %iv = [R, %entry], [%iv.next, %backedge]
6350     //   %iv.next = binop L, %iv
6351     BO = cast<BinaryOperator>(LU);
6352     Start = R;
6353     Step = L;
6354     return true;
6355   }
6356   return false;
6357 }
6358 
6359 bool llvm::matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
6360                                  Value *&Start, Value *&Step) {
6361   BinaryOperator *BO = nullptr;
6362   P = dyn_cast<PHINode>(I->getOperand(0));
6363   if (!P)
6364     P = dyn_cast<PHINode>(I->getOperand(1));
6365   return P && matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
6366 }
6367 
6368 /// Return true if "icmp Pred LHS RHS" is always true.
6369 static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
6370                             const Value *RHS, const DataLayout &DL,
6371                             unsigned Depth) {
6372   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
6373   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
6374     return true;
6375 
6376   switch (Pred) {
6377   default:
6378     return false;
6379 
6380   case CmpInst::ICMP_SLE: {
6381     const APInt *C;
6382 
6383     // LHS s<= LHS +_{nsw} C   if C >= 0
6384     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
6385       return !C->isNegative();
6386     return false;
6387   }
6388 
6389   case CmpInst::ICMP_ULE: {
6390     const APInt *C;
6391 
6392     // LHS u<= LHS +_{nuw} C   for any C
6393     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
6394       return true;
6395 
6396     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
6397     auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
6398                                        const Value *&X,
6399                                        const APInt *&CA, const APInt *&CB) {
6400       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
6401           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
6402         return true;
6403 
6404       // If X & C == 0 then (X | C) == X +_{nuw} C
6405       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
6406           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
6407         KnownBits Known(CA->getBitWidth());
6408         computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
6409                          /*CxtI*/ nullptr, /*DT*/ nullptr);
6410         if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
6411           return true;
6412       }
6413 
6414       return false;
6415     };
6416 
6417     const Value *X;
6418     const APInt *CLHS, *CRHS;
6419     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
6420       return CLHS->ule(*CRHS);
6421 
6422     return false;
6423   }
6424   }
6425 }
6426 
6427 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
6428 /// ALHS ARHS" is true.  Otherwise, return None.
6429 static Optional<bool>
6430 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
6431                       const Value *ARHS, const Value *BLHS, const Value *BRHS,
6432                       const DataLayout &DL, unsigned Depth) {
6433   switch (Pred) {
6434   default:
6435     return None;
6436 
6437   case CmpInst::ICMP_SLT:
6438   case CmpInst::ICMP_SLE:
6439     if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
6440         isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
6441       return true;
6442     return None;
6443 
6444   case CmpInst::ICMP_ULT:
6445   case CmpInst::ICMP_ULE:
6446     if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
6447         isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
6448       return true;
6449     return None;
6450   }
6451 }
6452 
6453 /// Return true if the operands of the two compares match.  IsSwappedOps is true
6454 /// when the operands match, but are swapped.
6455 static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
6456                           const Value *BLHS, const Value *BRHS,
6457                           bool &IsSwappedOps) {
6458 
6459   bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
6460   IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
6461   return IsMatchingOps || IsSwappedOps;
6462 }
6463 
6464 /// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true.
6465 /// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false.
6466 /// Otherwise, return None if we can't infer anything.
6467 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
6468                                                     CmpInst::Predicate BPred,
6469                                                     bool AreSwappedOps) {
6470   // Canonicalize the predicate as if the operands were not commuted.
6471   if (AreSwappedOps)
6472     BPred = ICmpInst::getSwappedPredicate(BPred);
6473 
6474   if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
6475     return true;
6476   if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
6477     return false;
6478 
6479   return None;
6480 }
6481 
6482 /// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true.
6483 /// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false.
6484 /// Otherwise, return None if we can't infer anything.
6485 static Optional<bool>
6486 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred,
6487                                  const ConstantInt *C1,
6488                                  CmpInst::Predicate BPred,
6489                                  const ConstantInt *C2) {
6490   ConstantRange DomCR =
6491       ConstantRange::makeExactICmpRegion(APred, C1->getValue());
6492   ConstantRange CR = ConstantRange::makeExactICmpRegion(BPred, C2->getValue());
6493   ConstantRange Intersection = DomCR.intersectWith(CR);
6494   ConstantRange Difference = DomCR.difference(CR);
6495   if (Intersection.isEmptySet())
6496     return false;
6497   if (Difference.isEmptySet())
6498     return true;
6499   return None;
6500 }
6501 
6502 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
6503 /// false.  Otherwise, return None if we can't infer anything.
6504 static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
6505                                          CmpInst::Predicate BPred,
6506                                          const Value *BLHS, const Value *BRHS,
6507                                          const DataLayout &DL, bool LHSIsTrue,
6508                                          unsigned Depth) {
6509   Value *ALHS = LHS->getOperand(0);
6510   Value *ARHS = LHS->getOperand(1);
6511 
6512   // The rest of the logic assumes the LHS condition is true.  If that's not the
6513   // case, invert the predicate to make it so.
6514   CmpInst::Predicate APred =
6515       LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
6516 
6517   // Can we infer anything when the two compares have matching operands?
6518   bool AreSwappedOps;
6519   if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) {
6520     if (Optional<bool> Implication = isImpliedCondMatchingOperands(
6521             APred, BPred, AreSwappedOps))
6522       return Implication;
6523     // No amount of additional analysis will infer the second condition, so
6524     // early exit.
6525     return None;
6526   }
6527 
6528   // Can we infer anything when the LHS operands match and the RHS operands are
6529   // constants (not necessarily matching)?
6530   if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
6531     if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
6532             APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS)))
6533       return Implication;
6534     // No amount of additional analysis will infer the second condition, so
6535     // early exit.
6536     return None;
6537   }
6538 
6539   if (APred == BPred)
6540     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
6541   return None;
6542 }
6543 
6544 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
6545 /// false.  Otherwise, return None if we can't infer anything.  We expect the
6546 /// RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select' instruction.
6547 static Optional<bool>
6548 isImpliedCondAndOr(const Instruction *LHS, CmpInst::Predicate RHSPred,
6549                    const Value *RHSOp0, const Value *RHSOp1,
6550                    const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
6551   // The LHS must be an 'or', 'and', or a 'select' instruction.
6552   assert((LHS->getOpcode() == Instruction::And ||
6553           LHS->getOpcode() == Instruction::Or ||
6554           LHS->getOpcode() == Instruction::Select) &&
6555          "Expected LHS to be 'and', 'or', or 'select'.");
6556 
6557   assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
6558 
6559   // If the result of an 'or' is false, then we know both legs of the 'or' are
6560   // false.  Similarly, if the result of an 'and' is true, then we know both
6561   // legs of the 'and' are true.
6562   const Value *ALHS, *ARHS;
6563   if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
6564       (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
6565     // FIXME: Make this non-recursion.
6566     if (Optional<bool> Implication = isImpliedCondition(
6567             ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
6568       return Implication;
6569     if (Optional<bool> Implication = isImpliedCondition(
6570             ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
6571       return Implication;
6572     return None;
6573   }
6574   return None;
6575 }
6576 
6577 Optional<bool>
6578 llvm::isImpliedCondition(const Value *LHS, CmpInst::Predicate RHSPred,
6579                          const Value *RHSOp0, const Value *RHSOp1,
6580                          const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
6581   // Bail out when we hit the limit.
6582   if (Depth == MaxAnalysisRecursionDepth)
6583     return None;
6584 
6585   // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
6586   // example.
6587   if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
6588     return None;
6589 
6590   Type *OpTy = LHS->getType();
6591   assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
6592 
6593   // FIXME: Extending the code below to handle vectors.
6594   if (OpTy->isVectorTy())
6595     return None;
6596 
6597   assert(OpTy->isIntegerTy(1) && "implied by above");
6598 
6599   // Both LHS and RHS are icmps.
6600   const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
6601   if (LHSCmp)
6602     return isImpliedCondICmps(LHSCmp, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6603                               Depth);
6604 
6605   /// The LHS should be an 'or', 'and', or a 'select' instruction.  We expect
6606   /// the RHS to be an icmp.
6607   /// FIXME: Add support for and/or/select on the RHS.
6608   if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
6609     if ((LHSI->getOpcode() == Instruction::And ||
6610          LHSI->getOpcode() == Instruction::Or ||
6611          LHSI->getOpcode() == Instruction::Select))
6612       return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
6613                                 Depth);
6614   }
6615   return None;
6616 }
6617 
6618 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
6619                                         const DataLayout &DL, bool LHSIsTrue,
6620                                         unsigned Depth) {
6621   // LHS ==> RHS by definition
6622   if (LHS == RHS)
6623     return LHSIsTrue;
6624 
6625   const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
6626   if (RHSCmp)
6627     return isImpliedCondition(LHS, RHSCmp->getPredicate(),
6628                               RHSCmp->getOperand(0), RHSCmp->getOperand(1), DL,
6629                               LHSIsTrue, Depth);
6630   return None;
6631 }
6632 
6633 // Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
6634 // condition dominating ContextI or nullptr, if no condition is found.
6635 static std::pair<Value *, bool>
6636 getDomPredecessorCondition(const Instruction *ContextI) {
6637   if (!ContextI || !ContextI->getParent())
6638     return {nullptr, false};
6639 
6640   // TODO: This is a poor/cheap way to determine dominance. Should we use a
6641   // dominator tree (eg, from a SimplifyQuery) instead?
6642   const BasicBlock *ContextBB = ContextI->getParent();
6643   const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
6644   if (!PredBB)
6645     return {nullptr, false};
6646 
6647   // We need a conditional branch in the predecessor.
6648   Value *PredCond;
6649   BasicBlock *TrueBB, *FalseBB;
6650   if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
6651     return {nullptr, false};
6652 
6653   // The branch should get simplified. Don't bother simplifying this condition.
6654   if (TrueBB == FalseBB)
6655     return {nullptr, false};
6656 
6657   assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
6658          "Predecessor block does not point to successor?");
6659 
6660   // Is this condition implied by the predecessor condition?
6661   return {PredCond, TrueBB == ContextBB};
6662 }
6663 
6664 Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
6665                                              const Instruction *ContextI,
6666                                              const DataLayout &DL) {
6667   assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
6668   auto PredCond = getDomPredecessorCondition(ContextI);
6669   if (PredCond.first)
6670     return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
6671   return None;
6672 }
6673 
6674 Optional<bool> llvm::isImpliedByDomCondition(CmpInst::Predicate Pred,
6675                                              const Value *LHS, const Value *RHS,
6676                                              const Instruction *ContextI,
6677                                              const DataLayout &DL) {
6678   auto PredCond = getDomPredecessorCondition(ContextI);
6679   if (PredCond.first)
6680     return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
6681                               PredCond.second);
6682   return None;
6683 }
6684 
6685 static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
6686                               APInt &Upper, const InstrInfoQuery &IIQ,
6687                               bool PreferSignedRange) {
6688   unsigned Width = Lower.getBitWidth();
6689   const APInt *C;
6690   switch (BO.getOpcode()) {
6691   case Instruction::Add:
6692     if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
6693       bool HasNSW = IIQ.hasNoSignedWrap(&BO);
6694       bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
6695 
6696       // If the caller expects a signed compare, then try to use a signed range.
6697       // Otherwise if both no-wraps are set, use the unsigned range because it
6698       // is never larger than the signed range. Example:
6699       // "add nuw nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
6700       if (PreferSignedRange && HasNSW && HasNUW)
6701         HasNUW = false;
6702 
6703       if (HasNUW) {
6704         // 'add nuw x, C' produces [C, UINT_MAX].
6705         Lower = *C;
6706       } else if (HasNSW) {
6707         if (C->isNegative()) {
6708           // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
6709           Lower = APInt::getSignedMinValue(Width);
6710           Upper = APInt::getSignedMaxValue(Width) + *C + 1;
6711         } else {
6712           // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
6713           Lower = APInt::getSignedMinValue(Width) + *C;
6714           Upper = APInt::getSignedMaxValue(Width) + 1;
6715         }
6716       }
6717     }
6718     break;
6719 
6720   case Instruction::And:
6721     if (match(BO.getOperand(1), m_APInt(C)))
6722       // 'and x, C' produces [0, C].
6723       Upper = *C + 1;
6724     break;
6725 
6726   case Instruction::Or:
6727     if (match(BO.getOperand(1), m_APInt(C)))
6728       // 'or x, C' produces [C, UINT_MAX].
6729       Lower = *C;
6730     break;
6731 
6732   case Instruction::AShr:
6733     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
6734       // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
6735       Lower = APInt::getSignedMinValue(Width).ashr(*C);
6736       Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
6737     } else if (match(BO.getOperand(0), m_APInt(C))) {
6738       unsigned ShiftAmount = Width - 1;
6739       if (!C->isZero() && IIQ.isExact(&BO))
6740         ShiftAmount = C->countTrailingZeros();
6741       if (C->isNegative()) {
6742         // 'ashr C, x' produces [C, C >> (Width-1)]
6743         Lower = *C;
6744         Upper = C->ashr(ShiftAmount) + 1;
6745       } else {
6746         // 'ashr C, x' produces [C >> (Width-1), C]
6747         Lower = C->ashr(ShiftAmount);
6748         Upper = *C + 1;
6749       }
6750     }
6751     break;
6752 
6753   case Instruction::LShr:
6754     if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
6755       // 'lshr x, C' produces [0, UINT_MAX >> C].
6756       Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
6757     } else if (match(BO.getOperand(0), m_APInt(C))) {
6758       // 'lshr C, x' produces [C >> (Width-1), C].
6759       unsigned ShiftAmount = Width - 1;
6760       if (!C->isZero() && IIQ.isExact(&BO))
6761         ShiftAmount = C->countTrailingZeros();
6762       Lower = C->lshr(ShiftAmount);
6763       Upper = *C + 1;
6764     }
6765     break;
6766 
6767   case Instruction::Shl:
6768     if (match(BO.getOperand(0), m_APInt(C))) {
6769       if (IIQ.hasNoUnsignedWrap(&BO)) {
6770         // 'shl nuw C, x' produces [C, C << CLZ(C)]
6771         Lower = *C;
6772         Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
6773       } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
6774         if (C->isNegative()) {
6775           // 'shl nsw C, x' produces [C << CLO(C)-1, C]
6776           unsigned ShiftAmount = C->countLeadingOnes() - 1;
6777           Lower = C->shl(ShiftAmount);
6778           Upper = *C + 1;
6779         } else {
6780           // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
6781           unsigned ShiftAmount = C->countLeadingZeros() - 1;
6782           Lower = *C;
6783           Upper = C->shl(ShiftAmount) + 1;
6784         }
6785       }
6786     }
6787     break;
6788 
6789   case Instruction::SDiv:
6790     if (match(BO.getOperand(1), m_APInt(C))) {
6791       APInt IntMin = APInt::getSignedMinValue(Width);
6792       APInt IntMax = APInt::getSignedMaxValue(Width);
6793       if (C->isAllOnes()) {
6794         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
6795         //    where C != -1 and C != 0 and C != 1
6796         Lower = IntMin + 1;
6797         Upper = IntMax + 1;
6798       } else if (C->countLeadingZeros() < Width - 1) {
6799         // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
6800         //    where C != -1 and C != 0 and C != 1
6801         Lower = IntMin.sdiv(*C);
6802         Upper = IntMax.sdiv(*C);
6803         if (Lower.sgt(Upper))
6804           std::swap(Lower, Upper);
6805         Upper = Upper + 1;
6806         assert(Upper != Lower && "Upper part of range has wrapped!");
6807       }
6808     } else if (match(BO.getOperand(0), m_APInt(C))) {
6809       if (C->isMinSignedValue()) {
6810         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
6811         Lower = *C;
6812         Upper = Lower.lshr(1) + 1;
6813       } else {
6814         // 'sdiv C, x' produces [-|C|, |C|].
6815         Upper = C->abs() + 1;
6816         Lower = (-Upper) + 1;
6817       }
6818     }
6819     break;
6820 
6821   case Instruction::UDiv:
6822     if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
6823       // 'udiv x, C' produces [0, UINT_MAX / C].
6824       Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
6825     } else if (match(BO.getOperand(0), m_APInt(C))) {
6826       // 'udiv C, x' produces [0, C].
6827       Upper = *C + 1;
6828     }
6829     break;
6830 
6831   case Instruction::SRem:
6832     if (match(BO.getOperand(1), m_APInt(C))) {
6833       // 'srem x, C' produces (-|C|, |C|).
6834       Upper = C->abs();
6835       Lower = (-Upper) + 1;
6836     }
6837     break;
6838 
6839   case Instruction::URem:
6840     if (match(BO.getOperand(1), m_APInt(C)))
6841       // 'urem x, C' produces [0, C).
6842       Upper = *C;
6843     break;
6844 
6845   default:
6846     break;
6847   }
6848 }
6849 
6850 static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower,
6851                                   APInt &Upper) {
6852   unsigned Width = Lower.getBitWidth();
6853   const APInt *C;
6854   switch (II.getIntrinsicID()) {
6855   case Intrinsic::ctpop:
6856   case Intrinsic::ctlz:
6857   case Intrinsic::cttz:
6858     // Maximum of set/clear bits is the bit width.
6859     assert(Lower == 0 && "Expected lower bound to be zero");
6860     Upper = Width + 1;
6861     break;
6862   case Intrinsic::uadd_sat:
6863     // uadd.sat(x, C) produces [C, UINT_MAX].
6864     if (match(II.getOperand(0), m_APInt(C)) ||
6865         match(II.getOperand(1), m_APInt(C)))
6866       Lower = *C;
6867     break;
6868   case Intrinsic::sadd_sat:
6869     if (match(II.getOperand(0), m_APInt(C)) ||
6870         match(II.getOperand(1), m_APInt(C))) {
6871       if (C->isNegative()) {
6872         // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
6873         Lower = APInt::getSignedMinValue(Width);
6874         Upper = APInt::getSignedMaxValue(Width) + *C + 1;
6875       } else {
6876         // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
6877         Lower = APInt::getSignedMinValue(Width) + *C;
6878         Upper = APInt::getSignedMaxValue(Width) + 1;
6879       }
6880     }
6881     break;
6882   case Intrinsic::usub_sat:
6883     // usub.sat(C, x) produces [0, C].
6884     if (match(II.getOperand(0), m_APInt(C)))
6885       Upper = *C + 1;
6886     // usub.sat(x, C) produces [0, UINT_MAX - C].
6887     else if (match(II.getOperand(1), m_APInt(C)))
6888       Upper = APInt::getMaxValue(Width) - *C + 1;
6889     break;
6890   case Intrinsic::ssub_sat:
6891     if (match(II.getOperand(0), m_APInt(C))) {
6892       if (C->isNegative()) {
6893         // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
6894         Lower = APInt::getSignedMinValue(Width);
6895         Upper = *C - APInt::getSignedMinValue(Width) + 1;
6896       } else {
6897         // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
6898         Lower = *C - APInt::getSignedMaxValue(Width);
6899         Upper = APInt::getSignedMaxValue(Width) + 1;
6900       }
6901     } else if (match(II.getOperand(1), m_APInt(C))) {
6902       if (C->isNegative()) {
6903         // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
6904         Lower = APInt::getSignedMinValue(Width) - *C;
6905         Upper = APInt::getSignedMaxValue(Width) + 1;
6906       } else {
6907         // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
6908         Lower = APInt::getSignedMinValue(Width);
6909         Upper = APInt::getSignedMaxValue(Width) - *C + 1;
6910       }
6911     }
6912     break;
6913   case Intrinsic::umin:
6914   case Intrinsic::umax:
6915   case Intrinsic::smin:
6916   case Intrinsic::smax:
6917     if (!match(II.getOperand(0), m_APInt(C)) &&
6918         !match(II.getOperand(1), m_APInt(C)))
6919       break;
6920 
6921     switch (II.getIntrinsicID()) {
6922     case Intrinsic::umin:
6923       Upper = *C + 1;
6924       break;
6925     case Intrinsic::umax:
6926       Lower = *C;
6927       break;
6928     case Intrinsic::smin:
6929       Lower = APInt::getSignedMinValue(Width);
6930       Upper = *C + 1;
6931       break;
6932     case Intrinsic::smax:
6933       Lower = *C;
6934       Upper = APInt::getSignedMaxValue(Width) + 1;
6935       break;
6936     default:
6937       llvm_unreachable("Must be min/max intrinsic");
6938     }
6939     break;
6940   case Intrinsic::abs:
6941     // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
6942     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
6943     if (match(II.getOperand(1), m_One()))
6944       Upper = APInt::getSignedMaxValue(Width) + 1;
6945     else
6946       Upper = APInt::getSignedMinValue(Width) + 1;
6947     break;
6948   default:
6949     break;
6950   }
6951 }
6952 
6953 static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower,
6954                                       APInt &Upper, const InstrInfoQuery &IIQ) {
6955   const Value *LHS = nullptr, *RHS = nullptr;
6956   SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS);
6957   if (R.Flavor == SPF_UNKNOWN)
6958     return;
6959 
6960   unsigned BitWidth = SI.getType()->getScalarSizeInBits();
6961 
6962   if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
6963     // If the negation part of the abs (in RHS) has the NSW flag,
6964     // then the result of abs(X) is [0..SIGNED_MAX],
6965     // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
6966     Lower = APInt::getZero(BitWidth);
6967     if (match(RHS, m_Neg(m_Specific(LHS))) &&
6968         IIQ.hasNoSignedWrap(cast<Instruction>(RHS)))
6969       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
6970     else
6971       Upper = APInt::getSignedMinValue(BitWidth) + 1;
6972     return;
6973   }
6974 
6975   if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
6976     // The result of -abs(X) is <= 0.
6977     Lower = APInt::getSignedMinValue(BitWidth);
6978     Upper = APInt(BitWidth, 1);
6979     return;
6980   }
6981 
6982   const APInt *C;
6983   if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
6984     return;
6985 
6986   switch (R.Flavor) {
6987     case SPF_UMIN:
6988       Upper = *C + 1;
6989       break;
6990     case SPF_UMAX:
6991       Lower = *C;
6992       break;
6993     case SPF_SMIN:
6994       Lower = APInt::getSignedMinValue(BitWidth);
6995       Upper = *C + 1;
6996       break;
6997     case SPF_SMAX:
6998       Lower = *C;
6999       Upper = APInt::getSignedMaxValue(BitWidth) + 1;
7000       break;
7001     default:
7002       break;
7003   }
7004 }
7005 
7006 static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper) {
7007   // The maximum representable value of a half is 65504. For floats the maximum
7008   // value is 3.4e38 which requires roughly 129 bits.
7009   unsigned BitWidth = I->getType()->getScalarSizeInBits();
7010   if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
7011     return;
7012   if (isa<FPToSIInst>(I) && BitWidth >= 17) {
7013     Lower = APInt(BitWidth, -65504);
7014     Upper = APInt(BitWidth, 65505);
7015   }
7016 
7017   if (isa<FPToUIInst>(I) && BitWidth >= 16) {
7018     // For a fptoui the lower limit is left as 0.
7019     Upper = APInt(BitWidth, 65505);
7020   }
7021 }
7022 
7023 ConstantRange llvm::computeConstantRange(const Value *V, bool ForSigned,
7024                                          bool UseInstrInfo, AssumptionCache *AC,
7025                                          const Instruction *CtxI,
7026                                          const DominatorTree *DT,
7027                                          unsigned Depth) {
7028   assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
7029 
7030   if (Depth == MaxAnalysisRecursionDepth)
7031     return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
7032 
7033   const APInt *C;
7034   if (match(V, m_APInt(C)))
7035     return ConstantRange(*C);
7036 
7037   InstrInfoQuery IIQ(UseInstrInfo);
7038   unsigned BitWidth = V->getType()->getScalarSizeInBits();
7039   APInt Lower = APInt(BitWidth, 0);
7040   APInt Upper = APInt(BitWidth, 0);
7041   if (auto *BO = dyn_cast<BinaryOperator>(V))
7042     setLimitsForBinOp(*BO, Lower, Upper, IIQ, ForSigned);
7043   else if (auto *II = dyn_cast<IntrinsicInst>(V))
7044     setLimitsForIntrinsic(*II, Lower, Upper);
7045   else if (auto *SI = dyn_cast<SelectInst>(V))
7046     setLimitsForSelectPattern(*SI, Lower, Upper, IIQ);
7047   else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V))
7048     setLimitForFPToI(cast<Instruction>(V), Lower, Upper);
7049 
7050   ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper);
7051 
7052   if (auto *I = dyn_cast<Instruction>(V))
7053     if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range))
7054       CR = CR.intersectWith(getConstantRangeFromMetadata(*Range));
7055 
7056   if (CtxI && AC) {
7057     // Try to restrict the range based on information from assumptions.
7058     for (auto &AssumeVH : AC->assumptionsFor(V)) {
7059       if (!AssumeVH)
7060         continue;
7061       CallInst *I = cast<CallInst>(AssumeVH);
7062       assert(I->getParent()->getParent() == CtxI->getParent()->getParent() &&
7063              "Got assumption for the wrong function!");
7064       assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
7065              "must be an assume intrinsic");
7066 
7067       if (!isValidAssumeForContext(I, CtxI, DT))
7068         continue;
7069       Value *Arg = I->getArgOperand(0);
7070       ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
7071       // Currently we just use information from comparisons.
7072       if (!Cmp || Cmp->getOperand(0) != V)
7073         continue;
7074       // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
7075       ConstantRange RHS =
7076           computeConstantRange(Cmp->getOperand(1), /* ForSigned */ false,
7077                                UseInstrInfo, AC, I, DT, Depth + 1);
7078       CR = CR.intersectWith(
7079           ConstantRange::makeAllowedICmpRegion(Cmp->getPredicate(), RHS));
7080     }
7081   }
7082 
7083   return CR;
7084 }
7085 
7086 static Optional<int64_t>
7087 getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) {
7088   // Skip over the first indices.
7089   gep_type_iterator GTI = gep_type_begin(GEP);
7090   for (unsigned i = 1; i != Idx; ++i, ++GTI)
7091     /*skip along*/;
7092 
7093   // Compute the offset implied by the rest of the indices.
7094   int64_t Offset = 0;
7095   for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
7096     ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
7097     if (!OpC)
7098       return None;
7099     if (OpC->isZero())
7100       continue; // No offset.
7101 
7102     // Handle struct indices, which add their field offset to the pointer.
7103     if (StructType *STy = GTI.getStructTypeOrNull()) {
7104       Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
7105       continue;
7106     }
7107 
7108     // Otherwise, we have a sequential type like an array or fixed-length
7109     // vector. Multiply the index by the ElementSize.
7110     TypeSize Size = DL.getTypeAllocSize(GTI.getIndexedType());
7111     if (Size.isScalable())
7112       return None;
7113     Offset += Size.getFixedSize() * OpC->getSExtValue();
7114   }
7115 
7116   return Offset;
7117 }
7118 
7119 Optional<int64_t> llvm::isPointerOffset(const Value *Ptr1, const Value *Ptr2,
7120                                         const DataLayout &DL) {
7121   APInt Offset1(DL.getIndexTypeSizeInBits(Ptr1->getType()), 0);
7122   APInt Offset2(DL.getIndexTypeSizeInBits(Ptr2->getType()), 0);
7123   Ptr1 = Ptr1->stripAndAccumulateConstantOffsets(DL, Offset1, true);
7124   Ptr2 = Ptr2->stripAndAccumulateConstantOffsets(DL, Offset2, true);
7125 
7126   // Handle the trivial case first.
7127   if (Ptr1 == Ptr2)
7128     return Offset2.getSExtValue() - Offset1.getSExtValue();
7129 
7130   const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1);
7131   const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2);
7132 
7133   // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
7134   // base.  After that base, they may have some number of common (and
7135   // potentially variable) indices.  After that they handle some constant
7136   // offset, which determines their offset from each other.  At this point, we
7137   // handle no other case.
7138   if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0) ||
7139       GEP1->getSourceElementType() != GEP2->getSourceElementType())
7140     return None;
7141 
7142   // Skip any common indices and track the GEP types.
7143   unsigned Idx = 1;
7144   for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
7145     if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
7146       break;
7147 
7148   auto IOffset1 = getOffsetFromIndex(GEP1, Idx, DL);
7149   auto IOffset2 = getOffsetFromIndex(GEP2, Idx, DL);
7150   if (!IOffset1 || !IOffset2)
7151     return None;
7152   return *IOffset2 - *IOffset1 + Offset2.getSExtValue() -
7153          Offset1.getSExtValue();
7154 }
7155