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