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