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