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