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