1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/Loads.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/MemoryBuiltins.h"
23 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
24 #include "llvm/Analysis/VectorUtils.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/GetElementPtrTypeIterator.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/Statepoint.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/KnownBits.h"
43 #include "llvm/Support/MathExtras.h"
44 #include <algorithm>
45 #include <array>
46 #include <cstring>
47 using namespace llvm;
48 using namespace llvm::PatternMatch;
49 
50 const unsigned MaxDepth = 6;
51 
52 // Controls the number of uses of the value searched for possible
53 // dominating comparisons.
54 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
55                                               cl::Hidden, cl::init(20));
56 
57 // This optimization is known to cause performance regressions is some cases,
58 // keep it under a temporary flag for now.
59 static cl::opt<bool>
60 DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
61                               cl::Hidden, cl::init(true));
62 
63 /// Returns the bitwidth of the given scalar or pointer type. For vector types,
64 /// returns the element type's bitwidth.
65 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
66   if (unsigned BitWidth = Ty->getScalarSizeInBits())
67     return BitWidth;
68 
69   return DL.getPointerTypeSizeInBits(Ty);
70 }
71 
72 namespace {
73 // Simplifying using an assume can only be done in a particular control-flow
74 // context (the context instruction provides that context). If an assume and
75 // the context instruction are not in the same block then the DT helps in
76 // figuring out if we can use it.
77 struct Query {
78   const DataLayout &DL;
79   AssumptionCache *AC;
80   const Instruction *CxtI;
81   const DominatorTree *DT;
82   // Unlike the other analyses, this may be a nullptr because not all clients
83   // provide it currently.
84   OptimizationRemarkEmitter *ORE;
85 
86   /// Set of assumptions that should be excluded from further queries.
87   /// This is because of the potential for mutual recursion to cause
88   /// computeKnownBits to repeatedly visit the same assume intrinsic. The
89   /// classic case of this is assume(x = y), which will attempt to determine
90   /// bits in x from bits in y, which will attempt to determine bits in y from
91   /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
92   /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
93   /// (all of which can call computeKnownBits), and so on.
94   std::array<const Value *, MaxDepth> Excluded;
95   unsigned NumExcluded;
96 
97   Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
98         const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
99       : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), NumExcluded(0) {}
100 
101   Query(const Query &Q, const Value *NewExcl)
102       : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
103         NumExcluded(Q.NumExcluded) {
104     Excluded = Q.Excluded;
105     Excluded[NumExcluded++] = NewExcl;
106     assert(NumExcluded <= Excluded.size());
107   }
108 
109   bool isExcluded(const Value *Value) const {
110     if (NumExcluded == 0)
111       return false;
112     auto End = Excluded.begin() + NumExcluded;
113     return std::find(Excluded.begin(), End, Value) != End;
114   }
115 };
116 } // end anonymous namespace
117 
118 // Given the provided Value and, potentially, a context instruction, return
119 // the preferred context instruction (if any).
120 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
121   // If we've been provided with a context instruction, then use that (provided
122   // it has been inserted).
123   if (CxtI && CxtI->getParent())
124     return CxtI;
125 
126   // If the value is really an already-inserted instruction, then use that.
127   CxtI = dyn_cast<Instruction>(V);
128   if (CxtI && CxtI->getParent())
129     return CxtI;
130 
131   return nullptr;
132 }
133 
134 static void computeKnownBits(const Value *V, KnownBits &Known,
135                              unsigned Depth, const Query &Q);
136 
137 void llvm::computeKnownBits(const Value *V, KnownBits &Known,
138                             const DataLayout &DL, unsigned Depth,
139                             AssumptionCache *AC, const Instruction *CxtI,
140                             const DominatorTree *DT,
141                             OptimizationRemarkEmitter *ORE) {
142   ::computeKnownBits(V, Known, Depth,
143                      Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
144 }
145 
146 static KnownBits computeKnownBits(const Value *V, unsigned Depth,
147                                   const Query &Q);
148 
149 KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
150                                  unsigned Depth, AssumptionCache *AC,
151                                  const Instruction *CxtI,
152                                  const DominatorTree *DT,
153                                  OptimizationRemarkEmitter *ORE) {
154   return ::computeKnownBits(V, Depth,
155                             Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
156 }
157 
158 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
159                                const DataLayout &DL,
160                                AssumptionCache *AC, const Instruction *CxtI,
161                                const DominatorTree *DT) {
162   assert(LHS->getType() == RHS->getType() &&
163          "LHS and RHS should have the same type");
164   assert(LHS->getType()->isIntOrIntVectorTy() &&
165          "LHS and RHS should be integers");
166   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
167   KnownBits LHSKnown(IT->getBitWidth());
168   KnownBits RHSKnown(IT->getBitWidth());
169   computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
170   computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
171   return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
172 }
173 
174 
175 bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
176   for (const User *U : CxtI->users()) {
177     if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
178       if (IC->isEquality())
179         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
180           if (C->isNullValue())
181             continue;
182     return false;
183   }
184   return true;
185 }
186 
187 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
188                                    const Query &Q);
189 
190 bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
191                                   bool OrZero,
192                                   unsigned Depth, AssumptionCache *AC,
193                                   const Instruction *CxtI,
194                                   const DominatorTree *DT) {
195   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
196                                   Query(DL, AC, safeCxtI(V, CxtI), DT));
197 }
198 
199 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
200 
201 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
202                           AssumptionCache *AC, const Instruction *CxtI,
203                           const DominatorTree *DT) {
204   return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
205 }
206 
207 bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
208                               unsigned Depth,
209                               AssumptionCache *AC, const Instruction *CxtI,
210                               const DominatorTree *DT) {
211   KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
212   return Known.isNonNegative();
213 }
214 
215 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
216                            AssumptionCache *AC, const Instruction *CxtI,
217                            const DominatorTree *DT) {
218   if (auto *CI = dyn_cast<ConstantInt>(V))
219     return CI->getValue().isStrictlyPositive();
220 
221   // TODO: We'd doing two recursive queries here.  We should factor this such
222   // that only a single query is needed.
223   return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
224     isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
225 }
226 
227 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
228                            AssumptionCache *AC, const Instruction *CxtI,
229                            const DominatorTree *DT) {
230   KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
231   return Known.isNegative();
232 }
233 
234 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
235 
236 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
237                            const DataLayout &DL,
238                            AssumptionCache *AC, const Instruction *CxtI,
239                            const DominatorTree *DT) {
240   return ::isKnownNonEqual(V1, V2, Query(DL, AC,
241                                          safeCxtI(V1, safeCxtI(V2, CxtI)),
242                                          DT));
243 }
244 
245 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
246                               const Query &Q);
247 
248 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
249                              const DataLayout &DL,
250                              unsigned Depth, AssumptionCache *AC,
251                              const Instruction *CxtI, const DominatorTree *DT) {
252   return ::MaskedValueIsZero(V, Mask, Depth,
253                              Query(DL, AC, safeCxtI(V, CxtI), DT));
254 }
255 
256 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
257                                    const Query &Q);
258 
259 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
260                                   unsigned Depth, AssumptionCache *AC,
261                                   const Instruction *CxtI,
262                                   const DominatorTree *DT) {
263   return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
264 }
265 
266 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
267                                    bool NSW,
268                                    KnownBits &KnownOut, KnownBits &Known2,
269                                    unsigned Depth, const Query &Q) {
270   unsigned BitWidth = KnownOut.getBitWidth();
271 
272   // If an initial sequence of bits in the result is not needed, the
273   // corresponding bits in the operands are not needed.
274   KnownBits LHSKnown(BitWidth);
275   computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
276   computeKnownBits(Op1, Known2, Depth + 1, Q);
277 
278   KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
279 }
280 
281 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
282                                 KnownBits &Known, KnownBits &Known2,
283                                 unsigned Depth, const Query &Q) {
284   unsigned BitWidth = Known.getBitWidth();
285   computeKnownBits(Op1, Known, Depth + 1, Q);
286   computeKnownBits(Op0, Known2, Depth + 1, Q);
287 
288   bool isKnownNegative = false;
289   bool isKnownNonNegative = false;
290   // If the multiplication is known not to overflow, compute the sign bit.
291   if (NSW) {
292     if (Op0 == Op1) {
293       // The product of a number with itself is non-negative.
294       isKnownNonNegative = true;
295     } else {
296       bool isKnownNonNegativeOp1 = Known.isNonNegative();
297       bool isKnownNonNegativeOp0 = Known2.isNonNegative();
298       bool isKnownNegativeOp1 = Known.isNegative();
299       bool isKnownNegativeOp0 = Known2.isNegative();
300       // The product of two numbers with the same sign is non-negative.
301       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
302         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
303       // The product of a negative number and a non-negative number is either
304       // negative or zero.
305       if (!isKnownNonNegative)
306         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
307                            isKnownNonZero(Op0, Depth, Q)) ||
308                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
309                            isKnownNonZero(Op1, Depth, Q));
310     }
311   }
312 
313   // If low bits are zero in either operand, output low known-0 bits.
314   // Also compute a conservative estimate for high known-0 bits.
315   // More trickiness is possible, but this is sufficient for the
316   // interesting case of alignment computation.
317   unsigned TrailZ = Known.countMinTrailingZeros() +
318                     Known2.countMinTrailingZeros();
319   unsigned LeadZ =  std::max(Known.countMinLeadingZeros() +
320                              Known2.countMinLeadingZeros(),
321                              BitWidth) - BitWidth;
322 
323   TrailZ = std::min(TrailZ, BitWidth);
324   LeadZ = std::min(LeadZ, BitWidth);
325   Known.resetAll();
326   Known.Zero.setLowBits(TrailZ);
327   Known.Zero.setHighBits(LeadZ);
328 
329   // Only make use of no-wrap flags if we failed to compute the sign bit
330   // directly.  This matters if the multiplication always overflows, in
331   // which case we prefer to follow the result of the direct computation,
332   // though as the program is invoking undefined behaviour we can choose
333   // whatever we like here.
334   if (isKnownNonNegative && !Known.isNegative())
335     Known.makeNonNegative();
336   else if (isKnownNegative && !Known.isNonNegative())
337     Known.makeNegative();
338 }
339 
340 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
341                                              KnownBits &Known) {
342   unsigned BitWidth = Known.getBitWidth();
343   unsigned NumRanges = Ranges.getNumOperands() / 2;
344   assert(NumRanges >= 1);
345 
346   Known.Zero.setAllBits();
347   Known.One.setAllBits();
348 
349   for (unsigned i = 0; i < NumRanges; ++i) {
350     ConstantInt *Lower =
351         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
352     ConstantInt *Upper =
353         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
354     ConstantRange Range(Lower->getValue(), Upper->getValue());
355 
356     // The first CommonPrefixBits of all values in Range are equal.
357     unsigned CommonPrefixBits =
358         (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
359 
360     APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
361     Known.One &= Range.getUnsignedMax() & Mask;
362     Known.Zero &= ~Range.getUnsignedMax() & Mask;
363   }
364 }
365 
366 static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
367   SmallVector<const Value *, 16> WorkSet(1, I);
368   SmallPtrSet<const Value *, 32> Visited;
369   SmallPtrSet<const Value *, 16> EphValues;
370 
371   // The instruction defining an assumption's condition itself is always
372   // considered ephemeral to that assumption (even if it has other
373   // non-ephemeral users). See r246696's test case for an example.
374   if (is_contained(I->operands(), E))
375     return true;
376 
377   while (!WorkSet.empty()) {
378     const Value *V = WorkSet.pop_back_val();
379     if (!Visited.insert(V).second)
380       continue;
381 
382     // If all uses of this value are ephemeral, then so is this value.
383     if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
384       if (V == E)
385         return true;
386 
387       if (V == I || isSafeToSpeculativelyExecute(V)) {
388        EphValues.insert(V);
389        if (const User *U = dyn_cast<User>(V))
390          for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
391               J != JE; ++J)
392            WorkSet.push_back(*J);
393       }
394     }
395   }
396 
397   return false;
398 }
399 
400 // Is this an intrinsic that cannot be speculated but also cannot trap?
401 static bool isAssumeLikeIntrinsic(const Instruction *I) {
402   if (const CallInst *CI = dyn_cast<CallInst>(I))
403     if (Function *F = CI->getCalledFunction())
404       switch (F->getIntrinsicID()) {
405       default: break;
406       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
407       case Intrinsic::assume:
408       case Intrinsic::dbg_declare:
409       case Intrinsic::dbg_value:
410       case Intrinsic::invariant_start:
411       case Intrinsic::invariant_end:
412       case Intrinsic::lifetime_start:
413       case Intrinsic::lifetime_end:
414       case Intrinsic::objectsize:
415       case Intrinsic::ptr_annotation:
416       case Intrinsic::var_annotation:
417         return true;
418       }
419 
420   return false;
421 }
422 
423 bool llvm::isValidAssumeForContext(const Instruction *Inv,
424                                    const Instruction *CxtI,
425                                    const DominatorTree *DT) {
426 
427   // There are two restrictions on the use of an assume:
428   //  1. The assume must dominate the context (or the control flow must
429   //     reach the assume whenever it reaches the context).
430   //  2. The context must not be in the assume's set of ephemeral values
431   //     (otherwise we will use the assume to prove that the condition
432   //     feeding the assume is trivially true, thus causing the removal of
433   //     the assume).
434 
435   if (DT) {
436     if (DT->dominates(Inv, CxtI))
437       return true;
438   } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
439     // We don't have a DT, but this trivially dominates.
440     return true;
441   }
442 
443   // With or without a DT, the only remaining case we will check is if the
444   // instructions are in the same BB.  Give up if that is not the case.
445   if (Inv->getParent() != CxtI->getParent())
446     return false;
447 
448   // If we have a dom tree, then we now know that the assume doens't dominate
449   // the other instruction.  If we don't have a dom tree then we can check if
450   // the assume is first in the BB.
451   if (!DT) {
452     // Search forward from the assume until we reach the context (or the end
453     // of the block); the common case is that the assume will come first.
454     for (auto I = std::next(BasicBlock::const_iterator(Inv)),
455          IE = Inv->getParent()->end(); I != IE; ++I)
456       if (&*I == CxtI)
457         return true;
458   }
459 
460   // The context comes first, but they're both in the same block. Make sure
461   // there is nothing in between that might interrupt the control flow.
462   for (BasicBlock::const_iterator I =
463          std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
464        I != IE; ++I)
465     if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
466       return false;
467 
468   return !isEphemeralValueOf(Inv, CxtI);
469 }
470 
471 static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
472                                        unsigned Depth, const Query &Q) {
473   // Use of assumptions is context-sensitive. If we don't have a context, we
474   // cannot use them!
475   if (!Q.AC || !Q.CxtI)
476     return;
477 
478   unsigned BitWidth = Known.getBitWidth();
479 
480   // Note that the patterns below need to be kept in sync with the code
481   // in AssumptionCache::updateAffectedValues.
482 
483   for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
484     if (!AssumeVH)
485       continue;
486     CallInst *I = cast<CallInst>(AssumeVH);
487     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
488            "Got assumption for the wrong function!");
489     if (Q.isExcluded(I))
490       continue;
491 
492     // Warning: This loop can end up being somewhat performance sensetive.
493     // We're running this loop for once for each value queried resulting in a
494     // runtime of ~O(#assumes * #values).
495 
496     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
497            "must be an assume intrinsic");
498 
499     Value *Arg = I->getArgOperand(0);
500 
501     if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
502       assert(BitWidth == 1 && "assume operand is not i1?");
503       Known.setAllOnes();
504       return;
505     }
506     if (match(Arg, m_Not(m_Specific(V))) &&
507         isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
508       assert(BitWidth == 1 && "assume operand is not i1?");
509       Known.setAllZero();
510       return;
511     }
512 
513     // The remaining tests are all recursive, so bail out if we hit the limit.
514     if (Depth == MaxDepth)
515       continue;
516 
517     Value *A, *B;
518     auto m_V = m_CombineOr(m_Specific(V),
519                            m_CombineOr(m_PtrToInt(m_Specific(V)),
520                            m_BitCast(m_Specific(V))));
521 
522     CmpInst::Predicate Pred;
523     ConstantInt *C;
524     // assume(v = a)
525     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
526         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
527       KnownBits RHSKnown(BitWidth);
528       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
529       Known.Zero |= RHSKnown.Zero;
530       Known.One  |= RHSKnown.One;
531     // assume(v & b = a)
532     } else if (match(Arg,
533                      m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
534                Pred == ICmpInst::ICMP_EQ &&
535                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
536       KnownBits RHSKnown(BitWidth);
537       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
538       KnownBits MaskKnown(BitWidth);
539       computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
540 
541       // For those bits in the mask that are known to be one, we can propagate
542       // known bits from the RHS to V.
543       Known.Zero |= RHSKnown.Zero & MaskKnown.One;
544       Known.One  |= RHSKnown.One  & MaskKnown.One;
545     // assume(~(v & b) = a)
546     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
547                                    m_Value(A))) &&
548                Pred == ICmpInst::ICMP_EQ &&
549                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
550       KnownBits RHSKnown(BitWidth);
551       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
552       KnownBits MaskKnown(BitWidth);
553       computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
554 
555       // For those bits in the mask that are known to be one, we can propagate
556       // inverted known bits from the RHS to V.
557       Known.Zero |= RHSKnown.One  & MaskKnown.One;
558       Known.One  |= RHSKnown.Zero & MaskKnown.One;
559     // assume(v | b = a)
560     } else if (match(Arg,
561                      m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
562                Pred == ICmpInst::ICMP_EQ &&
563                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
564       KnownBits RHSKnown(BitWidth);
565       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
566       KnownBits BKnown(BitWidth);
567       computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
568 
569       // For those bits in B that are known to be zero, we can propagate known
570       // bits from the RHS to V.
571       Known.Zero |= RHSKnown.Zero & BKnown.Zero;
572       Known.One  |= RHSKnown.One  & BKnown.Zero;
573     // assume(~(v | b) = a)
574     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
575                                    m_Value(A))) &&
576                Pred == ICmpInst::ICMP_EQ &&
577                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
578       KnownBits RHSKnown(BitWidth);
579       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
580       KnownBits BKnown(BitWidth);
581       computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
582 
583       // For those bits in B that are known to be zero, we can propagate
584       // inverted known bits from the RHS to V.
585       Known.Zero |= RHSKnown.One  & BKnown.Zero;
586       Known.One  |= RHSKnown.Zero & BKnown.Zero;
587     // assume(v ^ b = a)
588     } else if (match(Arg,
589                      m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
590                Pred == ICmpInst::ICMP_EQ &&
591                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
592       KnownBits RHSKnown(BitWidth);
593       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
594       KnownBits BKnown(BitWidth);
595       computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
596 
597       // For those bits in B that are known to be zero, we can propagate known
598       // bits from the RHS to V. For those bits in B that are known to be one,
599       // we can propagate inverted known bits from the RHS to V.
600       Known.Zero |= RHSKnown.Zero & BKnown.Zero;
601       Known.One  |= RHSKnown.One  & BKnown.Zero;
602       Known.Zero |= RHSKnown.One  & BKnown.One;
603       Known.One  |= RHSKnown.Zero & BKnown.One;
604     // assume(~(v ^ b) = a)
605     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
606                                    m_Value(A))) &&
607                Pred == ICmpInst::ICMP_EQ &&
608                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
609       KnownBits RHSKnown(BitWidth);
610       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
611       KnownBits BKnown(BitWidth);
612       computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
613 
614       // For those bits in B that are known to be zero, we can propagate
615       // inverted known bits from the RHS to V. For those bits in B that are
616       // known to be one, we can propagate known bits from the RHS to V.
617       Known.Zero |= RHSKnown.One  & BKnown.Zero;
618       Known.One  |= RHSKnown.Zero & BKnown.Zero;
619       Known.Zero |= RHSKnown.Zero & BKnown.One;
620       Known.One  |= RHSKnown.One  & BKnown.One;
621     // assume(v << c = a)
622     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
623                                    m_Value(A))) &&
624                Pred == ICmpInst::ICMP_EQ &&
625                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
626       KnownBits RHSKnown(BitWidth);
627       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
628       // For those bits in RHS that are known, we can propagate them to known
629       // bits in V shifted to the right by C.
630       RHSKnown.Zero.lshrInPlace(C->getZExtValue());
631       Known.Zero |= RHSKnown.Zero;
632       RHSKnown.One.lshrInPlace(C->getZExtValue());
633       Known.One  |= RHSKnown.One;
634     // assume(~(v << c) = a)
635     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
636                                    m_Value(A))) &&
637                Pred == ICmpInst::ICMP_EQ &&
638                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
639       KnownBits RHSKnown(BitWidth);
640       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
641       // For those bits in RHS that are known, we can propagate them inverted
642       // to known bits in V shifted to the right by C.
643       RHSKnown.One.lshrInPlace(C->getZExtValue());
644       Known.Zero |= RHSKnown.One;
645       RHSKnown.Zero.lshrInPlace(C->getZExtValue());
646       Known.One  |= RHSKnown.Zero;
647     // assume(v >> c = a)
648     } else if (match(Arg,
649                      m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
650                               m_Value(A))) &&
651                Pred == ICmpInst::ICMP_EQ &&
652                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
653       KnownBits RHSKnown(BitWidth);
654       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
655       // For those bits in RHS that are known, we can propagate them to known
656       // bits in V shifted to the right by C.
657       Known.Zero |= RHSKnown.Zero << C->getZExtValue();
658       Known.One  |= RHSKnown.One  << C->getZExtValue();
659     // assume(~(v >> c) = a)
660     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
661                                    m_Value(A))) &&
662                Pred == ICmpInst::ICMP_EQ &&
663                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
664       KnownBits RHSKnown(BitWidth);
665       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
666       // For those bits in RHS that are known, we can propagate them inverted
667       // to known bits in V shifted to the right by C.
668       Known.Zero |= RHSKnown.One  << C->getZExtValue();
669       Known.One  |= RHSKnown.Zero << C->getZExtValue();
670     // assume(v >=_s c) where c is non-negative
671     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
672                Pred == ICmpInst::ICMP_SGE &&
673                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
674       KnownBits RHSKnown(BitWidth);
675       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
676 
677       if (RHSKnown.isNonNegative()) {
678         // We know that the sign bit is zero.
679         Known.makeNonNegative();
680       }
681     // assume(v >_s c) where c is at least -1.
682     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
683                Pred == ICmpInst::ICMP_SGT &&
684                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
685       KnownBits RHSKnown(BitWidth);
686       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
687 
688       if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
689         // We know that the sign bit is zero.
690         Known.makeNonNegative();
691       }
692     // assume(v <=_s c) where c is negative
693     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
694                Pred == ICmpInst::ICMP_SLE &&
695                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
696       KnownBits RHSKnown(BitWidth);
697       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
698 
699       if (RHSKnown.isNegative()) {
700         // We know that the sign bit is one.
701         Known.makeNegative();
702       }
703     // assume(v <_s c) where c is non-positive
704     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
705                Pred == ICmpInst::ICMP_SLT &&
706                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
707       KnownBits RHSKnown(BitWidth);
708       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
709 
710       if (RHSKnown.isZero() || RHSKnown.isNegative()) {
711         // We know that the sign bit is one.
712         Known.makeNegative();
713       }
714     // assume(v <=_u c)
715     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
716                Pred == ICmpInst::ICMP_ULE &&
717                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
718       KnownBits RHSKnown(BitWidth);
719       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
720 
721       // Whatever high bits in c are zero are known to be zero.
722       Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
723       // assume(v <_u c)
724     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
725                Pred == ICmpInst::ICMP_ULT &&
726                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
727       KnownBits RHSKnown(BitWidth);
728       computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
729 
730       // Whatever high bits in c are zero are known to be zero (if c is a power
731       // of 2, then one more).
732       if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
733         Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
734       else
735         Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
736     }
737   }
738 
739   // If assumptions conflict with each other or previous known bits, then we
740   // have a logical fallacy. It's possible that the assumption is not reachable,
741   // so this isn't a real bug. On the other hand, the program may have undefined
742   // behavior, or we might have a bug in the compiler. We can't assert/crash, so
743   // clear out the known bits, try to warn the user, and hope for the best.
744   if (Known.Zero.intersects(Known.One)) {
745     Known.resetAll();
746 
747     if (Q.ORE) {
748       auto *CxtI = const_cast<Instruction *>(Q.CxtI);
749       OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
750       Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
751                          "have undefined behavior, or compiler may have "
752                          "internal error.");
753     }
754   }
755 }
756 
757 // Compute known bits from a shift operator, including those with a
758 // non-constant shift amount. Known is the outputs of this function. Known2 is a
759 // pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
760 // operator-specific functors that, given the known-zero or known-one bits
761 // respectively, and a shift amount, compute the implied known-zero or known-one
762 // bits of the shift operator's result respectively for that shift amount. The
763 // results from calling KZF and KOF are conservatively combined for all
764 // permitted shift amounts.
765 static void computeKnownBitsFromShiftOperator(
766     const Operator *I, KnownBits &Known, KnownBits &Known2,
767     unsigned Depth, const Query &Q,
768     function_ref<APInt(const APInt &, unsigned)> KZF,
769     function_ref<APInt(const APInt &, unsigned)> KOF) {
770   unsigned BitWidth = Known.getBitWidth();
771 
772   if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
773     unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
774 
775     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
776     Known.Zero = KZF(Known.Zero, ShiftAmt);
777     Known.One  = KOF(Known.One, ShiftAmt);
778     // If there is conflict between Known.Zero and Known.One, this must be an
779     // overflowing left shift, so the shift result is undefined. Clear Known
780     // bits so that other code could propagate this undef.
781     if ((Known.Zero & Known.One) != 0)
782       Known.resetAll();
783 
784     return;
785   }
786 
787   computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
788 
789   // If the shift amount could be greater than or equal to the bit-width of the LHS, the
790   // value could be undef, so we don't know anything about it.
791   if ((~Known.Zero).uge(BitWidth)) {
792     Known.resetAll();
793     return;
794   }
795 
796   // Note: We cannot use Known.Zero.getLimitedValue() here, because if
797   // BitWidth > 64 and any upper bits are known, we'll end up returning the
798   // limit value (which implies all bits are known).
799   uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
800   uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
801 
802   // It would be more-clearly correct to use the two temporaries for this
803   // calculation. Reusing the APInts here to prevent unnecessary allocations.
804   Known.resetAll();
805 
806   // If we know the shifter operand is nonzero, we can sometimes infer more
807   // known bits. However this is expensive to compute, so be lazy about it and
808   // only compute it when absolutely necessary.
809   Optional<bool> ShifterOperandIsNonZero;
810 
811   // Early exit if we can't constrain any well-defined shift amount.
812   if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
813       !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
814     ShifterOperandIsNonZero =
815         isKnownNonZero(I->getOperand(1), Depth + 1, Q);
816     if (!*ShifterOperandIsNonZero)
817       return;
818   }
819 
820   computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
821 
822   Known.Zero.setAllBits();
823   Known.One.setAllBits();
824   for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
825     // Combine the shifted known input bits only for those shift amounts
826     // compatible with its known constraints.
827     if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
828       continue;
829     if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
830       continue;
831     // If we know the shifter is nonzero, we may be able to infer more known
832     // bits. This check is sunk down as far as possible to avoid the expensive
833     // call to isKnownNonZero if the cheaper checks above fail.
834     if (ShiftAmt == 0) {
835       if (!ShifterOperandIsNonZero.hasValue())
836         ShifterOperandIsNonZero =
837             isKnownNonZero(I->getOperand(1), Depth + 1, Q);
838       if (*ShifterOperandIsNonZero)
839         continue;
840     }
841 
842     Known.Zero &= KZF(Known2.Zero, ShiftAmt);
843     Known.One  &= KOF(Known2.One, ShiftAmt);
844   }
845 
846   // If there are no compatible shift amounts, then we've proven that the shift
847   // amount must be >= the BitWidth, and the result is undefined. We could
848   // return anything we'd like, but we need to make sure the sets of known bits
849   // stay disjoint (it should be better for some other code to actually
850   // propagate the undef than to pick a value here using known bits).
851   if (Known.Zero.intersects(Known.One))
852     Known.resetAll();
853 }
854 
855 static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
856                                          unsigned Depth, const Query &Q) {
857   unsigned BitWidth = Known.getBitWidth();
858 
859   KnownBits Known2(Known);
860   switch (I->getOpcode()) {
861   default: break;
862   case Instruction::Load:
863     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
864       computeKnownBitsFromRangeMetadata(*MD, Known);
865     break;
866   case Instruction::And: {
867     // If either the LHS or the RHS are Zero, the result is zero.
868     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
869     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
870 
871     // Output known-1 bits are only known if set in both the LHS & RHS.
872     Known.One &= Known2.One;
873     // Output known-0 are known to be clear if zero in either the LHS | RHS.
874     Known.Zero |= Known2.Zero;
875 
876     // and(x, add (x, -1)) is a common idiom that always clears the low bit;
877     // here we handle the more general case of adding any odd number by
878     // matching the form add(x, add(x, y)) where y is odd.
879     // TODO: This could be generalized to clearing any bit set in y where the
880     // following bit is known to be unset in y.
881     Value *Y = nullptr;
882     if (!Known.Zero[0] && !Known.One[0] &&
883         (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
884                                        m_Value(Y))) ||
885          match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
886                                        m_Value(Y))))) {
887       Known2.resetAll();
888       computeKnownBits(Y, Known2, Depth + 1, Q);
889       if (Known2.countMinTrailingOnes() > 0)
890         Known.Zero.setBit(0);
891     }
892     break;
893   }
894   case Instruction::Or: {
895     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
896     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
897 
898     // Output known-0 bits are only known if clear in both the LHS & RHS.
899     Known.Zero &= Known2.Zero;
900     // Output known-1 are known to be set if set in either the LHS | RHS.
901     Known.One |= Known2.One;
902     break;
903   }
904   case Instruction::Xor: {
905     computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
906     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
907 
908     // Output known-0 bits are known if clear or set in both the LHS & RHS.
909     APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
910     // Output known-1 are known to be set if set in only one of the LHS, RHS.
911     Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
912     Known.Zero = std::move(KnownZeroOut);
913     break;
914   }
915   case Instruction::Mul: {
916     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
917     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
918                         Known2, Depth, Q);
919     break;
920   }
921   case Instruction::UDiv: {
922     // For the purposes of computing leading zeros we can conservatively
923     // treat a udiv as a logical right shift by the power of 2 known to
924     // be less than the denominator.
925     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
926     unsigned LeadZ = Known2.countMinLeadingZeros();
927 
928     Known2.resetAll();
929     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
930     unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
931     if (RHSMaxLeadingZeros != BitWidth)
932       LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
933 
934     Known.Zero.setHighBits(LeadZ);
935     break;
936   }
937   case Instruction::Select: {
938     const Value *LHS, *RHS;
939     SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
940     if (SelectPatternResult::isMinOrMax(SPF)) {
941       computeKnownBits(RHS, Known, Depth + 1, Q);
942       computeKnownBits(LHS, Known2, Depth + 1, Q);
943     } else {
944       computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
945       computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
946     }
947 
948     unsigned MaxHighOnes = 0;
949     unsigned MaxHighZeros = 0;
950     if (SPF == SPF_SMAX) {
951       // If both sides are negative, the result is negative.
952       if (Known.isNegative() && Known2.isNegative())
953         // We can derive a lower bound on the result by taking the max of the
954         // leading one bits.
955         MaxHighOnes =
956             std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
957       // If either side is non-negative, the result is non-negative.
958       else if (Known.isNonNegative() || Known2.isNonNegative())
959         MaxHighZeros = 1;
960     } else if (SPF == SPF_SMIN) {
961       // If both sides are non-negative, the result is non-negative.
962       if (Known.isNonNegative() && Known2.isNonNegative())
963         // We can derive an upper bound on the result by taking the max of the
964         // leading zero bits.
965         MaxHighZeros = std::max(Known.countMinLeadingZeros(),
966                                 Known2.countMinLeadingZeros());
967       // If either side is negative, the result is negative.
968       else if (Known.isNegative() || Known2.isNegative())
969         MaxHighOnes = 1;
970     } else if (SPF == SPF_UMAX) {
971       // We can derive a lower bound on the result by taking the max of the
972       // leading one bits.
973       MaxHighOnes =
974           std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
975     } else if (SPF == SPF_UMIN) {
976       // We can derive an upper bound on the result by taking the max of the
977       // leading zero bits.
978       MaxHighZeros =
979           std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
980     }
981 
982     // Only known if known in both the LHS and RHS.
983     Known.One &= Known2.One;
984     Known.Zero &= Known2.Zero;
985     if (MaxHighOnes > 0)
986       Known.One.setHighBits(MaxHighOnes);
987     if (MaxHighZeros > 0)
988       Known.Zero.setHighBits(MaxHighZeros);
989     break;
990   }
991   case Instruction::FPTrunc:
992   case Instruction::FPExt:
993   case Instruction::FPToUI:
994   case Instruction::FPToSI:
995   case Instruction::SIToFP:
996   case Instruction::UIToFP:
997     break; // Can't work with floating point.
998   case Instruction::PtrToInt:
999   case Instruction::IntToPtr:
1000     // Fall through and handle them the same as zext/trunc.
1001     LLVM_FALLTHROUGH;
1002   case Instruction::ZExt:
1003   case Instruction::Trunc: {
1004     Type *SrcTy = I->getOperand(0)->getType();
1005 
1006     unsigned SrcBitWidth;
1007     // Note that we handle pointer operands here because of inttoptr/ptrtoint
1008     // which fall through here.
1009     SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
1010 
1011     assert(SrcBitWidth && "SrcBitWidth can't be zero");
1012     Known = Known.zextOrTrunc(SrcBitWidth);
1013     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1014     Known = Known.zextOrTrunc(BitWidth);
1015     // Any top bits are known to be zero.
1016     if (BitWidth > SrcBitWidth)
1017       Known.Zero.setBitsFrom(SrcBitWidth);
1018     break;
1019   }
1020   case Instruction::BitCast: {
1021     Type *SrcTy = I->getOperand(0)->getType();
1022     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
1023         // TODO: For now, not handling conversions like:
1024         // (bitcast i64 %x to <2 x i32>)
1025         !I->getType()->isVectorTy()) {
1026       computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1027       break;
1028     }
1029     break;
1030   }
1031   case Instruction::SExt: {
1032     // Compute the bits in the result that are not present in the input.
1033     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1034 
1035     Known = Known.trunc(SrcBitWidth);
1036     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1037     // If the sign bit of the input is known set or clear, then we know the
1038     // top bits of the result.
1039     Known = Known.sext(BitWidth);
1040     break;
1041   }
1042   case Instruction::Shl: {
1043     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1044     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1045     auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1046       APInt KZResult = KnownZero << ShiftAmt;
1047       KZResult.setLowBits(ShiftAmt); // Low bits known 0.
1048       // If this shift has "nsw" keyword, then the result is either a poison
1049       // value or has the same sign bit as the first operand.
1050       if (NSW && KnownZero.isSignBitSet())
1051         KZResult.setSignBit();
1052       return KZResult;
1053     };
1054 
1055     auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1056       APInt KOResult = KnownOne << ShiftAmt;
1057       if (NSW && KnownOne.isSignBitSet())
1058         KOResult.setSignBit();
1059       return KOResult;
1060     };
1061 
1062     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1063     break;
1064   }
1065   case Instruction::LShr: {
1066     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1067     auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1068       APInt KZResult = KnownZero.lshr(ShiftAmt);
1069       // High bits known zero.
1070       KZResult.setHighBits(ShiftAmt);
1071       return KZResult;
1072     };
1073 
1074     auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1075       return KnownOne.lshr(ShiftAmt);
1076     };
1077 
1078     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1079     break;
1080   }
1081   case Instruction::AShr: {
1082     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1083     auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1084       return KnownZero.ashr(ShiftAmt);
1085     };
1086 
1087     auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1088       return KnownOne.ashr(ShiftAmt);
1089     };
1090 
1091     computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
1092     break;
1093   }
1094   case Instruction::Sub: {
1095     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1096     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1097                            Known, Known2, Depth, Q);
1098     break;
1099   }
1100   case Instruction::Add: {
1101     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1102     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1103                            Known, Known2, Depth, Q);
1104     break;
1105   }
1106   case Instruction::SRem:
1107     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1108       APInt RA = Rem->getValue().abs();
1109       if (RA.isPowerOf2()) {
1110         APInt LowBits = RA - 1;
1111         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1112 
1113         // The low bits of the first operand are unchanged by the srem.
1114         Known.Zero = Known2.Zero & LowBits;
1115         Known.One = Known2.One & LowBits;
1116 
1117         // If the first operand is non-negative or has all low bits zero, then
1118         // the upper bits are all zero.
1119         if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
1120           Known.Zero |= ~LowBits;
1121 
1122         // If the first operand is negative and not all low bits are zero, then
1123         // the upper bits are all one.
1124         if (Known2.isNegative() && LowBits.intersects(Known2.One))
1125           Known.One |= ~LowBits;
1126 
1127         assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1128         break;
1129       }
1130     }
1131 
1132     // The sign bit is the LHS's sign bit, except when the result of the
1133     // remainder is zero.
1134     computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1135     // If it's known zero, our sign bit is also zero.
1136     if (Known2.isNonNegative())
1137       Known.makeNonNegative();
1138 
1139     break;
1140   case Instruction::URem: {
1141     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1142       const APInt &RA = Rem->getValue();
1143       if (RA.isPowerOf2()) {
1144         APInt LowBits = (RA - 1);
1145         computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1146         Known.Zero |= ~LowBits;
1147         Known.One &= LowBits;
1148         break;
1149       }
1150     }
1151 
1152     // Since the result is less than or equal to either operand, any leading
1153     // zero bits in either operand must also exist in the result.
1154     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1155     computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1156 
1157     unsigned Leaders =
1158         std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
1159     Known.resetAll();
1160     Known.Zero.setHighBits(Leaders);
1161     break;
1162   }
1163 
1164   case Instruction::Alloca: {
1165     const AllocaInst *AI = cast<AllocaInst>(I);
1166     unsigned Align = AI->getAlignment();
1167     if (Align == 0)
1168       Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
1169 
1170     if (Align > 0)
1171       Known.Zero.setLowBits(countTrailingZeros(Align));
1172     break;
1173   }
1174   case Instruction::GetElementPtr: {
1175     // Analyze all of the subscripts of this getelementptr instruction
1176     // to determine if we can prove known low zero bits.
1177     KnownBits LocalKnown(BitWidth);
1178     computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
1179     unsigned TrailZ = LocalKnown.countMinTrailingZeros();
1180 
1181     gep_type_iterator GTI = gep_type_begin(I);
1182     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1183       Value *Index = I->getOperand(i);
1184       if (StructType *STy = GTI.getStructTypeOrNull()) {
1185         // Handle struct member offset arithmetic.
1186 
1187         // Handle case when index is vector zeroinitializer
1188         Constant *CIndex = cast<Constant>(Index);
1189         if (CIndex->isZeroValue())
1190           continue;
1191 
1192         if (CIndex->getType()->isVectorTy())
1193           Index = CIndex->getSplatValue();
1194 
1195         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1196         const StructLayout *SL = Q.DL.getStructLayout(STy);
1197         uint64_t Offset = SL->getElementOffset(Idx);
1198         TrailZ = std::min<unsigned>(TrailZ,
1199                                     countTrailingZeros(Offset));
1200       } else {
1201         // Handle array index arithmetic.
1202         Type *IndexedTy = GTI.getIndexedType();
1203         if (!IndexedTy->isSized()) {
1204           TrailZ = 0;
1205           break;
1206         }
1207         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1208         uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1209         LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1210         computeKnownBits(Index, LocalKnown, Depth + 1, Q);
1211         TrailZ = std::min(TrailZ,
1212                           unsigned(countTrailingZeros(TypeSize) +
1213                                    LocalKnown.countMinTrailingZeros()));
1214       }
1215     }
1216 
1217     Known.Zero.setLowBits(TrailZ);
1218     break;
1219   }
1220   case Instruction::PHI: {
1221     const PHINode *P = cast<PHINode>(I);
1222     // Handle the case of a simple two-predecessor recurrence PHI.
1223     // There's a lot more that could theoretically be done here, but
1224     // this is sufficient to catch some interesting cases.
1225     if (P->getNumIncomingValues() == 2) {
1226       for (unsigned i = 0; i != 2; ++i) {
1227         Value *L = P->getIncomingValue(i);
1228         Value *R = P->getIncomingValue(!i);
1229         Operator *LU = dyn_cast<Operator>(L);
1230         if (!LU)
1231           continue;
1232         unsigned Opcode = LU->getOpcode();
1233         // Check for operations that have the property that if
1234         // both their operands have low zero bits, the result
1235         // will have low zero bits.
1236         if (Opcode == Instruction::Add ||
1237             Opcode == Instruction::Sub ||
1238             Opcode == Instruction::And ||
1239             Opcode == Instruction::Or ||
1240             Opcode == Instruction::Mul) {
1241           Value *LL = LU->getOperand(0);
1242           Value *LR = LU->getOperand(1);
1243           // Find a recurrence.
1244           if (LL == I)
1245             L = LR;
1246           else if (LR == I)
1247             L = LL;
1248           else
1249             break;
1250           // Ok, we have a PHI of the form L op= R. Check for low
1251           // zero bits.
1252           computeKnownBits(R, Known2, Depth + 1, Q);
1253 
1254           // We need to take the minimum number of known bits
1255           KnownBits Known3(Known);
1256           computeKnownBits(L, Known3, Depth + 1, Q);
1257 
1258           Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1259                                          Known3.countMinTrailingZeros()));
1260 
1261           if (DontImproveNonNegativePhiBits)
1262             break;
1263 
1264           auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1265           if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1266             // If initial value of recurrence is nonnegative, and we are adding
1267             // a nonnegative number with nsw, the result can only be nonnegative
1268             // or poison value regardless of the number of times we execute the
1269             // add in phi recurrence. If initial value is negative and we are
1270             // adding a negative number with nsw, the result can only be
1271             // negative or poison value. Similar arguments apply to sub and mul.
1272             //
1273             // (add non-negative, non-negative) --> non-negative
1274             // (add negative, negative) --> negative
1275             if (Opcode == Instruction::Add) {
1276               if (Known2.isNonNegative() && Known3.isNonNegative())
1277                 Known.makeNonNegative();
1278               else if (Known2.isNegative() && Known3.isNegative())
1279                 Known.makeNegative();
1280             }
1281 
1282             // (sub nsw non-negative, negative) --> non-negative
1283             // (sub nsw negative, non-negative) --> negative
1284             else if (Opcode == Instruction::Sub && LL == I) {
1285               if (Known2.isNonNegative() && Known3.isNegative())
1286                 Known.makeNonNegative();
1287               else if (Known2.isNegative() && Known3.isNonNegative())
1288                 Known.makeNegative();
1289             }
1290 
1291             // (mul nsw non-negative, non-negative) --> non-negative
1292             else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1293                      Known3.isNonNegative())
1294               Known.makeNonNegative();
1295           }
1296 
1297           break;
1298         }
1299       }
1300     }
1301 
1302     // Unreachable blocks may have zero-operand PHI nodes.
1303     if (P->getNumIncomingValues() == 0)
1304       break;
1305 
1306     // Otherwise take the unions of the known bit sets of the operands,
1307     // taking conservative care to avoid excessive recursion.
1308     if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
1309       // Skip if every incoming value references to ourself.
1310       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1311         break;
1312 
1313       Known.Zero.setAllBits();
1314       Known.One.setAllBits();
1315       for (Value *IncValue : P->incoming_values()) {
1316         // Skip direct self references.
1317         if (IncValue == P) continue;
1318 
1319         Known2 = KnownBits(BitWidth);
1320         // Recurse, but cap the recursion to one level, because we don't
1321         // want to waste time spinning around in loops.
1322         computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1323         Known.Zero &= Known2.Zero;
1324         Known.One &= Known2.One;
1325         // If all bits have been ruled out, there's no need to check
1326         // more operands.
1327         if (!Known.Zero && !Known.One)
1328           break;
1329       }
1330     }
1331     break;
1332   }
1333   case Instruction::Call:
1334   case Instruction::Invoke:
1335     // If range metadata is attached to this call, set known bits from that,
1336     // and then intersect with known bits based on other properties of the
1337     // function.
1338     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1339       computeKnownBitsFromRangeMetadata(*MD, Known);
1340     if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
1341       computeKnownBits(RV, Known2, Depth + 1, Q);
1342       Known.Zero |= Known2.Zero;
1343       Known.One |= Known2.One;
1344     }
1345     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1346       switch (II->getIntrinsicID()) {
1347       default: break;
1348       case Intrinsic::bitreverse:
1349         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1350         Known.Zero |= Known2.Zero.reverseBits();
1351         Known.One |= Known2.One.reverseBits();
1352         break;
1353       case Intrinsic::bswap:
1354         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1355         Known.Zero |= Known2.Zero.byteSwap();
1356         Known.One |= Known2.One.byteSwap();
1357         break;
1358       case Intrinsic::ctlz: {
1359         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1360         // If we have a known 1, its position is our upper bound.
1361         unsigned PossibleLZ = Known2.One.countLeadingZeros();
1362         // If this call is undefined for 0, the result will be less than 2^n.
1363         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1364           PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1365         unsigned LowBits = Log2_32(PossibleLZ)+1;
1366         Known.Zero.setBitsFrom(LowBits);
1367         break;
1368       }
1369       case Intrinsic::cttz: {
1370         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1371         // If we have a known 1, its position is our upper bound.
1372         unsigned PossibleTZ = Known2.One.countTrailingZeros();
1373         // If this call is undefined for 0, the result will be less than 2^n.
1374         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1375           PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1376         unsigned LowBits = Log2_32(PossibleTZ)+1;
1377         Known.Zero.setBitsFrom(LowBits);
1378         break;
1379       }
1380       case Intrinsic::ctpop: {
1381         computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1382         // We can bound the space the count needs.  Also, bits known to be zero
1383         // can't contribute to the population.
1384         unsigned BitsPossiblySet = Known2.countMaxPopulation();
1385         unsigned LowBits = Log2_32(BitsPossiblySet)+1;
1386         Known.Zero.setBitsFrom(LowBits);
1387         // TODO: we could bound KnownOne using the lower bound on the number
1388         // of bits which might be set provided by popcnt KnownOne2.
1389         break;
1390       }
1391       case Intrinsic::x86_sse42_crc32_64_64:
1392         Known.Zero.setBitsFrom(32);
1393         break;
1394       }
1395     }
1396     break;
1397   case Instruction::ExtractElement:
1398     // Look through extract element. At the moment we keep this simple and skip
1399     // tracking the specific element. But at least we might find information
1400     // valid for all elements of the vector (for example if vector is sign
1401     // extended, shifted, etc).
1402     computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1403     break;
1404   case Instruction::ExtractValue:
1405     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1406       const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1407       if (EVI->getNumIndices() != 1) break;
1408       if (EVI->getIndices()[0] == 0) {
1409         switch (II->getIntrinsicID()) {
1410         default: break;
1411         case Intrinsic::uadd_with_overflow:
1412         case Intrinsic::sadd_with_overflow:
1413           computeKnownBitsAddSub(true, II->getArgOperand(0),
1414                                  II->getArgOperand(1), false, Known, Known2,
1415                                  Depth, Q);
1416           break;
1417         case Intrinsic::usub_with_overflow:
1418         case Intrinsic::ssub_with_overflow:
1419           computeKnownBitsAddSub(false, II->getArgOperand(0),
1420                                  II->getArgOperand(1), false, Known, Known2,
1421                                  Depth, Q);
1422           break;
1423         case Intrinsic::umul_with_overflow:
1424         case Intrinsic::smul_with_overflow:
1425           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1426                               Known, Known2, Depth, Q);
1427           break;
1428         }
1429       }
1430     }
1431   }
1432 }
1433 
1434 /// Determine which bits of V are known to be either zero or one and return
1435 /// them.
1436 KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1437   KnownBits Known(getBitWidth(V->getType(), Q.DL));
1438   computeKnownBits(V, Known, Depth, Q);
1439   return Known;
1440 }
1441 
1442 /// Determine which bits of V are known to be either zero or one and return
1443 /// them in the Known bit set.
1444 ///
1445 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
1446 /// we cannot optimize based on the assumption that it is zero without changing
1447 /// it to be an explicit zero.  If we don't change it to zero, other code could
1448 /// optimized based on the contradictory assumption that it is non-zero.
1449 /// Because instcombine aggressively folds operations with undef args anyway,
1450 /// this won't lose us code quality.
1451 ///
1452 /// This function is defined on values with integer type, values with pointer
1453 /// type, and vectors of integers.  In the case
1454 /// where V is a vector, known zero, and known one values are the
1455 /// same width as the vector element, and the bit is set only if it is true
1456 /// for all of the elements in the vector.
1457 void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1458                       const Query &Q) {
1459   assert(V && "No Value?");
1460   assert(Depth <= MaxDepth && "Limit Search Depth");
1461   unsigned BitWidth = Known.getBitWidth();
1462 
1463   assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
1464           V->getType()->isPtrOrPtrVectorTy()) &&
1465          "Not integer or pointer type!");
1466   assert(Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth &&
1467          "V and Known should have same BitWidth");
1468   (void)BitWidth;
1469 
1470   const APInt *C;
1471   if (match(V, m_APInt(C))) {
1472     // We know all of the bits for a scalar constant or a splat vector constant!
1473     Known.One = *C;
1474     Known.Zero = ~Known.One;
1475     return;
1476   }
1477   // Null and aggregate-zero are all-zeros.
1478   if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1479     Known.setAllZero();
1480     return;
1481   }
1482   // Handle a constant vector by taking the intersection of the known bits of
1483   // each element.
1484   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1485     // We know that CDS must be a vector of integers. Take the intersection of
1486     // each element.
1487     Known.Zero.setAllBits(); Known.One.setAllBits();
1488     APInt Elt(BitWidth, 0);
1489     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1490       Elt = CDS->getElementAsInteger(i);
1491       Known.Zero &= ~Elt;
1492       Known.One &= Elt;
1493     }
1494     return;
1495   }
1496 
1497   if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1498     // We know that CV must be a vector of integers. Take the intersection of
1499     // each element.
1500     Known.Zero.setAllBits(); Known.One.setAllBits();
1501     APInt Elt(BitWidth, 0);
1502     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1503       Constant *Element = CV->getAggregateElement(i);
1504       auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1505       if (!ElementCI) {
1506         Known.resetAll();
1507         return;
1508       }
1509       Elt = ElementCI->getValue();
1510       Known.Zero &= ~Elt;
1511       Known.One &= Elt;
1512     }
1513     return;
1514   }
1515 
1516   // Start out not knowing anything.
1517   Known.resetAll();
1518 
1519   // We can't imply anything about undefs.
1520   if (isa<UndefValue>(V))
1521     return;
1522 
1523   // There's no point in looking through other users of ConstantData for
1524   // assumptions.  Confirm that we've handled them all.
1525   assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1526 
1527   // Limit search depth.
1528   // All recursive calls that increase depth must come after this.
1529   if (Depth == MaxDepth)
1530     return;
1531 
1532   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1533   // the bits of its aliasee.
1534   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1535     if (!GA->isInterposable())
1536       computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1537     return;
1538   }
1539 
1540   if (const Operator *I = dyn_cast<Operator>(V))
1541     computeKnownBitsFromOperator(I, Known, Depth, Q);
1542 
1543   // Aligned pointers have trailing zeros - refine Known.Zero set
1544   if (V->getType()->isPointerTy()) {
1545     unsigned Align = V->getPointerAlignment(Q.DL);
1546     if (Align)
1547       Known.Zero.setLowBits(countTrailingZeros(Align));
1548   }
1549 
1550   // computeKnownBitsFromAssume strictly refines Known.
1551   // Therefore, we run them after computeKnownBitsFromOperator.
1552 
1553   // Check whether a nearby assume intrinsic can determine some known bits.
1554   computeKnownBitsFromAssume(V, Known, Depth, Q);
1555 
1556   assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1557 }
1558 
1559 /// Return true if the given value is known to have exactly one
1560 /// bit set when defined. For vectors return true if every element is known to
1561 /// be a power of two when defined. Supports values with integer or pointer
1562 /// types and vectors of integers.
1563 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1564                             const Query &Q) {
1565   assert(Depth <= MaxDepth && "Limit Search Depth");
1566 
1567   if (const Constant *C = dyn_cast<Constant>(V)) {
1568     if (C->isNullValue())
1569       return OrZero;
1570 
1571     const APInt *ConstIntOrConstSplatInt;
1572     if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1573       return ConstIntOrConstSplatInt->isPowerOf2();
1574   }
1575 
1576   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1577   // it is shifted off the end then the result is undefined.
1578   if (match(V, m_Shl(m_One(), m_Value())))
1579     return true;
1580 
1581   // (signmask) >>l X is clearly a power of two if the one is not shifted off
1582   // the bottom.  If it is shifted off the bottom then the result is undefined.
1583   if (match(V, m_LShr(m_SignMask(), m_Value())))
1584     return true;
1585 
1586   // The remaining tests are all recursive, so bail out if we hit the limit.
1587   if (Depth++ == MaxDepth)
1588     return false;
1589 
1590   Value *X = nullptr, *Y = nullptr;
1591   // A shift left or a logical shift right of a power of two is a power of two
1592   // or zero.
1593   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1594                  match(V, m_LShr(m_Value(X), m_Value()))))
1595     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
1596 
1597   if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1598     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1599 
1600   if (const SelectInst *SI = dyn_cast<SelectInst>(V))
1601     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1602            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1603 
1604   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1605     // A power of two and'd with anything is a power of two or zero.
1606     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1607         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
1608       return true;
1609     // X & (-X) is always a power of two or zero.
1610     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1611       return true;
1612     return false;
1613   }
1614 
1615   // Adding a power-of-two or zero to the same power-of-two or zero yields
1616   // either the original power-of-two, a larger power-of-two or zero.
1617   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1618     const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1619     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1620       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1621           match(X, m_And(m_Value(), m_Specific(Y))))
1622         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1623           return true;
1624       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1625           match(Y, m_And(m_Value(), m_Specific(X))))
1626         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1627           return true;
1628 
1629       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1630       KnownBits LHSBits(BitWidth);
1631       computeKnownBits(X, LHSBits, Depth, Q);
1632 
1633       KnownBits RHSBits(BitWidth);
1634       computeKnownBits(Y, RHSBits, Depth, Q);
1635       // If i8 V is a power of two or zero:
1636       //  ZeroBits: 1 1 1 0 1 1 1 1
1637       // ~ZeroBits: 0 0 0 1 0 0 0 0
1638       if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
1639         // If OrZero isn't set, we cannot give back a zero result.
1640         // Make sure either the LHS or RHS has a bit set.
1641         if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
1642           return true;
1643     }
1644   }
1645 
1646   // An exact divide or right shift can only shift off zero bits, so the result
1647   // is a power of two only if the first operand is a power of two and not
1648   // copying a sign bit (sdiv int_min, 2).
1649   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1650       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1651     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1652                                   Depth, Q);
1653   }
1654 
1655   return false;
1656 }
1657 
1658 /// \brief Test whether a GEP's result is known to be non-null.
1659 ///
1660 /// Uses properties inherent in a GEP to try to determine whether it is known
1661 /// to be non-null.
1662 ///
1663 /// Currently this routine does not support vector GEPs.
1664 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
1665                               const Query &Q) {
1666   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1667     return false;
1668 
1669   // FIXME: Support vector-GEPs.
1670   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1671 
1672   // If the base pointer is non-null, we cannot walk to a null address with an
1673   // inbounds GEP in address space zero.
1674   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
1675     return true;
1676 
1677   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1678   // If so, then the GEP cannot produce a null pointer, as doing so would
1679   // inherently violate the inbounds contract within address space zero.
1680   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1681        GTI != GTE; ++GTI) {
1682     // Struct types are easy -- they must always be indexed by a constant.
1683     if (StructType *STy = GTI.getStructTypeOrNull()) {
1684       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1685       unsigned ElementIdx = OpC->getZExtValue();
1686       const StructLayout *SL = Q.DL.getStructLayout(STy);
1687       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1688       if (ElementOffset > 0)
1689         return true;
1690       continue;
1691     }
1692 
1693     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1694     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1695       continue;
1696 
1697     // Fast path the constant operand case both for efficiency and so we don't
1698     // increment Depth when just zipping down an all-constant GEP.
1699     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1700       if (!OpC->isZero())
1701         return true;
1702       continue;
1703     }
1704 
1705     // We post-increment Depth here because while isKnownNonZero increments it
1706     // as well, when we pop back up that increment won't persist. We don't want
1707     // to recurse 10k times just because we have 10k GEP operands. We don't
1708     // bail completely out because we want to handle constant GEPs regardless
1709     // of depth.
1710     if (Depth++ >= MaxDepth)
1711       continue;
1712 
1713     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
1714       return true;
1715   }
1716 
1717   return false;
1718 }
1719 
1720 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1721 /// ensure that the value it's attached to is never Value?  'RangeType' is
1722 /// is the type of the value described by the range.
1723 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
1724   const unsigned NumRanges = Ranges->getNumOperands() / 2;
1725   assert(NumRanges >= 1);
1726   for (unsigned i = 0; i < NumRanges; ++i) {
1727     ConstantInt *Lower =
1728         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1729     ConstantInt *Upper =
1730         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1731     ConstantRange Range(Lower->getValue(), Upper->getValue());
1732     if (Range.contains(Value))
1733       return false;
1734   }
1735   return true;
1736 }
1737 
1738 /// Return true if the given value is known to be non-zero when defined. For
1739 /// vectors, return true if every element is known to be non-zero when
1740 /// defined. For pointers, if the context instruction and dominator tree are
1741 /// specified, perform context-sensitive analysis and return true if the
1742 /// pointer couldn't possibly be null at the specified instruction.
1743 /// Supports values with integer or pointer type and vectors of integers.
1744 bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
1745   if (auto *C = dyn_cast<Constant>(V)) {
1746     if (C->isNullValue())
1747       return false;
1748     if (isa<ConstantInt>(C))
1749       // Must be non-zero due to null test above.
1750       return true;
1751 
1752     // For constant vectors, check that all elements are undefined or known
1753     // non-zero to determine that the whole vector is known non-zero.
1754     if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1755       for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1756         Constant *Elt = C->getAggregateElement(i);
1757         if (!Elt || Elt->isNullValue())
1758           return false;
1759         if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1760           return false;
1761       }
1762       return true;
1763     }
1764 
1765     return false;
1766   }
1767 
1768   if (auto *I = dyn_cast<Instruction>(V)) {
1769     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1770       // If the possible ranges don't contain zero, then the value is
1771       // definitely non-zero.
1772       if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
1773         const APInt ZeroValue(Ty->getBitWidth(), 0);
1774         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1775           return true;
1776       }
1777     }
1778   }
1779 
1780   // The remaining tests are all recursive, so bail out if we hit the limit.
1781   if (Depth++ >= MaxDepth)
1782     return false;
1783 
1784   // Check for pointer simplifications.
1785   if (V->getType()->isPointerTy()) {
1786     if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
1787       return true;
1788     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1789       if (isGEPKnownNonNull(GEP, Depth, Q))
1790         return true;
1791   }
1792 
1793   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
1794 
1795   // X | Y != 0 if X != 0 or Y != 0.
1796   Value *X = nullptr, *Y = nullptr;
1797   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1798     return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
1799 
1800   // ext X != 0 if X != 0.
1801   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1802     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
1803 
1804   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1805   // if the lowest bit is shifted off the end.
1806   if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1807     // shl nuw can't remove any non-zero bits.
1808     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1809     if (BO->hasNoUnsignedWrap())
1810       return isKnownNonZero(X, Depth, Q);
1811 
1812     KnownBits Known(BitWidth);
1813     computeKnownBits(X, Known, Depth, Q);
1814     if (Known.One[0])
1815       return true;
1816   }
1817   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1818   // defined if the sign bit is shifted off the end.
1819   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1820     // shr exact can only shift out zero bits.
1821     const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1822     if (BO->isExact())
1823       return isKnownNonZero(X, Depth, Q);
1824 
1825     KnownBits Known = computeKnownBits(X, Depth, Q);
1826     if (Known.isNegative())
1827       return true;
1828 
1829     // If the shifter operand is a constant, and all of the bits shifted
1830     // out are known to be zero, and X is known non-zero then at least one
1831     // non-zero bit must remain.
1832     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
1833       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1834       // Is there a known one in the portion not shifted out?
1835       if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
1836         return true;
1837       // Are all the bits to be shifted out known zero?
1838       if (Known.countMinTrailingZeros() >= ShiftVal)
1839         return isKnownNonZero(X, Depth, Q);
1840     }
1841   }
1842   // div exact can only produce a zero if the dividend is zero.
1843   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1844     return isKnownNonZero(X, Depth, Q);
1845   }
1846   // X + Y.
1847   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1848     KnownBits XKnown = computeKnownBits(X, Depth, Q);
1849     KnownBits YKnown = computeKnownBits(Y, Depth, Q);
1850 
1851     // If X and Y are both non-negative (as signed values) then their sum is not
1852     // zero unless both X and Y are zero.
1853     if (XKnown.isNonNegative() && YKnown.isNonNegative())
1854       if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
1855         return true;
1856 
1857     // If X and Y are both negative (as signed values) then their sum is not
1858     // zero unless both X and Y equal INT_MIN.
1859     if (XKnown.isNegative() && YKnown.isNegative()) {
1860       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1861       // The sign bit of X is set.  If some other bit is set then X is not equal
1862       // to INT_MIN.
1863       if (XKnown.One.intersects(Mask))
1864         return true;
1865       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1866       // to INT_MIN.
1867       if (YKnown.One.intersects(Mask))
1868         return true;
1869     }
1870 
1871     // The sum of a non-negative number and a power of two is not zero.
1872     if (XKnown.isNonNegative() &&
1873         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
1874       return true;
1875     if (YKnown.isNonNegative() &&
1876         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
1877       return true;
1878   }
1879   // X * Y.
1880   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1881     const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1882     // If X and Y are non-zero then so is X * Y as long as the multiplication
1883     // does not overflow.
1884     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1885         isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
1886       return true;
1887   }
1888   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1889   else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
1890     if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1891         isKnownNonZero(SI->getFalseValue(), Depth, Q))
1892       return true;
1893   }
1894   // PHI
1895   else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
1896     // Try and detect a recurrence that monotonically increases from a
1897     // starting value, as these are common as induction variables.
1898     if (PN->getNumIncomingValues() == 2) {
1899       Value *Start = PN->getIncomingValue(0);
1900       Value *Induction = PN->getIncomingValue(1);
1901       if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1902         std::swap(Start, Induction);
1903       if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1904         if (!C->isZero() && !C->isNegative()) {
1905           ConstantInt *X;
1906           if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1907                match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1908               !X->isNegative())
1909             return true;
1910         }
1911       }
1912     }
1913     // Check if all incoming values are non-zero constant.
1914     bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1915       return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
1916     });
1917     if (AllNonZeroConstants)
1918       return true;
1919   }
1920 
1921   KnownBits Known(BitWidth);
1922   computeKnownBits(V, Known, Depth, Q);
1923   return Known.One != 0;
1924 }
1925 
1926 /// Return true if V2 == V1 + X, where X is known non-zero.
1927 static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1928   const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
1929   if (!BO || BO->getOpcode() != Instruction::Add)
1930     return false;
1931   Value *Op = nullptr;
1932   if (V2 == BO->getOperand(0))
1933     Op = BO->getOperand(1);
1934   else if (V2 == BO->getOperand(1))
1935     Op = BO->getOperand(0);
1936   else
1937     return false;
1938   return isKnownNonZero(Op, 0, Q);
1939 }
1940 
1941 /// Return true if it is known that V1 != V2.
1942 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
1943   if (V1 == V2)
1944     return false;
1945   if (V1->getType() != V2->getType())
1946     // We can't look through casts yet.
1947     return false;
1948   if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
1949     return true;
1950 
1951   if (V1->getType()->isIntOrIntVectorTy()) {
1952     // Are any known bits in V1 contradictory to known bits in V2? If V1
1953     // has a known zero where V2 has a known one, they must not be equal.
1954     KnownBits Known1 = computeKnownBits(V1, 0, Q);
1955     KnownBits Known2 = computeKnownBits(V2, 0, Q);
1956 
1957     if (Known1.Zero.intersects(Known2.One) ||
1958         Known2.Zero.intersects(Known1.One))
1959       return true;
1960   }
1961   return false;
1962 }
1963 
1964 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
1965 /// simplify operations downstream. Mask is known to be zero for bits that V
1966 /// cannot have.
1967 ///
1968 /// This function is defined on values with integer type, values with pointer
1969 /// type, and vectors of integers.  In the case
1970 /// where V is a vector, the mask, known zero, and known one values are the
1971 /// same width as the vector element, and the bit is set only if it is true
1972 /// for all of the elements in the vector.
1973 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
1974                        const Query &Q) {
1975   KnownBits Known(Mask.getBitWidth());
1976   computeKnownBits(V, Known, Depth, Q);
1977   return Mask.isSubsetOf(Known.Zero);
1978 }
1979 
1980 /// For vector constants, loop over the elements and find the constant with the
1981 /// minimum number of sign bits. Return 0 if the value is not a vector constant
1982 /// or if any element was not analyzed; otherwise, return the count for the
1983 /// element with the minimum number of sign bits.
1984 static unsigned computeNumSignBitsVectorConstant(const Value *V,
1985                                                  unsigned TyBits) {
1986   const auto *CV = dyn_cast<Constant>(V);
1987   if (!CV || !CV->getType()->isVectorTy())
1988     return 0;
1989 
1990   unsigned MinSignBits = TyBits;
1991   unsigned NumElts = CV->getType()->getVectorNumElements();
1992   for (unsigned i = 0; i != NumElts; ++i) {
1993     // If we find a non-ConstantInt, bail out.
1994     auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
1995     if (!Elt)
1996       return 0;
1997 
1998     // If the sign bit is 1, flip the bits, so we always count leading zeros.
1999     APInt EltVal = Elt->getValue();
2000     if (EltVal.isNegative())
2001       EltVal = ~EltVal;
2002     MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2003   }
2004 
2005   return MinSignBits;
2006 }
2007 
2008 static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2009                                        const Query &Q);
2010 
2011 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2012                                    const Query &Q) {
2013   unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2014   assert(Result > 0 && "At least one sign bit needs to be present!");
2015   return Result;
2016 }
2017 
2018 /// Return the number of times the sign bit of the register is replicated into
2019 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2020 /// (itself), but other cases can give us information. For example, immediately
2021 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2022 /// other, so we return 3. For vectors, return the number of sign bits for the
2023 /// vector element with the mininum number of known sign bits.
2024 static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2025                                        const Query &Q) {
2026   assert(Depth <= MaxDepth && "Limit Search Depth");
2027 
2028   // We return the minimum number of sign bits that are guaranteed to be present
2029   // in V, so for undef we have to conservatively return 1.  We don't have the
2030   // same behavior for poison though -- that's a FIXME today.
2031 
2032   unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
2033   unsigned Tmp, Tmp2;
2034   unsigned FirstAnswer = 1;
2035 
2036   // Note that ConstantInt is handled by the general computeKnownBits case
2037   // below.
2038 
2039   if (Depth == MaxDepth)
2040     return 1;  // Limit search depth.
2041 
2042   const Operator *U = dyn_cast<Operator>(V);
2043   switch (Operator::getOpcode(V)) {
2044   default: break;
2045   case Instruction::SExt:
2046     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2047     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2048 
2049   case Instruction::SDiv: {
2050     const APInt *Denominator;
2051     // sdiv X, C -> adds log(C) sign bits.
2052     if (match(U->getOperand(1), m_APInt(Denominator))) {
2053 
2054       // Ignore non-positive denominator.
2055       if (!Denominator->isStrictlyPositive())
2056         break;
2057 
2058       // Calculate the incoming numerator bits.
2059       unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2060 
2061       // Add floor(log(C)) bits to the numerator bits.
2062       return std::min(TyBits, NumBits + Denominator->logBase2());
2063     }
2064     break;
2065   }
2066 
2067   case Instruction::SRem: {
2068     const APInt *Denominator;
2069     // srem X, C -> we know that the result is within [-C+1,C) when C is a
2070     // positive constant.  This let us put a lower bound on the number of sign
2071     // bits.
2072     if (match(U->getOperand(1), m_APInt(Denominator))) {
2073 
2074       // Ignore non-positive denominator.
2075       if (!Denominator->isStrictlyPositive())
2076         break;
2077 
2078       // Calculate the incoming numerator bits. SRem by a positive constant
2079       // can't lower the number of sign bits.
2080       unsigned NumrBits =
2081           ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2082 
2083       // Calculate the leading sign bit constraints by examining the
2084       // denominator.  Given that the denominator is positive, there are two
2085       // cases:
2086       //
2087       //  1. the numerator is positive.  The result range is [0,C) and [0,C) u<
2088       //     (1 << ceilLogBase2(C)).
2089       //
2090       //  2. the numerator is negative.  Then the result range is (-C,0] and
2091       //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2092       //
2093       // Thus a lower bound on the number of sign bits is `TyBits -
2094       // ceilLogBase2(C)`.
2095 
2096       unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2097       return std::max(NumrBits, ResBits);
2098     }
2099     break;
2100   }
2101 
2102   case Instruction::AShr: {
2103     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2104     // ashr X, C   -> adds C sign bits.  Vectors too.
2105     const APInt *ShAmt;
2106     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2107       unsigned ShAmtLimited = ShAmt->getZExtValue();
2108       if (ShAmtLimited >= TyBits)
2109         break;  // Bad shift.
2110       Tmp += ShAmtLimited;
2111       if (Tmp > TyBits) Tmp = TyBits;
2112     }
2113     return Tmp;
2114   }
2115   case Instruction::Shl: {
2116     const APInt *ShAmt;
2117     if (match(U->getOperand(1), m_APInt(ShAmt))) {
2118       // shl destroys sign bits.
2119       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2120       Tmp2 = ShAmt->getZExtValue();
2121       if (Tmp2 >= TyBits ||      // Bad shift.
2122           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
2123       return Tmp - Tmp2;
2124     }
2125     break;
2126   }
2127   case Instruction::And:
2128   case Instruction::Or:
2129   case Instruction::Xor:    // NOT is handled here.
2130     // Logical binary ops preserve the number of sign bits at the worst.
2131     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2132     if (Tmp != 1) {
2133       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2134       FirstAnswer = std::min(Tmp, Tmp2);
2135       // We computed what we know about the sign bits as our first
2136       // answer. Now proceed to the generic code that uses
2137       // computeKnownBits, and pick whichever answer is better.
2138     }
2139     break;
2140 
2141   case Instruction::Select:
2142     Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2143     if (Tmp == 1) return 1;  // Early out.
2144     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
2145     return std::min(Tmp, Tmp2);
2146 
2147   case Instruction::Add:
2148     // Add can have at most one carry bit.  Thus we know that the output
2149     // is, at worst, one more bit than the inputs.
2150     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2151     if (Tmp == 1) return 1;  // Early out.
2152 
2153     // Special case decrementing a value (ADD X, -1):
2154     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2155       if (CRHS->isAllOnesValue()) {
2156         KnownBits Known(TyBits);
2157         computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
2158 
2159         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2160         // sign bits set.
2161         if ((Known.Zero | 1).isAllOnesValue())
2162           return TyBits;
2163 
2164         // If we are subtracting one from a positive number, there is no carry
2165         // out of the result.
2166         if (Known.isNonNegative())
2167           return Tmp;
2168       }
2169 
2170     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2171     if (Tmp2 == 1) return 1;
2172     return std::min(Tmp, Tmp2)-1;
2173 
2174   case Instruction::Sub:
2175     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2176     if (Tmp2 == 1) return 1;
2177 
2178     // Handle NEG.
2179     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2180       if (CLHS->isNullValue()) {
2181         KnownBits Known(TyBits);
2182         computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
2183         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2184         // sign bits set.
2185         if ((Known.Zero | 1).isAllOnesValue())
2186           return TyBits;
2187 
2188         // If the input is known to be positive (the sign bit is known clear),
2189         // the output of the NEG has the same number of sign bits as the input.
2190         if (Known.isNonNegative())
2191           return Tmp2;
2192 
2193         // Otherwise, we treat this like a SUB.
2194       }
2195 
2196     // Sub can have at most one carry bit.  Thus we know that the output
2197     // is, at worst, one more bit than the inputs.
2198     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2199     if (Tmp == 1) return 1;  // Early out.
2200     return std::min(Tmp, Tmp2)-1;
2201 
2202   case Instruction::Mul: {
2203     // The output of the Mul can be at most twice the valid bits in the inputs.
2204     unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2205     if (SignBitsOp0 == 1) return 1;  // Early out.
2206     unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2207     if (SignBitsOp1 == 1) return 1;
2208     unsigned OutValidBits =
2209         (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2210     return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2211   }
2212 
2213   case Instruction::PHI: {
2214     const PHINode *PN = cast<PHINode>(U);
2215     unsigned NumIncomingValues = PN->getNumIncomingValues();
2216     // Don't analyze large in-degree PHIs.
2217     if (NumIncomingValues > 4) break;
2218     // Unreachable blocks may have zero-operand PHI nodes.
2219     if (NumIncomingValues == 0) break;
2220 
2221     // Take the minimum of all incoming values.  This can't infinitely loop
2222     // because of our depth threshold.
2223     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
2224     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2225       if (Tmp == 1) return Tmp;
2226       Tmp = std::min(
2227           Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
2228     }
2229     return Tmp;
2230   }
2231 
2232   case Instruction::Trunc:
2233     // FIXME: it's tricky to do anything useful for this, but it is an important
2234     // case for targets like X86.
2235     break;
2236 
2237   case Instruction::ExtractElement:
2238     // Look through extract element. At the moment we keep this simple and skip
2239     // tracking the specific element. But at least we might find information
2240     // valid for all elements of the vector (for example if vector is sign
2241     // extended, shifted, etc).
2242     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2243   }
2244 
2245   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2246   // use this information.
2247 
2248   // If we can examine all elements of a vector constant successfully, we're
2249   // done (we can't do any better than that). If not, keep trying.
2250   if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2251     return VecSignBits;
2252 
2253   KnownBits Known(TyBits);
2254   computeKnownBits(V, Known, Depth, Q);
2255 
2256   // If we know that the sign bit is either zero or one, determine the number of
2257   // identical bits in the top of the input value.
2258   return std::max(FirstAnswer, Known.countMinSignBits());
2259 }
2260 
2261 /// This function computes the integer multiple of Base that equals V.
2262 /// If successful, it returns true and returns the multiple in
2263 /// Multiple. If unsuccessful, it returns false. It looks
2264 /// through SExt instructions only if LookThroughSExt is true.
2265 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2266                            bool LookThroughSExt, unsigned Depth) {
2267   const unsigned MaxDepth = 6;
2268 
2269   assert(V && "No Value?");
2270   assert(Depth <= MaxDepth && "Limit Search Depth");
2271   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2272 
2273   Type *T = V->getType();
2274 
2275   ConstantInt *CI = dyn_cast<ConstantInt>(V);
2276 
2277   if (Base == 0)
2278     return false;
2279 
2280   if (Base == 1) {
2281     Multiple = V;
2282     return true;
2283   }
2284 
2285   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2286   Constant *BaseVal = ConstantInt::get(T, Base);
2287   if (CO && CO == BaseVal) {
2288     // Multiple is 1.
2289     Multiple = ConstantInt::get(T, 1);
2290     return true;
2291   }
2292 
2293   if (CI && CI->getZExtValue() % Base == 0) {
2294     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2295     return true;
2296   }
2297 
2298   if (Depth == MaxDepth) return false;  // Limit search depth.
2299 
2300   Operator *I = dyn_cast<Operator>(V);
2301   if (!I) return false;
2302 
2303   switch (I->getOpcode()) {
2304   default: break;
2305   case Instruction::SExt:
2306     if (!LookThroughSExt) return false;
2307     // otherwise fall through to ZExt
2308     LLVM_FALLTHROUGH;
2309   case Instruction::ZExt:
2310     return ComputeMultiple(I->getOperand(0), Base, Multiple,
2311                            LookThroughSExt, Depth+1);
2312   case Instruction::Shl:
2313   case Instruction::Mul: {
2314     Value *Op0 = I->getOperand(0);
2315     Value *Op1 = I->getOperand(1);
2316 
2317     if (I->getOpcode() == Instruction::Shl) {
2318       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2319       if (!Op1CI) return false;
2320       // Turn Op0 << Op1 into Op0 * 2^Op1
2321       APInt Op1Int = Op1CI->getValue();
2322       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2323       APInt API(Op1Int.getBitWidth(), 0);
2324       API.setBit(BitToSet);
2325       Op1 = ConstantInt::get(V->getContext(), API);
2326     }
2327 
2328     Value *Mul0 = nullptr;
2329     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2330       if (Constant *Op1C = dyn_cast<Constant>(Op1))
2331         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2332           if (Op1C->getType()->getPrimitiveSizeInBits() <
2333               MulC->getType()->getPrimitiveSizeInBits())
2334             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2335           if (Op1C->getType()->getPrimitiveSizeInBits() >
2336               MulC->getType()->getPrimitiveSizeInBits())
2337             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2338 
2339           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2340           Multiple = ConstantExpr::getMul(MulC, Op1C);
2341           return true;
2342         }
2343 
2344       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2345         if (Mul0CI->getValue() == 1) {
2346           // V == Base * Op1, so return Op1
2347           Multiple = Op1;
2348           return true;
2349         }
2350     }
2351 
2352     Value *Mul1 = nullptr;
2353     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2354       if (Constant *Op0C = dyn_cast<Constant>(Op0))
2355         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2356           if (Op0C->getType()->getPrimitiveSizeInBits() <
2357               MulC->getType()->getPrimitiveSizeInBits())
2358             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2359           if (Op0C->getType()->getPrimitiveSizeInBits() >
2360               MulC->getType()->getPrimitiveSizeInBits())
2361             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2362 
2363           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2364           Multiple = ConstantExpr::getMul(MulC, Op0C);
2365           return true;
2366         }
2367 
2368       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2369         if (Mul1CI->getValue() == 1) {
2370           // V == Base * Op0, so return Op0
2371           Multiple = Op0;
2372           return true;
2373         }
2374     }
2375   }
2376   }
2377 
2378   // We could not determine if V is a multiple of Base.
2379   return false;
2380 }
2381 
2382 Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2383                                             const TargetLibraryInfo *TLI) {
2384   const Function *F = ICS.getCalledFunction();
2385   if (!F)
2386     return Intrinsic::not_intrinsic;
2387 
2388   if (F->isIntrinsic())
2389     return F->getIntrinsicID();
2390 
2391   if (!TLI)
2392     return Intrinsic::not_intrinsic;
2393 
2394   LibFunc Func;
2395   // We're going to make assumptions on the semantics of the functions, check
2396   // that the target knows that it's available in this environment and it does
2397   // not have local linkage.
2398   if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2399     return Intrinsic::not_intrinsic;
2400 
2401   if (!ICS.onlyReadsMemory())
2402     return Intrinsic::not_intrinsic;
2403 
2404   // Otherwise check if we have a call to a function that can be turned into a
2405   // vector intrinsic.
2406   switch (Func) {
2407   default:
2408     break;
2409   case LibFunc_sin:
2410   case LibFunc_sinf:
2411   case LibFunc_sinl:
2412     return Intrinsic::sin;
2413   case LibFunc_cos:
2414   case LibFunc_cosf:
2415   case LibFunc_cosl:
2416     return Intrinsic::cos;
2417   case LibFunc_exp:
2418   case LibFunc_expf:
2419   case LibFunc_expl:
2420     return Intrinsic::exp;
2421   case LibFunc_exp2:
2422   case LibFunc_exp2f:
2423   case LibFunc_exp2l:
2424     return Intrinsic::exp2;
2425   case LibFunc_log:
2426   case LibFunc_logf:
2427   case LibFunc_logl:
2428     return Intrinsic::log;
2429   case LibFunc_log10:
2430   case LibFunc_log10f:
2431   case LibFunc_log10l:
2432     return Intrinsic::log10;
2433   case LibFunc_log2:
2434   case LibFunc_log2f:
2435   case LibFunc_log2l:
2436     return Intrinsic::log2;
2437   case LibFunc_fabs:
2438   case LibFunc_fabsf:
2439   case LibFunc_fabsl:
2440     return Intrinsic::fabs;
2441   case LibFunc_fmin:
2442   case LibFunc_fminf:
2443   case LibFunc_fminl:
2444     return Intrinsic::minnum;
2445   case LibFunc_fmax:
2446   case LibFunc_fmaxf:
2447   case LibFunc_fmaxl:
2448     return Intrinsic::maxnum;
2449   case LibFunc_copysign:
2450   case LibFunc_copysignf:
2451   case LibFunc_copysignl:
2452     return Intrinsic::copysign;
2453   case LibFunc_floor:
2454   case LibFunc_floorf:
2455   case LibFunc_floorl:
2456     return Intrinsic::floor;
2457   case LibFunc_ceil:
2458   case LibFunc_ceilf:
2459   case LibFunc_ceill:
2460     return Intrinsic::ceil;
2461   case LibFunc_trunc:
2462   case LibFunc_truncf:
2463   case LibFunc_truncl:
2464     return Intrinsic::trunc;
2465   case LibFunc_rint:
2466   case LibFunc_rintf:
2467   case LibFunc_rintl:
2468     return Intrinsic::rint;
2469   case LibFunc_nearbyint:
2470   case LibFunc_nearbyintf:
2471   case LibFunc_nearbyintl:
2472     return Intrinsic::nearbyint;
2473   case LibFunc_round:
2474   case LibFunc_roundf:
2475   case LibFunc_roundl:
2476     return Intrinsic::round;
2477   case LibFunc_pow:
2478   case LibFunc_powf:
2479   case LibFunc_powl:
2480     return Intrinsic::pow;
2481   case LibFunc_sqrt:
2482   case LibFunc_sqrtf:
2483   case LibFunc_sqrtl:
2484     if (ICS->hasNoNaNs())
2485       return Intrinsic::sqrt;
2486     return Intrinsic::not_intrinsic;
2487   }
2488 
2489   return Intrinsic::not_intrinsic;
2490 }
2491 
2492 /// Return true if we can prove that the specified FP value is never equal to
2493 /// -0.0.
2494 ///
2495 /// NOTE: this function will need to be revisited when we support non-default
2496 /// rounding modes!
2497 ///
2498 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2499                                 unsigned Depth) {
2500   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2501     return !CFP->getValueAPF().isNegZero();
2502 
2503   if (Depth == MaxDepth)
2504     return false;  // Limit search depth.
2505 
2506   const Operator *I = dyn_cast<Operator>(V);
2507   if (!I) return false;
2508 
2509   // Check if the nsz fast-math flag is set
2510   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2511     if (FPO->hasNoSignedZeros())
2512       return true;
2513 
2514   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2515   if (I->getOpcode() == Instruction::FAdd)
2516     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2517       if (CFP->isNullValue())
2518         return true;
2519 
2520   // sitofp and uitofp turn into +0.0 for zero.
2521   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2522     return true;
2523 
2524   if (const CallInst *CI = dyn_cast<CallInst>(I)) {
2525     Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
2526     switch (IID) {
2527     default:
2528       break;
2529     // sqrt(-0.0) = -0.0, no other negative results are possible.
2530     case Intrinsic::sqrt:
2531       return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2532     // fabs(x) != -0.0
2533     case Intrinsic::fabs:
2534       return true;
2535     }
2536   }
2537 
2538   return false;
2539 }
2540 
2541 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2542 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2543 /// bit despite comparing equal.
2544 static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2545                                             const TargetLibraryInfo *TLI,
2546                                             bool SignBitOnly,
2547                                             unsigned Depth) {
2548   // TODO: This function does not do the right thing when SignBitOnly is true
2549   // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2550   // which flips the sign bits of NaNs.  See
2551   // https://llvm.org/bugs/show_bug.cgi?id=31702.
2552 
2553   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2554     return !CFP->getValueAPF().isNegative() ||
2555            (!SignBitOnly && CFP->getValueAPF().isZero());
2556   }
2557 
2558   if (Depth == MaxDepth)
2559     return false; // Limit search depth.
2560 
2561   const Operator *I = dyn_cast<Operator>(V);
2562   if (!I)
2563     return false;
2564 
2565   switch (I->getOpcode()) {
2566   default:
2567     break;
2568   // Unsigned integers are always nonnegative.
2569   case Instruction::UIToFP:
2570     return true;
2571   case Instruction::FMul:
2572     // x*x is always non-negative or a NaN.
2573     if (I->getOperand(0) == I->getOperand(1) &&
2574         (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
2575       return true;
2576 
2577     LLVM_FALLTHROUGH;
2578   case Instruction::FAdd:
2579   case Instruction::FDiv:
2580   case Instruction::FRem:
2581     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2582                                            Depth + 1) &&
2583            cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2584                                            Depth + 1);
2585   case Instruction::Select:
2586     return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2587                                            Depth + 1) &&
2588            cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2589                                            Depth + 1);
2590   case Instruction::FPExt:
2591   case Instruction::FPTrunc:
2592     // Widening/narrowing never change sign.
2593     return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2594                                            Depth + 1);
2595   case Instruction::Call:
2596     const auto *CI = cast<CallInst>(I);
2597     Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
2598     switch (IID) {
2599     default:
2600       break;
2601     case Intrinsic::maxnum:
2602       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2603                                              Depth + 1) ||
2604              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2605                                              Depth + 1);
2606     case Intrinsic::minnum:
2607       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2608                                              Depth + 1) &&
2609              cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2610                                              Depth + 1);
2611     case Intrinsic::exp:
2612     case Intrinsic::exp2:
2613     case Intrinsic::fabs:
2614       return true;
2615 
2616     case Intrinsic::sqrt:
2617       // sqrt(x) is always >= -0 or NaN.  Moreover, sqrt(x) == -0 iff x == -0.
2618       if (!SignBitOnly)
2619         return true;
2620       return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2621                                  CannotBeNegativeZero(CI->getOperand(0), TLI));
2622 
2623     case Intrinsic::powi:
2624       if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
2625         // powi(x,n) is non-negative if n is even.
2626         if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
2627           return true;
2628       }
2629       // TODO: This is not correct.  Given that exp is an integer, here are the
2630       // ways that pow can return a negative value:
2631       //
2632       //   pow(x, exp)    --> negative if exp is odd and x is negative.
2633       //   pow(-0, exp)   --> -inf if exp is negative odd.
2634       //   pow(-0, exp)   --> -0 if exp is positive odd.
2635       //   pow(-inf, exp) --> -0 if exp is negative odd.
2636       //   pow(-inf, exp) --> -inf if exp is positive odd.
2637       //
2638       // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2639       // but we must return false if x == -0.  Unfortunately we do not currently
2640       // have a way of expressing this constraint.  See details in
2641       // https://llvm.org/bugs/show_bug.cgi?id=31702.
2642       return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2643                                              Depth + 1);
2644 
2645     case Intrinsic::fma:
2646     case Intrinsic::fmuladd:
2647       // x*x+y is non-negative if y is non-negative.
2648       return I->getOperand(0) == I->getOperand(1) &&
2649              (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2650              cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2651                                              Depth + 1);
2652     }
2653     break;
2654   }
2655   return false;
2656 }
2657 
2658 bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2659                                        const TargetLibraryInfo *TLI) {
2660   return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2661 }
2662 
2663 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2664   return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2665 }
2666 
2667 /// If the specified value can be set by repeating the same byte in memory,
2668 /// return the i8 value that it is represented with.  This is
2669 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2670 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
2671 /// byte store (e.g. i16 0x1234), return null.
2672 Value *llvm::isBytewiseValue(Value *V) {
2673   // All byte-wide stores are splatable, even of arbitrary variables.
2674   if (V->getType()->isIntegerTy(8)) return V;
2675 
2676   // Handle 'null' ConstantArrayZero etc.
2677   if (Constant *C = dyn_cast<Constant>(V))
2678     if (C->isNullValue())
2679       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2680 
2681   // Constant float and double values can be handled as integer values if the
2682   // corresponding integer value is "byteable".  An important case is 0.0.
2683   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2684     if (CFP->getType()->isFloatTy())
2685       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2686     if (CFP->getType()->isDoubleTy())
2687       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2688     // Don't handle long double formats, which have strange constraints.
2689   }
2690 
2691   // We can handle constant integers that are multiple of 8 bits.
2692   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2693     if (CI->getBitWidth() % 8 == 0) {
2694       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2695 
2696       if (!CI->getValue().isSplat(8))
2697         return nullptr;
2698       return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2699     }
2700   }
2701 
2702   // A ConstantDataArray/Vector is splatable if all its members are equal and
2703   // also splatable.
2704   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2705     Value *Elt = CA->getElementAsConstant(0);
2706     Value *Val = isBytewiseValue(Elt);
2707     if (!Val)
2708       return nullptr;
2709 
2710     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2711       if (CA->getElementAsConstant(I) != Elt)
2712         return nullptr;
2713 
2714     return Val;
2715   }
2716 
2717   // Conceptually, we could handle things like:
2718   //   %a = zext i8 %X to i16
2719   //   %b = shl i16 %a, 8
2720   //   %c = or i16 %a, %b
2721   // but until there is an example that actually needs this, it doesn't seem
2722   // worth worrying about.
2723   return nullptr;
2724 }
2725 
2726 
2727 // This is the recursive version of BuildSubAggregate. It takes a few different
2728 // arguments. Idxs is the index within the nested struct From that we are
2729 // looking at now (which is of type IndexedType). IdxSkip is the number of
2730 // indices from Idxs that should be left out when inserting into the resulting
2731 // struct. To is the result struct built so far, new insertvalue instructions
2732 // build on that.
2733 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2734                                 SmallVectorImpl<unsigned> &Idxs,
2735                                 unsigned IdxSkip,
2736                                 Instruction *InsertBefore) {
2737   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2738   if (STy) {
2739     // Save the original To argument so we can modify it
2740     Value *OrigTo = To;
2741     // General case, the type indexed by Idxs is a struct
2742     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2743       // Process each struct element recursively
2744       Idxs.push_back(i);
2745       Value *PrevTo = To;
2746       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2747                              InsertBefore);
2748       Idxs.pop_back();
2749       if (!To) {
2750         // Couldn't find any inserted value for this index? Cleanup
2751         while (PrevTo != OrigTo) {
2752           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2753           PrevTo = Del->getAggregateOperand();
2754           Del->eraseFromParent();
2755         }
2756         // Stop processing elements
2757         break;
2758       }
2759     }
2760     // If we successfully found a value for each of our subaggregates
2761     if (To)
2762       return To;
2763   }
2764   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2765   // the struct's elements had a value that was inserted directly. In the latter
2766   // case, perhaps we can't determine each of the subelements individually, but
2767   // we might be able to find the complete struct somewhere.
2768 
2769   // Find the value that is at that particular spot
2770   Value *V = FindInsertedValue(From, Idxs);
2771 
2772   if (!V)
2773     return nullptr;
2774 
2775   // Insert the value in the new (sub) aggregrate
2776   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2777                                        "tmp", InsertBefore);
2778 }
2779 
2780 // This helper takes a nested struct and extracts a part of it (which is again a
2781 // struct) into a new value. For example, given the struct:
2782 // { a, { b, { c, d }, e } }
2783 // and the indices "1, 1" this returns
2784 // { c, d }.
2785 //
2786 // It does this by inserting an insertvalue for each element in the resulting
2787 // struct, as opposed to just inserting a single struct. This will only work if
2788 // each of the elements of the substruct are known (ie, inserted into From by an
2789 // insertvalue instruction somewhere).
2790 //
2791 // All inserted insertvalue instructions are inserted before InsertBefore
2792 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2793                                 Instruction *InsertBefore) {
2794   assert(InsertBefore && "Must have someplace to insert!");
2795   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2796                                                              idx_range);
2797   Value *To = UndefValue::get(IndexedType);
2798   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2799   unsigned IdxSkip = Idxs.size();
2800 
2801   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2802 }
2803 
2804 /// Given an aggregrate and an sequence of indices, see if
2805 /// the scalar value indexed is already around as a register, for example if it
2806 /// were inserted directly into the aggregrate.
2807 ///
2808 /// If InsertBefore is not null, this function will duplicate (modified)
2809 /// insertvalues when a part of a nested struct is extracted.
2810 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2811                                Instruction *InsertBefore) {
2812   // Nothing to index? Just return V then (this is useful at the end of our
2813   // recursion).
2814   if (idx_range.empty())
2815     return V;
2816   // We have indices, so V should have an indexable type.
2817   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2818          "Not looking at a struct or array?");
2819   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2820          "Invalid indices for type?");
2821 
2822   if (Constant *C = dyn_cast<Constant>(V)) {
2823     C = C->getAggregateElement(idx_range[0]);
2824     if (!C) return nullptr;
2825     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2826   }
2827 
2828   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2829     // Loop the indices for the insertvalue instruction in parallel with the
2830     // requested indices
2831     const unsigned *req_idx = idx_range.begin();
2832     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2833          i != e; ++i, ++req_idx) {
2834       if (req_idx == idx_range.end()) {
2835         // We can't handle this without inserting insertvalues
2836         if (!InsertBefore)
2837           return nullptr;
2838 
2839         // The requested index identifies a part of a nested aggregate. Handle
2840         // this specially. For example,
2841         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2842         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2843         // %C = extractvalue {i32, { i32, i32 } } %B, 1
2844         // This can be changed into
2845         // %A = insertvalue {i32, i32 } undef, i32 10, 0
2846         // %C = insertvalue {i32, i32 } %A, i32 11, 1
2847         // which allows the unused 0,0 element from the nested struct to be
2848         // removed.
2849         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2850                                  InsertBefore);
2851       }
2852 
2853       // This insert value inserts something else than what we are looking for.
2854       // See if the (aggregate) value inserted into has the value we are
2855       // looking for, then.
2856       if (*req_idx != *i)
2857         return FindInsertedValue(I->getAggregateOperand(), idx_range,
2858                                  InsertBefore);
2859     }
2860     // If we end up here, the indices of the insertvalue match with those
2861     // requested (though possibly only partially). Now we recursively look at
2862     // the inserted value, passing any remaining indices.
2863     return FindInsertedValue(I->getInsertedValueOperand(),
2864                              makeArrayRef(req_idx, idx_range.end()),
2865                              InsertBefore);
2866   }
2867 
2868   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2869     // If we're extracting a value from an aggregate that was extracted from
2870     // something else, we can extract from that something else directly instead.
2871     // However, we will need to chain I's indices with the requested indices.
2872 
2873     // Calculate the number of indices required
2874     unsigned size = I->getNumIndices() + idx_range.size();
2875     // Allocate some space to put the new indices in
2876     SmallVector<unsigned, 5> Idxs;
2877     Idxs.reserve(size);
2878     // Add indices from the extract value instruction
2879     Idxs.append(I->idx_begin(), I->idx_end());
2880 
2881     // Add requested indices
2882     Idxs.append(idx_range.begin(), idx_range.end());
2883 
2884     assert(Idxs.size() == size
2885            && "Number of indices added not correct?");
2886 
2887     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2888   }
2889   // Otherwise, we don't know (such as, extracting from a function return value
2890   // or load instruction)
2891   return nullptr;
2892 }
2893 
2894 /// Analyze the specified pointer to see if it can be expressed as a base
2895 /// pointer plus a constant offset. Return the base and offset to the caller.
2896 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2897                                               const DataLayout &DL) {
2898   unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2899   APInt ByteOffset(BitWidth, 0);
2900 
2901   // We walk up the defs but use a visited set to handle unreachable code. In
2902   // that case, we stop after accumulating the cycle once (not that it
2903   // matters).
2904   SmallPtrSet<Value *, 16> Visited;
2905   while (Visited.insert(Ptr).second) {
2906     if (Ptr->getType()->isVectorTy())
2907       break;
2908 
2909     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2910       // If one of the values we have visited is an addrspacecast, then
2911       // the pointer type of this GEP may be different from the type
2912       // of the Ptr parameter which was passed to this function.  This
2913       // means when we construct GEPOffset, we need to use the size
2914       // of GEP's pointer type rather than the size of the original
2915       // pointer type.
2916       APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
2917       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2918         break;
2919 
2920       ByteOffset += GEPOffset.getSExtValue();
2921 
2922       Ptr = GEP->getPointerOperand();
2923     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2924                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2925       Ptr = cast<Operator>(Ptr)->getOperand(0);
2926     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2927       if (GA->isInterposable())
2928         break;
2929       Ptr = GA->getAliasee();
2930     } else {
2931       break;
2932     }
2933   }
2934   Offset = ByteOffset.getSExtValue();
2935   return Ptr;
2936 }
2937 
2938 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
2939                                        unsigned CharSize) {
2940   // Make sure the GEP has exactly three arguments.
2941   if (GEP->getNumOperands() != 3)
2942     return false;
2943 
2944   // Make sure the index-ee is a pointer to array of \p CharSize integers.
2945   // CharSize.
2946   ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2947   if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
2948     return false;
2949 
2950   // Check to make sure that the first operand of the GEP is an integer and
2951   // has value 0 so that we are sure we're indexing into the initializer.
2952   const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2953   if (!FirstIdx || !FirstIdx->isZero())
2954     return false;
2955 
2956   return true;
2957 }
2958 
2959 bool llvm::getConstantDataArrayInfo(const Value *V,
2960                                     ConstantDataArraySlice &Slice,
2961                                     unsigned ElementSize, uint64_t Offset) {
2962   assert(V);
2963 
2964   // Look through bitcast instructions and geps.
2965   V = V->stripPointerCasts();
2966 
2967   // If the value is a GEP instruction or constant expression, treat it as an
2968   // offset.
2969   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2970     // The GEP operator should be based on a pointer to string constant, and is
2971     // indexing into the string constant.
2972     if (!isGEPBasedOnPointerToString(GEP, ElementSize))
2973       return false;
2974 
2975     // If the second index isn't a ConstantInt, then this is a variable index
2976     // into the array.  If this occurs, we can't say anything meaningful about
2977     // the string.
2978     uint64_t StartIdx = 0;
2979     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2980       StartIdx = CI->getZExtValue();
2981     else
2982       return false;
2983     return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
2984                                     StartIdx + Offset);
2985   }
2986 
2987   // The GEP instruction, constant or instruction, must reference a global
2988   // variable that is a constant and is initialized. The referenced constant
2989   // initializer is the array that we'll use for optimization.
2990   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2991   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2992     return false;
2993 
2994   const ConstantDataArray *Array;
2995   ArrayType *ArrayTy;
2996   if (GV->getInitializer()->isNullValue()) {
2997     Type *GVTy = GV->getValueType();
2998     if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
2999       // A zeroinitializer for the array; there is no ConstantDataArray.
3000       Array = nullptr;
3001     } else {
3002       const DataLayout &DL = GV->getParent()->getDataLayout();
3003       uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3004       uint64_t Length = SizeInBytes / (ElementSize / 8);
3005       if (Length <= Offset)
3006         return false;
3007 
3008       Slice.Array = nullptr;
3009       Slice.Offset = 0;
3010       Slice.Length = Length - Offset;
3011       return true;
3012     }
3013   } else {
3014     // This must be a ConstantDataArray.
3015     Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3016     if (!Array)
3017       return false;
3018     ArrayTy = Array->getType();
3019   }
3020   if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
3021     return false;
3022 
3023   uint64_t NumElts = ArrayTy->getArrayNumElements();
3024   if (Offset > NumElts)
3025     return false;
3026 
3027   Slice.Array = Array;
3028   Slice.Offset = Offset;
3029   Slice.Length = NumElts - Offset;
3030   return true;
3031 }
3032 
3033 /// This function computes the length of a null-terminated C string pointed to
3034 /// by V. If successful, it returns true and returns the string in Str.
3035 /// If unsuccessful, it returns false.
3036 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3037                                  uint64_t Offset, bool TrimAtNul) {
3038   ConstantDataArraySlice Slice;
3039   if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3040     return false;
3041 
3042   if (Slice.Array == nullptr) {
3043     if (TrimAtNul) {
3044       Str = StringRef();
3045       return true;
3046     }
3047     if (Slice.Length == 1) {
3048       Str = StringRef("", 1);
3049       return true;
3050     }
3051     // We cannot instantiate a StringRef as we do not have an appropriate string
3052     // of 0s at hand.
3053     return false;
3054   }
3055 
3056   // Start out with the entire array in the StringRef.
3057   Str = Slice.Array->getAsString();
3058   // Skip over 'offset' bytes.
3059   Str = Str.substr(Slice.Offset);
3060 
3061   if (TrimAtNul) {
3062     // Trim off the \0 and anything after it.  If the array is not nul
3063     // terminated, we just return the whole end of string.  The client may know
3064     // some other way that the string is length-bound.
3065     Str = Str.substr(0, Str.find('\0'));
3066   }
3067   return true;
3068 }
3069 
3070 // These next two are very similar to the above, but also look through PHI
3071 // nodes.
3072 // TODO: See if we can integrate these two together.
3073 
3074 /// If we can compute the length of the string pointed to by
3075 /// the specified pointer, return 'len+1'.  If we can't, return 0.
3076 static uint64_t GetStringLengthH(const Value *V,
3077                                  SmallPtrSetImpl<const PHINode*> &PHIs,
3078                                  unsigned CharSize) {
3079   // Look through noop bitcast instructions.
3080   V = V->stripPointerCasts();
3081 
3082   // If this is a PHI node, there are two cases: either we have already seen it
3083   // or we haven't.
3084   if (const PHINode *PN = dyn_cast<PHINode>(V)) {
3085     if (!PHIs.insert(PN).second)
3086       return ~0ULL;  // already in the set.
3087 
3088     // If it was new, see if all the input strings are the same length.
3089     uint64_t LenSoFar = ~0ULL;
3090     for (Value *IncValue : PN->incoming_values()) {
3091       uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
3092       if (Len == 0) return 0; // Unknown length -> unknown.
3093 
3094       if (Len == ~0ULL) continue;
3095 
3096       if (Len != LenSoFar && LenSoFar != ~0ULL)
3097         return 0;    // Disagree -> unknown.
3098       LenSoFar = Len;
3099     }
3100 
3101     // Success, all agree.
3102     return LenSoFar;
3103   }
3104 
3105   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
3106   if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
3107     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
3108     if (Len1 == 0) return 0;
3109     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
3110     if (Len2 == 0) return 0;
3111     if (Len1 == ~0ULL) return Len2;
3112     if (Len2 == ~0ULL) return Len1;
3113     if (Len1 != Len2) return 0;
3114     return Len1;
3115   }
3116 
3117   // Otherwise, see if we can read the string.
3118   ConstantDataArraySlice Slice;
3119   if (!getConstantDataArrayInfo(V, Slice, CharSize))
3120     return 0;
3121 
3122   if (Slice.Array == nullptr)
3123     return 1;
3124 
3125   // Search for nul characters
3126   unsigned NullIndex = 0;
3127   for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3128     if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3129       break;
3130   }
3131 
3132   return NullIndex + 1;
3133 }
3134 
3135 /// If we can compute the length of the string pointed to by
3136 /// the specified pointer, return 'len+1'.  If we can't, return 0.
3137 uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
3138   if (!V->getType()->isPointerTy()) return 0;
3139 
3140   SmallPtrSet<const PHINode*, 32> PHIs;
3141   uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
3142   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3143   // an empty string as a length.
3144   return Len == ~0ULL ? 1 : Len;
3145 }
3146 
3147 /// \brief \p PN defines a loop-variant pointer to an object.  Check if the
3148 /// previous iteration of the loop was referring to the same object as \p PN.
3149 static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3150                                          const LoopInfo *LI) {
3151   // Find the loop-defined value.
3152   Loop *L = LI->getLoopFor(PN->getParent());
3153   if (PN->getNumIncomingValues() != 2)
3154     return true;
3155 
3156   // Find the value from previous iteration.
3157   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3158   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3159     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3160   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3161     return true;
3162 
3163   // If a new pointer is loaded in the loop, the pointer references a different
3164   // object in every iteration.  E.g.:
3165   //    for (i)
3166   //       int *p = a[i];
3167   //       ...
3168   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3169     if (!L->isLoopInvariant(Load->getPointerOperand()))
3170       return false;
3171   return true;
3172 }
3173 
3174 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3175                                  unsigned MaxLookup) {
3176   if (!V->getType()->isPointerTy())
3177     return V;
3178   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3179     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3180       V = GEP->getPointerOperand();
3181     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3182                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3183       V = cast<Operator>(V)->getOperand(0);
3184     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3185       if (GA->isInterposable())
3186         return V;
3187       V = GA->getAliasee();
3188     } else if (isa<AllocaInst>(V)) {
3189       // An alloca can't be further simplified.
3190       return V;
3191     } else {
3192       if (auto CS = CallSite(V))
3193         if (Value *RV = CS.getReturnedArgOperand()) {
3194           V = RV;
3195           continue;
3196         }
3197 
3198       // See if InstructionSimplify knows any relevant tricks.
3199       if (Instruction *I = dyn_cast<Instruction>(V))
3200         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3201         if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
3202           V = Simplified;
3203           continue;
3204         }
3205 
3206       return V;
3207     }
3208     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3209   }
3210   return V;
3211 }
3212 
3213 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
3214                                 const DataLayout &DL, LoopInfo *LI,
3215                                 unsigned MaxLookup) {
3216   SmallPtrSet<Value *, 4> Visited;
3217   SmallVector<Value *, 4> Worklist;
3218   Worklist.push_back(V);
3219   do {
3220     Value *P = Worklist.pop_back_val();
3221     P = GetUnderlyingObject(P, DL, MaxLookup);
3222 
3223     if (!Visited.insert(P).second)
3224       continue;
3225 
3226     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3227       Worklist.push_back(SI->getTrueValue());
3228       Worklist.push_back(SI->getFalseValue());
3229       continue;
3230     }
3231 
3232     if (PHINode *PN = dyn_cast<PHINode>(P)) {
3233       // If this PHI changes the underlying object in every iteration of the
3234       // loop, don't look through it.  Consider:
3235       //   int **A;
3236       //   for (i) {
3237       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
3238       //     Curr = A[i];
3239       //     *Prev, *Curr;
3240       //
3241       // Prev is tracking Curr one iteration behind so they refer to different
3242       // underlying objects.
3243       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3244           isSameUnderlyingObjectInLoop(PN, LI))
3245         for (Value *IncValue : PN->incoming_values())
3246           Worklist.push_back(IncValue);
3247       continue;
3248     }
3249 
3250     Objects.push_back(P);
3251   } while (!Worklist.empty());
3252 }
3253 
3254 /// This is the function that does the work of looking through basic
3255 /// ptrtoint+arithmetic+inttoptr sequences.
3256 static const Value *getUnderlyingObjectFromInt(const Value *V) {
3257   do {
3258     if (const Operator *U = dyn_cast<Operator>(V)) {
3259       // If we find a ptrtoint, we can transfer control back to the
3260       // regular getUnderlyingObjectFromInt.
3261       if (U->getOpcode() == Instruction::PtrToInt)
3262         return U->getOperand(0);
3263       // If we find an add of a constant, a multiplied value, or a phi, it's
3264       // likely that the other operand will lead us to the base
3265       // object. We don't have to worry about the case where the
3266       // object address is somehow being computed by the multiply,
3267       // because our callers only care when the result is an
3268       // identifiable object.
3269       if (U->getOpcode() != Instruction::Add ||
3270           (!isa<ConstantInt>(U->getOperand(1)) &&
3271            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3272            !isa<PHINode>(U->getOperand(1))))
3273         return V;
3274       V = U->getOperand(0);
3275     } else {
3276       return V;
3277     }
3278     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3279   } while (true);
3280 }
3281 
3282 /// This is a wrapper around GetUnderlyingObjects and adds support for basic
3283 /// ptrtoint+arithmetic+inttoptr sequences.
3284 void llvm::getUnderlyingObjectsForCodeGen(const Value *V,
3285                           SmallVectorImpl<Value *> &Objects,
3286                           const DataLayout &DL) {
3287   SmallPtrSet<const Value *, 16> Visited;
3288   SmallVector<const Value *, 4> Working(1, V);
3289   do {
3290     V = Working.pop_back_val();
3291 
3292     SmallVector<Value *, 4> Objs;
3293     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3294 
3295     for (Value *V : Objs) {
3296       if (!Visited.insert(V).second)
3297         continue;
3298       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3299         const Value *O =
3300           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3301         if (O->getType()->isPointerTy()) {
3302           Working.push_back(O);
3303           continue;
3304         }
3305       }
3306       // If GetUnderlyingObjects fails to find an identifiable object,
3307       // getUnderlyingObjectsForCodeGen also fails for safety.
3308       if (!isIdentifiedObject(V)) {
3309         Objects.clear();
3310         return;
3311       }
3312       Objects.push_back(const_cast<Value *>(V));
3313     }
3314   } while (!Working.empty());
3315 }
3316 
3317 /// Return true if the only users of this pointer are lifetime markers.
3318 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3319   for (const User *U : V->users()) {
3320     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3321     if (!II) return false;
3322 
3323     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3324         II->getIntrinsicID() != Intrinsic::lifetime_end)
3325       return false;
3326   }
3327   return true;
3328 }
3329 
3330 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3331                                         const Instruction *CtxI,
3332                                         const DominatorTree *DT) {
3333   const Operator *Inst = dyn_cast<Operator>(V);
3334   if (!Inst)
3335     return false;
3336 
3337   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3338     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3339       if (C->canTrap())
3340         return false;
3341 
3342   switch (Inst->getOpcode()) {
3343   default:
3344     return true;
3345   case Instruction::UDiv:
3346   case Instruction::URem: {
3347     // x / y is undefined if y == 0.
3348     const APInt *V;
3349     if (match(Inst->getOperand(1), m_APInt(V)))
3350       return *V != 0;
3351     return false;
3352   }
3353   case Instruction::SDiv:
3354   case Instruction::SRem: {
3355     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3356     const APInt *Numerator, *Denominator;
3357     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3358       return false;
3359     // We cannot hoist this division if the denominator is 0.
3360     if (*Denominator == 0)
3361       return false;
3362     // It's safe to hoist if the denominator is not 0 or -1.
3363     if (*Denominator != -1)
3364       return true;
3365     // At this point we know that the denominator is -1.  It is safe to hoist as
3366     // long we know that the numerator is not INT_MIN.
3367     if (match(Inst->getOperand(0), m_APInt(Numerator)))
3368       return !Numerator->isMinSignedValue();
3369     // The numerator *might* be MinSignedValue.
3370     return false;
3371   }
3372   case Instruction::Load: {
3373     const LoadInst *LI = cast<LoadInst>(Inst);
3374     if (!LI->isUnordered() ||
3375         // Speculative load may create a race that did not exist in the source.
3376         LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
3377         // Speculative load may load data from dirty regions.
3378         LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3379       return false;
3380     const DataLayout &DL = LI->getModule()->getDataLayout();
3381     return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3382                                               LI->getAlignment(), DL, CtxI, DT);
3383   }
3384   case Instruction::Call: {
3385     auto *CI = cast<const CallInst>(Inst);
3386     const Function *Callee = CI->getCalledFunction();
3387 
3388     // The called function could have undefined behavior or side-effects, even
3389     // if marked readnone nounwind.
3390     return Callee && Callee->isSpeculatable();
3391   }
3392   case Instruction::VAArg:
3393   case Instruction::Alloca:
3394   case Instruction::Invoke:
3395   case Instruction::PHI:
3396   case Instruction::Store:
3397   case Instruction::Ret:
3398   case Instruction::Br:
3399   case Instruction::IndirectBr:
3400   case Instruction::Switch:
3401   case Instruction::Unreachable:
3402   case Instruction::Fence:
3403   case Instruction::AtomicRMW:
3404   case Instruction::AtomicCmpXchg:
3405   case Instruction::LandingPad:
3406   case Instruction::Resume:
3407   case Instruction::CatchSwitch:
3408   case Instruction::CatchPad:
3409   case Instruction::CatchRet:
3410   case Instruction::CleanupPad:
3411   case Instruction::CleanupRet:
3412     return false; // Misc instructions which have effects
3413   }
3414 }
3415 
3416 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3417   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3418 }
3419 
3420 /// Return true if we know that the specified value is never null.
3421 bool llvm::isKnownNonNull(const Value *V) {
3422   assert(V->getType()->isPointerTy() && "V must be pointer type");
3423 
3424   // Alloca never returns null, malloc might.
3425   if (isa<AllocaInst>(V)) return true;
3426 
3427   // A byval, inalloca, or nonnull argument is never null.
3428   if (const Argument *A = dyn_cast<Argument>(V))
3429     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3430 
3431   // A global variable in address space 0 is non null unless extern weak
3432   // or an absolute symbol reference. Other address spaces may have null as a
3433   // valid address for a global, so we can't assume anything.
3434   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3435     return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3436            GV->getType()->getAddressSpace() == 0;
3437 
3438   // A Load tagged with nonnull metadata is never null.
3439   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3440     return LI->getMetadata(LLVMContext::MD_nonnull);
3441 
3442   if (auto CS = ImmutableCallSite(V))
3443     if (CS.isReturnNonNull())
3444       return true;
3445 
3446   return false;
3447 }
3448 
3449 static bool isKnownNonNullFromDominatingCondition(const Value *V,
3450                                                   const Instruction *CtxI,
3451                                                   const DominatorTree *DT) {
3452   assert(V->getType()->isPointerTy() && "V must be pointer type");
3453   assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
3454   assert(CtxI && "Context instruction required for analysis");
3455   assert(DT && "Dominator tree required for analysis");
3456 
3457   unsigned NumUsesExplored = 0;
3458   for (auto *U : V->users()) {
3459     // Avoid massive lists
3460     if (NumUsesExplored >= DomConditionsMaxUses)
3461       break;
3462     NumUsesExplored++;
3463 
3464     // If the value is used as an argument to a call or invoke, then argument
3465     // attributes may provide an answer about null-ness.
3466     if (auto CS = ImmutableCallSite(U))
3467       if (auto *CalledFunc = CS.getCalledFunction())
3468         for (const Argument &Arg : CalledFunc->args())
3469           if (CS.getArgOperand(Arg.getArgNo()) == V &&
3470               Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3471             return true;
3472 
3473     // Consider only compare instructions uniquely controlling a branch
3474     CmpInst::Predicate Pred;
3475     if (!match(const_cast<User *>(U),
3476                m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3477         (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
3478       continue;
3479 
3480     for (auto *CmpU : U->users()) {
3481       if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3482         assert(BI->isConditional() && "uses a comparison!");
3483 
3484         BasicBlock *NonNullSuccessor =
3485             BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3486         BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3487         if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3488           return true;
3489       } else if (Pred == ICmpInst::ICMP_NE &&
3490                  match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3491                  DT->dominates(cast<Instruction>(CmpU), CtxI)) {
3492         return true;
3493       }
3494     }
3495   }
3496 
3497   return false;
3498 }
3499 
3500 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3501                             const DominatorTree *DT) {
3502   if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3503     return false;
3504 
3505   if (isKnownNonNull(V))
3506     return true;
3507 
3508   if (!CtxI || !DT)
3509     return false;
3510 
3511   return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
3512 }
3513 
3514 OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3515                                                    const Value *RHS,
3516                                                    const DataLayout &DL,
3517                                                    AssumptionCache *AC,
3518                                                    const Instruction *CxtI,
3519                                                    const DominatorTree *DT) {
3520   // Multiplying n * m significant bits yields a result of n + m significant
3521   // bits. If the total number of significant bits does not exceed the
3522   // result bit width (minus 1), there is no overflow.
3523   // This means if we have enough leading zero bits in the operands
3524   // we can guarantee that the result does not overflow.
3525   // Ref: "Hacker's Delight" by Henry Warren
3526   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3527   KnownBits LHSKnown(BitWidth);
3528   KnownBits RHSKnown(BitWidth);
3529   computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3530   computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3531   // Note that underestimating the number of zero bits gives a more
3532   // conservative answer.
3533   unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3534                       RHSKnown.countMinLeadingZeros();
3535   // First handle the easy case: if we have enough zero bits there's
3536   // definitely no overflow.
3537   if (ZeroBits >= BitWidth)
3538     return OverflowResult::NeverOverflows;
3539 
3540   // Get the largest possible values for each operand.
3541   APInt LHSMax = ~LHSKnown.Zero;
3542   APInt RHSMax = ~RHSKnown.Zero;
3543 
3544   // We know the multiply operation doesn't overflow if the maximum values for
3545   // each operand will not overflow after we multiply them together.
3546   bool MaxOverflow;
3547   (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
3548   if (!MaxOverflow)
3549     return OverflowResult::NeverOverflows;
3550 
3551   // We know it always overflows if multiplying the smallest possible values for
3552   // the operands also results in overflow.
3553   bool MinOverflow;
3554   (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
3555   if (MinOverflow)
3556     return OverflowResult::AlwaysOverflows;
3557 
3558   return OverflowResult::MayOverflow;
3559 }
3560 
3561 OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3562                                                    const Value *RHS,
3563                                                    const DataLayout &DL,
3564                                                    AssumptionCache *AC,
3565                                                    const Instruction *CxtI,
3566                                                    const DominatorTree *DT) {
3567   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3568   if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3569     KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
3570 
3571     if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
3572       // The sign bit is set in both cases: this MUST overflow.
3573       // Create a simple add instruction, and insert it into the struct.
3574       return OverflowResult::AlwaysOverflows;
3575     }
3576 
3577     if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
3578       // The sign bit is clear in both cases: this CANNOT overflow.
3579       // Create a simple add instruction, and insert it into the struct.
3580       return OverflowResult::NeverOverflows;
3581     }
3582   }
3583 
3584   return OverflowResult::MayOverflow;
3585 }
3586 
3587 /// \brief Return true if we can prove that adding the two values of the
3588 /// knownbits will not overflow.
3589 /// Otherwise return false.
3590 static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3591                                     const KnownBits &RHSKnown) {
3592   // Addition of two 2's complement numbers having opposite signs will never
3593   // overflow.
3594   if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3595       (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3596     return true;
3597 
3598   // If either of the values is known to be non-negative, adding them can only
3599   // overflow if the second is also non-negative, so we can assume that.
3600   // Two non-negative numbers will only overflow if there is a carry to the
3601   // sign bit, so we can check if even when the values are as big as possible
3602   // there is no overflow to the sign bit.
3603   if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3604     APInt MaxLHS = ~LHSKnown.Zero;
3605     MaxLHS.clearSignBit();
3606     APInt MaxRHS = ~RHSKnown.Zero;
3607     MaxRHS.clearSignBit();
3608     APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3609     return Result.isSignBitClear();
3610   }
3611 
3612   // If either of the values is known to be negative, adding them can only
3613   // overflow if the second is also negative, so we can assume that.
3614   // Two negative number will only overflow if there is no carry to the sign
3615   // bit, so we can check if even when the values are as small as possible
3616   // there is overflow to the sign bit.
3617   if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3618     APInt MinLHS = LHSKnown.One;
3619     MinLHS.clearSignBit();
3620     APInt MinRHS = RHSKnown.One;
3621     MinRHS.clearSignBit();
3622     APInt Result = std::move(MinLHS) + std::move(MinRHS);
3623     return Result.isSignBitSet();
3624   }
3625 
3626   // If we reached here it means that we know nothing about the sign bits.
3627   // In this case we can't know if there will be an overflow, since by
3628   // changing the sign bits any two values can be made to overflow.
3629   return false;
3630 }
3631 
3632 static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3633                                                   const Value *RHS,
3634                                                   const AddOperator *Add,
3635                                                   const DataLayout &DL,
3636                                                   AssumptionCache *AC,
3637                                                   const Instruction *CxtI,
3638                                                   const DominatorTree *DT) {
3639   if (Add && Add->hasNoSignedWrap()) {
3640     return OverflowResult::NeverOverflows;
3641   }
3642 
3643   // If LHS and RHS each have at least two sign bits, the addition will look
3644   // like
3645   //
3646   // XX..... +
3647   // YY.....
3648   //
3649   // If the carry into the most significant position is 0, X and Y can't both
3650   // be 1 and therefore the carry out of the addition is also 0.
3651   //
3652   // If the carry into the most significant position is 1, X and Y can't both
3653   // be 0 and therefore the carry out of the addition is also 1.
3654   //
3655   // Since the carry into the most significant position is always equal to
3656   // the carry out of the addition, there is no signed overflow.
3657   if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3658       ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3659     return OverflowResult::NeverOverflows;
3660 
3661   KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3662   KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
3663 
3664   if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
3665     return OverflowResult::NeverOverflows;
3666 
3667   // The remaining code needs Add to be available. Early returns if not so.
3668   if (!Add)
3669     return OverflowResult::MayOverflow;
3670 
3671   // If the sign of Add is the same as at least one of the operands, this add
3672   // CANNOT overflow. This is particularly useful when the sum is
3673   // @llvm.assume'ed non-negative rather than proved so from analyzing its
3674   // operands.
3675   bool LHSOrRHSKnownNonNegative =
3676       (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
3677   bool LHSOrRHSKnownNegative =
3678       (LHSKnown.isNegative() || RHSKnown.isNegative());
3679   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3680     KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3681     if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3682         (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
3683       return OverflowResult::NeverOverflows;
3684     }
3685   }
3686 
3687   return OverflowResult::MayOverflow;
3688 }
3689 
3690 bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3691                                      const DominatorTree &DT) {
3692 #ifndef NDEBUG
3693   auto IID = II->getIntrinsicID();
3694   assert((IID == Intrinsic::sadd_with_overflow ||
3695           IID == Intrinsic::uadd_with_overflow ||
3696           IID == Intrinsic::ssub_with_overflow ||
3697           IID == Intrinsic::usub_with_overflow ||
3698           IID == Intrinsic::smul_with_overflow ||
3699           IID == Intrinsic::umul_with_overflow) &&
3700          "Not an overflow intrinsic!");
3701 #endif
3702 
3703   SmallVector<const BranchInst *, 2> GuardingBranches;
3704   SmallVector<const ExtractValueInst *, 2> Results;
3705 
3706   for (const User *U : II->users()) {
3707     if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
3708       assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3709 
3710       if (EVI->getIndices()[0] == 0)
3711         Results.push_back(EVI);
3712       else {
3713         assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3714 
3715         for (const auto *U : EVI->users())
3716           if (const auto *B = dyn_cast<BranchInst>(U)) {
3717             assert(B->isConditional() && "How else is it using an i1?");
3718             GuardingBranches.push_back(B);
3719           }
3720       }
3721     } else {
3722       // We are using the aggregate directly in a way we don't want to analyze
3723       // here (storing it to a global, say).
3724       return false;
3725     }
3726   }
3727 
3728   auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
3729     BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3730     if (!NoWrapEdge.isSingleEdge())
3731       return false;
3732 
3733     // Check if all users of the add are provably no-wrap.
3734     for (const auto *Result : Results) {
3735       // If the extractvalue itself is not executed on overflow, the we don't
3736       // need to check each use separately, since domination is transitive.
3737       if (DT.dominates(NoWrapEdge, Result->getParent()))
3738         continue;
3739 
3740       for (auto &RU : Result->uses())
3741         if (!DT.dominates(NoWrapEdge, RU))
3742           return false;
3743     }
3744 
3745     return true;
3746   };
3747 
3748   return any_of(GuardingBranches, AllUsesGuardedByBranch);
3749 }
3750 
3751 
3752 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
3753                                                  const DataLayout &DL,
3754                                                  AssumptionCache *AC,
3755                                                  const Instruction *CxtI,
3756                                                  const DominatorTree *DT) {
3757   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3758                                        Add, DL, AC, CxtI, DT);
3759 }
3760 
3761 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3762                                                  const Value *RHS,
3763                                                  const DataLayout &DL,
3764                                                  AssumptionCache *AC,
3765                                                  const Instruction *CxtI,
3766                                                  const DominatorTree *DT) {
3767   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3768 }
3769 
3770 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3771   // A memory operation returns normally if it isn't volatile. A volatile
3772   // operation is allowed to trap.
3773   //
3774   // An atomic operation isn't guaranteed to return in a reasonable amount of
3775   // time because it's possible for another thread to interfere with it for an
3776   // arbitrary length of time, but programs aren't allowed to rely on that.
3777   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3778     return !LI->isVolatile();
3779   if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3780     return !SI->isVolatile();
3781   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3782     return !CXI->isVolatile();
3783   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3784     return !RMWI->isVolatile();
3785   if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3786     return !MII->isVolatile();
3787 
3788   // If there is no successor, then execution can't transfer to it.
3789   if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3790     return !CRI->unwindsToCaller();
3791   if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3792     return !CatchSwitch->unwindsToCaller();
3793   if (isa<ResumeInst>(I))
3794     return false;
3795   if (isa<ReturnInst>(I))
3796     return false;
3797   if (isa<UnreachableInst>(I))
3798     return false;
3799 
3800   // Calls can throw, or contain an infinite loop, or kill the process.
3801   if (auto CS = ImmutableCallSite(I)) {
3802     // Call sites that throw have implicit non-local control flow.
3803     if (!CS.doesNotThrow())
3804       return false;
3805 
3806     // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3807     // etc. and thus not return.  However, LLVM already assumes that
3808     //
3809     //  - Thread exiting actions are modeled as writes to memory invisible to
3810     //    the program.
3811     //
3812     //  - Loops that don't have side effects (side effects are volatile/atomic
3813     //    stores and IO) always terminate (see http://llvm.org/PR965).
3814     //    Furthermore IO itself is also modeled as writes to memory invisible to
3815     //    the program.
3816     //
3817     // We rely on those assumptions here, and use the memory effects of the call
3818     // target as a proxy for checking that it always returns.
3819 
3820     // FIXME: This isn't aggressive enough; a call which only writes to a global
3821     // is guaranteed to return.
3822     return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3823            match(I, m_Intrinsic<Intrinsic::assume>());
3824   }
3825 
3826   // Other instructions return normally.
3827   return true;
3828 }
3829 
3830 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3831                                                   const Loop *L) {
3832   // The loop header is guaranteed to be executed for every iteration.
3833   //
3834   // FIXME: Relax this constraint to cover all basic blocks that are
3835   // guaranteed to be executed at every iteration.
3836   if (I->getParent() != L->getHeader()) return false;
3837 
3838   for (const Instruction &LI : *L->getHeader()) {
3839     if (&LI == I) return true;
3840     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3841   }
3842   llvm_unreachable("Instruction not contained in its own parent basic block.");
3843 }
3844 
3845 bool llvm::propagatesFullPoison(const Instruction *I) {
3846   switch (I->getOpcode()) {
3847   case Instruction::Add:
3848   case Instruction::Sub:
3849   case Instruction::Xor:
3850   case Instruction::Trunc:
3851   case Instruction::BitCast:
3852   case Instruction::AddrSpaceCast:
3853   case Instruction::Mul:
3854   case Instruction::Shl:
3855   case Instruction::GetElementPtr:
3856     // These operations all propagate poison unconditionally. Note that poison
3857     // is not any particular value, so xor or subtraction of poison with
3858     // itself still yields poison, not zero.
3859     return true;
3860 
3861   case Instruction::AShr:
3862   case Instruction::SExt:
3863     // For these operations, one bit of the input is replicated across
3864     // multiple output bits. A replicated poison bit is still poison.
3865     return true;
3866 
3867   case Instruction::ICmp:
3868     // Comparing poison with any value yields poison.  This is why, for
3869     // instance, x s< (x +nsw 1) can be folded to true.
3870     return true;
3871 
3872   default:
3873     return false;
3874   }
3875 }
3876 
3877 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3878   switch (I->getOpcode()) {
3879     case Instruction::Store:
3880       return cast<StoreInst>(I)->getPointerOperand();
3881 
3882     case Instruction::Load:
3883       return cast<LoadInst>(I)->getPointerOperand();
3884 
3885     case Instruction::AtomicCmpXchg:
3886       return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3887 
3888     case Instruction::AtomicRMW:
3889       return cast<AtomicRMWInst>(I)->getPointerOperand();
3890 
3891     case Instruction::UDiv:
3892     case Instruction::SDiv:
3893     case Instruction::URem:
3894     case Instruction::SRem:
3895       return I->getOperand(1);
3896 
3897     default:
3898       return nullptr;
3899   }
3900 }
3901 
3902 bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
3903   // We currently only look for uses of poison values within the same basic
3904   // block, as that makes it easier to guarantee that the uses will be
3905   // executed given that PoisonI is executed.
3906   //
3907   // FIXME: Expand this to consider uses beyond the same basic block. To do
3908   // this, look out for the distinction between post-dominance and strong
3909   // post-dominance.
3910   const BasicBlock *BB = PoisonI->getParent();
3911 
3912   // Set of instructions that we have proved will yield poison if PoisonI
3913   // does.
3914   SmallSet<const Value *, 16> YieldsPoison;
3915   SmallSet<const BasicBlock *, 4> Visited;
3916   YieldsPoison.insert(PoisonI);
3917   Visited.insert(PoisonI->getParent());
3918 
3919   BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
3920 
3921   unsigned Iter = 0;
3922   while (Iter++ < MaxDepth) {
3923     for (auto &I : make_range(Begin, End)) {
3924       if (&I != PoisonI) {
3925         const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3926         if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3927           return true;
3928         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3929           return false;
3930       }
3931 
3932       // Mark poison that propagates from I through uses of I.
3933       if (YieldsPoison.count(&I)) {
3934         for (const User *User : I.users()) {
3935           const Instruction *UserI = cast<Instruction>(User);
3936           if (propagatesFullPoison(UserI))
3937             YieldsPoison.insert(User);
3938         }
3939       }
3940     }
3941 
3942     if (auto *NextBB = BB->getSingleSuccessor()) {
3943       if (Visited.insert(NextBB).second) {
3944         BB = NextBB;
3945         Begin = BB->getFirstNonPHI()->getIterator();
3946         End = BB->end();
3947         continue;
3948       }
3949     }
3950 
3951     break;
3952   };
3953   return false;
3954 }
3955 
3956 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
3957   if (FMF.noNaNs())
3958     return true;
3959 
3960   if (auto *C = dyn_cast<ConstantFP>(V))
3961     return !C->isNaN();
3962   return false;
3963 }
3964 
3965 static bool isKnownNonZero(const Value *V) {
3966   if (auto *C = dyn_cast<ConstantFP>(V))
3967     return !C->isZero();
3968   return false;
3969 }
3970 
3971 /// Match clamp pattern for float types without care about NaNs or signed zeros.
3972 /// Given non-min/max outer cmp/select from the clamp pattern this
3973 /// function recognizes if it can be substitued by a "canonical" min/max
3974 /// pattern.
3975 static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
3976                                                Value *CmpLHS, Value *CmpRHS,
3977                                                Value *TrueVal, Value *FalseVal,
3978                                                Value *&LHS, Value *&RHS) {
3979   // Try to match
3980   //   X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
3981   //   X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
3982   // and return description of the outer Max/Min.
3983 
3984   // First, check if select has inverse order:
3985   if (CmpRHS == FalseVal) {
3986     std::swap(TrueVal, FalseVal);
3987     Pred = CmpInst::getInversePredicate(Pred);
3988   }
3989 
3990   // Assume success now. If there's no match, callers should not use these anyway.
3991   LHS = TrueVal;
3992   RHS = FalseVal;
3993 
3994   const APFloat *FC1;
3995   if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
3996     return {SPF_UNKNOWN, SPNB_NA, false};
3997 
3998   const APFloat *FC2;
3999   switch (Pred) {
4000   case CmpInst::FCMP_OLT:
4001   case CmpInst::FCMP_OLE:
4002   case CmpInst::FCMP_ULT:
4003   case CmpInst::FCMP_ULE:
4004     if (match(FalseVal,
4005               m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4006                           m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4007         FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4008       return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4009     break;
4010   case CmpInst::FCMP_OGT:
4011   case CmpInst::FCMP_OGE:
4012   case CmpInst::FCMP_UGT:
4013   case CmpInst::FCMP_UGE:
4014     if (match(FalseVal,
4015               m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4016                           m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4017         FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4018       return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4019     break;
4020   default:
4021     break;
4022   }
4023 
4024   return {SPF_UNKNOWN, SPNB_NA, false};
4025 }
4026 
4027 /// Match non-obvious integer minimum and maximum sequences.
4028 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4029                                        Value *CmpLHS, Value *CmpRHS,
4030                                        Value *TrueVal, Value *FalseVal,
4031                                        Value *&LHS, Value *&RHS) {
4032   // Assume success. If there's no match, callers should not use these anyway.
4033   LHS = TrueVal;
4034   RHS = FalseVal;
4035 
4036   // Recognize variations of:
4037   // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4038   const APInt *C1;
4039   if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4040     const APInt *C2;
4041 
4042     // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4043     if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4044         C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
4045       return {SPF_SMAX, SPNB_NA, false};
4046 
4047     // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4048     if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4049         C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
4050       return {SPF_SMIN, SPNB_NA, false};
4051 
4052     // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4053     if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
4054         C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
4055       return {SPF_UMAX, SPNB_NA, false};
4056 
4057     // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4058     if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
4059         C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
4060       return {SPF_UMIN, SPNB_NA, false};
4061   }
4062 
4063   if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
4064     return {SPF_UNKNOWN, SPNB_NA, false};
4065 
4066   // Z = X -nsw Y
4067   // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4068   // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4069   if (match(TrueVal, m_Zero()) &&
4070       match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4071     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4072 
4073   // Z = X -nsw Y
4074   // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4075   // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4076   if (match(FalseVal, m_Zero()) &&
4077       match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
4078     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4079 
4080   if (!match(CmpRHS, m_APInt(C1)))
4081     return {SPF_UNKNOWN, SPNB_NA, false};
4082 
4083   // An unsigned min/max can be written with a signed compare.
4084   const APInt *C2;
4085   if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4086       (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4087     // Is the sign bit set?
4088     // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4089     // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
4090     if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
4091       return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4092 
4093     // Is the sign bit clear?
4094     // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4095     // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4096     if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4097         C2->isMinSignedValue())
4098       return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
4099   }
4100 
4101   // Look through 'not' ops to find disguised signed min/max.
4102   // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4103   // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4104   if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
4105       match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
4106     return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
4107 
4108   // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4109   // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4110   if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
4111       match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
4112     return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
4113 
4114   return {SPF_UNKNOWN, SPNB_NA, false};
4115 }
4116 
4117 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4118                                               FastMathFlags FMF,
4119                                               Value *CmpLHS, Value *CmpRHS,
4120                                               Value *TrueVal, Value *FalseVal,
4121                                               Value *&LHS, Value *&RHS) {
4122   LHS = CmpLHS;
4123   RHS = CmpRHS;
4124 
4125   // If the predicate is an "or-equal"  (FP) predicate, then signed zeroes may
4126   // return inconsistent results between implementations.
4127   //   (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4128   //   minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4129   // Therefore we behave conservatively and only proceed if at least one of the
4130   // operands is known to not be zero, or if we don't care about signed zeroes.
4131   switch (Pred) {
4132   default: break;
4133   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4134   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4135     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4136         !isKnownNonZero(CmpRHS))
4137       return {SPF_UNKNOWN, SPNB_NA, false};
4138   }
4139 
4140   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4141   bool Ordered = false;
4142 
4143   // When given one NaN and one non-NaN input:
4144   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4145   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4146   //     ordered comparison fails), which could be NaN or non-NaN.
4147   // so here we discover exactly what NaN behavior is required/accepted.
4148   if (CmpInst::isFPPredicate(Pred)) {
4149     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4150     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4151 
4152     if (LHSSafe && RHSSafe) {
4153       // Both operands are known non-NaN.
4154       NaNBehavior = SPNB_RETURNS_ANY;
4155     } else if (CmpInst::isOrdered(Pred)) {
4156       // An ordered comparison will return false when given a NaN, so it
4157       // returns the RHS.
4158       Ordered = true;
4159       if (LHSSafe)
4160         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
4161         NaNBehavior = SPNB_RETURNS_NAN;
4162       else if (RHSSafe)
4163         NaNBehavior = SPNB_RETURNS_OTHER;
4164       else
4165         // Completely unsafe.
4166         return {SPF_UNKNOWN, SPNB_NA, false};
4167     } else {
4168       Ordered = false;
4169       // An unordered comparison will return true when given a NaN, so it
4170       // returns the LHS.
4171       if (LHSSafe)
4172         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
4173         NaNBehavior = SPNB_RETURNS_OTHER;
4174       else if (RHSSafe)
4175         NaNBehavior = SPNB_RETURNS_NAN;
4176       else
4177         // Completely unsafe.
4178         return {SPF_UNKNOWN, SPNB_NA, false};
4179     }
4180   }
4181 
4182   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
4183     std::swap(CmpLHS, CmpRHS);
4184     Pred = CmpInst::getSwappedPredicate(Pred);
4185     if (NaNBehavior == SPNB_RETURNS_NAN)
4186       NaNBehavior = SPNB_RETURNS_OTHER;
4187     else if (NaNBehavior == SPNB_RETURNS_OTHER)
4188       NaNBehavior = SPNB_RETURNS_NAN;
4189     Ordered = !Ordered;
4190   }
4191 
4192   // ([if]cmp X, Y) ? X : Y
4193   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
4194     switch (Pred) {
4195     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
4196     case ICmpInst::ICMP_UGT:
4197     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
4198     case ICmpInst::ICMP_SGT:
4199     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
4200     case ICmpInst::ICMP_ULT:
4201     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
4202     case ICmpInst::ICMP_SLT:
4203     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4204     case FCmpInst::FCMP_UGT:
4205     case FCmpInst::FCMP_UGE:
4206     case FCmpInst::FCMP_OGT:
4207     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4208     case FCmpInst::FCMP_ULT:
4209     case FCmpInst::FCMP_ULE:
4210     case FCmpInst::FCMP_OLT:
4211     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
4212     }
4213   }
4214 
4215   const APInt *C1;
4216   if (match(CmpRHS, m_APInt(C1))) {
4217     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4218         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4219 
4220       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4221       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
4222       if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
4223         return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
4224       }
4225 
4226       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4227       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
4228       if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
4229         return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
4230       }
4231     }
4232   }
4233 
4234   if (CmpInst::isIntPredicate(Pred))
4235     return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4236 
4237   // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4238   // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4239   // semantics than minNum. Be conservative in such case.
4240   if (NaNBehavior != SPNB_RETURNS_ANY ||
4241       (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4242        !isKnownNonZero(CmpRHS)))
4243     return {SPF_UNKNOWN, SPNB_NA, false};
4244 
4245   return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4246 }
4247 
4248 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4249                               Instruction::CastOps *CastOp) {
4250   auto *Cast1 = dyn_cast<CastInst>(V1);
4251   if (!Cast1)
4252     return nullptr;
4253 
4254   *CastOp = Cast1->getOpcode();
4255   Type *SrcTy = Cast1->getSrcTy();
4256   if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4257     // If V1 and V2 are both the same cast from the same type, look through V1.
4258     if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4259       return Cast2->getOperand(0);
4260     return nullptr;
4261   }
4262 
4263   auto *C = dyn_cast<Constant>(V2);
4264   if (!C)
4265     return nullptr;
4266 
4267   Constant *CastedTo = nullptr;
4268   switch (*CastOp) {
4269   case Instruction::ZExt:
4270     if (CmpI->isUnsigned())
4271       CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4272     break;
4273   case Instruction::SExt:
4274     if (CmpI->isSigned())
4275       CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4276     break;
4277   case Instruction::Trunc:
4278     CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4279     break;
4280   case Instruction::FPTrunc:
4281     CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4282     break;
4283   case Instruction::FPExt:
4284     CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4285     break;
4286   case Instruction::FPToUI:
4287     CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4288     break;
4289   case Instruction::FPToSI:
4290     CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4291     break;
4292   case Instruction::UIToFP:
4293     CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4294     break;
4295   case Instruction::SIToFP:
4296     CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4297     break;
4298   default:
4299     break;
4300   }
4301 
4302   if (!CastedTo)
4303     return nullptr;
4304 
4305   // Make sure the cast doesn't lose any information.
4306   Constant *CastedBack =
4307       ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
4308   if (CastedBack != C)
4309     return nullptr;
4310 
4311   return CastedTo;
4312 }
4313 
4314 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
4315                                              Instruction::CastOps *CastOp) {
4316   SelectInst *SI = dyn_cast<SelectInst>(V);
4317   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
4318 
4319   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4320   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
4321 
4322   CmpInst::Predicate Pred = CmpI->getPredicate();
4323   Value *CmpLHS = CmpI->getOperand(0);
4324   Value *CmpRHS = CmpI->getOperand(1);
4325   Value *TrueVal = SI->getTrueValue();
4326   Value *FalseVal = SI->getFalseValue();
4327   FastMathFlags FMF;
4328   if (isa<FPMathOperator>(CmpI))
4329     FMF = CmpI->getFastMathFlags();
4330 
4331   // Bail out early.
4332   if (CmpI->isEquality())
4333     return {SPF_UNKNOWN, SPNB_NA, false};
4334 
4335   // Deal with type mismatches.
4336   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
4337     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
4338       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4339                                   cast<CastInst>(TrueVal)->getOperand(0), C,
4340                                   LHS, RHS);
4341     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
4342       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4343                                   C, cast<CastInst>(FalseVal)->getOperand(0),
4344                                   LHS, RHS);
4345   }
4346   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
4347                               LHS, RHS);
4348 }
4349 
4350 /// Return true if "icmp Pred LHS RHS" is always true.
4351 static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4352                             const Value *RHS, const DataLayout &DL,
4353                             unsigned Depth) {
4354   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
4355   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4356     return true;
4357 
4358   switch (Pred) {
4359   default:
4360     return false;
4361 
4362   case CmpInst::ICMP_SLE: {
4363     const APInt *C;
4364 
4365     // LHS s<= LHS +_{nsw} C   if C >= 0
4366     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
4367       return !C->isNegative();
4368     return false;
4369   }
4370 
4371   case CmpInst::ICMP_ULE: {
4372     const APInt *C;
4373 
4374     // LHS u<= LHS +_{nuw} C   for any C
4375     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
4376       return true;
4377 
4378     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
4379     auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4380                                        const Value *&X,
4381                                        const APInt *&CA, const APInt *&CB) {
4382       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4383           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4384         return true;
4385 
4386       // If X & C == 0 then (X | C) == X +_{nuw} C
4387       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4388           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
4389         KnownBits Known(CA->getBitWidth());
4390         computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4391                          /*CxtI*/ nullptr, /*DT*/ nullptr);
4392         if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
4393           return true;
4394       }
4395 
4396       return false;
4397     };
4398 
4399     const Value *X;
4400     const APInt *CLHS, *CRHS;
4401     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4402       return CLHS->ule(*CRHS);
4403 
4404     return false;
4405   }
4406   }
4407 }
4408 
4409 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
4410 /// ALHS ARHS" is true.  Otherwise, return None.
4411 static Optional<bool>
4412 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4413                       const Value *ARHS, const Value *BLHS, const Value *BRHS,
4414                       const DataLayout &DL, unsigned Depth) {
4415   switch (Pred) {
4416   default:
4417     return None;
4418 
4419   case CmpInst::ICMP_SLT:
4420   case CmpInst::ICMP_SLE:
4421     if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4422         isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
4423       return true;
4424     return None;
4425 
4426   case CmpInst::ICMP_ULT:
4427   case CmpInst::ICMP_ULE:
4428     if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4429         isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
4430       return true;
4431     return None;
4432   }
4433 }
4434 
4435 /// Return true if the operands of the two compares match.  IsSwappedOps is true
4436 /// when the operands match, but are swapped.
4437 static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4438                           const Value *BLHS, const Value *BRHS,
4439                           bool &IsSwappedOps) {
4440 
4441   bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4442   IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4443   return IsMatchingOps || IsSwappedOps;
4444 }
4445 
4446 /// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4447 /// true.  Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4448 /// BRHS" is false.  Otherwise, return None if we can't infer anything.
4449 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
4450                                                     const Value *ALHS,
4451                                                     const Value *ARHS,
4452                                                     CmpInst::Predicate BPred,
4453                                                     const Value *BLHS,
4454                                                     const Value *BRHS,
4455                                                     bool IsSwappedOps) {
4456   // Canonicalize the operands so they're matching.
4457   if (IsSwappedOps) {
4458     std::swap(BLHS, BRHS);
4459     BPred = ICmpInst::getSwappedPredicate(BPred);
4460   }
4461   if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
4462     return true;
4463   if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
4464     return false;
4465 
4466   return None;
4467 }
4468 
4469 /// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4470 /// true.  Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4471 /// C2" is false.  Otherwise, return None if we can't infer anything.
4472 static Optional<bool>
4473 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4474                                  const ConstantInt *C1,
4475                                  CmpInst::Predicate BPred,
4476                                  const Value *BLHS, const ConstantInt *C2) {
4477   assert(ALHS == BLHS && "LHS operands must match.");
4478   ConstantRange DomCR =
4479       ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4480   ConstantRange CR =
4481       ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4482   ConstantRange Intersection = DomCR.intersectWith(CR);
4483   ConstantRange Difference = DomCR.difference(CR);
4484   if (Intersection.isEmptySet())
4485     return false;
4486   if (Difference.isEmptySet())
4487     return true;
4488   return None;
4489 }
4490 
4491 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
4492 /// false.  Otherwise, return None if we can't infer anything.
4493 static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4494                                          const ICmpInst *RHS,
4495                                          const DataLayout &DL, bool LHSIsTrue,
4496                                          unsigned Depth) {
4497   Value *ALHS = LHS->getOperand(0);
4498   Value *ARHS = LHS->getOperand(1);
4499   // The rest of the logic assumes the LHS condition is true.  If that's not the
4500   // case, invert the predicate to make it so.
4501   ICmpInst::Predicate APred =
4502       LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
4503 
4504   Value *BLHS = RHS->getOperand(0);
4505   Value *BRHS = RHS->getOperand(1);
4506   ICmpInst::Predicate BPred = RHS->getPredicate();
4507 
4508   // Can we infer anything when the two compares have matching operands?
4509   bool IsSwappedOps;
4510   if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4511     if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4512             APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
4513       return Implication;
4514     // No amount of additional analysis will infer the second condition, so
4515     // early exit.
4516     return None;
4517   }
4518 
4519   // Can we infer anything when the LHS operands match and the RHS operands are
4520   // constants (not necessarily matching)?
4521   if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4522     if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4523             APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4524             cast<ConstantInt>(BRHS)))
4525       return Implication;
4526     // No amount of additional analysis will infer the second condition, so
4527     // early exit.
4528     return None;
4529   }
4530 
4531   if (APred == BPred)
4532     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
4533   return None;
4534 }
4535 
4536 /// Return true if LHS implies RHS is true.  Return false if LHS implies RHS is
4537 /// false.  Otherwise, return None if we can't infer anything.  We expect the
4538 /// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4539 static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4540                                          const ICmpInst *RHS,
4541                                          const DataLayout &DL, bool LHSIsTrue,
4542                                          unsigned Depth) {
4543   // The LHS must be an 'or' or an 'and' instruction.
4544   assert((LHS->getOpcode() == Instruction::And ||
4545           LHS->getOpcode() == Instruction::Or) &&
4546          "Expected LHS to be 'and' or 'or'.");
4547 
4548   assert(Depth <= MaxDepth && "Hit recursion limit");
4549 
4550   // If the result of an 'or' is false, then we know both legs of the 'or' are
4551   // false.  Similarly, if the result of an 'and' is true, then we know both
4552   // legs of the 'and' are true.
4553   Value *ALHS, *ARHS;
4554   if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4555       (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
4556     // FIXME: Make this non-recursion.
4557     if (Optional<bool> Implication =
4558             isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
4559       return Implication;
4560     if (Optional<bool> Implication =
4561             isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
4562       return Implication;
4563     return None;
4564   }
4565   return None;
4566 }
4567 
4568 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
4569                                         const DataLayout &DL, bool LHSIsTrue,
4570                                         unsigned Depth) {
4571   // Bail out when we hit the limit.
4572   if (Depth == MaxDepth)
4573     return None;
4574 
4575   // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4576   // example.
4577   if (LHS->getType() != RHS->getType())
4578     return None;
4579 
4580   Type *OpTy = LHS->getType();
4581   assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
4582 
4583   // LHS ==> RHS by definition
4584   if (LHS == RHS)
4585     return LHSIsTrue;
4586 
4587   // FIXME: Extending the code below to handle vectors.
4588   if (OpTy->isVectorTy())
4589     return None;
4590 
4591   assert(OpTy->isIntegerTy(1) && "implied by above");
4592 
4593   // Both LHS and RHS are icmps.
4594   const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4595   const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4596   if (LHSCmp && RHSCmp)
4597     return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
4598 
4599   // The LHS should be an 'or' or an 'and' instruction.  We expect the RHS to be
4600   // an icmp. FIXME: Add support for and/or on the RHS.
4601   const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4602   if (LHSBO && RHSCmp) {
4603     if ((LHSBO->getOpcode() == Instruction::And ||
4604          LHSBO->getOpcode() == Instruction::Or))
4605       return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
4606   }
4607   return None;
4608 }
4609