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