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