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