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