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