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