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