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