Make use of @llvm.assume in ValueTracking (computeKnownBits, etc.)
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Analysis/AssumptionTracker.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/MemoryBuiltins.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MathExtras.h"
36 #include <cstring>
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39
40 const unsigned MaxDepth = 6;
41
42 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
43 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
44 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
45   if (unsigned BitWidth = Ty->getScalarSizeInBits())
46     return BitWidth;
47
48   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
49 }
50
51 // Many of these functions have internal versions that take an assumption
52 // exclusion set. This is because of the potential for mutual recursion to
53 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
54 // classic case of this is assume(x = y), which will attempt to determine
55 // bits in x from bits in y, which will attempt to determine bits in y from
56 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
57 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
58 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
59 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
60
61 // Simplifying using an assume can only be done in a particular control-flow
62 // context (the context instruction provides that context). If an assume and
63 // the context instruction are not in the same block then the DT helps in
64 // figuring out if we can use it.
65 struct Query {
66   ExclInvsSet ExclInvs;
67   AssumptionTracker *AT;
68   const Instruction *CxtI;
69   const DominatorTree *DT;
70
71   Query(AssumptionTracker *AT = nullptr, const Instruction *CxtI = nullptr,
72         const DominatorTree *DT = nullptr)
73     : AT(AT), CxtI(CxtI), DT(DT) {}
74
75   Query(const Query &Q, const Value *NewExcl)
76     : ExclInvs(Q.ExclInvs), AT(Q.AT), CxtI(Q.CxtI), DT(Q.DT) {
77     ExclInvs.insert(NewExcl);
78   }
79 };
80
81 // Given the provided Value and, potentially, a context instruction, returned
82 // the preferred context instruction (if any).
83 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
84   // If we've been provided with a context instruction, then use that (provided
85   // it has been inserted).
86   if (CxtI && CxtI->getParent())
87     return CxtI;
88
89   // If the value is really an already-inserted instruction, then use that.
90   CxtI = dyn_cast<Instruction>(V);
91   if (CxtI && CxtI->getParent())
92     return CxtI;
93
94   return nullptr;
95 }
96
97 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
98                             const DataLayout *TD, unsigned Depth,
99                             const Query &Q);
100
101 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
102                             const DataLayout *TD, unsigned Depth,
103                             AssumptionTracker *AT, const Instruction *CxtI,
104                             const DominatorTree *DT) {
105   ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
106                      Query(AT, safeCxtI(V, CxtI), DT));
107 }
108
109 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
110                           const DataLayout *TD, unsigned Depth,
111                           const Query &Q);
112
113 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
114                           const DataLayout *TD, unsigned Depth,
115                           AssumptionTracker *AT, const Instruction *CxtI,
116                           const DominatorTree *DT) {
117   ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
118                    Query(AT, safeCxtI(V, CxtI), DT));
119 }
120
121 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
122                                    const Query &Q);
123
124 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
125                                   AssumptionTracker *AT,
126                                   const Instruction *CxtI,
127                                   const DominatorTree *DT) {
128   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
129                                   Query(AT, safeCxtI(V, CxtI), DT));
130 }
131
132 static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
133                            const Query &Q);
134
135 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
136                           AssumptionTracker *AT, const Instruction *CxtI,
137                           const DominatorTree *DT) {
138   return ::isKnownNonZero(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
139 }
140
141 static bool MaskedValueIsZero(Value *V, const APInt &Mask,
142                               const DataLayout *TD, unsigned Depth,
143                               const Query &Q);
144
145 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
146                              const DataLayout *TD, unsigned Depth,
147                              AssumptionTracker *AT, const Instruction *CxtI,
148                              const DominatorTree *DT) {
149   return ::MaskedValueIsZero(V, Mask, TD, Depth,
150                              Query(AT, safeCxtI(V, CxtI), DT));
151 }
152
153 static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
154                                    unsigned Depth, const Query &Q);
155
156 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
157                                   unsigned Depth, AssumptionTracker *AT,
158                                   const Instruction *CxtI,
159                                   const DominatorTree *DT) {
160   return ::ComputeNumSignBits(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
161 }
162
163 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
164                                    APInt &KnownZero, APInt &KnownOne,
165                                    APInt &KnownZero2, APInt &KnownOne2,
166                                    const DataLayout *TD, unsigned Depth,
167                                    const Query &Q) {
168   if (!Add) {
169     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
170       // We know that the top bits of C-X are clear if X contains less bits
171       // than C (i.e. no wrap-around can happen).  For example, 20-X is
172       // positive if we can prove that X is >= 0 and < 16.
173       if (!CLHS->getValue().isNegative()) {
174         unsigned BitWidth = KnownZero.getBitWidth();
175         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
176         // NLZ can't be BitWidth with no sign bit
177         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
178         computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
179
180         // If all of the MaskV bits are known to be zero, then we know the
181         // output top bits are zero, because we now know that the output is
182         // from [0-C].
183         if ((KnownZero2 & MaskV) == MaskV) {
184           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
185           // Top bits known zero.
186           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
187         }
188       }
189     }
190   }
191
192   unsigned BitWidth = KnownZero.getBitWidth();
193
194   // If an initial sequence of bits in the result is not needed, the
195   // corresponding bits in the operands are not needed.
196   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
197   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
198   computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
199
200   // Carry in a 1 for a subtract, rather than a 0.
201   APInt CarryIn(BitWidth, 0);
202   if (!Add) {
203     // Sum = LHS + ~RHS + 1
204     std::swap(KnownZero2, KnownOne2);
205     CarryIn.setBit(0);
206   }
207
208   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
209   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
210
211   // Compute known bits of the carry.
212   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
213   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
214
215   // Compute set of known bits (where all three relevant bits are known).
216   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
217   APInt RHSKnown = KnownZero2 | KnownOne2;
218   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
219   APInt Known = LHSKnown & RHSKnown & CarryKnown;
220
221   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
222          "known bits of sum differ");
223
224   // Compute known bits of the result.
225   KnownZero = ~PossibleSumOne & Known;
226   KnownOne = PossibleSumOne & Known;
227
228   // Are we still trying to solve for the sign bit?
229   if (!Known.isNegative()) {
230     if (NSW) {
231       // Adding two non-negative numbers, or subtracting a negative number from
232       // a non-negative one, can't wrap into negative.
233       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
234         KnownZero |= APInt::getSignBit(BitWidth);
235       // Adding two negative numbers, or subtracting a non-negative number from
236       // a negative one, can't wrap into non-negative.
237       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
238         KnownOne |= APInt::getSignBit(BitWidth);
239     }
240   }
241 }
242
243 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
244                                 APInt &KnownZero, APInt &KnownOne,
245                                 APInt &KnownZero2, APInt &KnownOne2,
246                                 const DataLayout *TD, unsigned Depth,
247                                 const Query &Q) {
248   unsigned BitWidth = KnownZero.getBitWidth();
249   computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
250   computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
251
252   bool isKnownNegative = false;
253   bool isKnownNonNegative = false;
254   // If the multiplication is known not to overflow, compute the sign bit.
255   if (NSW) {
256     if (Op0 == Op1) {
257       // The product of a number with itself is non-negative.
258       isKnownNonNegative = true;
259     } else {
260       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
261       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
262       bool isKnownNegativeOp1 = KnownOne.isNegative();
263       bool isKnownNegativeOp0 = KnownOne2.isNegative();
264       // The product of two numbers with the same sign is non-negative.
265       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
266         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
267       // The product of a negative number and a non-negative number is either
268       // negative or zero.
269       if (!isKnownNonNegative)
270         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
271                            isKnownNonZero(Op0, TD, Depth, Q)) ||
272                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
273                            isKnownNonZero(Op1, TD, Depth, Q));
274     }
275   }
276
277   // If low bits are zero in either operand, output low known-0 bits.
278   // Also compute a conserative estimate for high known-0 bits.
279   // More trickiness is possible, but this is sufficient for the
280   // interesting case of alignment computation.
281   KnownOne.clearAllBits();
282   unsigned TrailZ = KnownZero.countTrailingOnes() +
283                     KnownZero2.countTrailingOnes();
284   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
285                              KnownZero2.countLeadingOnes(),
286                              BitWidth) - BitWidth;
287
288   TrailZ = std::min(TrailZ, BitWidth);
289   LeadZ = std::min(LeadZ, BitWidth);
290   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
291               APInt::getHighBitsSet(BitWidth, LeadZ);
292
293   // Only make use of no-wrap flags if we failed to compute the sign bit
294   // directly.  This matters if the multiplication always overflows, in
295   // which case we prefer to follow the result of the direct computation,
296   // though as the program is invoking undefined behaviour we can choose
297   // whatever we like here.
298   if (isKnownNonNegative && !KnownOne.isNegative())
299     KnownZero.setBit(BitWidth - 1);
300   else if (isKnownNegative && !KnownZero.isNegative())
301     KnownOne.setBit(BitWidth - 1);
302 }
303
304 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
305                                              APInt &KnownZero) {
306   unsigned BitWidth = KnownZero.getBitWidth();
307   unsigned NumRanges = Ranges.getNumOperands() / 2;
308   assert(NumRanges >= 1);
309
310   // Use the high end of the ranges to find leading zeros.
311   unsigned MinLeadingZeros = BitWidth;
312   for (unsigned i = 0; i < NumRanges; ++i) {
313     ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
314     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
315     ConstantRange Range(Lower->getValue(), Upper->getValue());
316     if (Range.isWrappedSet())
317       MinLeadingZeros = 0; // -1 has no zeros
318     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
319     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
320   }
321
322   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
323 }
324
325 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
326   SmallVector<const Value *, 16> WorkSet(1, I);
327   SmallPtrSet<const Value *, 32> Visited;
328   SmallPtrSet<const Value *, 16> EphValues;
329
330   while (!WorkSet.empty()) {
331     const Value *V = WorkSet.pop_back_val();
332     if (!Visited.insert(V))
333       continue;
334
335     // If all uses of this value are ephemeral, then so is this value.
336     bool FoundNEUse = false;
337     for (const User *I : V->users())
338       if (!EphValues.count(I)) {
339         FoundNEUse = true;
340         break;
341       }
342
343     if (!FoundNEUse) {
344       if (V == E)
345         return true;
346
347       EphValues.insert(V);
348       if (const User *U = dyn_cast<User>(V))
349         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
350              J != JE; ++J) {
351           if (isSafeToSpeculativelyExecute(*J))
352             WorkSet.push_back(*J);
353         }
354     }
355   }
356
357   return false;
358 }
359
360 // Is this an intrinsic that cannot be speculated but also cannot trap?
361 static bool isAssumeLikeIntrinsic(const Instruction *I) {
362   if (const CallInst *CI = dyn_cast<CallInst>(I))
363     if (Function *F = CI->getCalledFunction())
364       switch (F->getIntrinsicID()) {
365       default: break;
366       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
367       case Intrinsic::assume:
368       case Intrinsic::dbg_declare:
369       case Intrinsic::dbg_value:
370       case Intrinsic::invariant_start:
371       case Intrinsic::invariant_end:
372       case Intrinsic::lifetime_start:
373       case Intrinsic::lifetime_end:
374       case Intrinsic::objectsize:
375       case Intrinsic::ptr_annotation:
376       case Intrinsic::var_annotation:
377         return true;
378       }
379
380   return false;
381 }
382
383 static bool isValidAssumeForContext(Value *V, const Query &Q,
384                                     const DataLayout *DL) {
385   Instruction *Inv = cast<Instruction>(V);
386
387   // There are two restrictions on the use of an assume:
388   //  1. The assume must dominate the context (or the control flow must
389   //     reach the assume whenever it reaches the context).
390   //  2. The context must not be in the assume's set of ephemeral values
391   //     (otherwise we will use the assume to prove that the condition
392   //     feeding the assume is trivially true, thus causing the removal of
393   //     the assume).
394
395   if (Q.DT) {
396     if (Q.DT->dominates(Inv, Q.CxtI)) {
397       return true;
398     } else if (Inv->getParent() == Q.CxtI->getParent()) {
399       // The context comes first, but they're both in the same block. Make sure
400       // there is nothing in between that might interrupt the control flow.
401       for (BasicBlock::const_iterator I =
402              std::next(BasicBlock::const_iterator(Q.CxtI)),
403                                       IE(Inv); I != IE; ++I)
404         if (!isSafeToSpeculativelyExecute(I, DL) &&
405             !isAssumeLikeIntrinsic(I))
406           return false;
407
408       return !isEphemeralValueOf(Inv, Q.CxtI);
409     }
410
411     return false;
412   }
413
414   // When we don't have a DT, we do a limited search...
415   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
416     return true;
417   } else if (Inv->getParent() == Q.CxtI->getParent()) {
418     // Search forward from the assume until we reach the context (or the end
419     // of the block); the common case is that the assume will come first.
420     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
421          IE = Inv->getParent()->end(); I != IE; ++I)
422       if (I == Q.CxtI)
423         return true;
424
425     // The context must come first...
426     for (BasicBlock::const_iterator I =
427            std::next(BasicBlock::const_iterator(Q.CxtI)),
428                                     IE(Inv); I != IE; ++I)
429       if (!isSafeToSpeculativelyExecute(I, DL) &&
430           !isAssumeLikeIntrinsic(I))
431         return false;
432
433     return !isEphemeralValueOf(Inv, Q.CxtI);
434   }
435
436   return false;
437 }
438
439 bool llvm::isValidAssumeForContext(const Instruction *I,
440                                    const Instruction *CxtI,
441                                    const DataLayout *DL,
442                                    const DominatorTree *DT) {
443   return ::isValidAssumeForContext(const_cast<Instruction*>(I),
444                                    Query(nullptr, CxtI, DT), DL);
445 }
446
447 template<typename LHS, typename RHS>
448 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
449                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
450 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
451   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
452 }
453
454 template<typename LHS, typename RHS>
455 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
456                         BinaryOp_match<RHS, LHS, Instruction::And>>
457 m_c_And(const LHS &L, const RHS &R) {
458   return m_CombineOr(m_And(L, R), m_And(R, L));
459 }
460
461 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
462                                        APInt &KnownOne,
463                                        const DataLayout *DL,
464                                        unsigned Depth, const Query &Q) {
465   // Use of assumptions is context-sensitive. If we don't have a context, we
466   // cannot use them!
467   if (!Q.AT || !Q.CxtI)
468     return;
469
470   unsigned BitWidth = KnownZero.getBitWidth();
471
472   Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
473   for (auto &CI : Q.AT->assumptions(F)) {
474     CallInst *I = CI;
475     if (Q.ExclInvs.count(I))
476       continue;
477
478     if (match(I, m_Intrinsic<Intrinsic::assume>(m_Specific(V))) &&
479         isValidAssumeForContext(I, Q, DL)) {
480       assert(BitWidth == 1 && "assume operand is not i1?");
481       KnownZero.clearAllBits();
482       KnownOne.setAllBits();
483       return;
484     }
485
486     Value *A, *B;
487     auto m_V = m_CombineOr(m_Specific(V),
488                            m_CombineOr(m_PtrToInt(m_Specific(V)),
489                            m_BitCast(m_Specific(V))));
490
491     CmpInst::Predicate Pred;
492     // assume(v = a)
493     if (match(I, m_Intrinsic<Intrinsic::assume>(
494                    m_c_ICmp(Pred, m_V, m_Value(A)))) &&
495         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
496       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
497       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
498       KnownZero |= RHSKnownZero;
499       KnownOne  |= RHSKnownOne;
500     // assume(v & b = a)
501     } else if (match(I, m_Intrinsic<Intrinsic::assume>(
502                        m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) &&
503                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
504       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
505       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
506       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
507       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
508
509       // For those bits in the mask that are known to be one, we can propagate
510       // known bits from the RHS to V.
511       KnownZero |= RHSKnownZero & MaskKnownOne;
512       KnownOne  |= RHSKnownOne  & MaskKnownOne;
513     }
514   }
515 }
516
517 /// Determine which bits of V are known to be either zero or one and return
518 /// them in the KnownZero/KnownOne bit sets.
519 ///
520 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
521 /// we cannot optimize based on the assumption that it is zero without changing
522 /// it to be an explicit zero.  If we don't change it to zero, other code could
523 /// optimized based on the contradictory assumption that it is non-zero.
524 /// Because instcombine aggressively folds operations with undef args anyway,
525 /// this won't lose us code quality.
526 ///
527 /// This function is defined on values with integer type, values with pointer
528 /// type (but only if TD is non-null), and vectors of integers.  In the case
529 /// where V is a vector, known zero, and known one values are the
530 /// same width as the vector element, and the bit is set only if it is true
531 /// for all of the elements in the vector.
532 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
533                       const DataLayout *TD, unsigned Depth,
534                       const Query &Q) {
535   assert(V && "No Value?");
536   assert(Depth <= MaxDepth && "Limit Search Depth");
537   unsigned BitWidth = KnownZero.getBitWidth();
538
539   assert((V->getType()->isIntOrIntVectorTy() ||
540           V->getType()->getScalarType()->isPointerTy()) &&
541          "Not integer or pointer type!");
542   assert((!TD ||
543           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
544          (!V->getType()->isIntOrIntVectorTy() ||
545           V->getType()->getScalarSizeInBits() == BitWidth) &&
546          KnownZero.getBitWidth() == BitWidth &&
547          KnownOne.getBitWidth() == BitWidth &&
548          "V, KnownOne and KnownZero should have same BitWidth");
549
550   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
551     // We know all of the bits for a constant!
552     KnownOne = CI->getValue();
553     KnownZero = ~KnownOne;
554     return;
555   }
556   // Null and aggregate-zero are all-zeros.
557   if (isa<ConstantPointerNull>(V) ||
558       isa<ConstantAggregateZero>(V)) {
559     KnownOne.clearAllBits();
560     KnownZero = APInt::getAllOnesValue(BitWidth);
561     return;
562   }
563   // Handle a constant vector by taking the intersection of the known bits of
564   // each element.  There is no real need to handle ConstantVector here, because
565   // we don't handle undef in any particularly useful way.
566   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
567     // We know that CDS must be a vector of integers. Take the intersection of
568     // each element.
569     KnownZero.setAllBits(); KnownOne.setAllBits();
570     APInt Elt(KnownZero.getBitWidth(), 0);
571     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
572       Elt = CDS->getElementAsInteger(i);
573       KnownZero &= ~Elt;
574       KnownOne &= Elt;
575     }
576     return;
577   }
578
579   // The address of an aligned GlobalValue has trailing zeros.
580   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
581     unsigned Align = GV->getAlignment();
582     if (Align == 0 && TD) {
583       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
584         Type *ObjectType = GVar->getType()->getElementType();
585         if (ObjectType->isSized()) {
586           // If the object is defined in the current Module, we'll be giving
587           // it the preferred alignment. Otherwise, we have to assume that it
588           // may only have the minimum ABI alignment.
589           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
590             Align = TD->getPreferredAlignment(GVar);
591           else
592             Align = TD->getABITypeAlignment(ObjectType);
593         }
594       }
595     }
596     if (Align > 0)
597       KnownZero = APInt::getLowBitsSet(BitWidth,
598                                        countTrailingZeros(Align));
599     else
600       KnownZero.clearAllBits();
601     KnownOne.clearAllBits();
602     return;
603   }
604   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
605   // the bits of its aliasee.
606   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
607     if (GA->mayBeOverridden()) {
608       KnownZero.clearAllBits(); KnownOne.clearAllBits();
609     } else {
610       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
611     }
612     return;
613   }
614
615   if (Argument *A = dyn_cast<Argument>(V)) {
616     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
617
618     if (!Align && TD && A->hasStructRetAttr()) {
619       // An sret parameter has at least the ABI alignment of the return type.
620       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
621       if (EltTy->isSized())
622         Align = TD->getABITypeAlignment(EltTy);
623     }
624
625     if (Align)
626       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
627
628     // Don't give up yet... there might be an assumption that provides more
629     // information...
630     computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
631     return;
632   }
633
634   // Start out not knowing anything.
635   KnownZero.clearAllBits(); KnownOne.clearAllBits();
636
637   if (Depth == MaxDepth)
638     return;  // Limit search depth.
639
640   // Check whether a nearby assume intrinsic can determine some known bits.
641   computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
642
643   Operator *I = dyn_cast<Operator>(V);
644   if (!I) return;
645
646   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
647   switch (I->getOpcode()) {
648   default: break;
649   case Instruction::Load:
650     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
651       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
652     break;
653   case Instruction::And: {
654     // If either the LHS or the RHS are Zero, the result is zero.
655     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
656     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
657
658     // Output known-1 bits are only known if set in both the LHS & RHS.
659     KnownOne &= KnownOne2;
660     // Output known-0 are known to be clear if zero in either the LHS | RHS.
661     KnownZero |= KnownZero2;
662     break;
663   }
664   case Instruction::Or: {
665     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
666     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
667
668     // Output known-0 bits are only known if clear in both the LHS & RHS.
669     KnownZero &= KnownZero2;
670     // Output known-1 are known to be set if set in either the LHS | RHS.
671     KnownOne |= KnownOne2;
672     break;
673   }
674   case Instruction::Xor: {
675     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
676     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
677
678     // Output known-0 bits are known if clear or set in both the LHS & RHS.
679     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
680     // Output known-1 are known to be set if set in only one of the LHS, RHS.
681     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
682     KnownZero = KnownZeroOut;
683     break;
684   }
685   case Instruction::Mul: {
686     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
687     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
688                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
689                          Depth, Q);
690     break;
691   }
692   case Instruction::UDiv: {
693     // For the purposes of computing leading zeros we can conservatively
694     // treat a udiv as a logical right shift by the power of 2 known to
695     // be less than the denominator.
696     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
697     unsigned LeadZ = KnownZero2.countLeadingOnes();
698
699     KnownOne2.clearAllBits();
700     KnownZero2.clearAllBits();
701     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
702     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
703     if (RHSUnknownLeadingOnes != BitWidth)
704       LeadZ = std::min(BitWidth,
705                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
706
707     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
708     break;
709   }
710   case Instruction::Select:
711     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
712     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
713
714     // Only known if known in both the LHS and RHS.
715     KnownOne &= KnownOne2;
716     KnownZero &= KnownZero2;
717     break;
718   case Instruction::FPTrunc:
719   case Instruction::FPExt:
720   case Instruction::FPToUI:
721   case Instruction::FPToSI:
722   case Instruction::SIToFP:
723   case Instruction::UIToFP:
724     break; // Can't work with floating point.
725   case Instruction::PtrToInt:
726   case Instruction::IntToPtr:
727   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
728     // We can't handle these if we don't know the pointer size.
729     if (!TD) break;
730     // FALL THROUGH and handle them the same as zext/trunc.
731   case Instruction::ZExt:
732   case Instruction::Trunc: {
733     Type *SrcTy = I->getOperand(0)->getType();
734
735     unsigned SrcBitWidth;
736     // Note that we handle pointer operands here because of inttoptr/ptrtoint
737     // which fall through here.
738     if(TD) {
739       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
740     } else {
741       SrcBitWidth = SrcTy->getScalarSizeInBits();
742       if (!SrcBitWidth) break;
743     }
744
745     assert(SrcBitWidth && "SrcBitWidth can't be zero");
746     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
747     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
748     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
749     KnownZero = KnownZero.zextOrTrunc(BitWidth);
750     KnownOne = KnownOne.zextOrTrunc(BitWidth);
751     // Any top bits are known to be zero.
752     if (BitWidth > SrcBitWidth)
753       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
754     break;
755   }
756   case Instruction::BitCast: {
757     Type *SrcTy = I->getOperand(0)->getType();
758     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
759         // TODO: For now, not handling conversions like:
760         // (bitcast i64 %x to <2 x i32>)
761         !I->getType()->isVectorTy()) {
762       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
763       break;
764     }
765     break;
766   }
767   case Instruction::SExt: {
768     // Compute the bits in the result that are not present in the input.
769     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
770
771     KnownZero = KnownZero.trunc(SrcBitWidth);
772     KnownOne = KnownOne.trunc(SrcBitWidth);
773     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
774     KnownZero = KnownZero.zext(BitWidth);
775     KnownOne = KnownOne.zext(BitWidth);
776
777     // If the sign bit of the input is known set or clear, then we know the
778     // top bits of the result.
779     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
780       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
781     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
782       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
783     break;
784   }
785   case Instruction::Shl:
786     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
787     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
788       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
789       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
790       KnownZero <<= ShiftAmt;
791       KnownOne  <<= ShiftAmt;
792       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
793       break;
794     }
795     break;
796   case Instruction::LShr:
797     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
798     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
799       // Compute the new bits that are at the top now.
800       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
801
802       // Unsigned shift right.
803       computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1, Q);
804       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
805       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
806       // high bits known zero.
807       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
808       break;
809     }
810     break;
811   case Instruction::AShr:
812     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
813     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
814       // Compute the new bits that are at the top now.
815       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
816
817       // Signed shift right.
818       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
819       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
820       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
821
822       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
823       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
824         KnownZero |= HighBits;
825       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
826         KnownOne |= HighBits;
827       break;
828     }
829     break;
830   case Instruction::Sub: {
831     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
832     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
833                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
834                             Depth, Q);
835     break;
836   }
837   case Instruction::Add: {
838     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
839     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
840                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
841                             Depth, Q);
842     break;
843   }
844   case Instruction::SRem:
845     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
846       APInt RA = Rem->getValue().abs();
847       if (RA.isPowerOf2()) {
848         APInt LowBits = RA - 1;
849         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
850                          Depth+1, Q);
851
852         // The low bits of the first operand are unchanged by the srem.
853         KnownZero = KnownZero2 & LowBits;
854         KnownOne = KnownOne2 & LowBits;
855
856         // If the first operand is non-negative or has all low bits zero, then
857         // the upper bits are all zero.
858         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
859           KnownZero |= ~LowBits;
860
861         // If the first operand is negative and not all low bits are zero, then
862         // the upper bits are all one.
863         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
864           KnownOne |= ~LowBits;
865
866         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
867       }
868     }
869
870     // The sign bit is the LHS's sign bit, except when the result of the
871     // remainder is zero.
872     if (KnownZero.isNonNegative()) {
873       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
874       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
875                        Depth+1, Q);
876       // If it's known zero, our sign bit is also zero.
877       if (LHSKnownZero.isNegative())
878         KnownZero.setBit(BitWidth - 1);
879     }
880
881     break;
882   case Instruction::URem: {
883     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
884       APInt RA = Rem->getValue();
885       if (RA.isPowerOf2()) {
886         APInt LowBits = (RA - 1);
887         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
888                          Depth+1, Q);
889         KnownZero |= ~LowBits;
890         KnownOne &= LowBits;
891         break;
892       }
893     }
894
895     // Since the result is less than or equal to either operand, any leading
896     // zero bits in either operand must also exist in the result.
897     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
898     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
899
900     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
901                                 KnownZero2.countLeadingOnes());
902     KnownOne.clearAllBits();
903     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
904     break;
905   }
906
907   case Instruction::Alloca: {
908     AllocaInst *AI = cast<AllocaInst>(V);
909     unsigned Align = AI->getAlignment();
910     if (Align == 0 && TD)
911       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
912
913     if (Align > 0)
914       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
915     break;
916   }
917   case Instruction::GetElementPtr: {
918     // Analyze all of the subscripts of this getelementptr instruction
919     // to determine if we can prove known low zero bits.
920     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
921     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
922                      Depth+1, Q);
923     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
924
925     gep_type_iterator GTI = gep_type_begin(I);
926     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
927       Value *Index = I->getOperand(i);
928       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
929         // Handle struct member offset arithmetic.
930         if (!TD) {
931           TrailZ = 0;
932           break;
933         }
934
935         // Handle case when index is vector zeroinitializer
936         Constant *CIndex = cast<Constant>(Index);
937         if (CIndex->isZeroValue())
938           continue;
939
940         if (CIndex->getType()->isVectorTy())
941           Index = CIndex->getSplatValue();
942
943         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
944         const StructLayout *SL = TD->getStructLayout(STy);
945         uint64_t Offset = SL->getElementOffset(Idx);
946         TrailZ = std::min<unsigned>(TrailZ,
947                                     countTrailingZeros(Offset));
948       } else {
949         // Handle array index arithmetic.
950         Type *IndexedTy = GTI.getIndexedType();
951         if (!IndexedTy->isSized()) {
952           TrailZ = 0;
953           break;
954         }
955         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
956         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
957         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
958         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
959         TrailZ = std::min(TrailZ,
960                           unsigned(countTrailingZeros(TypeSize) +
961                                    LocalKnownZero.countTrailingOnes()));
962       }
963     }
964
965     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
966     break;
967   }
968   case Instruction::PHI: {
969     PHINode *P = cast<PHINode>(I);
970     // Handle the case of a simple two-predecessor recurrence PHI.
971     // There's a lot more that could theoretically be done here, but
972     // this is sufficient to catch some interesting cases.
973     if (P->getNumIncomingValues() == 2) {
974       for (unsigned i = 0; i != 2; ++i) {
975         Value *L = P->getIncomingValue(i);
976         Value *R = P->getIncomingValue(!i);
977         Operator *LU = dyn_cast<Operator>(L);
978         if (!LU)
979           continue;
980         unsigned Opcode = LU->getOpcode();
981         // Check for operations that have the property that if
982         // both their operands have low zero bits, the result
983         // will have low zero bits.
984         if (Opcode == Instruction::Add ||
985             Opcode == Instruction::Sub ||
986             Opcode == Instruction::And ||
987             Opcode == Instruction::Or ||
988             Opcode == Instruction::Mul) {
989           Value *LL = LU->getOperand(0);
990           Value *LR = LU->getOperand(1);
991           // Find a recurrence.
992           if (LL == I)
993             L = LR;
994           else if (LR == I)
995             L = LL;
996           else
997             break;
998           // Ok, we have a PHI of the form L op= R. Check for low
999           // zero bits.
1000           computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
1001
1002           // We need to take the minimum number of known bits
1003           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1004           computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
1005
1006           KnownZero = APInt::getLowBitsSet(BitWidth,
1007                                            std::min(KnownZero2.countTrailingOnes(),
1008                                                     KnownZero3.countTrailingOnes()));
1009           break;
1010         }
1011       }
1012     }
1013
1014     // Unreachable blocks may have zero-operand PHI nodes.
1015     if (P->getNumIncomingValues() == 0)
1016       break;
1017
1018     // Otherwise take the unions of the known bit sets of the operands,
1019     // taking conservative care to avoid excessive recursion.
1020     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1021       // Skip if every incoming value references to ourself.
1022       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1023         break;
1024
1025       KnownZero = APInt::getAllOnesValue(BitWidth);
1026       KnownOne = APInt::getAllOnesValue(BitWidth);
1027       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1028         // Skip direct self references.
1029         if (P->getIncomingValue(i) == P) continue;
1030
1031         KnownZero2 = APInt(BitWidth, 0);
1032         KnownOne2 = APInt(BitWidth, 0);
1033         // Recurse, but cap the recursion to one level, because we don't
1034         // want to waste time spinning around in loops.
1035         computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
1036                          MaxDepth-1, Q);
1037         KnownZero &= KnownZero2;
1038         KnownOne &= KnownOne2;
1039         // If all bits have been ruled out, there's no need to check
1040         // more operands.
1041         if (!KnownZero && !KnownOne)
1042           break;
1043       }
1044     }
1045     break;
1046   }
1047   case Instruction::Call:
1048   case Instruction::Invoke:
1049     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1050       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1051     // If a range metadata is attached to this IntrinsicInst, intersect the
1052     // explicit range specified by the metadata and the implicit range of
1053     // the intrinsic.
1054     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1055       switch (II->getIntrinsicID()) {
1056       default: break;
1057       case Intrinsic::ctlz:
1058       case Intrinsic::cttz: {
1059         unsigned LowBits = Log2_32(BitWidth)+1;
1060         // If this call is undefined for 0, the result will be less than 2^n.
1061         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1062           LowBits -= 1;
1063         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1064         break;
1065       }
1066       case Intrinsic::ctpop: {
1067         unsigned LowBits = Log2_32(BitWidth)+1;
1068         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1069         break;
1070       }
1071       case Intrinsic::x86_sse42_crc32_64_64:
1072         KnownZero |= APInt::getHighBitsSet(64, 32);
1073         break;
1074       }
1075     }
1076     break;
1077   case Instruction::ExtractValue:
1078     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1079       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1080       if (EVI->getNumIndices() != 1) break;
1081       if (EVI->getIndices()[0] == 0) {
1082         switch (II->getIntrinsicID()) {
1083         default: break;
1084         case Intrinsic::uadd_with_overflow:
1085         case Intrinsic::sadd_with_overflow:
1086           computeKnownBitsAddSub(true, II->getArgOperand(0),
1087                                  II->getArgOperand(1), false, KnownZero,
1088                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1089           break;
1090         case Intrinsic::usub_with_overflow:
1091         case Intrinsic::ssub_with_overflow:
1092           computeKnownBitsAddSub(false, II->getArgOperand(0),
1093                                  II->getArgOperand(1), false, KnownZero,
1094                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
1095           break;
1096         case Intrinsic::umul_with_overflow:
1097         case Intrinsic::smul_with_overflow:
1098           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
1099                               false, KnownZero, KnownOne,
1100                               KnownZero2, KnownOne2, TD, Depth, Q);
1101           break;
1102         }
1103       }
1104     }
1105   }
1106
1107   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108 }
1109
1110 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
1111 /// one.  Convenience wrapper around computeKnownBits.
1112 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1113                     const DataLayout *TD, unsigned Depth,
1114                     const Query &Q) {
1115   unsigned BitWidth = getBitWidth(V->getType(), TD);
1116   if (!BitWidth) {
1117     KnownZero = false;
1118     KnownOne = false;
1119     return;
1120   }
1121   APInt ZeroBits(BitWidth, 0);
1122   APInt OneBits(BitWidth, 0);
1123   computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
1124   KnownOne = OneBits[BitWidth - 1];
1125   KnownZero = ZeroBits[BitWidth - 1];
1126 }
1127
1128 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
1129 /// bit set when defined. For vectors return true if every element is known to
1130 /// be a power of two when defined.  Supports values with integer or pointer
1131 /// types and vectors of integers.
1132 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1133                             const Query &Q) {
1134   if (Constant *C = dyn_cast<Constant>(V)) {
1135     if (C->isNullValue())
1136       return OrZero;
1137     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1138       return CI->getValue().isPowerOf2();
1139     // TODO: Handle vector constants.
1140   }
1141
1142   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
1143   // it is shifted off the end then the result is undefined.
1144   if (match(V, m_Shl(m_One(), m_Value())))
1145     return true;
1146
1147   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1148   // bottom.  If it is shifted off the bottom then the result is undefined.
1149   if (match(V, m_LShr(m_SignBit(), m_Value())))
1150     return true;
1151
1152   // The remaining tests are all recursive, so bail out if we hit the limit.
1153   if (Depth++ == MaxDepth)
1154     return false;
1155
1156   Value *X = nullptr, *Y = nullptr;
1157   // A shift of a power of two is a power of two or zero.
1158   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1159                  match(V, m_Shr(m_Value(X), m_Value()))))
1160     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
1161
1162   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1163     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1164
1165   if (SelectInst *SI = dyn_cast<SelectInst>(V))
1166     return
1167       isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1168       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1169
1170   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1171     // A power of two and'd with anything is a power of two or zero.
1172     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
1173         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
1174       return true;
1175     // X & (-X) is always a power of two or zero.
1176     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1177       return true;
1178     return false;
1179   }
1180
1181   // Adding a power-of-two or zero to the same power-of-two or zero yields
1182   // either the original power-of-two, a larger power-of-two or zero.
1183   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1184     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1185     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1186       if (match(X, m_And(m_Specific(Y), m_Value())) ||
1187           match(X, m_And(m_Value(), m_Specific(Y))))
1188         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1189           return true;
1190       if (match(Y, m_And(m_Specific(X), m_Value())) ||
1191           match(Y, m_And(m_Value(), m_Specific(X))))
1192         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1193           return true;
1194
1195       unsigned BitWidth = V->getType()->getScalarSizeInBits();
1196       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1197       computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
1198
1199       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1200       computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
1201       // If i8 V is a power of two or zero:
1202       //  ZeroBits: 1 1 1 0 1 1 1 1
1203       // ~ZeroBits: 0 0 0 1 0 0 0 0
1204       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1205         // If OrZero isn't set, we cannot give back a zero result.
1206         // Make sure either the LHS or RHS has a bit set.
1207         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1208           return true;
1209     }
1210   }
1211
1212   // An exact divide or right shift can only shift off zero bits, so the result
1213   // is a power of two only if the first operand is a power of two and not
1214   // copying a sign bit (sdiv int_min, 2).
1215   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1216       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1217     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1218                                   Depth, Q);
1219   }
1220
1221   return false;
1222 }
1223
1224 /// \brief Test whether a GEP's result is known to be non-null.
1225 ///
1226 /// Uses properties inherent in a GEP to try to determine whether it is known
1227 /// to be non-null.
1228 ///
1229 /// Currently this routine does not support vector GEPs.
1230 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
1231                               unsigned Depth, const Query &Q) {
1232   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1233     return false;
1234
1235   // FIXME: Support vector-GEPs.
1236   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1237
1238   // If the base pointer is non-null, we cannot walk to a null address with an
1239   // inbounds GEP in address space zero.
1240   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1241     return true;
1242
1243   // Past this, if we don't have DataLayout, we can't do much.
1244   if (!DL)
1245     return false;
1246
1247   // Walk the GEP operands and see if any operand introduces a non-zero offset.
1248   // If so, then the GEP cannot produce a null pointer, as doing so would
1249   // inherently violate the inbounds contract within address space zero.
1250   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1251        GTI != GTE; ++GTI) {
1252     // Struct types are easy -- they must always be indexed by a constant.
1253     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1254       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1255       unsigned ElementIdx = OpC->getZExtValue();
1256       const StructLayout *SL = DL->getStructLayout(STy);
1257       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1258       if (ElementOffset > 0)
1259         return true;
1260       continue;
1261     }
1262
1263     // If we have a zero-sized type, the index doesn't matter. Keep looping.
1264     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
1265       continue;
1266
1267     // Fast path the constant operand case both for efficiency and so we don't
1268     // increment Depth when just zipping down an all-constant GEP.
1269     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1270       if (!OpC->isZero())
1271         return true;
1272       continue;
1273     }
1274
1275     // We post-increment Depth here because while isKnownNonZero increments it
1276     // as well, when we pop back up that increment won't persist. We don't want
1277     // to recurse 10k times just because we have 10k GEP operands. We don't
1278     // bail completely out because we want to handle constant GEPs regardless
1279     // of depth.
1280     if (Depth++ >= MaxDepth)
1281       continue;
1282
1283     if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1284       return true;
1285   }
1286
1287   return false;
1288 }
1289
1290 /// isKnownNonZero - Return true if the given value is known to be non-zero
1291 /// when defined.  For vectors return true if every element is known to be
1292 /// non-zero when defined.  Supports values with integer or pointer type and
1293 /// vectors of integers.
1294 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
1295                     const Query &Q) {
1296   if (Constant *C = dyn_cast<Constant>(V)) {
1297     if (C->isNullValue())
1298       return false;
1299     if (isa<ConstantInt>(C))
1300       // Must be non-zero due to null test above.
1301       return true;
1302     // TODO: Handle vectors
1303     return false;
1304   }
1305
1306   // The remaining tests are all recursive, so bail out if we hit the limit.
1307   if (Depth++ >= MaxDepth)
1308     return false;
1309
1310   // Check for pointer simplifications.
1311   if (V->getType()->isPointerTy()) {
1312     if (isKnownNonNull(V))
1313       return true; 
1314     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1315       if (isGEPKnownNonNull(GEP, TD, Depth, Q))
1316         return true;
1317   }
1318
1319   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
1320
1321   // X | Y != 0 if X != 0 or Y != 0.
1322   Value *X = nullptr, *Y = nullptr;
1323   if (match(V, m_Or(m_Value(X), m_Value(Y))))
1324     return isKnownNonZero(X, TD, Depth, Q) ||
1325            isKnownNonZero(Y, TD, Depth, Q);
1326
1327   // ext X != 0 if X != 0.
1328   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1329     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
1330
1331   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
1332   // if the lowest bit is shifted off the end.
1333   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1334     // shl nuw can't remove any non-zero bits.
1335     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1336     if (BO->hasNoUnsignedWrap())
1337       return isKnownNonZero(X, TD, Depth, Q);
1338
1339     APInt KnownZero(BitWidth, 0);
1340     APInt KnownOne(BitWidth, 0);
1341     computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1342     if (KnownOne[0])
1343       return true;
1344   }
1345   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
1346   // defined if the sign bit is shifted off the end.
1347   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1348     // shr exact can only shift out zero bits.
1349     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1350     if (BO->isExact())
1351       return isKnownNonZero(X, TD, Depth, Q);
1352
1353     bool XKnownNonNegative, XKnownNegative;
1354     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1355     if (XKnownNegative)
1356       return true;
1357   }
1358   // div exact can only produce a zero if the dividend is zero.
1359   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1360     return isKnownNonZero(X, TD, Depth, Q);
1361   }
1362   // X + Y.
1363   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1364     bool XKnownNonNegative, XKnownNegative;
1365     bool YKnownNonNegative, YKnownNegative;
1366     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1367     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
1368
1369     // If X and Y are both non-negative (as signed values) then their sum is not
1370     // zero unless both X and Y are zero.
1371     if (XKnownNonNegative && YKnownNonNegative)
1372       if (isKnownNonZero(X, TD, Depth, Q) ||
1373           isKnownNonZero(Y, TD, Depth, Q))
1374         return true;
1375
1376     // If X and Y are both negative (as signed values) then their sum is not
1377     // zero unless both X and Y equal INT_MIN.
1378     if (BitWidth && XKnownNegative && YKnownNegative) {
1379       APInt KnownZero(BitWidth, 0);
1380       APInt KnownOne(BitWidth, 0);
1381       APInt Mask = APInt::getSignedMaxValue(BitWidth);
1382       // The sign bit of X is set.  If some other bit is set then X is not equal
1383       // to INT_MIN.
1384       computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
1385       if ((KnownOne & Mask) != 0)
1386         return true;
1387       // The sign bit of Y is set.  If some other bit is set then Y is not equal
1388       // to INT_MIN.
1389       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
1390       if ((KnownOne & Mask) != 0)
1391         return true;
1392     }
1393
1394     // The sum of a non-negative number and a power of two is not zero.
1395     if (XKnownNonNegative &&
1396         isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
1397       return true;
1398     if (YKnownNonNegative &&
1399         isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
1400       return true;
1401   }
1402   // X * Y.
1403   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1404     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1405     // If X and Y are non-zero then so is X * Y as long as the multiplication
1406     // does not overflow.
1407     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1408         isKnownNonZero(X, TD, Depth, Q) &&
1409         isKnownNonZero(Y, TD, Depth, Q))
1410       return true;
1411   }
1412   // (C ? X : Y) != 0 if X != 0 and Y != 0.
1413   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1414     if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
1415         isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
1416       return true;
1417   }
1418
1419   if (!BitWidth) return false;
1420   APInt KnownZero(BitWidth, 0);
1421   APInt KnownOne(BitWidth, 0);
1422   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1423   return KnownOne != 0;
1424 }
1425
1426 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1427 /// this predicate to simplify operations downstream.  Mask is known to be zero
1428 /// for bits that V cannot have.
1429 ///
1430 /// This function is defined on values with integer type, values with pointer
1431 /// type (but only if TD is non-null), and vectors of integers.  In the case
1432 /// where V is a vector, the mask, known zero, and known one values are the
1433 /// same width as the vector element, and the bit is set only if it is true
1434 /// for all of the elements in the vector.
1435 bool MaskedValueIsZero(Value *V, const APInt &Mask,
1436                        const DataLayout *TD, unsigned Depth,
1437                        const Query &Q) {
1438   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1439   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1440   return (KnownZero & Mask) == Mask;
1441 }
1442
1443
1444
1445 /// ComputeNumSignBits - Return the number of times the sign bit of the
1446 /// register is replicated into the other bits.  We know that at least 1 bit
1447 /// is always equal to the sign bit (itself), but other cases can give us
1448 /// information.  For example, immediately after an "ashr X, 2", we know that
1449 /// the top 3 bits are all equal to each other, so we return 3.
1450 ///
1451 /// 'Op' must have a scalar integer type.
1452 ///
1453 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
1454                             unsigned Depth, const Query &Q) {
1455   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1456          "ComputeNumSignBits requires a DataLayout object to operate "
1457          "on non-integer values!");
1458   Type *Ty = V->getType();
1459   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1460                          Ty->getScalarSizeInBits();
1461   unsigned Tmp, Tmp2;
1462   unsigned FirstAnswer = 1;
1463
1464   // Note that ConstantInt is handled by the general computeKnownBits case
1465   // below.
1466
1467   if (Depth == 6)
1468     return 1;  // Limit search depth.
1469
1470   Operator *U = dyn_cast<Operator>(V);
1471   switch (Operator::getOpcode(V)) {
1472   default: break;
1473   case Instruction::SExt:
1474     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1475     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
1476
1477   case Instruction::AShr: {
1478     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1479     // ashr X, C   -> adds C sign bits.  Vectors too.
1480     const APInt *ShAmt;
1481     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1482       Tmp += ShAmt->getZExtValue();
1483       if (Tmp > TyBits) Tmp = TyBits;
1484     }
1485     return Tmp;
1486   }
1487   case Instruction::Shl: {
1488     const APInt *ShAmt;
1489     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1490       // shl destroys sign bits.
1491       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1492       Tmp2 = ShAmt->getZExtValue();
1493       if (Tmp2 >= TyBits ||      // Bad shift.
1494           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
1495       return Tmp - Tmp2;
1496     }
1497     break;
1498   }
1499   case Instruction::And:
1500   case Instruction::Or:
1501   case Instruction::Xor:    // NOT is handled here.
1502     // Logical binary ops preserve the number of sign bits at the worst.
1503     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1504     if (Tmp != 1) {
1505       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1506       FirstAnswer = std::min(Tmp, Tmp2);
1507       // We computed what we know about the sign bits as our first
1508       // answer. Now proceed to the generic code that uses
1509       // computeKnownBits, and pick whichever answer is better.
1510     }
1511     break;
1512
1513   case Instruction::Select:
1514     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1515     if (Tmp == 1) return 1;  // Early out.
1516     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
1517     return std::min(Tmp, Tmp2);
1518
1519   case Instruction::Add:
1520     // Add can have at most one carry bit.  Thus we know that the output
1521     // is, at worst, one more bit than the inputs.
1522     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1523     if (Tmp == 1) return 1;  // Early out.
1524
1525     // Special case decrementing a value (ADD X, -1):
1526     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1527       if (CRHS->isAllOnesValue()) {
1528         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1529         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1530
1531         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1532         // sign bits set.
1533         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1534           return TyBits;
1535
1536         // If we are subtracting one from a positive number, there is no carry
1537         // out of the result.
1538         if (KnownZero.isNegative())
1539           return Tmp;
1540       }
1541
1542     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1543     if (Tmp2 == 1) return 1;
1544     return std::min(Tmp, Tmp2)-1;
1545
1546   case Instruction::Sub:
1547     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
1548     if (Tmp2 == 1) return 1;
1549
1550     // Handle NEG.
1551     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1552       if (CLHS->isNullValue()) {
1553         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1554         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
1555         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1556         // sign bits set.
1557         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
1558           return TyBits;
1559
1560         // If the input is known to be positive (the sign bit is known clear),
1561         // the output of the NEG has the same number of sign bits as the input.
1562         if (KnownZero.isNegative())
1563           return Tmp2;
1564
1565         // Otherwise, we treat this like a SUB.
1566       }
1567
1568     // Sub can have at most one carry bit.  Thus we know that the output
1569     // is, at worst, one more bit than the inputs.
1570     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
1571     if (Tmp == 1) return 1;  // Early out.
1572     return std::min(Tmp, Tmp2)-1;
1573
1574   case Instruction::PHI: {
1575     PHINode *PN = cast<PHINode>(U);
1576     // Don't analyze large in-degree PHIs.
1577     if (PN->getNumIncomingValues() > 4) break;
1578
1579     // Take the minimum of all incoming values.  This can't infinitely loop
1580     // because of our depth threshold.
1581     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
1582     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1583       if (Tmp == 1) return Tmp;
1584       Tmp = std::min(Tmp,
1585                      ComputeNumSignBits(PN->getIncomingValue(i), TD,
1586                                         Depth+1, Q));
1587     }
1588     return Tmp;
1589   }
1590
1591   case Instruction::Trunc:
1592     // FIXME: it's tricky to do anything useful for this, but it is an important
1593     // case for targets like X86.
1594     break;
1595   }
1596
1597   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1598   // use this information.
1599   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1600   APInt Mask;
1601   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
1602
1603   if (KnownZero.isNegative()) {        // sign bit is 0
1604     Mask = KnownZero;
1605   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1606     Mask = KnownOne;
1607   } else {
1608     // Nothing known.
1609     return FirstAnswer;
1610   }
1611
1612   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1613   // the number of identical bits in the top of the input value.
1614   Mask = ~Mask;
1615   Mask <<= Mask.getBitWidth()-TyBits;
1616   // Return # leading zeros.  We use 'min' here in case Val was zero before
1617   // shifting.  We don't want to return '64' as for an i32 "0".
1618   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1619 }
1620
1621 /// ComputeMultiple - This function computes the integer multiple of Base that
1622 /// equals V.  If successful, it returns true and returns the multiple in
1623 /// Multiple.  If unsuccessful, it returns false. It looks
1624 /// through SExt instructions only if LookThroughSExt is true.
1625 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1626                            bool LookThroughSExt, unsigned Depth) {
1627   const unsigned MaxDepth = 6;
1628
1629   assert(V && "No Value?");
1630   assert(Depth <= MaxDepth && "Limit Search Depth");
1631   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1632
1633   Type *T = V->getType();
1634
1635   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1636
1637   if (Base == 0)
1638     return false;
1639
1640   if (Base == 1) {
1641     Multiple = V;
1642     return true;
1643   }
1644
1645   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1646   Constant *BaseVal = ConstantInt::get(T, Base);
1647   if (CO && CO == BaseVal) {
1648     // Multiple is 1.
1649     Multiple = ConstantInt::get(T, 1);
1650     return true;
1651   }
1652
1653   if (CI && CI->getZExtValue() % Base == 0) {
1654     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1655     return true;
1656   }
1657
1658   if (Depth == MaxDepth) return false;  // Limit search depth.
1659
1660   Operator *I = dyn_cast<Operator>(V);
1661   if (!I) return false;
1662
1663   switch (I->getOpcode()) {
1664   default: break;
1665   case Instruction::SExt:
1666     if (!LookThroughSExt) return false;
1667     // otherwise fall through to ZExt
1668   case Instruction::ZExt:
1669     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1670                            LookThroughSExt, Depth+1);
1671   case Instruction::Shl:
1672   case Instruction::Mul: {
1673     Value *Op0 = I->getOperand(0);
1674     Value *Op1 = I->getOperand(1);
1675
1676     if (I->getOpcode() == Instruction::Shl) {
1677       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1678       if (!Op1CI) return false;
1679       // Turn Op0 << Op1 into Op0 * 2^Op1
1680       APInt Op1Int = Op1CI->getValue();
1681       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1682       APInt API(Op1Int.getBitWidth(), 0);
1683       API.setBit(BitToSet);
1684       Op1 = ConstantInt::get(V->getContext(), API);
1685     }
1686
1687     Value *Mul0 = nullptr;
1688     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1689       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1690         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1691           if (Op1C->getType()->getPrimitiveSizeInBits() <
1692               MulC->getType()->getPrimitiveSizeInBits())
1693             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1694           if (Op1C->getType()->getPrimitiveSizeInBits() >
1695               MulC->getType()->getPrimitiveSizeInBits())
1696             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1697
1698           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1699           Multiple = ConstantExpr::getMul(MulC, Op1C);
1700           return true;
1701         }
1702
1703       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1704         if (Mul0CI->getValue() == 1) {
1705           // V == Base * Op1, so return Op1
1706           Multiple = Op1;
1707           return true;
1708         }
1709     }
1710
1711     Value *Mul1 = nullptr;
1712     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1713       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1714         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1715           if (Op0C->getType()->getPrimitiveSizeInBits() <
1716               MulC->getType()->getPrimitiveSizeInBits())
1717             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1718           if (Op0C->getType()->getPrimitiveSizeInBits() >
1719               MulC->getType()->getPrimitiveSizeInBits())
1720             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1721
1722           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1723           Multiple = ConstantExpr::getMul(MulC, Op0C);
1724           return true;
1725         }
1726
1727       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1728         if (Mul1CI->getValue() == 1) {
1729           // V == Base * Op0, so return Op0
1730           Multiple = Op0;
1731           return true;
1732         }
1733     }
1734   }
1735   }
1736
1737   // We could not determine if V is a multiple of Base.
1738   return false;
1739 }
1740
1741 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
1742 /// value is never equal to -0.0.
1743 ///
1744 /// NOTE: this function will need to be revisited when we support non-default
1745 /// rounding modes!
1746 ///
1747 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1748   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1749     return !CFP->getValueAPF().isNegZero();
1750
1751   if (Depth == 6)
1752     return 1;  // Limit search depth.
1753
1754   const Operator *I = dyn_cast<Operator>(V);
1755   if (!I) return false;
1756
1757   // Check if the nsz fast-math flag is set
1758   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
1759     if (FPO->hasNoSignedZeros())
1760       return true;
1761
1762   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1763   if (I->getOpcode() == Instruction::FAdd)
1764     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
1765       if (CFP->isNullValue())
1766         return true;
1767
1768   // sitofp and uitofp turn into +0.0 for zero.
1769   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1770     return true;
1771
1772   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1773     // sqrt(-0.0) = -0.0, no other negative results are possible.
1774     if (II->getIntrinsicID() == Intrinsic::sqrt)
1775       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1776
1777   if (const CallInst *CI = dyn_cast<CallInst>(I))
1778     if (const Function *F = CI->getCalledFunction()) {
1779       if (F->isDeclaration()) {
1780         // abs(x) != -0.0
1781         if (F->getName() == "abs") return true;
1782         // fabs[lf](x) != -0.0
1783         if (F->getName() == "fabs") return true;
1784         if (F->getName() == "fabsf") return true;
1785         if (F->getName() == "fabsl") return true;
1786         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1787             F->getName() == "sqrtl")
1788           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
1789       }
1790     }
1791
1792   return false;
1793 }
1794
1795 /// isBytewiseValue - If the specified value can be set by repeating the same
1796 /// byte in memory, return the i8 value that it is represented with.  This is
1797 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1798 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1799 /// byte store (e.g. i16 0x1234), return null.
1800 Value *llvm::isBytewiseValue(Value *V) {
1801   // All byte-wide stores are splatable, even of arbitrary variables.
1802   if (V->getType()->isIntegerTy(8)) return V;
1803
1804   // Handle 'null' ConstantArrayZero etc.
1805   if (Constant *C = dyn_cast<Constant>(V))
1806     if (C->isNullValue())
1807       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
1808
1809   // Constant float and double values can be handled as integer values if the
1810   // corresponding integer value is "byteable".  An important case is 0.0.
1811   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1812     if (CFP->getType()->isFloatTy())
1813       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1814     if (CFP->getType()->isDoubleTy())
1815       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1816     // Don't handle long double formats, which have strange constraints.
1817   }
1818
1819   // We can handle constant integers that are power of two in size and a
1820   // multiple of 8 bits.
1821   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1822     unsigned Width = CI->getBitWidth();
1823     if (isPowerOf2_32(Width) && Width > 8) {
1824       // We can handle this value if the recursive binary decomposition is the
1825       // same at all levels.
1826       APInt Val = CI->getValue();
1827       APInt Val2;
1828       while (Val.getBitWidth() != 8) {
1829         unsigned NextWidth = Val.getBitWidth()/2;
1830         Val2  = Val.lshr(NextWidth);
1831         Val2 = Val2.trunc(Val.getBitWidth()/2);
1832         Val = Val.trunc(Val.getBitWidth()/2);
1833
1834         // If the top/bottom halves aren't the same, reject it.
1835         if (Val != Val2)
1836           return nullptr;
1837       }
1838       return ConstantInt::get(V->getContext(), Val);
1839     }
1840   }
1841
1842   // A ConstantDataArray/Vector is splatable if all its members are equal and
1843   // also splatable.
1844   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1845     Value *Elt = CA->getElementAsConstant(0);
1846     Value *Val = isBytewiseValue(Elt);
1847     if (!Val)
1848       return nullptr;
1849
1850     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1851       if (CA->getElementAsConstant(I) != Elt)
1852         return nullptr;
1853
1854     return Val;
1855   }
1856
1857   // Conceptually, we could handle things like:
1858   //   %a = zext i8 %X to i16
1859   //   %b = shl i16 %a, 8
1860   //   %c = or i16 %a, %b
1861   // but until there is an example that actually needs this, it doesn't seem
1862   // worth worrying about.
1863   return nullptr;
1864 }
1865
1866
1867 // This is the recursive version of BuildSubAggregate. It takes a few different
1868 // arguments. Idxs is the index within the nested struct From that we are
1869 // looking at now (which is of type IndexedType). IdxSkip is the number of
1870 // indices from Idxs that should be left out when inserting into the resulting
1871 // struct. To is the result struct built so far, new insertvalue instructions
1872 // build on that.
1873 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
1874                                 SmallVectorImpl<unsigned> &Idxs,
1875                                 unsigned IdxSkip,
1876                                 Instruction *InsertBefore) {
1877   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
1878   if (STy) {
1879     // Save the original To argument so we can modify it
1880     Value *OrigTo = To;
1881     // General case, the type indexed by Idxs is a struct
1882     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1883       // Process each struct element recursively
1884       Idxs.push_back(i);
1885       Value *PrevTo = To;
1886       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1887                              InsertBefore);
1888       Idxs.pop_back();
1889       if (!To) {
1890         // Couldn't find any inserted value for this index? Cleanup
1891         while (PrevTo != OrigTo) {
1892           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1893           PrevTo = Del->getAggregateOperand();
1894           Del->eraseFromParent();
1895         }
1896         // Stop processing elements
1897         break;
1898       }
1899     }
1900     // If we successfully found a value for each of our subaggregates
1901     if (To)
1902       return To;
1903   }
1904   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1905   // the struct's elements had a value that was inserted directly. In the latter
1906   // case, perhaps we can't determine each of the subelements individually, but
1907   // we might be able to find the complete struct somewhere.
1908
1909   // Find the value that is at that particular spot
1910   Value *V = FindInsertedValue(From, Idxs);
1911
1912   if (!V)
1913     return nullptr;
1914
1915   // Insert the value in the new (sub) aggregrate
1916   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
1917                                        "tmp", InsertBefore);
1918 }
1919
1920 // This helper takes a nested struct and extracts a part of it (which is again a
1921 // struct) into a new value. For example, given the struct:
1922 // { a, { b, { c, d }, e } }
1923 // and the indices "1, 1" this returns
1924 // { c, d }.
1925 //
1926 // It does this by inserting an insertvalue for each element in the resulting
1927 // struct, as opposed to just inserting a single struct. This will only work if
1928 // each of the elements of the substruct are known (ie, inserted into From by an
1929 // insertvalue instruction somewhere).
1930 //
1931 // All inserted insertvalue instructions are inserted before InsertBefore
1932 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
1933                                 Instruction *InsertBefore) {
1934   assert(InsertBefore && "Must have someplace to insert!");
1935   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1936                                                              idx_range);
1937   Value *To = UndefValue::get(IndexedType);
1938   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
1939   unsigned IdxSkip = Idxs.size();
1940
1941   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1942 }
1943
1944 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1945 /// the scalar value indexed is already around as a register, for example if it
1946 /// were inserted directly into the aggregrate.
1947 ///
1948 /// If InsertBefore is not null, this function will duplicate (modified)
1949 /// insertvalues when a part of a nested struct is extracted.
1950 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1951                                Instruction *InsertBefore) {
1952   // Nothing to index? Just return V then (this is useful at the end of our
1953   // recursion).
1954   if (idx_range.empty())
1955     return V;
1956   // We have indices, so V should have an indexable type.
1957   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1958          "Not looking at a struct or array?");
1959   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1960          "Invalid indices for type?");
1961
1962   if (Constant *C = dyn_cast<Constant>(V)) {
1963     C = C->getAggregateElement(idx_range[0]);
1964     if (!C) return nullptr;
1965     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1966   }
1967
1968   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1969     // Loop the indices for the insertvalue instruction in parallel with the
1970     // requested indices
1971     const unsigned *req_idx = idx_range.begin();
1972     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1973          i != e; ++i, ++req_idx) {
1974       if (req_idx == idx_range.end()) {
1975         // We can't handle this without inserting insertvalues
1976         if (!InsertBefore)
1977           return nullptr;
1978
1979         // The requested index identifies a part of a nested aggregate. Handle
1980         // this specially. For example,
1981         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1982         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1983         // %C = extractvalue {i32, { i32, i32 } } %B, 1
1984         // This can be changed into
1985         // %A = insertvalue {i32, i32 } undef, i32 10, 0
1986         // %C = insertvalue {i32, i32 } %A, i32 11, 1
1987         // which allows the unused 0,0 element from the nested struct to be
1988         // removed.
1989         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1990                                  InsertBefore);
1991       }
1992
1993       // This insert value inserts something else than what we are looking for.
1994       // See if the (aggregrate) value inserted into has the value we are
1995       // looking for, then.
1996       if (*req_idx != *i)
1997         return FindInsertedValue(I->getAggregateOperand(), idx_range,
1998                                  InsertBefore);
1999     }
2000     // If we end up here, the indices of the insertvalue match with those
2001     // requested (though possibly only partially). Now we recursively look at
2002     // the inserted value, passing any remaining indices.
2003     return FindInsertedValue(I->getInsertedValueOperand(),
2004                              makeArrayRef(req_idx, idx_range.end()),
2005                              InsertBefore);
2006   }
2007
2008   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2009     // If we're extracting a value from an aggregrate that was extracted from
2010     // something else, we can extract from that something else directly instead.
2011     // However, we will need to chain I's indices with the requested indices.
2012
2013     // Calculate the number of indices required
2014     unsigned size = I->getNumIndices() + idx_range.size();
2015     // Allocate some space to put the new indices in
2016     SmallVector<unsigned, 5> Idxs;
2017     Idxs.reserve(size);
2018     // Add indices from the extract value instruction
2019     Idxs.append(I->idx_begin(), I->idx_end());
2020
2021     // Add requested indices
2022     Idxs.append(idx_range.begin(), idx_range.end());
2023
2024     assert(Idxs.size() == size
2025            && "Number of indices added not correct?");
2026
2027     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2028   }
2029   // Otherwise, we don't know (such as, extracting from a function return value
2030   // or load instruction)
2031   return nullptr;
2032 }
2033
2034 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
2035 /// it can be expressed as a base pointer plus a constant offset.  Return the
2036 /// base and offset to the caller.
2037 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2038                                               const DataLayout *DL) {
2039   // Without DataLayout, conservatively assume 64-bit offsets, which is
2040   // the widest we support.
2041   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
2042   APInt ByteOffset(BitWidth, 0);
2043   while (1) {
2044     if (Ptr->getType()->isVectorTy())
2045       break;
2046
2047     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2048       if (DL) {
2049         APInt GEPOffset(BitWidth, 0);
2050         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
2051           break;
2052
2053         ByteOffset += GEPOffset;
2054       }
2055
2056       Ptr = GEP->getPointerOperand();
2057     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2058                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2059       Ptr = cast<Operator>(Ptr)->getOperand(0);
2060     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2061       if (GA->mayBeOverridden())
2062         break;
2063       Ptr = GA->getAliasee();
2064     } else {
2065       break;
2066     }
2067   }
2068   Offset = ByteOffset.getSExtValue();
2069   return Ptr;
2070 }
2071
2072
2073 /// getConstantStringInfo - This function computes the length of a
2074 /// null-terminated C string pointed to by V.  If successful, it returns true
2075 /// and returns the string in Str.  If unsuccessful, it returns false.
2076 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2077                                  uint64_t Offset, bool TrimAtNul) {
2078   assert(V);
2079
2080   // Look through bitcast instructions and geps.
2081   V = V->stripPointerCasts();
2082
2083   // If the value is a GEP instructionor  constant expression, treat it as an
2084   // offset.
2085   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2086     // Make sure the GEP has exactly three arguments.
2087     if (GEP->getNumOperands() != 3)
2088       return false;
2089
2090     // Make sure the index-ee is a pointer to array of i8.
2091     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2092     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2093     if (!AT || !AT->getElementType()->isIntegerTy(8))
2094       return false;
2095
2096     // Check to make sure that the first operand of the GEP is an integer and
2097     // has value 0 so that we are sure we're indexing into the initializer.
2098     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2099     if (!FirstIdx || !FirstIdx->isZero())
2100       return false;
2101
2102     // If the second index isn't a ConstantInt, then this is a variable index
2103     // into the array.  If this occurs, we can't say anything meaningful about
2104     // the string.
2105     uint64_t StartIdx = 0;
2106     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2107       StartIdx = CI->getZExtValue();
2108     else
2109       return false;
2110     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
2111   }
2112
2113   // The GEP instruction, constant or instruction, must reference a global
2114   // variable that is a constant and is initialized. The referenced constant
2115   // initializer is the array that we'll use for optimization.
2116   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2117   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2118     return false;
2119
2120   // Handle the all-zeros case
2121   if (GV->getInitializer()->isNullValue()) {
2122     // This is a degenerate case. The initializer is constant zero so the
2123     // length of the string must be zero.
2124     Str = "";
2125     return true;
2126   }
2127
2128   // Must be a Constant Array
2129   const ConstantDataArray *Array =
2130     dyn_cast<ConstantDataArray>(GV->getInitializer());
2131   if (!Array || !Array->isString())
2132     return false;
2133
2134   // Get the number of elements in the array
2135   uint64_t NumElts = Array->getType()->getArrayNumElements();
2136
2137   // Start out with the entire array in the StringRef.
2138   Str = Array->getAsString();
2139
2140   if (Offset > NumElts)
2141     return false;
2142
2143   // Skip over 'offset' bytes.
2144   Str = Str.substr(Offset);
2145
2146   if (TrimAtNul) {
2147     // Trim off the \0 and anything after it.  If the array is not nul
2148     // terminated, we just return the whole end of string.  The client may know
2149     // some other way that the string is length-bound.
2150     Str = Str.substr(0, Str.find('\0'));
2151   }
2152   return true;
2153 }
2154
2155 // These next two are very similar to the above, but also look through PHI
2156 // nodes.
2157 // TODO: See if we can integrate these two together.
2158
2159 /// GetStringLengthH - If we can compute the length of the string pointed to by
2160 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2161 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2162   // Look through noop bitcast instructions.
2163   V = V->stripPointerCasts();
2164
2165   // If this is a PHI node, there are two cases: either we have already seen it
2166   // or we haven't.
2167   if (PHINode *PN = dyn_cast<PHINode>(V)) {
2168     if (!PHIs.insert(PN))
2169       return ~0ULL;  // already in the set.
2170
2171     // If it was new, see if all the input strings are the same length.
2172     uint64_t LenSoFar = ~0ULL;
2173     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2174       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2175       if (Len == 0) return 0; // Unknown length -> unknown.
2176
2177       if (Len == ~0ULL) continue;
2178
2179       if (Len != LenSoFar && LenSoFar != ~0ULL)
2180         return 0;    // Disagree -> unknown.
2181       LenSoFar = Len;
2182     }
2183
2184     // Success, all agree.
2185     return LenSoFar;
2186   }
2187
2188   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2189   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2190     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2191     if (Len1 == 0) return 0;
2192     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2193     if (Len2 == 0) return 0;
2194     if (Len1 == ~0ULL) return Len2;
2195     if (Len2 == ~0ULL) return Len1;
2196     if (Len1 != Len2) return 0;
2197     return Len1;
2198   }
2199
2200   // Otherwise, see if we can read the string.
2201   StringRef StrData;
2202   if (!getConstantStringInfo(V, StrData))
2203     return 0;
2204
2205   return StrData.size()+1;
2206 }
2207
2208 /// GetStringLength - If we can compute the length of the string pointed to by
2209 /// the specified pointer, return 'len+1'.  If we can't, return 0.
2210 uint64_t llvm::GetStringLength(Value *V) {
2211   if (!V->getType()->isPointerTy()) return 0;
2212
2213   SmallPtrSet<PHINode*, 32> PHIs;
2214   uint64_t Len = GetStringLengthH(V, PHIs);
2215   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2216   // an empty string as a length.
2217   return Len == ~0ULL ? 1 : Len;
2218 }
2219
2220 Value *
2221 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
2222   if (!V->getType()->isPointerTy())
2223     return V;
2224   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2225     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2226       V = GEP->getPointerOperand();
2227     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2228                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2229       V = cast<Operator>(V)->getOperand(0);
2230     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2231       if (GA->mayBeOverridden())
2232         return V;
2233       V = GA->getAliasee();
2234     } else {
2235       // See if InstructionSimplify knows any relevant tricks.
2236       if (Instruction *I = dyn_cast<Instruction>(V))
2237         // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
2238         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
2239           V = Simplified;
2240           continue;
2241         }
2242
2243       return V;
2244     }
2245     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2246   }
2247   return V;
2248 }
2249
2250 void
2251 llvm::GetUnderlyingObjects(Value *V,
2252                            SmallVectorImpl<Value *> &Objects,
2253                            const DataLayout *TD,
2254                            unsigned MaxLookup) {
2255   SmallPtrSet<Value *, 4> Visited;
2256   SmallVector<Value *, 4> Worklist;
2257   Worklist.push_back(V);
2258   do {
2259     Value *P = Worklist.pop_back_val();
2260     P = GetUnderlyingObject(P, TD, MaxLookup);
2261
2262     if (!Visited.insert(P))
2263       continue;
2264
2265     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2266       Worklist.push_back(SI->getTrueValue());
2267       Worklist.push_back(SI->getFalseValue());
2268       continue;
2269     }
2270
2271     if (PHINode *PN = dyn_cast<PHINode>(P)) {
2272       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2273         Worklist.push_back(PN->getIncomingValue(i));
2274       continue;
2275     }
2276
2277     Objects.push_back(P);
2278   } while (!Worklist.empty());
2279 }
2280
2281 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
2282 /// are lifetime markers.
2283 ///
2284 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2285   for (const User *U : V->users()) {
2286     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2287     if (!II) return false;
2288
2289     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2290         II->getIntrinsicID() != Intrinsic::lifetime_end)
2291       return false;
2292   }
2293   return true;
2294 }
2295
2296 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
2297                                         const DataLayout *TD) {
2298   const Operator *Inst = dyn_cast<Operator>(V);
2299   if (!Inst)
2300     return false;
2301
2302   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2303     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2304       if (C->canTrap())
2305         return false;
2306
2307   switch (Inst->getOpcode()) {
2308   default:
2309     return true;
2310   case Instruction::UDiv:
2311   case Instruction::URem:
2312     // x / y is undefined if y == 0, but calculations like x / 3 are safe.
2313     return isKnownNonZero(Inst->getOperand(1), TD);
2314   case Instruction::SDiv:
2315   case Instruction::SRem: {
2316     Value *Op = Inst->getOperand(1);
2317     // x / y is undefined if y == 0
2318     if (!isKnownNonZero(Op, TD))
2319       return false;
2320     // x / y might be undefined if y == -1
2321     unsigned BitWidth = getBitWidth(Op->getType(), TD);
2322     if (BitWidth == 0)
2323       return false;
2324     APInt KnownZero(BitWidth, 0);
2325     APInt KnownOne(BitWidth, 0);
2326     computeKnownBits(Op, KnownZero, KnownOne, TD);
2327     return !!KnownZero;
2328   }
2329   case Instruction::Load: {
2330     const LoadInst *LI = cast<LoadInst>(Inst);
2331     if (!LI->isUnordered() ||
2332         // Speculative load may create a race that did not exist in the source.
2333         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2334       return false;
2335     return LI->getPointerOperand()->isDereferenceablePointer(TD);
2336   }
2337   case Instruction::Call: {
2338    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2339      switch (II->getIntrinsicID()) {
2340        // These synthetic intrinsics have no side-effects and just mark
2341        // information about their operands.
2342        // FIXME: There are other no-op synthetic instructions that potentially
2343        // should be considered at least *safe* to speculate...
2344        case Intrinsic::dbg_declare:
2345        case Intrinsic::dbg_value:
2346          return true;
2347
2348        case Intrinsic::bswap:
2349        case Intrinsic::ctlz:
2350        case Intrinsic::ctpop:
2351        case Intrinsic::cttz:
2352        case Intrinsic::objectsize:
2353        case Intrinsic::sadd_with_overflow:
2354        case Intrinsic::smul_with_overflow:
2355        case Intrinsic::ssub_with_overflow:
2356        case Intrinsic::uadd_with_overflow:
2357        case Intrinsic::umul_with_overflow:
2358        case Intrinsic::usub_with_overflow:
2359          return true;
2360        // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2361        // errno like libm sqrt would.
2362        case Intrinsic::sqrt:
2363        case Intrinsic::fma:
2364        case Intrinsic::fmuladd:
2365        case Intrinsic::fabs:
2366          return true;
2367        // TODO: some fp intrinsics are marked as having the same error handling
2368        // as libm. They're safe to speculate when they won't error.
2369        // TODO: are convert_{from,to}_fp16 safe?
2370        // TODO: can we list target-specific intrinsics here?
2371        default: break;
2372      }
2373    }
2374     return false; // The called function could have undefined behavior or
2375                   // side-effects, even if marked readnone nounwind.
2376   }
2377   case Instruction::VAArg:
2378   case Instruction::Alloca:
2379   case Instruction::Invoke:
2380   case Instruction::PHI:
2381   case Instruction::Store:
2382   case Instruction::Ret:
2383   case Instruction::Br:
2384   case Instruction::IndirectBr:
2385   case Instruction::Switch:
2386   case Instruction::Unreachable:
2387   case Instruction::Fence:
2388   case Instruction::LandingPad:
2389   case Instruction::AtomicRMW:
2390   case Instruction::AtomicCmpXchg:
2391   case Instruction::Resume:
2392     return false; // Misc instructions which have effects
2393   }
2394 }
2395
2396 /// isKnownNonNull - Return true if we know that the specified value is never
2397 /// null.
2398 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
2399   // Alloca never returns null, malloc might.
2400   if (isa<AllocaInst>(V)) return true;
2401
2402   // A byval, inalloca, or nonnull argument is never null.
2403   if (const Argument *A = dyn_cast<Argument>(V))
2404     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
2405
2406   // Global values are not null unless extern weak.
2407   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2408     return !GV->hasExternalWeakLinkage();
2409
2410   if (ImmutableCallSite CS = V)
2411     if (CS.isReturnNonNull())
2412       return true;
2413
2414   // operator new never returns null.
2415   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2416     return true;
2417
2418   return false;
2419 }