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