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