Revert r153521 as it's causing large regressions on the nightly testers.
[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/InstructionSimplify.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Operator.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/PatternMatch.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include <cstring>
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32
33 const unsigned MaxDepth = 6;
34
35 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
36 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
37 static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
38   if (unsigned BitWidth = Ty->getScalarSizeInBits())
39     return BitWidth;
40   assert(isa<PointerType>(Ty) && "Expected a pointer type!");
41   return TD ? TD->getPointerSizeInBits() : 0;
42 }
43
44 static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
45                                     const APInt &Mask,
46                                     APInt &KnownZero, APInt &KnownOne,
47                                     APInt &KnownZero2, APInt &KnownOne2,
48                                     const TargetData *TD, unsigned Depth) {
49   if (!Add) {
50     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
51       // We know that the top bits of C-X are clear if X contains less bits
52       // than C (i.e. no wrap-around can happen).  For example, 20-X is
53       // positive if we can prove that X is >= 0 and < 16.
54       if (!CLHS->getValue().isNegative()) {
55         unsigned BitWidth = Mask.getBitWidth();
56         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
57         // NLZ can't be BitWidth with no sign bit
58         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
59         llvm::ComputeMaskedBits(Op1, MaskV, KnownZero2, KnownOne2, TD, Depth+1);
60     
61         // If all of the MaskV bits are known to be zero, then we know the
62         // output top bits are zero, because we now know that the output is
63         // from [0-C].
64         if ((KnownZero2 & MaskV) == MaskV) {
65           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
66           // Top bits known zero.
67           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
68         }
69       }
70     }
71   }
72
73   unsigned BitWidth = Mask.getBitWidth();
74
75   // If one of the operands has trailing zeros, then the bits that the
76   // other operand has in those bit positions will be preserved in the
77   // result. For an add, this works with either operand. For a subtract,
78   // this only works if the known zeros are in the right operand.
79   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
80   APInt Mask2 = APInt::getLowBitsSet(BitWidth,
81                                      BitWidth - Mask.countLeadingZeros());
82   llvm::ComputeMaskedBits(Op0, Mask2, LHSKnownZero, LHSKnownOne, TD, Depth+1);
83   assert((LHSKnownZero & LHSKnownOne) == 0 &&
84          "Bits known to be one AND zero?");
85   unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
86
87   llvm::ComputeMaskedBits(Op1, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
88   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
89   unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
90
91   // Determine which operand has more trailing zeros, and use that
92   // many bits from the other operand.
93   if (LHSKnownZeroOut > RHSKnownZeroOut) {
94     if (Add) {
95       APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
96       KnownZero |= KnownZero2 & Mask;
97       KnownOne  |= KnownOne2 & Mask;
98     } else {
99       // If the known zeros are in the left operand for a subtract,
100       // fall back to the minimum known zeros in both operands.
101       KnownZero |= APInt::getLowBitsSet(BitWidth,
102                                         std::min(LHSKnownZeroOut,
103                                                  RHSKnownZeroOut));
104     }
105   } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
106     APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
107     KnownZero |= LHSKnownZero & Mask;
108     KnownOne  |= LHSKnownOne & Mask;
109   }
110
111   // Are we still trying to solve for the sign bit?
112   if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()) {
113     if (NSW) {
114       if (Add) {
115         // Adding two positive numbers can't wrap into negative
116         if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
117           KnownZero |= APInt::getSignBit(BitWidth);
118         // and adding two negative numbers can't wrap into positive.
119         else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
120           KnownOne |= APInt::getSignBit(BitWidth);
121       } else {
122         // Subtracting a negative number from a positive one can't wrap
123         if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
124           KnownZero |= APInt::getSignBit(BitWidth);
125         // neither can subtracting a positive number from a negative one.
126         else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
127           KnownOne |= APInt::getSignBit(BitWidth);
128       }
129     }
130   }
131 }
132
133 static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
134                                  const APInt &Mask,
135                                  APInt &KnownZero, APInt &KnownOne,
136                                  APInt &KnownZero2, APInt &KnownOne2,
137                                  const TargetData *TD, unsigned Depth) {
138   unsigned BitWidth = Mask.getBitWidth();
139   APInt Mask2 = APInt::getAllOnesValue(BitWidth);
140   ComputeMaskedBits(Op1, Mask2, KnownZero, KnownOne, TD, Depth+1);
141   ComputeMaskedBits(Op0, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
142   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
143   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
144
145   bool isKnownNegative = false;
146   bool isKnownNonNegative = false;
147   // If the multiplication is known not to overflow, compute the sign bit.
148   if (Mask.isNegative() && NSW) {
149     if (Op0 == Op1) {
150       // The product of a number with itself is non-negative.
151       isKnownNonNegative = true;
152     } else {
153       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
154       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
155       bool isKnownNegativeOp1 = KnownOne.isNegative();
156       bool isKnownNegativeOp0 = KnownOne2.isNegative();
157       // The product of two numbers with the same sign is non-negative.
158       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
159         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
160       // The product of a negative number and a non-negative number is either
161       // negative or zero.
162       if (!isKnownNonNegative)
163         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
164                            isKnownNonZero(Op0, TD, Depth)) ||
165                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
166                            isKnownNonZero(Op1, TD, Depth));
167     }
168   }
169
170   // If low bits are zero in either operand, output low known-0 bits.
171   // Also compute a conserative estimate for high known-0 bits.
172   // More trickiness is possible, but this is sufficient for the
173   // interesting case of alignment computation.
174   KnownOne.clearAllBits();
175   unsigned TrailZ = KnownZero.countTrailingOnes() +
176                     KnownZero2.countTrailingOnes();
177   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
178                              KnownZero2.countLeadingOnes(),
179                              BitWidth) - BitWidth;
180
181   TrailZ = std::min(TrailZ, BitWidth);
182   LeadZ = std::min(LeadZ, BitWidth);
183   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
184               APInt::getHighBitsSet(BitWidth, LeadZ);
185   KnownZero &= Mask;
186
187   // Only make use of no-wrap flags if we failed to compute the sign bit
188   // directly.  This matters if the multiplication always overflows, in
189   // which case we prefer to follow the result of the direct computation,
190   // though as the program is invoking undefined behaviour we can choose
191   // whatever we like here.
192   if (isKnownNonNegative && !KnownOne.isNegative())
193     KnownZero.setBit(BitWidth - 1);
194   else if (isKnownNegative && !KnownZero.isNegative())
195     KnownOne.setBit(BitWidth - 1);
196 }
197
198 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
199 /// known to be either zero or one and return them in the KnownZero/KnownOne
200 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
201 /// processing.
202 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
203 /// we cannot optimize based on the assumption that it is zero without changing
204 /// it to be an explicit zero.  If we don't change it to zero, other code could
205 /// optimized based on the contradictory assumption that it is non-zero.
206 /// Because instcombine aggressively folds operations with undef args anyway,
207 /// this won't lose us code quality.
208 ///
209 /// This function is defined on values with integer type, values with pointer
210 /// type (but only if TD is non-null), and vectors of integers.  In the case
211 /// where V is a vector, the mask, known zero, and known one values are the
212 /// same width as the vector element, and the bit is set only if it is true
213 /// for all of the elements in the vector.
214 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
215                              APInt &KnownZero, APInt &KnownOne,
216                              const TargetData *TD, unsigned Depth) {
217   assert(V && "No Value?");
218   assert(Depth <= MaxDepth && "Limit Search Depth");
219   unsigned BitWidth = Mask.getBitWidth();
220   assert((V->getType()->isIntOrIntVectorTy() ||
221           V->getType()->getScalarType()->isPointerTy()) &&
222          "Not integer or pointer type!");
223   assert((!TD ||
224           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
225          (!V->getType()->isIntOrIntVectorTy() ||
226           V->getType()->getScalarSizeInBits() == BitWidth) &&
227          KnownZero.getBitWidth() == BitWidth &&
228          KnownOne.getBitWidth() == BitWidth &&
229          "V, Mask, KnownOne and KnownZero should have same BitWidth");
230
231   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
232     // We know all of the bits for a constant!
233     KnownOne = CI->getValue() & Mask;
234     KnownZero = ~KnownOne & Mask;
235     return;
236   }
237   // Null and aggregate-zero are all-zeros.
238   if (isa<ConstantPointerNull>(V) ||
239       isa<ConstantAggregateZero>(V)) {
240     KnownOne.clearAllBits();
241     KnownZero = Mask;
242     return;
243   }
244   // Handle a constant vector by taking the intersection of the known bits of
245   // each element.  There is no real need to handle ConstantVector here, because
246   // we don't handle undef in any particularly useful way.
247   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
248     // We know that CDS must be a vector of integers. Take the intersection of
249     // each element.
250     KnownZero.setAllBits(); KnownOne.setAllBits();
251     APInt Elt(KnownZero.getBitWidth(), 0);
252     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
253       Elt = CDS->getElementAsInteger(i);
254       KnownZero &= ~Elt;
255       KnownOne &= Elt;      
256     }
257     return;
258   }
259   
260   // The address of an aligned GlobalValue has trailing zeros.
261   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
262     unsigned Align = GV->getAlignment();
263     if (Align == 0 && TD) {
264       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
265         Type *ObjectType = GVar->getType()->getElementType();
266         if (ObjectType->isSized()) {
267           // If the object is defined in the current Module, we'll be giving
268           // it the preferred alignment. Otherwise, we have to assume that it
269           // may only have the minimum ABI alignment.
270           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
271             Align = TD->getPreferredAlignment(GVar);
272           else
273             Align = TD->getABITypeAlignment(ObjectType);
274         }
275       }
276     }
277     if (Align > 0)
278       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
279                                               CountTrailingZeros_32(Align));
280     else
281       KnownZero.clearAllBits();
282     KnownOne.clearAllBits();
283     return;
284   }
285   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
286   // the bits of its aliasee.
287   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
288     if (GA->mayBeOverridden()) {
289       KnownZero.clearAllBits(); KnownOne.clearAllBits();
290     } else {
291       ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
292                         TD, Depth+1);
293     }
294     return;
295   }
296   
297   if (Argument *A = dyn_cast<Argument>(V)) {
298     // Get alignment information off byval arguments if specified in the IR.
299     if (A->hasByValAttr())
300       if (unsigned Align = A->getParamAlignment())
301         KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
302                                                 CountTrailingZeros_32(Align));
303     return;
304   }
305
306   // Start out not knowing anything.
307   KnownZero.clearAllBits(); KnownOne.clearAllBits();
308
309   if (Depth == MaxDepth || Mask == 0)
310     return;  // Limit search depth.
311
312   Operator *I = dyn_cast<Operator>(V);
313   if (!I) return;
314
315   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
316   switch (I->getOpcode()) {
317   default: break;
318   case Instruction::And: {
319     // If either the LHS or the RHS are Zero, the result is zero.
320     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
321     APInt Mask2(Mask & ~KnownZero);
322     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
323                       Depth+1);
324     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
325     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
326     
327     // Output known-1 bits are only known if set in both the LHS & RHS.
328     KnownOne &= KnownOne2;
329     // Output known-0 are known to be clear if zero in either the LHS | RHS.
330     KnownZero |= KnownZero2;
331     return;
332   }
333   case Instruction::Or: {
334     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
335     APInt Mask2(Mask & ~KnownOne);
336     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
337                       Depth+1);
338     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
339     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
340     
341     // Output known-0 bits are only known if clear in both the LHS & RHS.
342     KnownZero &= KnownZero2;
343     // Output known-1 are known to be set if set in either the LHS | RHS.
344     KnownOne |= KnownOne2;
345     return;
346   }
347   case Instruction::Xor: {
348     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
349     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
350                       Depth+1);
351     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
352     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
353     
354     // Output known-0 bits are known if clear or set in both the LHS & RHS.
355     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
356     // Output known-1 are known to be set if set in only one of the LHS, RHS.
357     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
358     KnownZero = KnownZeroOut;
359     return;
360   }
361   case Instruction::Mul: {
362     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
363     ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
364                          Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
365                          TD, Depth);
366     break;
367   }
368   case Instruction::UDiv: {
369     // For the purposes of computing leading zeros we can conservatively
370     // treat a udiv as a logical right shift by the power of 2 known to
371     // be less than the denominator.
372     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
373     ComputeMaskedBits(I->getOperand(0),
374                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
375     unsigned LeadZ = KnownZero2.countLeadingOnes();
376
377     KnownOne2.clearAllBits();
378     KnownZero2.clearAllBits();
379     ComputeMaskedBits(I->getOperand(1),
380                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
381     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
382     if (RHSUnknownLeadingOnes != BitWidth)
383       LeadZ = std::min(BitWidth,
384                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
385
386     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
387     return;
388   }
389   case Instruction::Select:
390     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
391     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
392                       Depth+1);
393     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
394     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
395
396     // Only known if known in both the LHS and RHS.
397     KnownOne &= KnownOne2;
398     KnownZero &= KnownZero2;
399     return;
400   case Instruction::FPTrunc:
401   case Instruction::FPExt:
402   case Instruction::FPToUI:
403   case Instruction::FPToSI:
404   case Instruction::SIToFP:
405   case Instruction::UIToFP:
406     return; // Can't work with floating point.
407   case Instruction::PtrToInt:
408   case Instruction::IntToPtr:
409     // We can't handle these if we don't know the pointer size.
410     if (!TD) return;
411     // FALL THROUGH and handle them the same as zext/trunc.
412   case Instruction::ZExt:
413   case Instruction::Trunc: {
414     Type *SrcTy = I->getOperand(0)->getType();
415     
416     unsigned SrcBitWidth;
417     // Note that we handle pointer operands here because of inttoptr/ptrtoint
418     // which fall through here.
419     if (SrcTy->isPointerTy())
420       SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
421     else
422       SrcBitWidth = SrcTy->getScalarSizeInBits();
423     
424     APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
425     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
426     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
427     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
428                       Depth+1);
429     KnownZero = KnownZero.zextOrTrunc(BitWidth);
430     KnownOne = KnownOne.zextOrTrunc(BitWidth);
431     // Any top bits are known to be zero.
432     if (BitWidth > SrcBitWidth)
433       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
434     return;
435   }
436   case Instruction::BitCast: {
437     Type *SrcTy = I->getOperand(0)->getType();
438     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
439         // TODO: For now, not handling conversions like:
440         // (bitcast i64 %x to <2 x i32>)
441         !I->getType()->isVectorTy()) {
442       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
443                         Depth+1);
444       return;
445     }
446     break;
447   }
448   case Instruction::SExt: {
449     // Compute the bits in the result that are not present in the input.
450     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
451       
452     APInt MaskIn = Mask.trunc(SrcBitWidth);
453     KnownZero = KnownZero.trunc(SrcBitWidth);
454     KnownOne = KnownOne.trunc(SrcBitWidth);
455     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
456                       Depth+1);
457     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
458     KnownZero = KnownZero.zext(BitWidth);
459     KnownOne = KnownOne.zext(BitWidth);
460
461     // If the sign bit of the input is known set or clear, then we know the
462     // top bits of the result.
463     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
464       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
465     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
466       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
467     return;
468   }
469   case Instruction::Shl:
470     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
471     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
472       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
473       APInt Mask2(Mask.lshr(ShiftAmt));
474       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
475                         Depth+1);
476       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
477       KnownZero <<= ShiftAmt;
478       KnownOne  <<= ShiftAmt;
479       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
480       return;
481     }
482     break;
483   case Instruction::LShr:
484     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
485     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
486       // Compute the new bits that are at the top now.
487       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
488       
489       // Unsigned shift right.
490       APInt Mask2(Mask.shl(ShiftAmt));
491       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
492                         Depth+1);
493       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
494       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
495       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
496       // high bits known zero.
497       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
498       return;
499     }
500     break;
501   case Instruction::AShr:
502     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
503     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
504       // Compute the new bits that are at the top now.
505       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
506       
507       // Signed shift right.
508       APInt Mask2(Mask.shl(ShiftAmt));
509       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
510                         Depth+1);
511       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
512       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
513       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
514         
515       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
516       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
517         KnownZero |= HighBits;
518       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
519         KnownOne |= HighBits;
520       return;
521     }
522     break;
523   case Instruction::Sub: {
524     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
525     ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
526                             Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
527                             TD, Depth);
528     break;
529   }
530   case Instruction::Add: {
531     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
532     ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
533                             Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
534                             TD, Depth);
535     break;
536   }
537   case Instruction::SRem:
538     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
539       APInt RA = Rem->getValue().abs();
540       if (RA.isPowerOf2()) {
541         APInt LowBits = RA - 1;
542         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
543         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
544                           Depth+1);
545
546         // The low bits of the first operand are unchanged by the srem.
547         KnownZero = KnownZero2 & LowBits;
548         KnownOne = KnownOne2 & LowBits;
549
550         // If the first operand is non-negative or has all low bits zero, then
551         // the upper bits are all zero.
552         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
553           KnownZero |= ~LowBits;
554
555         // If the first operand is negative and not all low bits are zero, then
556         // the upper bits are all one.
557         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
558           KnownOne |= ~LowBits;
559
560         KnownZero &= Mask;
561         KnownOne &= Mask;
562
563         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
564       }
565     }
566
567     // The sign bit is the LHS's sign bit, except when the result of the
568     // remainder is zero.
569     if (Mask.isNegative() && KnownZero.isNonNegative()) {
570       APInt Mask2 = APInt::getSignBit(BitWidth);
571       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
572       ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
573                         Depth+1);
574       // If it's known zero, our sign bit is also zero.
575       if (LHSKnownZero.isNegative())
576         KnownZero |= LHSKnownZero;
577     }
578
579     break;
580   case Instruction::URem: {
581     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
582       APInt RA = Rem->getValue();
583       if (RA.isPowerOf2()) {
584         APInt LowBits = (RA - 1);
585         APInt Mask2 = LowBits & Mask;
586         KnownZero |= ~LowBits & Mask;
587         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
588                           Depth+1);
589         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
590         break;
591       }
592     }
593
594     // Since the result is less than or equal to either operand, any leading
595     // zero bits in either operand must also exist in the result.
596     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
597     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
598                       TD, Depth+1);
599     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
600                       TD, Depth+1);
601
602     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
603                                 KnownZero2.countLeadingOnes());
604     KnownOne.clearAllBits();
605     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
606     break;
607   }
608
609   case Instruction::Alloca: {
610     AllocaInst *AI = cast<AllocaInst>(V);
611     unsigned Align = AI->getAlignment();
612     if (Align == 0 && TD)
613       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
614     
615     if (Align > 0)
616       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
617                                               CountTrailingZeros_32(Align));
618     break;
619   }
620   case Instruction::GetElementPtr: {
621     // Analyze all of the subscripts of this getelementptr instruction
622     // to determine if we can prove known low zero bits.
623     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
624     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
625     ComputeMaskedBits(I->getOperand(0), LocalMask,
626                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
627     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
628
629     gep_type_iterator GTI = gep_type_begin(I);
630     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
631       Value *Index = I->getOperand(i);
632       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
633         // Handle struct member offset arithmetic.
634         if (!TD) return;
635         const StructLayout *SL = TD->getStructLayout(STy);
636         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
637         uint64_t Offset = SL->getElementOffset(Idx);
638         TrailZ = std::min(TrailZ,
639                           CountTrailingZeros_64(Offset));
640       } else {
641         // Handle array index arithmetic.
642         Type *IndexedTy = GTI.getIndexedType();
643         if (!IndexedTy->isSized()) return;
644         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
645         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
646         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
647         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
648         ComputeMaskedBits(Index, LocalMask,
649                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
650         TrailZ = std::min(TrailZ,
651                           unsigned(CountTrailingZeros_64(TypeSize) +
652                                    LocalKnownZero.countTrailingOnes()));
653       }
654     }
655     
656     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
657     break;
658   }
659   case Instruction::PHI: {
660     PHINode *P = cast<PHINode>(I);
661     // Handle the case of a simple two-predecessor recurrence PHI.
662     // There's a lot more that could theoretically be done here, but
663     // this is sufficient to catch some interesting cases.
664     if (P->getNumIncomingValues() == 2) {
665       for (unsigned i = 0; i != 2; ++i) {
666         Value *L = P->getIncomingValue(i);
667         Value *R = P->getIncomingValue(!i);
668         Operator *LU = dyn_cast<Operator>(L);
669         if (!LU)
670           continue;
671         unsigned Opcode = LU->getOpcode();
672         // Check for operations that have the property that if
673         // both their operands have low zero bits, the result
674         // will have low zero bits.
675         if (Opcode == Instruction::Add ||
676             Opcode == Instruction::Sub ||
677             Opcode == Instruction::And ||
678             Opcode == Instruction::Or ||
679             Opcode == Instruction::Mul) {
680           Value *LL = LU->getOperand(0);
681           Value *LR = LU->getOperand(1);
682           // Find a recurrence.
683           if (LL == I)
684             L = LR;
685           else if (LR == I)
686             L = LL;
687           else
688             break;
689           // Ok, we have a PHI of the form L op= R. Check for low
690           // zero bits.
691           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
692           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
693           Mask2 = APInt::getLowBitsSet(BitWidth,
694                                        KnownZero2.countTrailingOnes());
695
696           // We need to take the minimum number of known bits
697           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
698           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
699
700           KnownZero = Mask &
701                       APInt::getLowBitsSet(BitWidth,
702                                            std::min(KnownZero2.countTrailingOnes(),
703                                                     KnownZero3.countTrailingOnes()));
704           break;
705         }
706       }
707     }
708
709     // Unreachable blocks may have zero-operand PHI nodes.
710     if (P->getNumIncomingValues() == 0)
711       return;
712
713     // Otherwise take the unions of the known bit sets of the operands,
714     // taking conservative care to avoid excessive recursion.
715     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
716       // Skip if every incoming value references to ourself.
717       if (P->hasConstantValue() == P)
718         break;
719
720       KnownZero = Mask;
721       KnownOne = Mask;
722       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
723         // Skip direct self references.
724         if (P->getIncomingValue(i) == P) continue;
725
726         KnownZero2 = APInt(BitWidth, 0);
727         KnownOne2 = APInt(BitWidth, 0);
728         // Recurse, but cap the recursion to one level, because we don't
729         // want to waste time spinning around in loops.
730         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
731                           KnownZero2, KnownOne2, TD, MaxDepth-1);
732         KnownZero &= KnownZero2;
733         KnownOne &= KnownOne2;
734         // If all bits have been ruled out, there's no need to check
735         // more operands.
736         if (!KnownZero && !KnownOne)
737           break;
738       }
739     }
740     break;
741   }
742   case Instruction::Call:
743     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
744       switch (II->getIntrinsicID()) {
745       default: break;
746       case Intrinsic::ctlz:
747       case Intrinsic::cttz: {
748         unsigned LowBits = Log2_32(BitWidth)+1;
749         // If this call is undefined for 0, the result will be less than 2^n.
750         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
751           LowBits -= 1;
752         KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
753         break;
754       }
755       case Intrinsic::ctpop: {
756         unsigned LowBits = Log2_32(BitWidth)+1;
757         KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
758         break;
759       }
760       case Intrinsic::x86_sse42_crc32_64_8:
761       case Intrinsic::x86_sse42_crc32_64_64:
762         KnownZero = Mask & APInt::getHighBitsSet(64, 32);
763         break;
764       }
765     }
766     break;
767   case Instruction::ExtractValue:
768     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
769       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
770       if (EVI->getNumIndices() != 1) break;
771       if (EVI->getIndices()[0] == 0) {
772         switch (II->getIntrinsicID()) {
773         default: break;
774         case Intrinsic::uadd_with_overflow:
775         case Intrinsic::sadd_with_overflow:
776           ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
777                                   II->getArgOperand(1), false, Mask,
778                                   KnownZero, KnownOne, KnownZero2, KnownOne2,
779                                   TD, Depth);
780           break;
781         case Intrinsic::usub_with_overflow:
782         case Intrinsic::ssub_with_overflow:
783           ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
784                                   II->getArgOperand(1), false, Mask,
785                                   KnownZero, KnownOne, KnownZero2, KnownOne2,
786                                   TD, Depth);
787           break;
788         case Intrinsic::umul_with_overflow:
789         case Intrinsic::smul_with_overflow:
790           ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
791                                false, Mask, KnownZero, KnownOne,
792                                KnownZero2, KnownOne2, TD, Depth);
793           break;
794         }
795       }
796     }
797   }
798 }
799
800 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
801 /// one.  Convenience wrapper around ComputeMaskedBits.
802 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
803                           const TargetData *TD, unsigned Depth) {
804   unsigned BitWidth = getBitWidth(V->getType(), TD);
805   if (!BitWidth) {
806     KnownZero = false;
807     KnownOne = false;
808     return;
809   }
810   APInt ZeroBits(BitWidth, 0);
811   APInt OneBits(BitWidth, 0);
812   ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
813                     Depth);
814   KnownOne = OneBits[BitWidth - 1];
815   KnownZero = ZeroBits[BitWidth - 1];
816 }
817
818 /// isPowerOfTwo - Return true if the given value is known to have exactly one
819 /// bit set when defined. For vectors return true if every element is known to
820 /// be a power of two when defined.  Supports values with integer or pointer
821 /// types and vectors of integers.
822 bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
823                         unsigned Depth) {
824   if (Constant *C = dyn_cast<Constant>(V)) {
825     if (C->isNullValue())
826       return OrZero;
827     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
828       return CI->getValue().isPowerOf2();
829     // TODO: Handle vector constants.
830   }
831
832   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
833   // it is shifted off the end then the result is undefined.
834   if (match(V, m_Shl(m_One(), m_Value())))
835     return true;
836
837   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
838   // bottom.  If it is shifted off the bottom then the result is undefined.
839   if (match(V, m_LShr(m_SignBit(), m_Value())))
840     return true;
841
842   // The remaining tests are all recursive, so bail out if we hit the limit.
843   if (Depth++ == MaxDepth)
844     return false;
845
846   Value *X = 0, *Y = 0;
847   // A shift of a power of two is a power of two or zero.
848   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
849                  match(V, m_Shr(m_Value(X), m_Value()))))
850     return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
851
852   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
853     return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
854
855   if (SelectInst *SI = dyn_cast<SelectInst>(V))
856     return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
857       isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
858
859   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
860     // A power of two and'd with anything is a power of two or zero.
861     if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
862         isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
863       return true;
864     // X & (-X) is always a power of two or zero.
865     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
866       return true;
867     return false;
868   }
869
870   // An exact divide or right shift can only shift off zero bits, so the result
871   // is a power of two only if the first operand is a power of two and not
872   // copying a sign bit (sdiv int_min, 2).
873   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
874       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
875     return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
876   }
877
878   return false;
879 }
880
881 /// isKnownNonZero - Return true if the given value is known to be non-zero
882 /// when defined.  For vectors return true if every element is known to be
883 /// non-zero when defined.  Supports values with integer or pointer type and
884 /// vectors of integers.
885 bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
886   if (Constant *C = dyn_cast<Constant>(V)) {
887     if (C->isNullValue())
888       return false;
889     if (isa<ConstantInt>(C))
890       // Must be non-zero due to null test above.
891       return true;
892     // TODO: Handle vectors
893     return false;
894   }
895
896   // The remaining tests are all recursive, so bail out if we hit the limit.
897   if (Depth++ >= MaxDepth)
898     return false;
899
900   unsigned BitWidth = getBitWidth(V->getType(), TD);
901
902   // X | Y != 0 if X != 0 or Y != 0.
903   Value *X = 0, *Y = 0;
904   if (match(V, m_Or(m_Value(X), m_Value(Y))))
905     return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
906
907   // ext X != 0 if X != 0.
908   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
909     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
910
911   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
912   // if the lowest bit is shifted off the end.
913   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
914     // shl nuw can't remove any non-zero bits.
915     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
916     if (BO->hasNoUnsignedWrap())
917       return isKnownNonZero(X, TD, Depth);
918
919     APInt KnownZero(BitWidth, 0);
920     APInt KnownOne(BitWidth, 0);
921     ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
922     if (KnownOne[0])
923       return true;
924   }
925   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
926   // defined if the sign bit is shifted off the end.
927   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
928     // shr exact can only shift out zero bits.
929     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
930     if (BO->isExact())
931       return isKnownNonZero(X, TD, Depth);
932
933     bool XKnownNonNegative, XKnownNegative;
934     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
935     if (XKnownNegative)
936       return true;
937   }
938   // div exact can only produce a zero if the dividend is zero.
939   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
940     return isKnownNonZero(X, TD, Depth);
941   }
942   // X + Y.
943   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
944     bool XKnownNonNegative, XKnownNegative;
945     bool YKnownNonNegative, YKnownNegative;
946     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
947     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
948
949     // If X and Y are both non-negative (as signed values) then their sum is not
950     // zero unless both X and Y are zero.
951     if (XKnownNonNegative && YKnownNonNegative)
952       if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
953         return true;
954
955     // If X and Y are both negative (as signed values) then their sum is not
956     // zero unless both X and Y equal INT_MIN.
957     if (BitWidth && XKnownNegative && YKnownNegative) {
958       APInt KnownZero(BitWidth, 0);
959       APInt KnownOne(BitWidth, 0);
960       APInt Mask = APInt::getSignedMaxValue(BitWidth);
961       // The sign bit of X is set.  If some other bit is set then X is not equal
962       // to INT_MIN.
963       ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
964       if ((KnownOne & Mask) != 0)
965         return true;
966       // The sign bit of Y is set.  If some other bit is set then Y is not equal
967       // to INT_MIN.
968       ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
969       if ((KnownOne & Mask) != 0)
970         return true;
971     }
972
973     // The sum of a non-negative number and a power of two is not zero.
974     if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
975       return true;
976     if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
977       return true;
978   }
979   // X * Y.
980   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
981     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
982     // If X and Y are non-zero then so is X * Y as long as the multiplication
983     // does not overflow.
984     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
985         isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
986       return true;
987   }
988   // (C ? X : Y) != 0 if X != 0 and Y != 0.
989   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
990     if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
991         isKnownNonZero(SI->getFalseValue(), TD, Depth))
992       return true;
993   }
994
995   if (!BitWidth) return false;
996   APInt KnownZero(BitWidth, 0);
997   APInt KnownOne(BitWidth, 0);
998   ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
999                     TD, Depth);
1000   return KnownOne != 0;
1001 }
1002
1003 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1004 /// this predicate to simplify operations downstream.  Mask is known to be zero
1005 /// for bits that V cannot have.
1006 ///
1007 /// This function is defined on values with integer type, values with pointer
1008 /// type (but only if TD is non-null), and vectors of integers.  In the case
1009 /// where V is a vector, the mask, known zero, and known one values are the
1010 /// same width as the vector element, and the bit is set only if it is true
1011 /// for all of the elements in the vector.
1012 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
1013                              const TargetData *TD, unsigned Depth) {
1014   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1015   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1016   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1017   return (KnownZero & Mask) == Mask;
1018 }
1019
1020
1021
1022 /// ComputeNumSignBits - Return the number of times the sign bit of the
1023 /// register is replicated into the other bits.  We know that at least 1 bit
1024 /// is always equal to the sign bit (itself), but other cases can give us
1025 /// information.  For example, immediately after an "ashr X, 2", we know that
1026 /// the top 3 bits are all equal to each other, so we return 3.
1027 ///
1028 /// 'Op' must have a scalar integer type.
1029 ///
1030 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
1031                                   unsigned Depth) {
1032   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
1033          "ComputeNumSignBits requires a TargetData object to operate "
1034          "on non-integer values!");
1035   Type *Ty = V->getType();
1036   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1037                          Ty->getScalarSizeInBits();
1038   unsigned Tmp, Tmp2;
1039   unsigned FirstAnswer = 1;
1040
1041   // Note that ConstantInt is handled by the general ComputeMaskedBits case
1042   // below.
1043
1044   if (Depth == 6)
1045     return 1;  // Limit search depth.
1046   
1047   Operator *U = dyn_cast<Operator>(V);
1048   switch (Operator::getOpcode(V)) {
1049   default: break;
1050   case Instruction::SExt:
1051     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1052     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1053     
1054   case Instruction::AShr: {
1055     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1056     // ashr X, C   -> adds C sign bits.  Vectors too.
1057     const APInt *ShAmt;
1058     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1059       Tmp += ShAmt->getZExtValue();
1060       if (Tmp > TyBits) Tmp = TyBits;
1061     }
1062     return Tmp;
1063   }
1064   case Instruction::Shl: {
1065     const APInt *ShAmt;
1066     if (match(U->getOperand(1), m_APInt(ShAmt))) {
1067       // shl destroys sign bits.
1068       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1069       Tmp2 = ShAmt->getZExtValue();
1070       if (Tmp2 >= TyBits ||      // Bad shift.
1071           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
1072       return Tmp - Tmp2;
1073     }
1074     break;
1075   }
1076   case Instruction::And:
1077   case Instruction::Or:
1078   case Instruction::Xor:    // NOT is handled here.
1079     // Logical binary ops preserve the number of sign bits at the worst.
1080     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1081     if (Tmp != 1) {
1082       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1083       FirstAnswer = std::min(Tmp, Tmp2);
1084       // We computed what we know about the sign bits as our first
1085       // answer. Now proceed to the generic code that uses
1086       // ComputeMaskedBits, and pick whichever answer is better.
1087     }
1088     break;
1089
1090   case Instruction::Select:
1091     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1092     if (Tmp == 1) return 1;  // Early out.
1093     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1094     return std::min(Tmp, Tmp2);
1095     
1096   case Instruction::Add:
1097     // Add can have at most one carry bit.  Thus we know that the output
1098     // is, at worst, one more bit than the inputs.
1099     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1100     if (Tmp == 1) return 1;  // Early out.
1101       
1102     // Special case decrementing a value (ADD X, -1):
1103     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
1104       if (CRHS->isAllOnesValue()) {
1105         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1106         APInt Mask = APInt::getAllOnesValue(TyBits);
1107         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1108                           Depth+1);
1109         
1110         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1111         // sign bits set.
1112         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1113           return TyBits;
1114         
1115         // If we are subtracting one from a positive number, there is no carry
1116         // out of the result.
1117         if (KnownZero.isNegative())
1118           return Tmp;
1119       }
1120       
1121     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1122     if (Tmp2 == 1) return 1;
1123     return std::min(Tmp, Tmp2)-1;
1124     
1125   case Instruction::Sub:
1126     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1127     if (Tmp2 == 1) return 1;
1128       
1129     // Handle NEG.
1130     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1131       if (CLHS->isNullValue()) {
1132         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1133         APInt Mask = APInt::getAllOnesValue(TyBits);
1134         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
1135                           TD, Depth+1);
1136         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1137         // sign bits set.
1138         if ((KnownZero | APInt(TyBits, 1)) == Mask)
1139           return TyBits;
1140         
1141         // If the input is known to be positive (the sign bit is known clear),
1142         // the output of the NEG has the same number of sign bits as the input.
1143         if (KnownZero.isNegative())
1144           return Tmp2;
1145         
1146         // Otherwise, we treat this like a SUB.
1147       }
1148     
1149     // Sub can have at most one carry bit.  Thus we know that the output
1150     // is, at worst, one more bit than the inputs.
1151     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1152     if (Tmp == 1) return 1;  // Early out.
1153     return std::min(Tmp, Tmp2)-1;
1154       
1155   case Instruction::PHI: {
1156     PHINode *PN = cast<PHINode>(U);
1157     // Don't analyze large in-degree PHIs.
1158     if (PN->getNumIncomingValues() > 4) break;
1159     
1160     // Take the minimum of all incoming values.  This can't infinitely loop
1161     // because of our depth threshold.
1162     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1163     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1164       if (Tmp == 1) return Tmp;
1165       Tmp = std::min(Tmp,
1166                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
1167     }
1168     return Tmp;
1169   }
1170
1171   case Instruction::Trunc:
1172     // FIXME: it's tricky to do anything useful for this, but it is an important
1173     // case for targets like X86.
1174     break;
1175   }
1176   
1177   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1178   // use this information.
1179   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1180   APInt Mask = APInt::getAllOnesValue(TyBits);
1181   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1182   
1183   if (KnownZero.isNegative()) {        // sign bit is 0
1184     Mask = KnownZero;
1185   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1186     Mask = KnownOne;
1187   } else {
1188     // Nothing known.
1189     return FirstAnswer;
1190   }
1191   
1192   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1193   // the number of identical bits in the top of the input value.
1194   Mask = ~Mask;
1195   Mask <<= Mask.getBitWidth()-TyBits;
1196   // Return # leading zeros.  We use 'min' here in case Val was zero before
1197   // shifting.  We don't want to return '64' as for an i32 "0".
1198   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1199 }
1200
1201 /// ComputeMultiple - This function computes the integer multiple of Base that
1202 /// equals V.  If successful, it returns true and returns the multiple in
1203 /// Multiple.  If unsuccessful, it returns false. It looks
1204 /// through SExt instructions only if LookThroughSExt is true.
1205 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
1206                            bool LookThroughSExt, unsigned Depth) {
1207   const unsigned MaxDepth = 6;
1208
1209   assert(V && "No Value?");
1210   assert(Depth <= MaxDepth && "Limit Search Depth");
1211   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
1212
1213   Type *T = V->getType();
1214
1215   ConstantInt *CI = dyn_cast<ConstantInt>(V);
1216
1217   if (Base == 0)
1218     return false;
1219     
1220   if (Base == 1) {
1221     Multiple = V;
1222     return true;
1223   }
1224
1225   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1226   Constant *BaseVal = ConstantInt::get(T, Base);
1227   if (CO && CO == BaseVal) {
1228     // Multiple is 1.
1229     Multiple = ConstantInt::get(T, 1);
1230     return true;
1231   }
1232
1233   if (CI && CI->getZExtValue() % Base == 0) {
1234     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1235     return true;  
1236   }
1237   
1238   if (Depth == MaxDepth) return false;  // Limit search depth.
1239         
1240   Operator *I = dyn_cast<Operator>(V);
1241   if (!I) return false;
1242
1243   switch (I->getOpcode()) {
1244   default: break;
1245   case Instruction::SExt:
1246     if (!LookThroughSExt) return false;
1247     // otherwise fall through to ZExt
1248   case Instruction::ZExt:
1249     return ComputeMultiple(I->getOperand(0), Base, Multiple,
1250                            LookThroughSExt, Depth+1);
1251   case Instruction::Shl:
1252   case Instruction::Mul: {
1253     Value *Op0 = I->getOperand(0);
1254     Value *Op1 = I->getOperand(1);
1255
1256     if (I->getOpcode() == Instruction::Shl) {
1257       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1258       if (!Op1CI) return false;
1259       // Turn Op0 << Op1 into Op0 * 2^Op1
1260       APInt Op1Int = Op1CI->getValue();
1261       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
1262       APInt API(Op1Int.getBitWidth(), 0);
1263       API.setBit(BitToSet);
1264       Op1 = ConstantInt::get(V->getContext(), API);
1265     }
1266
1267     Value *Mul0 = NULL;
1268     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1269       if (Constant *Op1C = dyn_cast<Constant>(Op1))
1270         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1271           if (Op1C->getType()->getPrimitiveSizeInBits() < 
1272               MulC->getType()->getPrimitiveSizeInBits())
1273             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1274           if (Op1C->getType()->getPrimitiveSizeInBits() > 
1275               MulC->getType()->getPrimitiveSizeInBits())
1276             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1277           
1278           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1279           Multiple = ConstantExpr::getMul(MulC, Op1C);
1280           return true;
1281         }
1282
1283       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1284         if (Mul0CI->getValue() == 1) {
1285           // V == Base * Op1, so return Op1
1286           Multiple = Op1;
1287           return true;
1288         }
1289     }
1290
1291     Value *Mul1 = NULL;
1292     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1293       if (Constant *Op0C = dyn_cast<Constant>(Op0))
1294         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1295           if (Op0C->getType()->getPrimitiveSizeInBits() < 
1296               MulC->getType()->getPrimitiveSizeInBits())
1297             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1298           if (Op0C->getType()->getPrimitiveSizeInBits() > 
1299               MulC->getType()->getPrimitiveSizeInBits())
1300             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1301           
1302           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1303           Multiple = ConstantExpr::getMul(MulC, Op0C);
1304           return true;
1305         }
1306
1307       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1308         if (Mul1CI->getValue() == 1) {
1309           // V == Base * Op0, so return Op0
1310           Multiple = Op0;
1311           return true;
1312         }
1313     }
1314   }
1315   }
1316
1317   // We could not determine if V is a multiple of Base.
1318   return false;
1319 }
1320
1321 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1322 /// value is never equal to -0.0.
1323 ///
1324 /// NOTE: this function will need to be revisited when we support non-default
1325 /// rounding modes!
1326 ///
1327 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1328   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1329     return !CFP->getValueAPF().isNegZero();
1330   
1331   if (Depth == 6)
1332     return 1;  // Limit search depth.
1333
1334   const Operator *I = dyn_cast<Operator>(V);
1335   if (I == 0) return false;
1336   
1337   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1338   if (I->getOpcode() == Instruction::FAdd &&
1339       isa<ConstantFP>(I->getOperand(1)) && 
1340       cast<ConstantFP>(I->getOperand(1))->isNullValue())
1341     return true;
1342     
1343   // sitofp and uitofp turn into +0.0 for zero.
1344   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1345     return true;
1346   
1347   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1348     // sqrt(-0.0) = -0.0, no other negative results are possible.
1349     if (II->getIntrinsicID() == Intrinsic::sqrt)
1350       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
1351   
1352   if (const CallInst *CI = dyn_cast<CallInst>(I))
1353     if (const Function *F = CI->getCalledFunction()) {
1354       if (F->isDeclaration()) {
1355         // abs(x) != -0.0
1356         if (F->getName() == "abs") return true;
1357         // fabs[lf](x) != -0.0
1358         if (F->getName() == "fabs") return true;
1359         if (F->getName() == "fabsf") return true;
1360         if (F->getName() == "fabsl") return true;
1361         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1362             F->getName() == "sqrtl")
1363           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
1364       }
1365     }
1366   
1367   return false;
1368 }
1369
1370 /// isBytewiseValue - If the specified value can be set by repeating the same
1371 /// byte in memory, return the i8 value that it is represented with.  This is
1372 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1373 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1374 /// byte store (e.g. i16 0x1234), return null.
1375 Value *llvm::isBytewiseValue(Value *V) {
1376   // All byte-wide stores are splatable, even of arbitrary variables.
1377   if (V->getType()->isIntegerTy(8)) return V;
1378
1379   // Handle 'null' ConstantArrayZero etc.
1380   if (Constant *C = dyn_cast<Constant>(V))
1381     if (C->isNullValue())
1382       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
1383   
1384   // Constant float and double values can be handled as integer values if the
1385   // corresponding integer value is "byteable".  An important case is 0.0. 
1386   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1387     if (CFP->getType()->isFloatTy())
1388       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1389     if (CFP->getType()->isDoubleTy())
1390       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1391     // Don't handle long double formats, which have strange constraints.
1392   }
1393   
1394   // We can handle constant integers that are power of two in size and a 
1395   // multiple of 8 bits.
1396   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1397     unsigned Width = CI->getBitWidth();
1398     if (isPowerOf2_32(Width) && Width > 8) {
1399       // We can handle this value if the recursive binary decomposition is the
1400       // same at all levels.
1401       APInt Val = CI->getValue();
1402       APInt Val2;
1403       while (Val.getBitWidth() != 8) {
1404         unsigned NextWidth = Val.getBitWidth()/2;
1405         Val2  = Val.lshr(NextWidth);
1406         Val2 = Val2.trunc(Val.getBitWidth()/2);
1407         Val = Val.trunc(Val.getBitWidth()/2);
1408         
1409         // If the top/bottom halves aren't the same, reject it.
1410         if (Val != Val2)
1411           return 0;
1412       }
1413       return ConstantInt::get(V->getContext(), Val);
1414     }
1415   }
1416   
1417   // A ConstantDataArray/Vector is splatable if all its members are equal and
1418   // also splatable.
1419   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1420     Value *Elt = CA->getElementAsConstant(0);
1421     Value *Val = isBytewiseValue(Elt);
1422     if (!Val)
1423       return 0;
1424     
1425     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1426       if (CA->getElementAsConstant(I) != Elt)
1427         return 0;
1428     
1429     return Val;
1430   }
1431
1432   // Conceptually, we could handle things like:
1433   //   %a = zext i8 %X to i16
1434   //   %b = shl i16 %a, 8
1435   //   %c = or i16 %a, %b
1436   // but until there is an example that actually needs this, it doesn't seem
1437   // worth worrying about.
1438   return 0;
1439 }
1440
1441
1442 // This is the recursive version of BuildSubAggregate. It takes a few different
1443 // arguments. Idxs is the index within the nested struct From that we are
1444 // looking at now (which is of type IndexedType). IdxSkip is the number of
1445 // indices from Idxs that should be left out when inserting into the resulting
1446 // struct. To is the result struct built so far, new insertvalue instructions
1447 // build on that.
1448 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
1449                                 SmallVector<unsigned, 10> &Idxs,
1450                                 unsigned IdxSkip,
1451                                 Instruction *InsertBefore) {
1452   llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1453   if (STy) {
1454     // Save the original To argument so we can modify it
1455     Value *OrigTo = To;
1456     // General case, the type indexed by Idxs is a struct
1457     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1458       // Process each struct element recursively
1459       Idxs.push_back(i);
1460       Value *PrevTo = To;
1461       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1462                              InsertBefore);
1463       Idxs.pop_back();
1464       if (!To) {
1465         // Couldn't find any inserted value for this index? Cleanup
1466         while (PrevTo != OrigTo) {
1467           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1468           PrevTo = Del->getAggregateOperand();
1469           Del->eraseFromParent();
1470         }
1471         // Stop processing elements
1472         break;
1473       }
1474     }
1475     // If we successfully found a value for each of our subaggregates
1476     if (To)
1477       return To;
1478   }
1479   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1480   // the struct's elements had a value that was inserted directly. In the latter
1481   // case, perhaps we can't determine each of the subelements individually, but
1482   // we might be able to find the complete struct somewhere.
1483   
1484   // Find the value that is at that particular spot
1485   Value *V = FindInsertedValue(From, Idxs);
1486
1487   if (!V)
1488     return NULL;
1489
1490   // Insert the value in the new (sub) aggregrate
1491   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
1492                                        "tmp", InsertBefore);
1493 }
1494
1495 // This helper takes a nested struct and extracts a part of it (which is again a
1496 // struct) into a new value. For example, given the struct:
1497 // { a, { b, { c, d }, e } }
1498 // and the indices "1, 1" this returns
1499 // { c, d }.
1500 //
1501 // It does this by inserting an insertvalue for each element in the resulting
1502 // struct, as opposed to just inserting a single struct. This will only work if
1503 // each of the elements of the substruct are known (ie, inserted into From by an
1504 // insertvalue instruction somewhere).
1505 //
1506 // All inserted insertvalue instructions are inserted before InsertBefore
1507 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
1508                                 Instruction *InsertBefore) {
1509   assert(InsertBefore && "Must have someplace to insert!");
1510   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1511                                                              idx_range);
1512   Value *To = UndefValue::get(IndexedType);
1513   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
1514   unsigned IdxSkip = Idxs.size();
1515
1516   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1517 }
1518
1519 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1520 /// the scalar value indexed is already around as a register, for example if it
1521 /// were inserted directly into the aggregrate.
1522 ///
1523 /// If InsertBefore is not null, this function will duplicate (modified)
1524 /// insertvalues when a part of a nested struct is extracted.
1525 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1526                                Instruction *InsertBefore) {
1527   // Nothing to index? Just return V then (this is useful at the end of our
1528   // recursion).
1529   if (idx_range.empty())
1530     return V;
1531   // We have indices, so V should have an indexable type.
1532   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1533          "Not looking at a struct or array?");
1534   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1535          "Invalid indices for type?");
1536
1537   if (Constant *C = dyn_cast<Constant>(V)) {
1538     C = C->getAggregateElement(idx_range[0]);
1539     if (C == 0) return 0;
1540     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1541   }
1542     
1543   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1544     // Loop the indices for the insertvalue instruction in parallel with the
1545     // requested indices
1546     const unsigned *req_idx = idx_range.begin();
1547     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1548          i != e; ++i, ++req_idx) {
1549       if (req_idx == idx_range.end()) {
1550         // We can't handle this without inserting insertvalues
1551         if (!InsertBefore)
1552           return 0;
1553
1554         // The requested index identifies a part of a nested aggregate. Handle
1555         // this specially. For example,
1556         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1557         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1558         // %C = extractvalue {i32, { i32, i32 } } %B, 1
1559         // This can be changed into
1560         // %A = insertvalue {i32, i32 } undef, i32 10, 0
1561         // %C = insertvalue {i32, i32 } %A, i32 11, 1
1562         // which allows the unused 0,0 element from the nested struct to be
1563         // removed.
1564         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1565                                  InsertBefore);
1566       }
1567       
1568       // This insert value inserts something else than what we are looking for.
1569       // See if the (aggregrate) value inserted into has the value we are
1570       // looking for, then.
1571       if (*req_idx != *i)
1572         return FindInsertedValue(I->getAggregateOperand(), idx_range,
1573                                  InsertBefore);
1574     }
1575     // If we end up here, the indices of the insertvalue match with those
1576     // requested (though possibly only partially). Now we recursively look at
1577     // the inserted value, passing any remaining indices.
1578     return FindInsertedValue(I->getInsertedValueOperand(),
1579                              makeArrayRef(req_idx, idx_range.end()),
1580                              InsertBefore);
1581   }
1582   
1583   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1584     // If we're extracting a value from an aggregrate that was extracted from
1585     // something else, we can extract from that something else directly instead.
1586     // However, we will need to chain I's indices with the requested indices.
1587    
1588     // Calculate the number of indices required 
1589     unsigned size = I->getNumIndices() + idx_range.size();
1590     // Allocate some space to put the new indices in
1591     SmallVector<unsigned, 5> Idxs;
1592     Idxs.reserve(size);
1593     // Add indices from the extract value instruction
1594     Idxs.append(I->idx_begin(), I->idx_end());
1595     
1596     // Add requested indices
1597     Idxs.append(idx_range.begin(), idx_range.end());
1598
1599     assert(Idxs.size() == size 
1600            && "Number of indices added not correct?");
1601     
1602     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
1603   }
1604   // Otherwise, we don't know (such as, extracting from a function return value
1605   // or load instruction)
1606   return 0;
1607 }
1608
1609 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1610 /// it can be expressed as a base pointer plus a constant offset.  Return the
1611 /// base and offset to the caller.
1612 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1613                                               const TargetData &TD) {
1614   Operator *PtrOp = dyn_cast<Operator>(Ptr);
1615   if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1616     return Ptr;
1617   
1618   // Just look through bitcasts.
1619   if (PtrOp->getOpcode() == Instruction::BitCast)
1620     return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1621   
1622   // If this is a GEP with constant indices, we can look through it.
1623   GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1624   if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1625   
1626   gep_type_iterator GTI = gep_type_begin(GEP);
1627   for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1628        ++I, ++GTI) {
1629     ConstantInt *OpC = cast<ConstantInt>(*I);
1630     if (OpC->isZero()) continue;
1631     
1632     // Handle a struct and array indices which add their offset to the pointer.
1633     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1634       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1635     } else {
1636       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1637       Offset += OpC->getSExtValue()*Size;
1638     }
1639   }
1640   
1641   // Re-sign extend from the pointer size if needed to get overflow edge cases
1642   // right.
1643   unsigned PtrSize = TD.getPointerSizeInBits();
1644   if (PtrSize < 64)
1645     Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1646   
1647   return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1648 }
1649
1650
1651 /// getConstantStringInfo - This function computes the length of a
1652 /// null-terminated C string pointed to by V.  If successful, it returns true
1653 /// and returns the string in Str.  If unsuccessful, it returns false.
1654 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1655                                  uint64_t Offset, bool TrimAtNul) {
1656   assert(V);
1657
1658   // Look through bitcast instructions and geps.
1659   V = V->stripPointerCasts();
1660   
1661   // If the value is a GEP instructionor  constant expression, treat it as an
1662   // offset.
1663   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1664     // Make sure the GEP has exactly three arguments.
1665     if (GEP->getNumOperands() != 3)
1666       return false;
1667     
1668     // Make sure the index-ee is a pointer to array of i8.
1669     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1670     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1671     if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1672       return false;
1673     
1674     // Check to make sure that the first operand of the GEP is an integer and
1675     // has value 0 so that we are sure we're indexing into the initializer.
1676     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1677     if (FirstIdx == 0 || !FirstIdx->isZero())
1678       return false;
1679     
1680     // If the second index isn't a ConstantInt, then this is a variable index
1681     // into the array.  If this occurs, we can't say anything meaningful about
1682     // the string.
1683     uint64_t StartIdx = 0;
1684     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1685       StartIdx = CI->getZExtValue();
1686     else
1687       return false;
1688     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
1689   }
1690
1691   // The GEP instruction, constant or instruction, must reference a global
1692   // variable that is a constant and is initialized. The referenced constant
1693   // initializer is the array that we'll use for optimization.
1694   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
1695   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1696     return false;
1697
1698   // Handle the all-zeros case
1699   if (GV->getInitializer()->isNullValue()) {
1700     // This is a degenerate case. The initializer is constant zero so the
1701     // length of the string must be zero.
1702     Str = "";
1703     return true;
1704   }
1705   
1706   // Must be a Constant Array
1707   const ConstantDataArray *Array =
1708     dyn_cast<ConstantDataArray>(GV->getInitializer());
1709   if (Array == 0 || !Array->isString())
1710     return false;
1711   
1712   // Get the number of elements in the array
1713   uint64_t NumElts = Array->getType()->getArrayNumElements();
1714
1715   // Start out with the entire array in the StringRef.
1716   Str = Array->getAsString();
1717
1718   if (Offset > NumElts)
1719     return false;
1720   
1721   // Skip over 'offset' bytes.
1722   Str = Str.substr(Offset);
1723   
1724   if (TrimAtNul) {
1725     // Trim off the \0 and anything after it.  If the array is not nul
1726     // terminated, we just return the whole end of string.  The client may know
1727     // some other way that the string is length-bound.
1728     Str = Str.substr(0, Str.find('\0'));
1729   }
1730   return true;
1731 }
1732
1733 // These next two are very similar to the above, but also look through PHI
1734 // nodes.
1735 // TODO: See if we can integrate these two together.
1736
1737 /// GetStringLengthH - If we can compute the length of the string pointed to by
1738 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1739 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1740   // Look through noop bitcast instructions.
1741   V = V->stripPointerCasts();
1742
1743   // If this is a PHI node, there are two cases: either we have already seen it
1744   // or we haven't.
1745   if (PHINode *PN = dyn_cast<PHINode>(V)) {
1746     if (!PHIs.insert(PN))
1747       return ~0ULL;  // already in the set.
1748
1749     // If it was new, see if all the input strings are the same length.
1750     uint64_t LenSoFar = ~0ULL;
1751     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1752       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1753       if (Len == 0) return 0; // Unknown length -> unknown.
1754
1755       if (Len == ~0ULL) continue;
1756
1757       if (Len != LenSoFar && LenSoFar != ~0ULL)
1758         return 0;    // Disagree -> unknown.
1759       LenSoFar = Len;
1760     }
1761
1762     // Success, all agree.
1763     return LenSoFar;
1764   }
1765
1766   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1767   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1768     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1769     if (Len1 == 0) return 0;
1770     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1771     if (Len2 == 0) return 0;
1772     if (Len1 == ~0ULL) return Len2;
1773     if (Len2 == ~0ULL) return Len1;
1774     if (Len1 != Len2) return 0;
1775     return Len1;
1776   }
1777   
1778   // Otherwise, see if we can read the string.
1779   StringRef StrData;
1780   if (!getConstantStringInfo(V, StrData))
1781     return 0;
1782
1783   return StrData.size()+1;
1784 }
1785
1786 /// GetStringLength - If we can compute the length of the string pointed to by
1787 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1788 uint64_t llvm::GetStringLength(Value *V) {
1789   if (!V->getType()->isPointerTy()) return 0;
1790
1791   SmallPtrSet<PHINode*, 32> PHIs;
1792   uint64_t Len = GetStringLengthH(V, PHIs);
1793   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1794   // an empty string as a length.
1795   return Len == ~0ULL ? 1 : Len;
1796 }
1797
1798 Value *
1799 llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
1800   if (!V->getType()->isPointerTy())
1801     return V;
1802   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1803     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1804       V = GEP->getPointerOperand();
1805     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1806       V = cast<Operator>(V)->getOperand(0);
1807     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1808       if (GA->mayBeOverridden())
1809         return V;
1810       V = GA->getAliasee();
1811     } else {
1812       // See if InstructionSimplify knows any relevant tricks.
1813       if (Instruction *I = dyn_cast<Instruction>(V))
1814         // TODO: Acquire a DominatorTree and use it.
1815         if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
1816           V = Simplified;
1817           continue;
1818         }
1819
1820       return V;
1821     }
1822     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1823   }
1824   return V;
1825 }
1826
1827 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1828 /// are lifetime markers.
1829 ///
1830 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1831   for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1832        UI != UE; ++UI) {
1833     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1834     if (!II) return false;
1835
1836     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1837         II->getIntrinsicID() != Intrinsic::lifetime_end)
1838       return false;
1839   }
1840   return true;
1841 }
1842
1843 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
1844                                         const TargetData *TD) {
1845   const Operator *Inst = dyn_cast<Operator>(V);
1846   if (!Inst)
1847     return false;
1848
1849   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1850     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1851       if (C->canTrap())
1852         return false;
1853
1854   switch (Inst->getOpcode()) {
1855   default:
1856     return true;
1857   case Instruction::UDiv:
1858   case Instruction::URem:
1859     // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1860     return isKnownNonZero(Inst->getOperand(1), TD);
1861   case Instruction::SDiv:
1862   case Instruction::SRem: {
1863     Value *Op = Inst->getOperand(1);
1864     // x / y is undefined if y == 0
1865     if (!isKnownNonZero(Op, TD))
1866       return false;
1867     // x / y might be undefined if y == -1
1868     unsigned BitWidth = getBitWidth(Op->getType(), TD);
1869     if (BitWidth == 0)
1870       return false;
1871     APInt KnownZero(BitWidth, 0);
1872     APInt KnownOne(BitWidth, 0);
1873     ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1874                       KnownZero, KnownOne, TD);
1875     return !!KnownZero;
1876   }
1877   case Instruction::Load: {
1878     const LoadInst *LI = cast<LoadInst>(Inst);
1879     if (!LI->isUnordered())
1880       return false;
1881     return LI->getPointerOperand()->isDereferenceablePointer();
1882   }
1883   case Instruction::Call: {
1884    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1885      switch (II->getIntrinsicID()) {
1886        case Intrinsic::bswap:
1887        case Intrinsic::ctlz:
1888        case Intrinsic::ctpop:
1889        case Intrinsic::cttz:
1890        case Intrinsic::objectsize:
1891        case Intrinsic::sadd_with_overflow:
1892        case Intrinsic::smul_with_overflow:
1893        case Intrinsic::ssub_with_overflow:
1894        case Intrinsic::uadd_with_overflow:
1895        case Intrinsic::umul_with_overflow:
1896        case Intrinsic::usub_with_overflow:
1897          return true;
1898        // TODO: some fp intrinsics are marked as having the same error handling
1899        // as libm. They're safe to speculate when they won't error.
1900        // TODO: are convert_{from,to}_fp16 safe?
1901        // TODO: can we list target-specific intrinsics here?
1902        default: break;
1903      }
1904    }
1905     return false; // The called function could have undefined behavior or
1906                   // side-effects, even if marked readnone nounwind.
1907   }
1908   case Instruction::VAArg:
1909   case Instruction::Alloca:
1910   case Instruction::Invoke:
1911   case Instruction::PHI:
1912   case Instruction::Store:
1913   case Instruction::Ret:
1914   case Instruction::Br:
1915   case Instruction::IndirectBr:
1916   case Instruction::Switch:
1917   case Instruction::Unreachable:
1918   case Instruction::Fence:
1919   case Instruction::LandingPad:
1920   case Instruction::AtomicRMW:
1921   case Instruction::AtomicCmpXchg:
1922   case Instruction::Resume:
1923     return false; // Misc instructions which have effects
1924   }
1925 }