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