Global variable does not need linkage name.
[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/GlobalAlias.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Operator.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include <cstring>
28 using namespace llvm;
29
30 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
31 /// known to be either zero or one and return them in the KnownZero/KnownOne
32 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
33 /// processing.
34 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
35 /// we cannot optimize based on the assumption that it is zero without changing
36 /// it to be an explicit zero.  If we don't change it to zero, other code could
37 /// optimized based on the contradictory assumption that it is non-zero.
38 /// Because instcombine aggressively folds operations with undef args anyway,
39 /// this won't lose us code quality.
40 ///
41 /// This function is defined on values with integer type, values with pointer
42 /// type (but only if TD is non-null), and vectors of integers.  In the case
43 /// where V is a vector, the mask, known zero, and known one values are the
44 /// same width as the vector element, and the bit is set only if it is true
45 /// for all of the elements in the vector.
46 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
47                              APInt &KnownZero, APInt &KnownOne,
48                              const TargetData *TD, unsigned Depth) {
49   const unsigned MaxDepth = 6;
50   assert(V && "No Value?");
51   assert(Depth <= MaxDepth && "Limit Search Depth");
52   unsigned BitWidth = Mask.getBitWidth();
53   assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
54          && "Not integer or pointer type!");
55   assert((!TD ||
56           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
57          (!V->getType()->isIntOrIntVectorTy() ||
58           V->getType()->getScalarSizeInBits() == BitWidth) &&
59          KnownZero.getBitWidth() == BitWidth && 
60          KnownOne.getBitWidth() == BitWidth &&
61          "V, Mask, KnownOne and KnownZero should have same BitWidth");
62
63   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
64     // We know all of the bits for a constant!
65     KnownOne = CI->getValue() & Mask;
66     KnownZero = ~KnownOne & Mask;
67     return;
68   }
69   // Null and aggregate-zero are all-zeros.
70   if (isa<ConstantPointerNull>(V) ||
71       isa<ConstantAggregateZero>(V)) {
72     KnownOne.clearAllBits();
73     KnownZero = Mask;
74     return;
75   }
76   // Handle a constant vector by taking the intersection of the known bits of
77   // each element.
78   if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
79     KnownZero.setAllBits(); KnownOne.setAllBits();
80     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
81       APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
82       ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
83                         TD, Depth);
84       KnownZero &= KnownZero2;
85       KnownOne &= KnownOne2;
86     }
87     return;
88   }
89   // The address of an aligned GlobalValue has trailing zeros.
90   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
91     unsigned Align = GV->getAlignment();
92     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
93       const Type *ObjectType = GV->getType()->getElementType();
94       // If the object is defined in the current Module, we'll be giving
95       // it the preferred alignment. Otherwise, we have to assume that it
96       // may only have the minimum ABI alignment.
97       if (!GV->isDeclaration() && !GV->mayBeOverridden())
98         Align = TD->getPrefTypeAlignment(ObjectType);
99       else
100         Align = TD->getABITypeAlignment(ObjectType);
101     }
102     if (Align > 0)
103       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
104                                               CountTrailingZeros_32(Align));
105     else
106       KnownZero.clearAllBits();
107     KnownOne.clearAllBits();
108     return;
109   }
110   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
111   // the bits of its aliasee.
112   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
113     if (GA->mayBeOverridden()) {
114       KnownZero.clearAllBits(); KnownOne.clearAllBits();
115     } else {
116       ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
117                         TD, Depth+1);
118     }
119     return;
120   }
121
122   KnownZero.clearAllBits(); KnownOne.clearAllBits();   // Start out not knowing anything.
123
124   if (Depth == MaxDepth || Mask == 0)
125     return;  // Limit search depth.
126
127   Operator *I = dyn_cast<Operator>(V);
128   if (!I) return;
129
130   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
131   switch (I->getOpcode()) {
132   default: break;
133   case Instruction::And: {
134     // If either the LHS or the RHS are Zero, the result is zero.
135     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
136     APInt Mask2(Mask & ~KnownZero);
137     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
138                       Depth+1);
139     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
140     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
141     
142     // Output known-1 bits are only known if set in both the LHS & RHS.
143     KnownOne &= KnownOne2;
144     // Output known-0 are known to be clear if zero in either the LHS | RHS.
145     KnownZero |= KnownZero2;
146     return;
147   }
148   case Instruction::Or: {
149     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
150     APInt Mask2(Mask & ~KnownOne);
151     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
152                       Depth+1);
153     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
154     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
155     
156     // Output known-0 bits are only known if clear in both the LHS & RHS.
157     KnownZero &= KnownZero2;
158     // Output known-1 are known to be set if set in either the LHS | RHS.
159     KnownOne |= KnownOne2;
160     return;
161   }
162   case Instruction::Xor: {
163     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
164     ComputeMaskedBits(I->getOperand(0), Mask, 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 known if clear or set in both the LHS & RHS.
170     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
171     // Output known-1 are known to be set if set in only one of the LHS, RHS.
172     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
173     KnownZero = KnownZeroOut;
174     return;
175   }
176   case Instruction::Mul: {
177     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
178     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
179     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
180                       Depth+1);
181     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
182     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
183     
184     // If low bits are zero in either operand, output low known-0 bits.
185     // Also compute a conserative estimate for high known-0 bits.
186     // More trickiness is possible, but this is sufficient for the
187     // interesting case of alignment computation.
188     KnownOne.clearAllBits();
189     unsigned TrailZ = KnownZero.countTrailingOnes() +
190                       KnownZero2.countTrailingOnes();
191     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
192                                KnownZero2.countLeadingOnes(),
193                                BitWidth) - BitWidth;
194
195     TrailZ = std::min(TrailZ, BitWidth);
196     LeadZ = std::min(LeadZ, BitWidth);
197     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
198                 APInt::getHighBitsSet(BitWidth, LeadZ);
199     KnownZero &= Mask;
200     return;
201   }
202   case Instruction::UDiv: {
203     // For the purposes of computing leading zeros we can conservatively
204     // treat a udiv as a logical right shift by the power of 2 known to
205     // be less than the denominator.
206     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
207     ComputeMaskedBits(I->getOperand(0),
208                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
209     unsigned LeadZ = KnownZero2.countLeadingOnes();
210
211     KnownOne2.clearAllBits();
212     KnownZero2.clearAllBits();
213     ComputeMaskedBits(I->getOperand(1),
214                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
215     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
216     if (RHSUnknownLeadingOnes != BitWidth)
217       LeadZ = std::min(BitWidth,
218                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
219
220     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
221     return;
222   }
223   case Instruction::Select:
224     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
225     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
226                       Depth+1);
227     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
228     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
229
230     // Only known if known in both the LHS and RHS.
231     KnownOne &= KnownOne2;
232     KnownZero &= KnownZero2;
233     return;
234   case Instruction::FPTrunc:
235   case Instruction::FPExt:
236   case Instruction::FPToUI:
237   case Instruction::FPToSI:
238   case Instruction::SIToFP:
239   case Instruction::UIToFP:
240     return; // Can't work with floating point.
241   case Instruction::PtrToInt:
242   case Instruction::IntToPtr:
243     // We can't handle these if we don't know the pointer size.
244     if (!TD) return;
245     // FALL THROUGH and handle them the same as zext/trunc.
246   case Instruction::ZExt:
247   case Instruction::Trunc: {
248     const Type *SrcTy = I->getOperand(0)->getType();
249     
250     unsigned SrcBitWidth;
251     // Note that we handle pointer operands here because of inttoptr/ptrtoint
252     // which fall through here.
253     if (SrcTy->isPointerTy())
254       SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
255     else
256       SrcBitWidth = SrcTy->getScalarSizeInBits();
257     
258     APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
259     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
260     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
261     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
262                       Depth+1);
263     KnownZero = KnownZero.zextOrTrunc(BitWidth);
264     KnownOne = KnownOne.zextOrTrunc(BitWidth);
265     // Any top bits are known to be zero.
266     if (BitWidth > SrcBitWidth)
267       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
268     return;
269   }
270   case Instruction::BitCast: {
271     const Type *SrcTy = I->getOperand(0)->getType();
272     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
273         // TODO: For now, not handling conversions like:
274         // (bitcast i64 %x to <2 x i32>)
275         !I->getType()->isVectorTy()) {
276       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
277                         Depth+1);
278       return;
279     }
280     break;
281   }
282   case Instruction::SExt: {
283     // Compute the bits in the result that are not present in the input.
284     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
285       
286     APInt MaskIn = Mask.trunc(SrcBitWidth);
287     KnownZero = KnownZero.trunc(SrcBitWidth);
288     KnownOne = KnownOne.trunc(SrcBitWidth);
289     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
290                       Depth+1);
291     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
292     KnownZero = KnownZero.zext(BitWidth);
293     KnownOne = KnownOne.zext(BitWidth);
294
295     // If the sign bit of the input is known set or clear, then we know the
296     // top bits of the result.
297     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
298       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
299     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
300       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
301     return;
302   }
303   case Instruction::Shl:
304     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
305     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
306       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
307       APInt Mask2(Mask.lshr(ShiftAmt));
308       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
309                         Depth+1);
310       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
311       KnownZero <<= ShiftAmt;
312       KnownOne  <<= ShiftAmt;
313       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
314       return;
315     }
316     break;
317   case Instruction::LShr:
318     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
319     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
320       // Compute the new bits that are at the top now.
321       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
322       
323       // Unsigned shift right.
324       APInt Mask2(Mask.shl(ShiftAmt));
325       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
326                         Depth+1);
327       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
328       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
329       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
330       // high bits known zero.
331       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
332       return;
333     }
334     break;
335   case Instruction::AShr:
336     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
337     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
338       // Compute the new bits that are at the top now.
339       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
340       
341       // Signed shift right.
342       APInt Mask2(Mask.shl(ShiftAmt));
343       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
344                         Depth+1);
345       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
346       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
347       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
348         
349       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
350       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
351         KnownZero |= HighBits;
352       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
353         KnownOne |= HighBits;
354       return;
355     }
356     break;
357   case Instruction::Sub: {
358     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
359       // We know that the top bits of C-X are clear if X contains less bits
360       // than C (i.e. no wrap-around can happen).  For example, 20-X is
361       // positive if we can prove that X is >= 0 and < 16.
362       if (!CLHS->getValue().isNegative()) {
363         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
364         // NLZ can't be BitWidth with no sign bit
365         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
366         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
367                           TD, Depth+1);
368     
369         // If all of the MaskV bits are known to be zero, then we know the
370         // output top bits are zero, because we now know that the output is
371         // from [0-C].
372         if ((KnownZero2 & MaskV) == MaskV) {
373           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
374           // Top bits known zero.
375           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
376         }
377       }        
378     }
379   }
380   // fall through
381   case Instruction::Add: {
382     // If one of the operands has trailing zeros, then the bits that the
383     // other operand has in those bit positions will be preserved in the
384     // result. For an add, this works with either operand. For a subtract,
385     // this only works if the known zeros are in the right operand.
386     APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
387     APInt Mask2 = APInt::getLowBitsSet(BitWidth,
388                                        BitWidth - Mask.countLeadingZeros());
389     ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
390                       Depth+1);
391     assert((LHSKnownZero & LHSKnownOne) == 0 &&
392            "Bits known to be one AND zero?");
393     unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
394
395     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
396                       Depth+1);
397     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
398     unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
399
400     // Determine which operand has more trailing zeros, and use that
401     // many bits from the other operand.
402     if (LHSKnownZeroOut > RHSKnownZeroOut) {
403       if (I->getOpcode() == Instruction::Add) {
404         APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
405         KnownZero |= KnownZero2 & Mask;
406         KnownOne  |= KnownOne2 & Mask;
407       } else {
408         // If the known zeros are in the left operand for a subtract,
409         // fall back to the minimum known zeros in both operands.
410         KnownZero |= APInt::getLowBitsSet(BitWidth,
411                                           std::min(LHSKnownZeroOut,
412                                                    RHSKnownZeroOut));
413       }
414     } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
415       APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
416       KnownZero |= LHSKnownZero & Mask;
417       KnownOne  |= LHSKnownOne & Mask;
418     }
419     return;
420   }
421   case Instruction::SRem:
422     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
423       APInt RA = Rem->getValue().abs();
424       if (RA.isPowerOf2()) {
425         APInt LowBits = RA - 1;
426         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
427         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
428                           Depth+1);
429
430         // The low bits of the first operand are unchanged by the srem.
431         KnownZero = KnownZero2 & LowBits;
432         KnownOne = KnownOne2 & LowBits;
433
434         // If the first operand is non-negative or has all low bits zero, then
435         // the upper bits are all zero.
436         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
437           KnownZero |= ~LowBits;
438
439         // If the first operand is negative and not all low bits are zero, then
440         // the upper bits are all one.
441         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
442           KnownOne |= ~LowBits;
443
444         KnownZero &= Mask;
445         KnownOne &= Mask;
446
447         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
448       }
449     }
450     break;
451   case Instruction::URem: {
452     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
453       APInt RA = Rem->getValue();
454       if (RA.isPowerOf2()) {
455         APInt LowBits = (RA - 1);
456         APInt Mask2 = LowBits & Mask;
457         KnownZero |= ~LowBits & Mask;
458         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
459                           Depth+1);
460         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
461         break;
462       }
463     }
464
465     // Since the result is less than or equal to either operand, any leading
466     // zero bits in either operand must also exist in the result.
467     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
468     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
469                       TD, Depth+1);
470     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
471                       TD, Depth+1);
472
473     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
474                                 KnownZero2.countLeadingOnes());
475     KnownOne.clearAllBits();
476     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
477     break;
478   }
479
480   case Instruction::Alloca: {
481     AllocaInst *AI = cast<AllocaInst>(V);
482     unsigned Align = AI->getAlignment();
483     if (Align == 0 && TD)
484       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
485     
486     if (Align > 0)
487       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
488                                               CountTrailingZeros_32(Align));
489     break;
490   }
491   case Instruction::GetElementPtr: {
492     // Analyze all of the subscripts of this getelementptr instruction
493     // to determine if we can prove known low zero bits.
494     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
495     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
496     ComputeMaskedBits(I->getOperand(0), LocalMask,
497                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
498     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
499
500     gep_type_iterator GTI = gep_type_begin(I);
501     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
502       Value *Index = I->getOperand(i);
503       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
504         // Handle struct member offset arithmetic.
505         if (!TD) return;
506         const StructLayout *SL = TD->getStructLayout(STy);
507         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
508         uint64_t Offset = SL->getElementOffset(Idx);
509         TrailZ = std::min(TrailZ,
510                           CountTrailingZeros_64(Offset));
511       } else {
512         // Handle array index arithmetic.
513         const Type *IndexedTy = GTI.getIndexedType();
514         if (!IndexedTy->isSized()) return;
515         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
516         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
517         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
518         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
519         ComputeMaskedBits(Index, LocalMask,
520                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
521         TrailZ = std::min(TrailZ,
522                           unsigned(CountTrailingZeros_64(TypeSize) +
523                                    LocalKnownZero.countTrailingOnes()));
524       }
525     }
526     
527     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
528     break;
529   }
530   case Instruction::PHI: {
531     PHINode *P = cast<PHINode>(I);
532     // Handle the case of a simple two-predecessor recurrence PHI.
533     // There's a lot more that could theoretically be done here, but
534     // this is sufficient to catch some interesting cases.
535     if (P->getNumIncomingValues() == 2) {
536       for (unsigned i = 0; i != 2; ++i) {
537         Value *L = P->getIncomingValue(i);
538         Value *R = P->getIncomingValue(!i);
539         Operator *LU = dyn_cast<Operator>(L);
540         if (!LU)
541           continue;
542         unsigned Opcode = LU->getOpcode();
543         // Check for operations that have the property that if
544         // both their operands have low zero bits, the result
545         // will have low zero bits.
546         if (Opcode == Instruction::Add ||
547             Opcode == Instruction::Sub ||
548             Opcode == Instruction::And ||
549             Opcode == Instruction::Or ||
550             Opcode == Instruction::Mul) {
551           Value *LL = LU->getOperand(0);
552           Value *LR = LU->getOperand(1);
553           // Find a recurrence.
554           if (LL == I)
555             L = LR;
556           else if (LR == I)
557             L = LL;
558           else
559             break;
560           // Ok, we have a PHI of the form L op= R. Check for low
561           // zero bits.
562           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
563           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
564           Mask2 = APInt::getLowBitsSet(BitWidth,
565                                        KnownZero2.countTrailingOnes());
566
567           // We need to take the minimum number of known bits
568           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
569           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
570
571           KnownZero = Mask &
572                       APInt::getLowBitsSet(BitWidth,
573                                            std::min(KnownZero2.countTrailingOnes(),
574                                                     KnownZero3.countTrailingOnes()));
575           break;
576         }
577       }
578     }
579
580     // Otherwise take the unions of the known bit sets of the operands,
581     // taking conservative care to avoid excessive recursion.
582     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
583       KnownZero = APInt::getAllOnesValue(BitWidth);
584       KnownOne = APInt::getAllOnesValue(BitWidth);
585       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
586         // Skip direct self references.
587         if (P->getIncomingValue(i) == P) continue;
588
589         KnownZero2 = APInt(BitWidth, 0);
590         KnownOne2 = APInt(BitWidth, 0);
591         // Recurse, but cap the recursion to one level, because we don't
592         // want to waste time spinning around in loops.
593         ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
594                           KnownZero2, KnownOne2, TD, MaxDepth-1);
595         KnownZero &= KnownZero2;
596         KnownOne &= KnownOne2;
597         // If all bits have been ruled out, there's no need to check
598         // more operands.
599         if (!KnownZero && !KnownOne)
600           break;
601       }
602     }
603     break;
604   }
605   case Instruction::Call:
606     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
607       switch (II->getIntrinsicID()) {
608       default: break;
609       case Intrinsic::ctpop:
610       case Intrinsic::ctlz:
611       case Intrinsic::cttz: {
612         unsigned LowBits = Log2_32(BitWidth)+1;
613         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
614         break;
615       }
616       }
617     }
618     break;
619   }
620 }
621
622 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
623 /// this predicate to simplify operations downstream.  Mask is known to be zero
624 /// for bits that V cannot have.
625 ///
626 /// This function is defined on values with integer type, values with pointer
627 /// type (but only if TD is non-null), and vectors of integers.  In the case
628 /// where V is a vector, the mask, known zero, and known one values are the
629 /// same width as the vector element, and the bit is set only if it is true
630 /// for all of the elements in the vector.
631 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
632                              const TargetData *TD, unsigned Depth) {
633   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
634   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
635   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
636   return (KnownZero & Mask) == Mask;
637 }
638
639
640
641 /// ComputeNumSignBits - Return the number of times the sign bit of the
642 /// register is replicated into the other bits.  We know that at least 1 bit
643 /// is always equal to the sign bit (itself), but other cases can give us
644 /// information.  For example, immediately after an "ashr X, 2", we know that
645 /// the top 3 bits are all equal to each other, so we return 3.
646 ///
647 /// 'Op' must have a scalar integer type.
648 ///
649 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
650                                   unsigned Depth) {
651   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
652          "ComputeNumSignBits requires a TargetData object to operate "
653          "on non-integer values!");
654   const Type *Ty = V->getType();
655   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
656                          Ty->getScalarSizeInBits();
657   unsigned Tmp, Tmp2;
658   unsigned FirstAnswer = 1;
659
660   // Note that ConstantInt is handled by the general ComputeMaskedBits case
661   // below.
662
663   if (Depth == 6)
664     return 1;  // Limit search depth.
665   
666   Operator *U = dyn_cast<Operator>(V);
667   switch (Operator::getOpcode(V)) {
668   default: break;
669   case Instruction::SExt:
670     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
671     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
672     
673   case Instruction::AShr:
674     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
675     // ashr X, C   -> adds C sign bits.
676     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
677       Tmp += C->getZExtValue();
678       if (Tmp > TyBits) Tmp = TyBits;
679     }
680     return Tmp;
681   case Instruction::Shl:
682     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
683       // shl destroys sign bits.
684       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
685       if (C->getZExtValue() >= TyBits ||      // Bad shift.
686           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
687       return Tmp - C->getZExtValue();
688     }
689     break;
690   case Instruction::And:
691   case Instruction::Or:
692   case Instruction::Xor:    // NOT is handled here.
693     // Logical binary ops preserve the number of sign bits at the worst.
694     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
695     if (Tmp != 1) {
696       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
697       FirstAnswer = std::min(Tmp, Tmp2);
698       // We computed what we know about the sign bits as our first
699       // answer. Now proceed to the generic code that uses
700       // ComputeMaskedBits, and pick whichever answer is better.
701     }
702     break;
703
704   case Instruction::Select:
705     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
706     if (Tmp == 1) return 1;  // Early out.
707     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
708     return std::min(Tmp, Tmp2);
709     
710   case Instruction::Add:
711     // Add can have at most one carry bit.  Thus we know that the output
712     // is, at worst, one more bit than the inputs.
713     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
714     if (Tmp == 1) return 1;  // Early out.
715       
716     // Special case decrementing a value (ADD X, -1):
717     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
718       if (CRHS->isAllOnesValue()) {
719         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
720         APInt Mask = APInt::getAllOnesValue(TyBits);
721         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
722                           Depth+1);
723         
724         // If the input is known to be 0 or 1, the output is 0/-1, which is all
725         // sign bits set.
726         if ((KnownZero | APInt(TyBits, 1)) == Mask)
727           return TyBits;
728         
729         // If we are subtracting one from a positive number, there is no carry
730         // out of the result.
731         if (KnownZero.isNegative())
732           return Tmp;
733       }
734       
735     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
736     if (Tmp2 == 1) return 1;
737     return std::min(Tmp, Tmp2)-1;
738     
739   case Instruction::Sub:
740     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
741     if (Tmp2 == 1) return 1;
742       
743     // Handle NEG.
744     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
745       if (CLHS->isNullValue()) {
746         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
747         APInt Mask = APInt::getAllOnesValue(TyBits);
748         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
749                           TD, Depth+1);
750         // If the input is known to be 0 or 1, the output is 0/-1, which is all
751         // sign bits set.
752         if ((KnownZero | APInt(TyBits, 1)) == Mask)
753           return TyBits;
754         
755         // If the input is known to be positive (the sign bit is known clear),
756         // the output of the NEG has the same number of sign bits as the input.
757         if (KnownZero.isNegative())
758           return Tmp2;
759         
760         // Otherwise, we treat this like a SUB.
761       }
762     
763     // Sub can have at most one carry bit.  Thus we know that the output
764     // is, at worst, one more bit than the inputs.
765     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
766     if (Tmp == 1) return 1;  // Early out.
767     return std::min(Tmp, Tmp2)-1;
768       
769   case Instruction::PHI: {
770     PHINode *PN = cast<PHINode>(U);
771     // Don't analyze large in-degree PHIs.
772     if (PN->getNumIncomingValues() > 4) break;
773     
774     // Take the minimum of all incoming values.  This can't infinitely loop
775     // because of our depth threshold.
776     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
777     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
778       if (Tmp == 1) return Tmp;
779       Tmp = std::min(Tmp,
780                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
781     }
782     return Tmp;
783   }
784
785   case Instruction::Trunc:
786     // FIXME: it's tricky to do anything useful for this, but it is an important
787     // case for targets like X86.
788     break;
789   }
790   
791   // Finally, if we can prove that the top bits of the result are 0's or 1's,
792   // use this information.
793   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
794   APInt Mask = APInt::getAllOnesValue(TyBits);
795   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
796   
797   if (KnownZero.isNegative()) {        // sign bit is 0
798     Mask = KnownZero;
799   } else if (KnownOne.isNegative()) {  // sign bit is 1;
800     Mask = KnownOne;
801   } else {
802     // Nothing known.
803     return FirstAnswer;
804   }
805   
806   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
807   // the number of identical bits in the top of the input value.
808   Mask = ~Mask;
809   Mask <<= Mask.getBitWidth()-TyBits;
810   // Return # leading zeros.  We use 'min' here in case Val was zero before
811   // shifting.  We don't want to return '64' as for an i32 "0".
812   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
813 }
814
815 /// ComputeMultiple - This function computes the integer multiple of Base that
816 /// equals V.  If successful, it returns true and returns the multiple in
817 /// Multiple.  If unsuccessful, it returns false. It looks
818 /// through SExt instructions only if LookThroughSExt is true.
819 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
820                            bool LookThroughSExt, unsigned Depth) {
821   const unsigned MaxDepth = 6;
822
823   assert(V && "No Value?");
824   assert(Depth <= MaxDepth && "Limit Search Depth");
825   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
826
827   const Type *T = V->getType();
828
829   ConstantInt *CI = dyn_cast<ConstantInt>(V);
830
831   if (Base == 0)
832     return false;
833     
834   if (Base == 1) {
835     Multiple = V;
836     return true;
837   }
838
839   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
840   Constant *BaseVal = ConstantInt::get(T, Base);
841   if (CO && CO == BaseVal) {
842     // Multiple is 1.
843     Multiple = ConstantInt::get(T, 1);
844     return true;
845   }
846
847   if (CI && CI->getZExtValue() % Base == 0) {
848     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
849     return true;  
850   }
851   
852   if (Depth == MaxDepth) return false;  // Limit search depth.
853         
854   Operator *I = dyn_cast<Operator>(V);
855   if (!I) return false;
856
857   switch (I->getOpcode()) {
858   default: break;
859   case Instruction::SExt:
860     if (!LookThroughSExt) return false;
861     // otherwise fall through to ZExt
862   case Instruction::ZExt:
863     return ComputeMultiple(I->getOperand(0), Base, Multiple,
864                            LookThroughSExt, Depth+1);
865   case Instruction::Shl:
866   case Instruction::Mul: {
867     Value *Op0 = I->getOperand(0);
868     Value *Op1 = I->getOperand(1);
869
870     if (I->getOpcode() == Instruction::Shl) {
871       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
872       if (!Op1CI) return false;
873       // Turn Op0 << Op1 into Op0 * 2^Op1
874       APInt Op1Int = Op1CI->getValue();
875       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
876       APInt API(Op1Int.getBitWidth(), 0);
877       API.setBit(BitToSet);
878       Op1 = ConstantInt::get(V->getContext(), API);
879     }
880
881     Value *Mul0 = NULL;
882     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
883       if (Constant *Op1C = dyn_cast<Constant>(Op1))
884         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
885           if (Op1C->getType()->getPrimitiveSizeInBits() < 
886               MulC->getType()->getPrimitiveSizeInBits())
887             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
888           if (Op1C->getType()->getPrimitiveSizeInBits() > 
889               MulC->getType()->getPrimitiveSizeInBits())
890             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
891           
892           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
893           Multiple = ConstantExpr::getMul(MulC, Op1C);
894           return true;
895         }
896
897       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
898         if (Mul0CI->getValue() == 1) {
899           // V == Base * Op1, so return Op1
900           Multiple = Op1;
901           return true;
902         }
903     }
904
905     Value *Mul1 = NULL;
906     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
907       if (Constant *Op0C = dyn_cast<Constant>(Op0))
908         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
909           if (Op0C->getType()->getPrimitiveSizeInBits() < 
910               MulC->getType()->getPrimitiveSizeInBits())
911             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
912           if (Op0C->getType()->getPrimitiveSizeInBits() > 
913               MulC->getType()->getPrimitiveSizeInBits())
914             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
915           
916           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
917           Multiple = ConstantExpr::getMul(MulC, Op0C);
918           return true;
919         }
920
921       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
922         if (Mul1CI->getValue() == 1) {
923           // V == Base * Op0, so return Op0
924           Multiple = Op0;
925           return true;
926         }
927     }
928   }
929   }
930
931   // We could not determine if V is a multiple of Base.
932   return false;
933 }
934
935 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
936 /// value is never equal to -0.0.
937 ///
938 /// NOTE: this function will need to be revisited when we support non-default
939 /// rounding modes!
940 ///
941 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
942   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
943     return !CFP->getValueAPF().isNegZero();
944   
945   if (Depth == 6)
946     return 1;  // Limit search depth.
947
948   const Operator *I = dyn_cast<Operator>(V);
949   if (I == 0) return false;
950   
951   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
952   if (I->getOpcode() == Instruction::FAdd &&
953       isa<ConstantFP>(I->getOperand(1)) && 
954       cast<ConstantFP>(I->getOperand(1))->isNullValue())
955     return true;
956     
957   // sitofp and uitofp turn into +0.0 for zero.
958   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
959     return true;
960   
961   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
962     // sqrt(-0.0) = -0.0, no other negative results are possible.
963     if (II->getIntrinsicID() == Intrinsic::sqrt)
964       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
965   
966   if (const CallInst *CI = dyn_cast<CallInst>(I))
967     if (const Function *F = CI->getCalledFunction()) {
968       if (F->isDeclaration()) {
969         // abs(x) != -0.0
970         if (F->getName() == "abs") return true;
971         // fabs[lf](x) != -0.0
972         if (F->getName() == "fabs") return true;
973         if (F->getName() == "fabsf") return true;
974         if (F->getName() == "fabsl") return true;
975         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
976             F->getName() == "sqrtl")
977           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
978       }
979     }
980   
981   return false;
982 }
983
984 // This is the recursive version of BuildSubAggregate. It takes a few different
985 // arguments. Idxs is the index within the nested struct From that we are
986 // looking at now (which is of type IndexedType). IdxSkip is the number of
987 // indices from Idxs that should be left out when inserting into the resulting
988 // struct. To is the result struct built so far, new insertvalue instructions
989 // build on that.
990 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
991                                 SmallVector<unsigned, 10> &Idxs,
992                                 unsigned IdxSkip,
993                                 Instruction *InsertBefore) {
994   const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
995   if (STy) {
996     // Save the original To argument so we can modify it
997     Value *OrigTo = To;
998     // General case, the type indexed by Idxs is a struct
999     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1000       // Process each struct element recursively
1001       Idxs.push_back(i);
1002       Value *PrevTo = To;
1003       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1004                              InsertBefore);
1005       Idxs.pop_back();
1006       if (!To) {
1007         // Couldn't find any inserted value for this index? Cleanup
1008         while (PrevTo != OrigTo) {
1009           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1010           PrevTo = Del->getAggregateOperand();
1011           Del->eraseFromParent();
1012         }
1013         // Stop processing elements
1014         break;
1015       }
1016     }
1017     // If we succesfully found a value for each of our subaggregates 
1018     if (To)
1019       return To;
1020   }
1021   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1022   // the struct's elements had a value that was inserted directly. In the latter
1023   // case, perhaps we can't determine each of the subelements individually, but
1024   // we might be able to find the complete struct somewhere.
1025   
1026   // Find the value that is at that particular spot
1027   Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
1028
1029   if (!V)
1030     return NULL;
1031
1032   // Insert the value in the new (sub) aggregrate
1033   return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1034                                        Idxs.end(), "tmp", InsertBefore);
1035 }
1036
1037 // This helper takes a nested struct and extracts a part of it (which is again a
1038 // struct) into a new value. For example, given the struct:
1039 // { a, { b, { c, d }, e } }
1040 // and the indices "1, 1" this returns
1041 // { c, d }.
1042 //
1043 // It does this by inserting an insertvalue for each element in the resulting
1044 // struct, as opposed to just inserting a single struct. This will only work if
1045 // each of the elements of the substruct are known (ie, inserted into From by an
1046 // insertvalue instruction somewhere).
1047 //
1048 // All inserted insertvalue instructions are inserted before InsertBefore
1049 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
1050                                 const unsigned *idx_end,
1051                                 Instruction *InsertBefore) {
1052   assert(InsertBefore && "Must have someplace to insert!");
1053   const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1054                                                              idx_begin,
1055                                                              idx_end);
1056   Value *To = UndefValue::get(IndexedType);
1057   SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1058   unsigned IdxSkip = Idxs.size();
1059
1060   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1061 }
1062
1063 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1064 /// the scalar value indexed is already around as a register, for example if it
1065 /// were inserted directly into the aggregrate.
1066 ///
1067 /// If InsertBefore is not null, this function will duplicate (modified)
1068 /// insertvalues when a part of a nested struct is extracted.
1069 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
1070                          const unsigned *idx_end, Instruction *InsertBefore) {
1071   // Nothing to index? Just return V then (this is useful at the end of our
1072   // recursion)
1073   if (idx_begin == idx_end)
1074     return V;
1075   // We have indices, so V should have an indexable type
1076   assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
1077          && "Not looking at a struct or array?");
1078   assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1079          && "Invalid indices for type?");
1080   const CompositeType *PTy = cast<CompositeType>(V->getType());
1081
1082   if (isa<UndefValue>(V))
1083     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
1084                                                               idx_begin,
1085                                                               idx_end));
1086   else if (isa<ConstantAggregateZero>(V))
1087     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
1088                                                                   idx_begin,
1089                                                                   idx_end));
1090   else if (Constant *C = dyn_cast<Constant>(V)) {
1091     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1092       // Recursively process this constant
1093       return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
1094                                idx_end, InsertBefore);
1095   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1096     // Loop the indices for the insertvalue instruction in parallel with the
1097     // requested indices
1098     const unsigned *req_idx = idx_begin;
1099     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1100          i != e; ++i, ++req_idx) {
1101       if (req_idx == idx_end) {
1102         if (InsertBefore)
1103           // The requested index identifies a part of a nested aggregate. Handle
1104           // this specially. For example,
1105           // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1106           // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1107           // %C = extractvalue {i32, { i32, i32 } } %B, 1
1108           // This can be changed into
1109           // %A = insertvalue {i32, i32 } undef, i32 10, 0
1110           // %C = insertvalue {i32, i32 } %A, i32 11, 1
1111           // which allows the unused 0,0 element from the nested struct to be
1112           // removed.
1113           return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
1114         else
1115           // We can't handle this without inserting insertvalues
1116           return 0;
1117       }
1118       
1119       // This insert value inserts something else than what we are looking for.
1120       // See if the (aggregrate) value inserted into has the value we are
1121       // looking for, then.
1122       if (*req_idx != *i)
1123         return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
1124                                  InsertBefore);
1125     }
1126     // If we end up here, the indices of the insertvalue match with those
1127     // requested (though possibly only partially). Now we recursively look at
1128     // the inserted value, passing any remaining indices.
1129     return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
1130                              InsertBefore);
1131   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1132     // If we're extracting a value from an aggregrate that was extracted from
1133     // something else, we can extract from that something else directly instead.
1134     // However, we will need to chain I's indices with the requested indices.
1135    
1136     // Calculate the number of indices required 
1137     unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1138     // Allocate some space to put the new indices in
1139     SmallVector<unsigned, 5> Idxs;
1140     Idxs.reserve(size);
1141     // Add indices from the extract value instruction
1142     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1143          i != e; ++i)
1144       Idxs.push_back(*i);
1145     
1146     // Add requested indices
1147     for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1148       Idxs.push_back(*i);
1149
1150     assert(Idxs.size() == size 
1151            && "Number of indices added not correct?");
1152     
1153     return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
1154                              InsertBefore);
1155   }
1156   // Otherwise, we don't know (such as, extracting from a function return value
1157   // or load instruction)
1158   return 0;
1159 }
1160
1161 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1162 /// it can be expressed as a base pointer plus a constant offset.  Return the
1163 /// base and offset to the caller.
1164 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1165                                               const TargetData &TD) {
1166   Operator *PtrOp = dyn_cast<Operator>(Ptr);
1167   if (PtrOp == 0) return Ptr;
1168   
1169   // Just look through bitcasts.
1170   if (PtrOp->getOpcode() == Instruction::BitCast)
1171     return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1172   
1173   // If this is a GEP with constant indices, we can look through it.
1174   GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1175   if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1176   
1177   gep_type_iterator GTI = gep_type_begin(GEP);
1178   for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1179        ++I, ++GTI) {
1180     ConstantInt *OpC = cast<ConstantInt>(*I);
1181     if (OpC->isZero()) continue;
1182     
1183     // Handle a struct and array indices which add their offset to the pointer.
1184     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1185       Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1186     } else {
1187       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1188       Offset += OpC->getSExtValue()*Size;
1189     }
1190   }
1191   
1192   // Re-sign extend from the pointer size if needed to get overflow edge cases
1193   // right.
1194   unsigned PtrSize = TD.getPointerSizeInBits();
1195   if (PtrSize < 64)
1196     Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1197   
1198   return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1199 }
1200
1201
1202 /// GetConstantStringInfo - This function computes the length of a
1203 /// null-terminated C string pointed to by V.  If successful, it returns true
1204 /// and returns the string in Str.  If unsuccessful, it returns false.
1205 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1206                                  uint64_t Offset,
1207                                  bool StopAtNul) {
1208   // If V is NULL then return false;
1209   if (V == NULL) return false;
1210
1211   // Look through bitcast instructions.
1212   if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1213     return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1214   
1215   // If the value is not a GEP instruction nor a constant expression with a
1216   // GEP instruction, then return false because ConstantArray can't occur
1217   // any other way
1218   const User *GEP = 0;
1219   if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1220     GEP = GEPI;
1221   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1222     if (CE->getOpcode() == Instruction::BitCast)
1223       return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1224     if (CE->getOpcode() != Instruction::GetElementPtr)
1225       return false;
1226     GEP = CE;
1227   }
1228   
1229   if (GEP) {
1230     // Make sure the GEP has exactly three arguments.
1231     if (GEP->getNumOperands() != 3)
1232       return false;
1233     
1234     // Make sure the index-ee is a pointer to array of i8.
1235     const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1236     const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1237     if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1238       return false;
1239     
1240     // Check to make sure that the first operand of the GEP is an integer and
1241     // has value 0 so that we are sure we're indexing into the initializer.
1242     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1243     if (FirstIdx == 0 || !FirstIdx->isZero())
1244       return false;
1245     
1246     // If the second index isn't a ConstantInt, then this is a variable index
1247     // into the array.  If this occurs, we can't say anything meaningful about
1248     // the string.
1249     uint64_t StartIdx = 0;
1250     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1251       StartIdx = CI->getZExtValue();
1252     else
1253       return false;
1254     return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1255                                  StopAtNul);
1256   }
1257   
1258   // The GEP instruction, constant or instruction, must reference a global
1259   // variable that is a constant and is initialized. The referenced constant
1260   // initializer is the array that we'll use for optimization.
1261   const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1262   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1263     return false;
1264   const Constant *GlobalInit = GV->getInitializer();
1265   
1266   // Handle the ConstantAggregateZero case
1267   if (isa<ConstantAggregateZero>(GlobalInit)) {
1268     // This is a degenerate case. The initializer is constant zero so the
1269     // length of the string must be zero.
1270     Str.clear();
1271     return true;
1272   }
1273   
1274   // Must be a Constant Array
1275   const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1276   if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
1277     return false;
1278   
1279   // Get the number of elements in the array
1280   uint64_t NumElts = Array->getType()->getNumElements();
1281   
1282   if (Offset > NumElts)
1283     return false;
1284   
1285   // Traverse the constant array from 'Offset' which is the place the GEP refers
1286   // to in the array.
1287   Str.reserve(NumElts-Offset);
1288   for (unsigned i = Offset; i != NumElts; ++i) {
1289     const Constant *Elt = Array->getOperand(i);
1290     const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1291     if (!CI) // This array isn't suitable, non-int initializer.
1292       return false;
1293     if (StopAtNul && CI->isZero())
1294       return true; // we found end of string, success!
1295     Str += (char)CI->getZExtValue();
1296   }
1297   
1298   // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1299   return true;
1300 }
1301
1302 // These next two are very similar to the above, but also look through PHI
1303 // nodes.
1304 // TODO: See if we can integrate these two together.
1305
1306 /// GetStringLengthH - If we can compute the length of the string pointed to by
1307 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1308 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1309   // Look through noop bitcast instructions.
1310   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1311     return GetStringLengthH(BCI->getOperand(0), PHIs);
1312
1313   // If this is a PHI node, there are two cases: either we have already seen it
1314   // or we haven't.
1315   if (PHINode *PN = dyn_cast<PHINode>(V)) {
1316     if (!PHIs.insert(PN))
1317       return ~0ULL;  // already in the set.
1318
1319     // If it was new, see if all the input strings are the same length.
1320     uint64_t LenSoFar = ~0ULL;
1321     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1322       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1323       if (Len == 0) return 0; // Unknown length -> unknown.
1324
1325       if (Len == ~0ULL) continue;
1326
1327       if (Len != LenSoFar && LenSoFar != ~0ULL)
1328         return 0;    // Disagree -> unknown.
1329       LenSoFar = Len;
1330     }
1331
1332     // Success, all agree.
1333     return LenSoFar;
1334   }
1335
1336   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1337   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1338     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1339     if (Len1 == 0) return 0;
1340     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1341     if (Len2 == 0) return 0;
1342     if (Len1 == ~0ULL) return Len2;
1343     if (Len2 == ~0ULL) return Len1;
1344     if (Len1 != Len2) return 0;
1345     return Len1;
1346   }
1347
1348   // If the value is not a GEP instruction nor a constant expression with a
1349   // GEP instruction, then return unknown.
1350   User *GEP = 0;
1351   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1352     GEP = GEPI;
1353   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1354     if (CE->getOpcode() != Instruction::GetElementPtr)
1355       return 0;
1356     GEP = CE;
1357   } else {
1358     return 0;
1359   }
1360
1361   // Make sure the GEP has exactly three arguments.
1362   if (GEP->getNumOperands() != 3)
1363     return 0;
1364
1365   // Check to make sure that the first operand of the GEP is an integer and
1366   // has value 0 so that we are sure we're indexing into the initializer.
1367   if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1368     if (!Idx->isZero())
1369       return 0;
1370   } else
1371     return 0;
1372
1373   // If the second index isn't a ConstantInt, then this is a variable index
1374   // into the array.  If this occurs, we can't say anything meaningful about
1375   // the string.
1376   uint64_t StartIdx = 0;
1377   if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1378     StartIdx = CI->getZExtValue();
1379   else
1380     return 0;
1381
1382   // The GEP instruction, constant or instruction, must reference a global
1383   // variable that is a constant and is initialized. The referenced constant
1384   // initializer is the array that we'll use for optimization.
1385   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1386   if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1387       GV->mayBeOverridden())
1388     return 0;
1389   Constant *GlobalInit = GV->getInitializer();
1390
1391   // Handle the ConstantAggregateZero case, which is a degenerate case. The
1392   // initializer is constant zero so the length of the string must be zero.
1393   if (isa<ConstantAggregateZero>(GlobalInit))
1394     return 1;  // Len = 0 offset by 1.
1395
1396   // Must be a Constant Array
1397   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1398   if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1399     return false;
1400
1401   // Get the number of elements in the array
1402   uint64_t NumElts = Array->getType()->getNumElements();
1403
1404   // Traverse the constant array from StartIdx (derived above) which is
1405   // the place the GEP refers to in the array.
1406   for (unsigned i = StartIdx; i != NumElts; ++i) {
1407     Constant *Elt = Array->getOperand(i);
1408     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1409     if (!CI) // This array isn't suitable, non-int initializer.
1410       return 0;
1411     if (CI->isZero())
1412       return i-StartIdx+1; // We found end of string, success!
1413   }
1414
1415   return 0; // The array isn't null terminated, conservatively return 'unknown'.
1416 }
1417
1418 /// GetStringLength - If we can compute the length of the string pointed to by
1419 /// the specified pointer, return 'len+1'.  If we can't, return 0.
1420 uint64_t llvm::GetStringLength(Value *V) {
1421   if (!V->getType()->isPointerTy()) return 0;
1422
1423   SmallPtrSet<PHINode*, 32> PHIs;
1424   uint64_t Len = GetStringLengthH(V, PHIs);
1425   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1426   // an empty string as a length.
1427   return Len == ~0ULL ? 1 : Len;
1428 }