Rename getABITypeSize to getTypePaddedSize, as
[oota-llvm.git] / lib / Analysis / ValueTracking.cpp
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <cstring>
24 using namespace llvm;
25
26 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
27 /// opcode value. Otherwise return UserOp1.
28 static unsigned getOpcode(const Value *V) {
29   if (const Instruction *I = dyn_cast<Instruction>(V))
30     return I->getOpcode();
31   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
32     return CE->getOpcode();
33   // Use UserOp1 to mean there's no opcode.
34   return Instruction::UserOp1;
35 }
36
37
38 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
39 /// known to be either zero or one and return them in the KnownZero/KnownOne
40 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
41 /// processing.
42 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
43 /// we cannot optimize based on the assumption that it is zero without changing
44 /// it to be an explicit zero.  If we don't change it to zero, other code could
45 /// optimized based on the contradictory assumption that it is non-zero.
46 /// Because instcombine aggressively folds operations with undef args anyway,
47 /// this won't lose us code quality.
48 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
49                              APInt &KnownZero, APInt &KnownOne,
50                              TargetData *TD, unsigned Depth) {
51   assert(V && "No Value?");
52   assert(Depth <= 6 && "Limit Search Depth");
53   uint32_t BitWidth = Mask.getBitWidth();
54   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
55          "Not integer or pointer type!");
56   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
57          (!isa<IntegerType>(V->getType()) ||
58           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
59          KnownZero.getBitWidth() == BitWidth && 
60          KnownOne.getBitWidth() == BitWidth &&
61          "V, Mask, KnownOne and KnownZero should have same BitWidth");
62
63   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
64     // We know all of the bits for a constant!
65     KnownOne = CI->getValue() & Mask;
66     KnownZero = ~KnownOne & Mask;
67     return;
68   }
69   // Null is all-zeros.
70   if (isa<ConstantPointerNull>(V)) {
71     KnownOne.clear();
72     KnownZero = Mask;
73     return;
74   }
75   // The address of an aligned GlobalValue has trailing zeros.
76   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
77     unsigned Align = GV->getAlignment();
78     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
79       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
80     if (Align > 0)
81       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
82                                               CountTrailingZeros_32(Align));
83     else
84       KnownZero.clear();
85     KnownOne.clear();
86     return;
87   }
88
89   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
90
91   if (Depth == 6 || Mask == 0)
92     return;  // Limit search depth.
93
94   User *I = dyn_cast<User>(V);
95   if (!I) return;
96
97   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
98   switch (getOpcode(I)) {
99   default: break;
100   case Instruction::And: {
101     // If either the LHS or the RHS are Zero, the result is zero.
102     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
103     APInt Mask2(Mask & ~KnownZero);
104     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
105                       Depth+1);
106     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
107     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
108     
109     // Output known-1 bits are only known if set in both the LHS & RHS.
110     KnownOne &= KnownOne2;
111     // Output known-0 are known to be clear if zero in either the LHS | RHS.
112     KnownZero |= KnownZero2;
113     return;
114   }
115   case Instruction::Or: {
116     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
117     APInt Mask2(Mask & ~KnownOne);
118     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
119                       Depth+1);
120     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
121     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
122     
123     // Output known-0 bits are only known if clear in both the LHS & RHS.
124     KnownZero &= KnownZero2;
125     // Output known-1 are known to be set if set in either the LHS | RHS.
126     KnownOne |= KnownOne2;
127     return;
128   }
129   case Instruction::Xor: {
130     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
131     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
132                       Depth+1);
133     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
134     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
135     
136     // Output known-0 bits are known if clear or set in both the LHS & RHS.
137     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
138     // Output known-1 are known to be set if set in only one of the LHS, RHS.
139     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
140     KnownZero = KnownZeroOut;
141     return;
142   }
143   case Instruction::Mul: {
144     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
145     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
146     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
147                       Depth+1);
148     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
149     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
150     
151     // If low bits are zero in either operand, output low known-0 bits.
152     // Also compute a conserative estimate for high known-0 bits.
153     // More trickiness is possible, but this is sufficient for the
154     // interesting case of alignment computation.
155     KnownOne.clear();
156     unsigned TrailZ = KnownZero.countTrailingOnes() +
157                       KnownZero2.countTrailingOnes();
158     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
159                                KnownZero2.countLeadingOnes(),
160                                BitWidth) - BitWidth;
161
162     TrailZ = std::min(TrailZ, BitWidth);
163     LeadZ = std::min(LeadZ, BitWidth);
164     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
165                 APInt::getHighBitsSet(BitWidth, LeadZ);
166     KnownZero &= Mask;
167     return;
168   }
169   case Instruction::UDiv: {
170     // For the purposes of computing leading zeros we can conservatively
171     // treat a udiv as a logical right shift by the power of 2 known to
172     // be less than the denominator.
173     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
174     ComputeMaskedBits(I->getOperand(0),
175                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
176     unsigned LeadZ = KnownZero2.countLeadingOnes();
177
178     KnownOne2.clear();
179     KnownZero2.clear();
180     ComputeMaskedBits(I->getOperand(1),
181                       AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
182     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
183     if (RHSUnknownLeadingOnes != BitWidth)
184       LeadZ = std::min(BitWidth,
185                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
186
187     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
188     return;
189   }
190   case Instruction::Select:
191     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
192     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
193                       Depth+1);
194     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
195     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
196
197     // Only known if known in both the LHS and RHS.
198     KnownOne &= KnownOne2;
199     KnownZero &= KnownZero2;
200     return;
201   case Instruction::FPTrunc:
202   case Instruction::FPExt:
203   case Instruction::FPToUI:
204   case Instruction::FPToSI:
205   case Instruction::SIToFP:
206   case Instruction::UIToFP:
207     return; // Can't work with floating point.
208   case Instruction::PtrToInt:
209   case Instruction::IntToPtr:
210     // We can't handle these if we don't know the pointer size.
211     if (!TD) return;
212     // FALL THROUGH and handle them the same as zext/trunc.
213   case Instruction::ZExt:
214   case Instruction::Trunc: {
215     // Note that we handle pointer operands here because of inttoptr/ptrtoint
216     // which fall through here.
217     const Type *SrcTy = I->getOperand(0)->getType();
218     uint32_t SrcBitWidth = TD ?
219       TD->getTypeSizeInBits(SrcTy) :
220       SrcTy->getPrimitiveSizeInBits();
221     APInt MaskIn(Mask);
222     MaskIn.zextOrTrunc(SrcBitWidth);
223     KnownZero.zextOrTrunc(SrcBitWidth);
224     KnownOne.zextOrTrunc(SrcBitWidth);
225     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
226                       Depth+1);
227     KnownZero.zextOrTrunc(BitWidth);
228     KnownOne.zextOrTrunc(BitWidth);
229     // Any top bits are known to be zero.
230     if (BitWidth > SrcBitWidth)
231       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
232     return;
233   }
234   case Instruction::BitCast: {
235     const Type *SrcTy = I->getOperand(0)->getType();
236     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
237       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
238                         Depth+1);
239       return;
240     }
241     break;
242   }
243   case Instruction::SExt: {
244     // Compute the bits in the result that are not present in the input.
245     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
246     uint32_t SrcBitWidth = SrcTy->getBitWidth();
247       
248     APInt MaskIn(Mask); 
249     MaskIn.trunc(SrcBitWidth);
250     KnownZero.trunc(SrcBitWidth);
251     KnownOne.trunc(SrcBitWidth);
252     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
253                       Depth+1);
254     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
255     KnownZero.zext(BitWidth);
256     KnownOne.zext(BitWidth);
257
258     // If the sign bit of the input is known set or clear, then we know the
259     // top bits of the result.
260     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
261       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
262     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
263       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
264     return;
265   }
266   case Instruction::Shl:
267     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
268     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
269       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
270       APInt Mask2(Mask.lshr(ShiftAmt));
271       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
272                         Depth+1);
273       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
274       KnownZero <<= ShiftAmt;
275       KnownOne  <<= ShiftAmt;
276       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
277       return;
278     }
279     break;
280   case Instruction::LShr:
281     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
282     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
283       // Compute the new bits that are at the top now.
284       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
285       
286       // Unsigned shift right.
287       APInt Mask2(Mask.shl(ShiftAmt));
288       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
289                         Depth+1);
290       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
291       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
292       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
293       // high bits known zero.
294       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
295       return;
296     }
297     break;
298   case Instruction::AShr:
299     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
300     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
301       // Compute the new bits that are at the top now.
302       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
303       
304       // Signed shift right.
305       APInt Mask2(Mask.shl(ShiftAmt));
306       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
307                         Depth+1);
308       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
309       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
310       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
311         
312       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
313       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
314         KnownZero |= HighBits;
315       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
316         KnownOne |= HighBits;
317       return;
318     }
319     break;
320   case Instruction::Sub: {
321     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
322       // We know that the top bits of C-X are clear if X contains less bits
323       // than C (i.e. no wrap-around can happen).  For example, 20-X is
324       // positive if we can prove that X is >= 0 and < 16.
325       if (!CLHS->getValue().isNegative()) {
326         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
327         // NLZ can't be BitWidth with no sign bit
328         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
329         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
330                           TD, Depth+1);
331     
332         // If all of the MaskV bits are known to be zero, then we know the
333         // output top bits are zero, because we now know that the output is
334         // from [0-C].
335         if ((KnownZero2 & MaskV) == MaskV) {
336           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
337           // Top bits known zero.
338           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
339         }
340       }        
341     }
342   }
343   // fall through
344   case Instruction::Add: {
345     // Output known-0 bits are known if clear or set in both the low clear bits
346     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
347     // low 3 bits clear.
348     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
349     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
350                       Depth+1);
351     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
352     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
353
354     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 
355                       Depth+1);
356     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
357     KnownZeroOut = std::min(KnownZeroOut, 
358                             KnownZero2.countTrailingOnes());
359
360     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
361     return;
362   }
363   case Instruction::SRem:
364     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
365       APInt RA = Rem->getValue();
366       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
367         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
368         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
369         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 
370                           Depth+1);
371
372         // If the sign bit of the first operand is zero, the sign bit of
373         // the result is zero. If the first operand has no one bits below
374         // the second operand's single 1 bit, its sign will be zero.
375         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
376           KnownZero2 |= ~LowBits;
377
378         KnownZero |= KnownZero2 & Mask;
379
380         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
381       }
382     }
383     break;
384   case Instruction::URem: {
385     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
386       APInt RA = Rem->getValue();
387       if (RA.isPowerOf2()) {
388         APInt LowBits = (RA - 1);
389         APInt Mask2 = LowBits & Mask;
390         KnownZero |= ~LowBits & Mask;
391         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
392                           Depth+1);
393         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
394         break;
395       }
396     }
397
398     // Since the result is less than or equal to either operand, any leading
399     // zero bits in either operand must also exist in the result.
400     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
401     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
402                       TD, Depth+1);
403     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
404                       TD, Depth+1);
405
406     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
407                                 KnownZero2.countLeadingOnes());
408     KnownOne.clear();
409     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
410     break;
411   }
412
413   case Instruction::Alloca:
414   case Instruction::Malloc: {
415     AllocationInst *AI = cast<AllocationInst>(V);
416     unsigned Align = AI->getAlignment();
417     if (Align == 0 && TD) {
418       if (isa<AllocaInst>(AI))
419         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
420       else if (isa<MallocInst>(AI)) {
421         // Malloc returns maximally aligned memory.
422         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
423         Align =
424           std::max(Align,
425                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
426         Align =
427           std::max(Align,
428                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
429       }
430     }
431     
432     if (Align > 0)
433       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
434                                               CountTrailingZeros_32(Align));
435     break;
436   }
437   case Instruction::GetElementPtr: {
438     // Analyze all of the subscripts of this getelementptr instruction
439     // to determine if we can prove known low zero bits.
440     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
441     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
442     ComputeMaskedBits(I->getOperand(0), LocalMask,
443                       LocalKnownZero, LocalKnownOne, TD, Depth+1);
444     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
445
446     gep_type_iterator GTI = gep_type_begin(I);
447     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
448       Value *Index = I->getOperand(i);
449       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
450         // Handle struct member offset arithmetic.
451         if (!TD) return;
452         const StructLayout *SL = TD->getStructLayout(STy);
453         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
454         uint64_t Offset = SL->getElementOffset(Idx);
455         TrailZ = std::min(TrailZ,
456                           CountTrailingZeros_64(Offset));
457       } else {
458         // Handle array index arithmetic.
459         const Type *IndexedTy = GTI.getIndexedType();
460         if (!IndexedTy->isSized()) return;
461         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
462         uint64_t TypeSize = TD ? TD->getTypePaddedSize(IndexedTy) : 1;
463         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
464         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
465         ComputeMaskedBits(Index, LocalMask,
466                           LocalKnownZero, LocalKnownOne, TD, Depth+1);
467         TrailZ = std::min(TrailZ,
468                           CountTrailingZeros_64(TypeSize) +
469                             LocalKnownZero.countTrailingOnes());
470       }
471     }
472     
473     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
474     break;
475   }
476   case Instruction::PHI: {
477     PHINode *P = cast<PHINode>(I);
478     // Handle the case of a simple two-predecessor recurrence PHI.
479     // There's a lot more that could theoretically be done here, but
480     // this is sufficient to catch some interesting cases.
481     if (P->getNumIncomingValues() == 2) {
482       for (unsigned i = 0; i != 2; ++i) {
483         Value *L = P->getIncomingValue(i);
484         Value *R = P->getIncomingValue(!i);
485         User *LU = dyn_cast<User>(L);
486         if (!LU)
487           continue;
488         unsigned Opcode = getOpcode(LU);
489         // Check for operations that have the property that if
490         // both their operands have low zero bits, the result
491         // will have low zero bits.
492         if (Opcode == Instruction::Add ||
493             Opcode == Instruction::Sub ||
494             Opcode == Instruction::And ||
495             Opcode == Instruction::Or ||
496             Opcode == Instruction::Mul) {
497           Value *LL = LU->getOperand(0);
498           Value *LR = LU->getOperand(1);
499           // Find a recurrence.
500           if (LL == I)
501             L = LR;
502           else if (LR == I)
503             L = LL;
504           else
505             break;
506           // Ok, we have a PHI of the form L op= R. Check for low
507           // zero bits.
508           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
509           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
510           Mask2 = APInt::getLowBitsSet(BitWidth,
511                                        KnownZero2.countTrailingOnes());
512
513           // We need to take the minimum number of known bits
514           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
515           ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
516
517           KnownZero = Mask &
518                       APInt::getLowBitsSet(BitWidth,
519                                            std::min(KnownZero2.countTrailingOnes(),
520                                                     KnownZero3.countTrailingOnes()));
521           break;
522         }
523       }
524     }
525     break;
526   }
527   case Instruction::Call:
528     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
529       switch (II->getIntrinsicID()) {
530       default: break;
531       case Intrinsic::ctpop:
532       case Intrinsic::ctlz:
533       case Intrinsic::cttz: {
534         unsigned LowBits = Log2_32(BitWidth)+1;
535         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
536         break;
537       }
538       }
539     }
540     break;
541   }
542 }
543
544 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
545 /// this predicate to simplify operations downstream.  Mask is known to be zero
546 /// for bits that V cannot have.
547 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
548                              TargetData *TD, unsigned Depth) {
549   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
550   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
551   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
552   return (KnownZero & Mask) == Mask;
553 }
554
555
556
557 /// ComputeNumSignBits - Return the number of times the sign bit of the
558 /// register is replicated into the other bits.  We know that at least 1 bit
559 /// is always equal to the sign bit (itself), but other cases can give us
560 /// information.  For example, immediately after an "ashr X, 2", we know that
561 /// the top 3 bits are all equal to each other, so we return 3.
562 ///
563 /// 'Op' must have a scalar integer type.
564 ///
565 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
566   const IntegerType *Ty = cast<IntegerType>(V->getType());
567   unsigned TyBits = Ty->getBitWidth();
568   unsigned Tmp, Tmp2;
569   unsigned FirstAnswer = 1;
570
571   // Note that ConstantInt is handled by the general ComputeMaskedBits case
572   // below.
573
574   if (Depth == 6)
575     return 1;  // Limit search depth.
576   
577   User *U = dyn_cast<User>(V);
578   switch (getOpcode(V)) {
579   default: break;
580   case Instruction::SExt:
581     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
582     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
583     
584   case Instruction::AShr:
585     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
586     // ashr X, C   -> adds C sign bits.
587     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
588       Tmp += C->getZExtValue();
589       if (Tmp > TyBits) Tmp = TyBits;
590     }
591     return Tmp;
592   case Instruction::Shl:
593     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
594       // shl destroys sign bits.
595       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
596       if (C->getZExtValue() >= TyBits ||      // Bad shift.
597           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
598       return Tmp - C->getZExtValue();
599     }
600     break;
601   case Instruction::And:
602   case Instruction::Or:
603   case Instruction::Xor:    // NOT is handled here.
604     // Logical binary ops preserve the number of sign bits at the worst.
605     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
606     if (Tmp != 1) {
607       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
608       FirstAnswer = std::min(Tmp, Tmp2);
609       // We computed what we know about the sign bits as our first
610       // answer. Now proceed to the generic code that uses
611       // ComputeMaskedBits, and pick whichever answer is better.
612     }
613     break;
614
615   case Instruction::Select:
616     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
617     if (Tmp == 1) return 1;  // Early out.
618     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
619     return std::min(Tmp, Tmp2);
620     
621   case Instruction::Add:
622     // Add can have at most one carry bit.  Thus we know that the output
623     // is, at worst, one more bit than the inputs.
624     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
625     if (Tmp == 1) return 1;  // Early out.
626       
627     // Special case decrementing a value (ADD X, -1):
628     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
629       if (CRHS->isAllOnesValue()) {
630         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
631         APInt Mask = APInt::getAllOnesValue(TyBits);
632         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
633                           Depth+1);
634         
635         // If the input is known to be 0 or 1, the output is 0/-1, which is all
636         // sign bits set.
637         if ((KnownZero | APInt(TyBits, 1)) == Mask)
638           return TyBits;
639         
640         // If we are subtracting one from a positive number, there is no carry
641         // out of the result.
642         if (KnownZero.isNegative())
643           return Tmp;
644       }
645       
646     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
647     if (Tmp2 == 1) return 1;
648       return std::min(Tmp, Tmp2)-1;
649     break;
650     
651   case Instruction::Sub:
652     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
653     if (Tmp2 == 1) return 1;
654       
655     // Handle NEG.
656     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
657       if (CLHS->isNullValue()) {
658         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
659         APInt Mask = APInt::getAllOnesValue(TyBits);
660         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 
661                           TD, Depth+1);
662         // If the input is known to be 0 or 1, the output is 0/-1, which is all
663         // sign bits set.
664         if ((KnownZero | APInt(TyBits, 1)) == Mask)
665           return TyBits;
666         
667         // If the input is known to be positive (the sign bit is known clear),
668         // the output of the NEG has the same number of sign bits as the input.
669         if (KnownZero.isNegative())
670           return Tmp2;
671         
672         // Otherwise, we treat this like a SUB.
673       }
674     
675     // Sub can have at most one carry bit.  Thus we know that the output
676     // is, at worst, one more bit than the inputs.
677     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
678     if (Tmp == 1) return 1;  // Early out.
679       return std::min(Tmp, Tmp2)-1;
680     break;
681   case Instruction::Trunc:
682     // FIXME: it's tricky to do anything useful for this, but it is an important
683     // case for targets like X86.
684     break;
685   }
686   
687   // Finally, if we can prove that the top bits of the result are 0's or 1's,
688   // use this information.
689   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
690   APInt Mask = APInt::getAllOnesValue(TyBits);
691   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
692   
693   if (KnownZero.isNegative()) {        // sign bit is 0
694     Mask = KnownZero;
695   } else if (KnownOne.isNegative()) {  // sign bit is 1;
696     Mask = KnownOne;
697   } else {
698     // Nothing known.
699     return FirstAnswer;
700   }
701   
702   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
703   // the number of identical bits in the top of the input value.
704   Mask = ~Mask;
705   Mask <<= Mask.getBitWidth()-TyBits;
706   // Return # leading zeros.  We use 'min' here in case Val was zero before
707   // shifting.  We don't want to return '64' as for an i32 "0".
708   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
709 }
710
711 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
712 /// value is never equal to -0.0.
713 ///
714 /// NOTE: this function will need to be revisited when we support non-default
715 /// rounding modes!
716 ///
717 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
718   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
719     return !CFP->getValueAPF().isNegZero();
720   
721   if (Depth == 6)
722     return 1;  // Limit search depth.
723
724   const Instruction *I = dyn_cast<Instruction>(V);
725   if (I == 0) return false;
726   
727   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
728   if (I->getOpcode() == Instruction::Add &&
729       isa<ConstantFP>(I->getOperand(1)) && 
730       cast<ConstantFP>(I->getOperand(1))->isNullValue())
731     return true;
732     
733   // sitofp and uitofp turn into +0.0 for zero.
734   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
735     return true;
736   
737   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
738     // sqrt(-0.0) = -0.0, no other negative results are possible.
739     if (II->getIntrinsicID() == Intrinsic::sqrt)
740       return CannotBeNegativeZero(II->getOperand(1), Depth+1);
741   
742   if (const CallInst *CI = dyn_cast<CallInst>(I))
743     if (const Function *F = CI->getCalledFunction()) {
744       if (F->isDeclaration()) {
745         switch (F->getNameLen()) {
746         case 3:  // abs(x) != -0.0
747           if (!strcmp(F->getNameStart(), "abs")) return true;
748           break;
749         case 4:  // abs[lf](x) != -0.0
750           if (!strcmp(F->getNameStart(), "absf")) return true;
751           if (!strcmp(F->getNameStart(), "absl")) return true;
752           break;
753         }
754       }
755     }
756   
757   return false;
758 }
759
760 // This is the recursive version of BuildSubAggregate. It takes a few different
761 // arguments. Idxs is the index within the nested struct From that we are
762 // looking at now (which is of type IndexedType). IdxSkip is the number of
763 // indices from Idxs that should be left out when inserting into the resulting
764 // struct. To is the result struct built so far, new insertvalue instructions
765 // build on that.
766 Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
767                                  SmallVector<unsigned, 10> &Idxs,
768                                  unsigned IdxSkip,
769                                  Instruction *InsertBefore) {
770   const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
771   if (STy) {
772     // Save the original To argument so we can modify it
773     Value *OrigTo = To;
774     // General case, the type indexed by Idxs is a struct
775     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
776       // Process each struct element recursively
777       Idxs.push_back(i);
778       Value *PrevTo = To;
779       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
780                              InsertBefore);
781       Idxs.pop_back();
782       if (!To) {
783         // Couldn't find any inserted value for this index? Cleanup
784         while (PrevTo != OrigTo) {
785           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
786           PrevTo = Del->getAggregateOperand();
787           Del->eraseFromParent();
788         }
789         // Stop processing elements
790         break;
791       }
792     }
793     // If we succesfully found a value for each of our subaggregates 
794     if (To)
795       return To;
796   }
797   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
798   // the struct's elements had a value that was inserted directly. In the latter
799   // case, perhaps we can't determine each of the subelements individually, but
800   // we might be able to find the complete struct somewhere.
801   
802   // Find the value that is at that particular spot
803   Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
804
805   if (!V)
806     return NULL;
807
808   // Insert the value in the new (sub) aggregrate
809   return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
810                                        Idxs.end(), "tmp", InsertBefore);
811 }
812
813 // This helper takes a nested struct and extracts a part of it (which is again a
814 // struct) into a new value. For example, given the struct:
815 // { a, { b, { c, d }, e } }
816 // and the indices "1, 1" this returns
817 // { c, d }.
818 //
819 // It does this by inserting an insertvalue for each element in the resulting
820 // struct, as opposed to just inserting a single struct. This will only work if
821 // each of the elements of the substruct are known (ie, inserted into From by an
822 // insertvalue instruction somewhere).
823 //
824 // All inserted insertvalue instructions are inserted before InsertBefore
825 Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
826                          const unsigned *idx_end, Instruction *InsertBefore) {
827   assert(InsertBefore && "Must have someplace to insert!");
828   const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
829                                                              idx_begin,
830                                                              idx_end);
831   Value *To = UndefValue::get(IndexedType);
832   SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
833   unsigned IdxSkip = Idxs.size();
834
835   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
836 }
837
838 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
839 /// the scalar value indexed is already around as a register, for example if it
840 /// were inserted directly into the aggregrate.
841 ///
842 /// If InsertBefore is not null, this function will duplicate (modified)
843 /// insertvalues when a part of a nested struct is extracted.
844 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
845                          const unsigned *idx_end, Instruction *InsertBefore) {
846   // Nothing to index? Just return V then (this is useful at the end of our
847   // recursion)
848   if (idx_begin == idx_end)
849     return V;
850   // We have indices, so V should have an indexable type
851   assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
852          && "Not looking at a struct or array?");
853   assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
854          && "Invalid indices for type?");
855   const CompositeType *PTy = cast<CompositeType>(V->getType());
856   
857   if (isa<UndefValue>(V))
858     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
859                                                               idx_begin,
860                                                               idx_end));
861   else if (isa<ConstantAggregateZero>(V))
862     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
863                                                                      idx_begin,
864                                                                      idx_end));
865   else if (Constant *C = dyn_cast<Constant>(V)) {
866     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
867       // Recursively process this constant
868       return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, idx_end,
869                                InsertBefore);
870   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
871     // Loop the indices for the insertvalue instruction in parallel with the
872     // requested indices
873     const unsigned *req_idx = idx_begin;
874     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
875          i != e; ++i, ++req_idx) {
876       if (req_idx == idx_end) {
877         if (InsertBefore)
878           // The requested index identifies a part of a nested aggregate. Handle
879           // this specially. For example,
880           // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
881           // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
882           // %C = extractvalue {i32, { i32, i32 } } %B, 1
883           // This can be changed into
884           // %A = insertvalue {i32, i32 } undef, i32 10, 0
885           // %C = insertvalue {i32, i32 } %A, i32 11, 1
886           // which allows the unused 0,0 element from the nested struct to be
887           // removed.
888           return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
889         else
890           // We can't handle this without inserting insertvalues
891           return 0;
892       }
893       
894       // This insert value inserts something else than what we are looking for.
895       // See if the (aggregrate) value inserted into has the value we are
896       // looking for, then.
897       if (*req_idx != *i)
898         return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
899                                  InsertBefore);
900     }
901     // If we end up here, the indices of the insertvalue match with those
902     // requested (though possibly only partially). Now we recursively look at
903     // the inserted value, passing any remaining indices.
904     return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
905                              InsertBefore);
906   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
907     // If we're extracting a value from an aggregrate that was extracted from
908     // something else, we can extract from that something else directly instead.
909     // However, we will need to chain I's indices with the requested indices.
910    
911     // Calculate the number of indices required 
912     unsigned size = I->getNumIndices() + (idx_end - idx_begin);
913     // Allocate some space to put the new indices in
914     SmallVector<unsigned, 5> Idxs;
915     Idxs.reserve(size);
916     // Add indices from the extract value instruction
917     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
918          i != e; ++i)
919       Idxs.push_back(*i);
920     
921     // Add requested indices
922     for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
923       Idxs.push_back(*i);
924
925     assert(Idxs.size() == size 
926            && "Number of indices added not correct?");
927     
928     return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
929                              InsertBefore);
930   }
931   // Otherwise, we don't know (such as, extracting from a function return value
932   // or load instruction)
933   return 0;
934 }
935
936 /// GetConstantStringInfo - This function computes the length of a
937 /// null-terminated C string pointed to by V.  If successful, it returns true
938 /// and returns the string in Str.  If unsuccessful, it returns false.
939 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
940                                  bool StopAtNul) {
941   // If V is NULL then return false;
942   if (V == NULL) return false;
943
944   // Look through bitcast instructions.
945   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
946     return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
947   
948   // If the value is not a GEP instruction nor a constant expression with a
949   // GEP instruction, then return false because ConstantArray can't occur
950   // any other way
951   User *GEP = 0;
952   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
953     GEP = GEPI;
954   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
955     if (CE->getOpcode() == Instruction::BitCast)
956       return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
957     if (CE->getOpcode() != Instruction::GetElementPtr)
958       return false;
959     GEP = CE;
960   }
961   
962   if (GEP) {
963     // Make sure the GEP has exactly three arguments.
964     if (GEP->getNumOperands() != 3)
965       return false;
966     
967     // Make sure the index-ee is a pointer to array of i8.
968     const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
969     const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
970     if (AT == 0 || AT->getElementType() != Type::Int8Ty)
971       return false;
972     
973     // Check to make sure that the first operand of the GEP is an integer and
974     // has value 0 so that we are sure we're indexing into the initializer.
975     ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
976     if (FirstIdx == 0 || !FirstIdx->isZero())
977       return false;
978     
979     // If the second index isn't a ConstantInt, then this is a variable index
980     // into the array.  If this occurs, we can't say anything meaningful about
981     // the string.
982     uint64_t StartIdx = 0;
983     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
984       StartIdx = CI->getZExtValue();
985     else
986       return false;
987     return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
988                                  StopAtNul);
989   }
990   
991   // The GEP instruction, constant or instruction, must reference a global
992   // variable that is a constant and is initialized. The referenced constant
993   // initializer is the array that we'll use for optimization.
994   GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
995   if (!GV || !GV->isConstant() || !GV->hasInitializer())
996     return false;
997   Constant *GlobalInit = GV->getInitializer();
998   
999   // Handle the ConstantAggregateZero case
1000   if (isa<ConstantAggregateZero>(GlobalInit)) {
1001     // This is a degenerate case. The initializer is constant zero so the
1002     // length of the string must be zero.
1003     Str.clear();
1004     return true;
1005   }
1006   
1007   // Must be a Constant Array
1008   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1009   if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1010     return false;
1011   
1012   // Get the number of elements in the array
1013   uint64_t NumElts = Array->getType()->getNumElements();
1014   
1015   if (Offset > NumElts)
1016     return false;
1017   
1018   // Traverse the constant array from 'Offset' which is the place the GEP refers
1019   // to in the array.
1020   Str.reserve(NumElts-Offset);
1021   for (unsigned i = Offset; i != NumElts; ++i) {
1022     Constant *Elt = Array->getOperand(i);
1023     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1024     if (!CI) // This array isn't suitable, non-int initializer.
1025       return false;
1026     if (StopAtNul && CI->isZero())
1027       return true; // we found end of string, success!
1028     Str += (char)CI->getZExtValue();
1029   }
1030   
1031   // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1032   return true;
1033 }