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