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