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