Fix llvm::ComputeNumSignBits to handle pointer types
[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/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <cstring>
24 using namespace llvm;
25
26 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
27 /// opcode value. Otherwise return UserOp1.
28 static unsigned getOpcode(const Value *V) {
29   if (const Instruction *I = dyn_cast<Instruction>(V))
30     return I->getOpcode();
31   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
32     return CE->getOpcode();
33   // Use UserOp1 to mean there's no opcode.
34   return Instruction::UserOp1;
35 }
36
37
38 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
39 /// known to be either zero or one and return them in the KnownZero/KnownOne
40 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
41 /// processing.
42 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
43 /// we cannot optimize based on the assumption that it is zero without changing
44 /// it to be an explicit zero.  If we don't change it to zero, other code could
45 /// optimized based on the contradictory assumption that it is non-zero.
46 /// Because instcombine aggressively folds operations with undef args anyway,
47 /// this won't lose us code quality.
48 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
49                              APInt &KnownZero, APInt &KnownOne,
50                              TargetData *TD, unsigned Depth) {
51   const unsigned MaxDepth = 6;
52   assert(V && "No Value?");
53   assert(Depth <= MaxDepth && "Limit Search Depth");
54   unsigned BitWidth = Mask.getBitWidth();
55   assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) &&
56          "Not integer or pointer type!");
57   assert((!TD ||
58           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
59          (!V->getType()->isIntOrIntVector() ||
60           V->getType()->getScalarSizeInBits() == BitWidth) &&
61          KnownZero.getBitWidth() == BitWidth && 
62          KnownOne.getBitWidth() == BitWidth &&
63          "V, Mask, KnownOne and KnownZero should have same BitWidth");
64
65   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
66     // We know all of the bits for a constant!
67     KnownOne = CI->getValue() & Mask;
68     KnownZero = ~KnownOne & Mask;
69     return;
70   }
71   // Null and aggregate-zero are all-zeros.
72   if (isa<ConstantPointerNull>(V) ||
73       isa<ConstantAggregateZero>(V)) {
74     KnownOne.clear();
75     KnownZero = Mask;
76     return;
77   }
78   // Handle a constant vector by taking the intersection of the known bits of
79   // each element.
80   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
81     KnownZero.set(); KnownOne.set();
82     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
83       APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
84       ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
85                         TD, Depth);
86       KnownZero &= KnownZero2;
87       KnownOne &= KnownOne2;
88     }
89     return;
90   }
91   // The address of an aligned GlobalValue has trailing zeros.
92   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
93     unsigned Align = GV->getAlignment();
94     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
95       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
96     if (Align > 0)
97       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
98                                               CountTrailingZeros_32(Align));
99     else
100       KnownZero.clear();
101     KnownOne.clear();
102     return;
103   }
104
105   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
106
107   if (Depth == MaxDepth || Mask == 0)
108     return;  // Limit search depth.
109
110   User *I = dyn_cast<User>(V);
111   if (!I) return;
112
113   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
114   switch (getOpcode(I)) {
115   default: break;
116   case Instruction::And: {
117     // If either the LHS or the RHS are Zero, the result is zero.
118     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
119     APInt Mask2(Mask & ~KnownZero);
120     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
121                       Depth+1);
122     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
123     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
124     
125     // Output known-1 bits are only known if set in both the LHS & RHS.
126     KnownOne &= KnownOne2;
127     // Output known-0 are known to be clear if zero in either the LHS | RHS.
128     KnownZero |= KnownZero2;
129     return;
130   }
131   case Instruction::Or: {
132     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
133     APInt Mask2(Mask & ~KnownOne);
134     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
135                       Depth+1);
136     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
137     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
138     
139     // Output known-0 bits are only known if clear in both the LHS & RHS.
140     KnownZero &= KnownZero2;
141     // Output known-1 are known to be set if set in either the LHS | RHS.
142     KnownOne |= KnownOne2;
143     return;
144   }
145   case Instruction::Xor: {
146     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
147     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
148                       Depth+1);
149     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
150     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
151     
152     // Output known-0 bits are known if clear or set in both the LHS & RHS.
153     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
154     // Output known-1 are known to be set if set in only one of the LHS, RHS.
155     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
156     KnownZero = KnownZeroOut;
157     return;
158   }
159   case Instruction::Mul: {
160     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
161     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
162     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
163                       Depth+1);
164     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
165     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
166     
167     // If low bits are zero in either operand, output low known-0 bits.
168     // Also compute a conserative estimate for high known-0 bits.
169     // More trickiness is possible, but this is sufficient for the
170     // interesting case of alignment computation.
171     KnownOne.clear();
172     unsigned TrailZ = KnownZero.countTrailingOnes() +
173                       KnownZero2.countTrailingOnes();
174     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
175                                KnownZero2.countLeadingOnes(),
176                                BitWidth) - BitWidth;
177
178     TrailZ = std::min(TrailZ, BitWidth);
179     LeadZ = std::min(LeadZ, BitWidth);
180     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
181                 APInt::getHighBitsSet(BitWidth, LeadZ);
182     KnownZero &= Mask;
183     return;
184   }
185   case Instruction::UDiv: {
186     // For the purposes of computing leading zeros we can conservatively
187     // treat a udiv as a logical right shift by the power of 2 known to
188     // be less than the denominator.
189     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
190     ComputeMaskedBits(I->getOperand(0),
191                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
192     unsigned LeadZ = KnownZero2.countLeadingOnes();
193
194     KnownOne2.clear();
195     KnownZero2.clear();
196     ComputeMaskedBits(I->getOperand(1),
197                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
198     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
199     if (RHSUnknownLeadingOnes != BitWidth)
200       LeadZ = std::min(BitWidth,
201                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
202
203     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
204     return;
205   }
206   case Instruction::Select:
207     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
208     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
209                       Depth+1);
210     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
211     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
212
213     // Only known if known in both the LHS and RHS.
214     KnownOne &= KnownOne2;
215     KnownZero &= KnownZero2;
216     return;
217   case Instruction::FPTrunc:
218   case Instruction::FPExt:
219   case Instruction::FPToUI:
220   case Instruction::FPToSI:
221   case Instruction::SIToFP:
222   case Instruction::UIToFP:
223     return; // Can't work with floating point.
224   case Instruction::PtrToInt:
225   case Instruction::IntToPtr:
226     // We can't handle these if we don't know the pointer size.
227     if (!TD) return;
228     // FALL THROUGH and handle them the same as zext/trunc.
229   case Instruction::ZExt:
230   case Instruction::Trunc: {
231     // Note that we handle pointer operands here because of inttoptr/ptrtoint
232     // which fall through here.
233     const Type *SrcTy = I->getOperand(0)->getType();
234     unsigned SrcBitWidth = TD ?
235       TD->getTypeSizeInBits(SrcTy) :
236       SrcTy->getScalarSizeInBits();
237     APInt MaskIn(Mask);
238     MaskIn.zextOrTrunc(SrcBitWidth);
239     KnownZero.zextOrTrunc(SrcBitWidth);
240     KnownOne.zextOrTrunc(SrcBitWidth);
241     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
242                       Depth+1);
243     KnownZero.zextOrTrunc(BitWidth);
244     KnownOne.zextOrTrunc(BitWidth);
245     // Any top bits are known to be zero.
246     if (BitWidth > SrcBitWidth)
247       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
248     return;
249   }
250   case Instruction::BitCast: {
251     const Type *SrcTy = I->getOperand(0)->getType();
252     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
253       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
254                         Depth+1);
255       return;
256     }
257     break;
258   }
259   case Instruction::SExt: {
260     // Compute the bits in the result that are not present in the input.
261     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
262     unsigned SrcBitWidth = SrcTy->getBitWidth();
263       
264     APInt MaskIn(Mask); 
265     MaskIn.trunc(SrcBitWidth);
266     KnownZero.trunc(SrcBitWidth);
267     KnownOne.trunc(SrcBitWidth);
268     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
269                       Depth+1);
270     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
271     KnownZero.zext(BitWidth);
272     KnownOne.zext(BitWidth);
273
274     // If the sign bit of the input is known set or clear, then we know the
275     // top bits of the result.
276     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
277       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
278     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
279       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
280     return;
281   }
282   case Instruction::Shl:
283     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
284     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
285       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
286       APInt Mask2(Mask.lshr(ShiftAmt));
287       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
288                         Depth+1);
289       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
290       KnownZero <<= ShiftAmt;
291       KnownOne  <<= ShiftAmt;
292       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
293       return;
294     }
295     break;
296   case Instruction::LShr:
297     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
299       // Compute the new bits that are at the top now.
300       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
301       
302       // Unsigned shift right.
303       APInt Mask2(Mask.shl(ShiftAmt));
304       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
305                         Depth+1);
306       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
307       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
308       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
309       // high bits known zero.
310       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
311       return;
312     }
313     break;
314   case Instruction::AShr:
315     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
316     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
317       // Compute the new bits that are at the top now.
318       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
319       
320       // Signed shift right.
321       APInt Mask2(Mask.shl(ShiftAmt));
322       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
323                         Depth+1);
324       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
325       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
326       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
327         
328       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
329       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
330         KnownZero |= HighBits;
331       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
332         KnownOne |= HighBits;
333       return;
334     }
335     break;
336   case Instruction::Sub: {
337     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
338       // We know that the top bits of C-X are clear if X contains less bits
339       // than C (i.e. no wrap-around can happen).  For example, 20-X is
340       // positive if we can prove that X is >= 0 and < 16.
341       if (!CLHS->getValue().isNegative()) {
342         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
343         // NLZ can't be BitWidth with no sign bit
344         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
345         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
346                           TD, Depth+1);
347     
348         // If all of the MaskV bits are known to be zero, then we know the
349         // output top bits are zero, because we now know that the output is
350         // from [0-C].
351         if ((KnownZero2 & MaskV) == MaskV) {
352           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
353           // Top bits known zero.
354           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
355         }
356       }        
357     }
358   }
359   // fall through
360   case Instruction::Add: {
361     // If one of the operands has trailing zeros, than the bits that the
362     // other operand has in those bit positions will be preserved in the
363     // result. For an add, this works with either operand. For a subtract,
364     // this only works if the known zeros are in the right operand.
365     APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
366     APInt Mask2 = APInt::getLowBitsSet(BitWidth,
367                                        BitWidth - Mask.countLeadingZeros());
368     ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
369                       Depth+1);
370     assert((LHSKnownZero & LHSKnownOne) == 0 &&
371            "Bits known to be one AND zero?");
372     unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
373
374     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
375                       Depth+1);
376     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
377     unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
378
379     // Determine which operand has more trailing zeros, and use that
380     // many bits from the other operand.
381     if (LHSKnownZeroOut > RHSKnownZeroOut) {
382       if (getOpcode(I) == Instruction::Add) {
383         APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
384         KnownZero |= KnownZero2 & Mask;
385         KnownOne  |= KnownOne2 & Mask;
386       } else {
387         // If the known zeros are in the left operand for a subtract,
388         // fall back to the minimum known zeros in both operands.
389         KnownZero |= APInt::getLowBitsSet(BitWidth,
390                                           std::min(LHSKnownZeroOut,
391                                                    RHSKnownZeroOut));
392       }
393     } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
394       APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
395       KnownZero |= LHSKnownZero & Mask;
396       KnownOne  |= LHSKnownOne & Mask;
397     }
398     return;
399   }
400   case Instruction::SRem:
401     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
402       APInt RA = Rem->getValue();
403       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
404         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
405         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
406         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
407                           Depth+1);
408
409         // If the sign bit of the first operand is zero, the sign bit of
410         // the result is zero. If the first operand has no one bits below
411         // the second operand's single 1 bit, its sign will be zero.
412         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
413           KnownZero2 |= ~LowBits;
414
415         KnownZero |= KnownZero2 & Mask;
416
417         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
418       }
419     }
420     break;
421   case Instruction::URem: {
422     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
423       APInt RA = Rem->getValue();
424       if (RA.isPowerOf2()) {
425         APInt LowBits = (RA - 1);
426         APInt Mask2 = LowBits & Mask;
427         KnownZero |= ~LowBits & Mask;
428         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
429                           Depth+1);
430         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
431         break;
432       }
433     }
434
435     // Since the result is less than or equal to either operand, any leading
436     // zero bits in either operand must also exist in the result.
437     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
438     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
439                       TD, Depth+1);
440     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
441                       TD, Depth+1);
442
443     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
444                                 KnownZero2.countLeadingOnes());
445     KnownOne.clear();
446     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
447     break;
448   }
449
450   case Instruction::Alloca:
451   case Instruction::Malloc: {
452     AllocationInst *AI = cast<AllocationInst>(V);
453     unsigned Align = AI->getAlignment();
454     if (Align == 0 && TD) {
455       if (isa<AllocaInst>(AI))
456         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
457       else if (isa<MallocInst>(AI)) {
458         // Malloc returns maximally aligned memory.
459         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
460         Align =
461           std::max(Align,
462                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
463         Align =
464           std::max(Align,
465                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
466       }
467     }
468     
469     if (Align > 0)
470       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
471                                               CountTrailingZeros_32(Align));
472     break;
473   }
474   case Instruction::GetElementPtr: {
475     // Analyze all of the subscripts of this getelementptr instruction
476     // to determine if we can prove known low zero bits.
477     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
478     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
479     ComputeMaskedBits(I->getOperand(0), LocalMask,
480                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
481     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
482
483     gep_type_iterator GTI = gep_type_begin(I);
484     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
485       Value *Index = I->getOperand(i);
486       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
487         // Handle struct member offset arithmetic.
488         if (!TD) return;
489         const StructLayout *SL = TD->getStructLayout(STy);
490         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
491         uint64_t Offset = SL->getElementOffset(Idx);
492         TrailZ = std::min(TrailZ,
493                           CountTrailingZeros_64(Offset));
494       } else {
495         // Handle array index arithmetic.
496         const Type *IndexedTy = GTI.getIndexedType();
497         if (!IndexedTy->isSized()) return;
498         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
499         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
500         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
501         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
502         ComputeMaskedBits(Index, LocalMask,
503                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
504         TrailZ = std::min(TrailZ,
505                           unsigned(CountTrailingZeros_64(TypeSize) +
506                                    LocalKnownZero.countTrailingOnes()));
507       }
508     }
509     
510     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
511     break;
512   }
513   case Instruction::PHI: {
514     PHINode *P = cast<PHINode>(I);
515     // Handle the case of a simple two-predecessor recurrence PHI.
516     // There's a lot more that could theoretically be done here, but
517     // this is sufficient to catch some interesting cases.
518     if (P->getNumIncomingValues() == 2) {
519       for (unsigned i = 0; i != 2; ++i) {
520         Value *L = P->getIncomingValue(i);
521         Value *R = P->getIncomingValue(!i);
522         User *LU = dyn_cast<User>(L);
523         if (!LU)
524           continue;
525         unsigned Opcode = getOpcode(LU);
526         // Check for operations that have the property that if
527         // both their operands have low zero bits, the result
528         // will have low zero bits.
529         if (Opcode == Instruction::Add ||
530             Opcode == Instruction::Sub ||
531             Opcode == Instruction::And ||
532             Opcode == Instruction::Or ||
533             Opcode == Instruction::Mul) {
534           Value *LL = LU->getOperand(0);
535           Value *LR = LU->getOperand(1);
536           // Find a recurrence.
537           if (LL == I)
538             L = LR;
539           else if (LR == I)
540             L = LL;
541           else
542             break;
543           // Ok, we have a PHI of the form L op= R. Check for low
544           // zero bits.
545           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
546           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
547           Mask2 = APInt::getLowBitsSet(BitWidth,
548                                        KnownZero2.countTrailingOnes());
549
550           // We need to take the minimum number of known bits
551           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
552           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
553
554           KnownZero = Mask &
555                       APInt::getLowBitsSet(BitWidth,
556                                            std::min(KnownZero2.countTrailingOnes(),
557                                                     KnownZero3.countTrailingOnes()));
558           break;
559         }
560       }
561     }
562
563     // Otherwise take the unions of the known bit sets of the operands,
564     // taking conservative care to avoid excessive recursion.
565     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
566       KnownZero = APInt::getAllOnesValue(BitWidth);
567       KnownOne = APInt::getAllOnesValue(BitWidth);
568       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
569         // Skip direct self references.
570         if (P->getIncomingValue(i) == P) continue;
571
572         KnownZero2 = APInt(BitWidth, 0);
573         KnownOne2 = APInt(BitWidth, 0);
574         // Recurse, but cap the recursion to one level, because we don't
575         // want to waste time spinning around in loops.
576         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
577                           KnownZero2, KnownOne2, TD, MaxDepth-1);
578         KnownZero &= KnownZero2;
579         KnownOne &= KnownOne2;
580         // If all bits have been ruled out, there's no need to check
581         // more operands.
582         if (!KnownZero && !KnownOne)
583           break;
584       }
585     }
586     break;
587   }
588   case Instruction::Call:
589     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
590       switch (II->getIntrinsicID()) {
591       default: break;
592       case Intrinsic::ctpop:
593       case Intrinsic::ctlz:
594       case Intrinsic::cttz: {
595         unsigned LowBits = Log2_32(BitWidth)+1;
596         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
597         break;
598       }
599       }
600     }
601     break;
602   }
603 }
604
605 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
606 /// this predicate to simplify operations downstream.  Mask is known to be zero
607 /// for bits that V cannot have.
608 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
609                              TargetData *TD, unsigned Depth) {
610   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
611   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
612   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
613   return (KnownZero & Mask) == Mask;
614 }
615
616
617
618 /// ComputeNumSignBits - Return the number of times the sign bit of the
619 /// register is replicated into the other bits.  We know that at least 1 bit
620 /// is always equal to the sign bit (itself), but other cases can give us
621 /// information.  For example, immediately after an "ashr X, 2", we know that
622 /// the top 3 bits are all equal to each other, so we return 3.
623 ///
624 /// 'Op' must have a scalar integer type.
625 ///
626 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
627   assert((TD || V->getType()->isIntOrIntVector()) &&
628          "ComputeNumSignBits requires a TargetData object to operate "
629          "on non-integer values!");
630   const Type *Ty = V->getType();
631   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
632                          Ty->getScalarSizeInBits();
633   unsigned Tmp, Tmp2;
634   unsigned FirstAnswer = 1;
635
636   // Note that ConstantInt is handled by the general ComputeMaskedBits case
637   // below.
638
639   if (Depth == 6)
640     return 1;  // Limit search depth.
641   
642   User *U = dyn_cast<User>(V);
643   switch (getOpcode(V)) {
644   default: break;
645   case Instruction::SExt:
646     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
647     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
648     
649   case Instruction::AShr:
650     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
651     // ashr X, C   -> adds C sign bits.
652     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
653       Tmp += C->getZExtValue();
654       if (Tmp > TyBits) Tmp = TyBits;
655     }
656     return Tmp;
657   case Instruction::Shl:
658     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
659       // shl destroys sign bits.
660       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
661       if (C->getZExtValue() >= TyBits ||      // Bad shift.
662           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
663       return Tmp - C->getZExtValue();
664     }
665     break;
666   case Instruction::And:
667   case Instruction::Or:
668   case Instruction::Xor:    // NOT is handled here.
669     // Logical binary ops preserve the number of sign bits at the worst.
670     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
671     if (Tmp != 1) {
672       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
673       FirstAnswer = std::min(Tmp, Tmp2);
674       // We computed what we know about the sign bits as our first
675       // answer. Now proceed to the generic code that uses
676       // ComputeMaskedBits, and pick whichever answer is better.
677     }
678     break;
679
680   case Instruction::Select:
681     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
682     if (Tmp == 1) return 1;  // Early out.
683     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
684     return std::min(Tmp, Tmp2);
685     
686   case Instruction::Add:
687     // Add can have at most one carry bit.  Thus we know that the output
688     // is, at worst, one more bit than the inputs.
689     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
690     if (Tmp == 1) return 1;  // Early out.
691       
692     // Special case decrementing a value (ADD X, -1):
693     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
694       if (CRHS->isAllOnesValue()) {
695         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
696         APInt Mask = APInt::getAllOnesValue(TyBits);
697         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
698                           Depth+1);
699         
700         // If the input is known to be 0 or 1, the output is 0/-1, which is all
701         // sign bits set.
702         if ((KnownZero | APInt(TyBits, 1)) == Mask)
703           return TyBits;
704         
705         // If we are subtracting one from a positive number, there is no carry
706         // out of the result.
707         if (KnownZero.isNegative())
708           return Tmp;
709       }
710       
711     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
712     if (Tmp2 == 1) return 1;
713       return std::min(Tmp, Tmp2)-1;
714     break;
715     
716   case Instruction::Sub:
717     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
718     if (Tmp2 == 1) return 1;
719       
720     // Handle NEG.
721     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
722       if (CLHS->isNullValue()) {
723         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
724         APInt Mask = APInt::getAllOnesValue(TyBits);
725         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
726                           TD, Depth+1);
727         // If the input is known to be 0 or 1, the output is 0/-1, which is all
728         // sign bits set.
729         if ((KnownZero | APInt(TyBits, 1)) == Mask)
730           return TyBits;
731         
732         // If the input is known to be positive (the sign bit is known clear),
733         // the output of the NEG has the same number of sign bits as the input.
734         if (KnownZero.isNegative())
735           return Tmp2;
736         
737         // Otherwise, we treat this like a SUB.
738       }
739     
740     // Sub can have at most one carry bit.  Thus we know that the output
741     // is, at worst, one more bit than the inputs.
742     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
743     if (Tmp == 1) return 1;  // Early out.
744       return std::min(Tmp, Tmp2)-1;
745     break;
746   case Instruction::Trunc:
747     // FIXME: it's tricky to do anything useful for this, but it is an important
748     // case for targets like X86.
749     break;
750   }
751   
752   // Finally, if we can prove that the top bits of the result are 0's or 1's,
753   // use this information.
754   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
755   APInt Mask = APInt::getAllOnesValue(TyBits);
756   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
757   
758   if (KnownZero.isNegative()) {        // sign bit is 0
759     Mask = KnownZero;
760   } else if (KnownOne.isNegative()) {  // sign bit is 1;
761     Mask = KnownOne;
762   } else {
763     // Nothing known.
764     return FirstAnswer;
765   }
766   
767   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
768   // the number of identical bits in the top of the input value.
769   Mask = ~Mask;
770   Mask <<= Mask.getBitWidth()-TyBits;
771   // Return # leading zeros.  We use 'min' here in case Val was zero before
772   // shifting.  We don't want to return '64' as for an i32 "0".
773   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
774 }
775
776 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
777 /// value is never equal to -0.0.
778 ///
779 /// NOTE: this function will need to be revisited when we support non-default
780 /// rounding modes!
781 ///
782 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
783   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
784     return !CFP->getValueAPF().isNegZero();
785   
786   if (Depth == 6)
787     return 1;  // Limit search depth.
788
789   const Instruction *I = dyn_cast<Instruction>(V);
790   if (I == 0) return false;
791   
792   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
793   if (I->getOpcode() == Instruction::FAdd &&
794       isa<ConstantFP>(I->getOperand(1)) && 
795       cast<ConstantFP>(I->getOperand(1))->isNullValue())
796     return true;
797     
798   // sitofp and uitofp turn into +0.0 for zero.
799   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
800     return true;
801   
802   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
803     // sqrt(-0.0) = -0.0, no other negative results are possible.
804     if (II->getIntrinsicID() == Intrinsic::sqrt)
805       return CannotBeNegativeZero(II->getOperand(1), Depth+1);
806   
807   if (const CallInst *CI = dyn_cast<CallInst>(I))
808     if (const Function *F = CI->getCalledFunction()) {
809       if (F->isDeclaration()) {
810         switch (F->getNameLen()) {
811         case 3:  // abs(x) != -0.0
812           if (!strcmp(F->getNameStart(), "abs")) return true;
813           break;
814         case 4:  // abs[lf](x) != -0.0
815           if (!strcmp(F->getNameStart(), "absf")) return true;
816           if (!strcmp(F->getNameStart(), "absl")) return true;
817           break;
818         }
819       }
820     }
821   
822   return false;
823 }
824
825 // This is the recursive version of BuildSubAggregate. It takes a few different
826 // arguments. Idxs is the index within the nested struct From that we are
827 // looking at now (which is of type IndexedType). IdxSkip is the number of
828 // indices from Idxs that should be left out when inserting into the resulting
829 // struct. To is the result struct built so far, new insertvalue instructions
830 // build on that.
831 Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
832                                  SmallVector<unsigned, 10> &Idxs,
833                                  unsigned IdxSkip,
834                                  Instruction *InsertBefore) {
835   const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
836   if (STy) {
837     // Save the original To argument so we can modify it
838     Value *OrigTo = To;
839     // General case, the type indexed by Idxs is a struct
840     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
841       // Process each struct element recursively
842       Idxs.push_back(i);
843       Value *PrevTo = To;
844       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
845                              InsertBefore);
846       Idxs.pop_back();
847       if (!To) {
848         // Couldn't find any inserted value for this index? Cleanup
849         while (PrevTo != OrigTo) {
850           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
851           PrevTo = Del->getAggregateOperand();
852           Del->eraseFromParent();
853         }
854         // Stop processing elements
855         break;
856       }
857     }
858     // If we succesfully found a value for each of our subaggregates 
859     if (To)
860       return To;
861   }
862   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
863   // the struct's elements had a value that was inserted directly. In the latter
864   // case, perhaps we can't determine each of the subelements individually, but
865   // we might be able to find the complete struct somewhere.
866   
867   // Find the value that is at that particular spot
868   Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
869
870   if (!V)
871     return NULL;
872
873   // Insert the value in the new (sub) aggregrate
874   return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
875                                        Idxs.end(), "tmp", InsertBefore);
876 }
877
878 // This helper takes a nested struct and extracts a part of it (which is again a
879 // struct) into a new value. For example, given the struct:
880 // { a, { b, { c, d }, e } }
881 // and the indices "1, 1" this returns
882 // { c, d }.
883 //
884 // It does this by inserting an insertvalue for each element in the resulting
885 // struct, as opposed to just inserting a single struct. This will only work if
886 // each of the elements of the substruct are known (ie, inserted into From by an
887 // insertvalue instruction somewhere).
888 //
889 // All inserted insertvalue instructions are inserted before InsertBefore
890 Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
891                          const unsigned *idx_end, Instruction *InsertBefore) {
892   assert(InsertBefore && "Must have someplace to insert!");
893   const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
894                                                              idx_begin,
895                                                              idx_end);
896   Value *To = UndefValue::get(IndexedType);
897   SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
898   unsigned IdxSkip = Idxs.size();
899
900   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
901 }
902
903 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
904 /// the scalar value indexed is already around as a register, for example if it
905 /// were inserted directly into the aggregrate.
906 ///
907 /// If InsertBefore is not null, this function will duplicate (modified)
908 /// insertvalues when a part of a nested struct is extracted.
909 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
910                          const unsigned *idx_end, Instruction *InsertBefore) {
911   // Nothing to index? Just return V then (this is useful at the end of our
912   // recursion)
913   if (idx_begin == idx_end)
914     return V;
915   // We have indices, so V should have an indexable type
916   assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
917          && "Not looking at a struct or array?");
918   assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
919          && "Invalid indices for type?");
920   const CompositeType *PTy = cast<CompositeType>(V->getType());
921   
922   if (isa<UndefValue>(V))
923     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
924                                                               idx_begin,
925                                                               idx_end));
926   else if (isa<ConstantAggregateZero>(V))
927     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
928                                                                      idx_begin,
929                                                                      idx_end));
930   else if (Constant *C = dyn_cast<Constant>(V)) {
931     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
932       // Recursively process this constant
933       return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, idx_end,
934                                InsertBefore);
935   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
936     // Loop the indices for the insertvalue instruction in parallel with the
937     // requested indices
938     const unsigned *req_idx = idx_begin;
939     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
940          i != e; ++i, ++req_idx) {
941       if (req_idx == idx_end) {
942         if (InsertBefore)
943           // The requested index identifies a part of a nested aggregate. Handle
944           // this specially. For example,
945           // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
946           // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
947           // %C = extractvalue {i32, { i32, i32 } } %B, 1
948           // This can be changed into
949           // %A = insertvalue {i32, i32 } undef, i32 10, 0
950           // %C = insertvalue {i32, i32 } %A, i32 11, 1
951           // which allows the unused 0,0 element from the nested struct to be
952           // removed.
953           return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
954         else
955           // We can't handle this without inserting insertvalues
956           return 0;
957       }
958       
959       // This insert value inserts something else than what we are looking for.
960       // See if the (aggregrate) value inserted into has the value we are
961       // looking for, then.
962       if (*req_idx != *i)
963         return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
964                                  InsertBefore);
965     }
966     // If we end up here, the indices of the insertvalue match with those
967     // requested (though possibly only partially). Now we recursively look at
968     // the inserted value, passing any remaining indices.
969     return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
970                              InsertBefore);
971   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
972     // If we're extracting a value from an aggregrate that was extracted from
973     // something else, we can extract from that something else directly instead.
974     // However, we will need to chain I's indices with the requested indices.
975    
976     // Calculate the number of indices required 
977     unsigned size = I->getNumIndices() + (idx_end - idx_begin);
978     // Allocate some space to put the new indices in
979     SmallVector<unsigned, 5> Idxs;
980     Idxs.reserve(size);
981     // Add indices from the extract value instruction
982     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
983          i != e; ++i)
984       Idxs.push_back(*i);
985     
986     // Add requested indices
987     for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
988       Idxs.push_back(*i);
989
990     assert(Idxs.size() == size 
991            && "Number of indices added not correct?");
992     
993     return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
994                              InsertBefore);
995   }
996   // Otherwise, we don't know (such as, extracting from a function return value
997   // or load instruction)
998   return 0;
999 }
1000
1001 /// GetConstantStringInfo - This function computes the length of a
1002 /// null-terminated C string pointed to by V.  If successful, it returns true
1003 /// and returns the string in Str.  If unsuccessful, it returns false.
1004 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
1005                                  bool StopAtNul) {
1006   // If V is NULL then return false;
1007   if (V == NULL) return false;
1008
1009   // Look through bitcast instructions.
1010   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1011     return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1012   
1013   // If the value is not a GEP instruction nor a constant expression with a
1014   // GEP instruction, then return false because ConstantArray can't occur
1015   // any other way
1016   User *GEP = 0;
1017   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1018     GEP = GEPI;
1019   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1020     if (CE->getOpcode() == Instruction::BitCast)
1021       return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1022     if (CE->getOpcode() != Instruction::GetElementPtr)
1023       return false;
1024     GEP = CE;
1025   }
1026   
1027   if (GEP) {
1028     // Make sure the GEP has exactly three arguments.
1029     if (GEP->getNumOperands() != 3)
1030       return false;
1031     
1032     // Make sure the index-ee is a pointer to array of i8.
1033     const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1034     const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1035     if (AT == 0 || AT->getElementType() != Type::Int8Ty)
1036       return false;
1037     
1038     // Check to make sure that the first operand of the GEP is an integer and
1039     // has value 0 so that we are sure we're indexing into the initializer.
1040     ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1041     if (FirstIdx == 0 || !FirstIdx->isZero())
1042       return false;
1043     
1044     // If the second index isn't a ConstantInt, then this is a variable index
1045     // into the array.  If this occurs, we can't say anything meaningful about
1046     // the string.
1047     uint64_t StartIdx = 0;
1048     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1049       StartIdx = CI->getZExtValue();
1050     else
1051       return false;
1052     return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1053                                  StopAtNul);
1054   }
1055   
1056   // The GEP instruction, constant or instruction, must reference a global
1057   // variable that is a constant and is initialized. The referenced constant
1058   // initializer is the array that we'll use for optimization.
1059   GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1060   if (!GV || !GV->isConstant() || !GV->hasInitializer())
1061     return false;
1062   Constant *GlobalInit = GV->getInitializer();
1063   
1064   // Handle the ConstantAggregateZero case
1065   if (isa<ConstantAggregateZero>(GlobalInit)) {
1066     // This is a degenerate case. The initializer is constant zero so the
1067     // length of the string must be zero.
1068     Str.clear();
1069     return true;
1070   }
1071   
1072   // Must be a Constant Array
1073   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1074   if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1075     return false;
1076   
1077   // Get the number of elements in the array
1078   uint64_t NumElts = Array->getType()->getNumElements();
1079   
1080   if (Offset > NumElts)
1081     return false;
1082   
1083   // Traverse the constant array from 'Offset' which is the place the GEP refers
1084   // to in the array.
1085   Str.reserve(NumElts-Offset);
1086   for (unsigned i = Offset; i != NumElts; ++i) {
1087     Constant *Elt = Array->getOperand(i);
1088     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1089     if (!CI) // This array isn't suitable, non-int initializer.
1090       return false;
1091     if (StopAtNul && CI->isZero())
1092       return true; // we found end of string, success!
1093     Str += (char)CI->getZExtValue();
1094   }
1095   
1096   // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1097   return true;
1098 }