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