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