1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
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"
24 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
25 /// opcode value. Otherwise return UserOp1.
26 static unsigned getOpcode(const Value *V) {
27 if (const Instruction *I = dyn_cast<Instruction>(V))
28 return I->getOpcode();
29 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
30 return CE->getOpcode();
31 // Use UserOp1 to mean there's no opcode.
32 return Instruction::UserOp1;
36 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
37 /// known to be either zero or one and return them in the KnownZero/KnownOne
38 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
40 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
41 /// we cannot optimize based on the assumption that it is zero without changing
42 /// it to be an explicit zero. If we don't change it to zero, other code could
43 /// optimized based on the contradictory assumption that it is non-zero.
44 /// Because instcombine aggressively folds operations with undef args anyway,
45 /// this won't lose us code quality.
46 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
47 APInt &KnownZero, APInt &KnownOne,
48 TargetData *TD, unsigned Depth) {
49 assert(V && "No Value?");
50 assert(Depth <= 6 && "Limit Search Depth");
51 uint32_t BitWidth = Mask.getBitWidth();
52 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
53 "Not integer or pointer type!");
54 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
55 (!isa<IntegerType>(V->getType()) ||
56 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
57 KnownZero.getBitWidth() == BitWidth &&
58 KnownOne.getBitWidth() == BitWidth &&
59 "V, Mask, KnownOne and KnownZero should have same BitWidth");
61 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
62 // We know all of the bits for a constant!
63 KnownOne = CI->getValue() & Mask;
64 KnownZero = ~KnownOne & Mask;
68 if (isa<ConstantPointerNull>(V)) {
73 // The address of an aligned GlobalValue has trailing zeros.
74 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
75 unsigned Align = GV->getAlignment();
76 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
77 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
79 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
80 CountTrailingZeros_32(Align));
87 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
89 if (Depth == 6 || Mask == 0)
90 return; // Limit search depth.
92 User *I = dyn_cast<User>(V);
95 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
96 switch (getOpcode(I)) {
98 case Instruction::And: {
99 // If either the LHS or the RHS are Zero, the result is zero.
100 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
101 APInt Mask2(Mask & ~KnownZero);
102 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
104 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
105 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
107 // Output known-1 bits are only known if set in both the LHS & RHS.
108 KnownOne &= KnownOne2;
109 // Output known-0 are known to be clear if zero in either the LHS | RHS.
110 KnownZero |= KnownZero2;
113 case Instruction::Or: {
114 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
115 APInt Mask2(Mask & ~KnownOne);
116 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
118 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
119 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
121 // Output known-0 bits are only known if clear in both the LHS & RHS.
122 KnownZero &= KnownZero2;
123 // Output known-1 are known to be set if set in either the LHS | RHS.
124 KnownOne |= KnownOne2;
127 case Instruction::Xor: {
128 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
129 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
131 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
132 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
134 // Output known-0 bits are known if clear or set in both the LHS & RHS.
135 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
136 // Output known-1 are known to be set if set in only one of the LHS, RHS.
137 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
138 KnownZero = KnownZeroOut;
141 case Instruction::Mul: {
142 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
143 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
144 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
147 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
149 // If low bits are zero in either operand, output low known-0 bits.
150 // Also compute a conserative estimate for high known-0 bits.
151 // More trickiness is possible, but this is sufficient for the
152 // interesting case of alignment computation.
154 unsigned TrailZ = KnownZero.countTrailingOnes() +
155 KnownZero2.countTrailingOnes();
156 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
157 KnownZero2.countLeadingOnes(),
158 BitWidth) - BitWidth;
160 TrailZ = std::min(TrailZ, BitWidth);
161 LeadZ = std::min(LeadZ, BitWidth);
162 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
163 APInt::getHighBitsSet(BitWidth, LeadZ);
167 case Instruction::UDiv: {
168 // For the purposes of computing leading zeros we can conservatively
169 // treat a udiv as a logical right shift by the power of 2 known to
170 // be less than the denominator.
171 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
172 ComputeMaskedBits(I->getOperand(0),
173 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
174 unsigned LeadZ = KnownZero2.countLeadingOnes();
178 ComputeMaskedBits(I->getOperand(1),
179 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
180 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
181 if (RHSUnknownLeadingOnes != BitWidth)
182 LeadZ = std::min(BitWidth,
183 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
185 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
188 case Instruction::Select:
189 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
190 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
192 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
193 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
195 // Only known if known in both the LHS and RHS.
196 KnownOne &= KnownOne2;
197 KnownZero &= KnownZero2;
199 case Instruction::FPTrunc:
200 case Instruction::FPExt:
201 case Instruction::FPToUI:
202 case Instruction::FPToSI:
203 case Instruction::SIToFP:
204 case Instruction::UIToFP:
205 return; // Can't work with floating point.
206 case Instruction::PtrToInt:
207 case Instruction::IntToPtr:
208 // We can't handle these if we don't know the pointer size.
210 // FALL THROUGH and handle them the same as zext/trunc.
211 case Instruction::ZExt:
212 case Instruction::Trunc: {
213 // Note that we handle pointer operands here because of inttoptr/ptrtoint
214 // which fall through here.
215 const Type *SrcTy = I->getOperand(0)->getType();
216 uint32_t SrcBitWidth = TD ?
217 TD->getTypeSizeInBits(SrcTy) :
218 SrcTy->getPrimitiveSizeInBits();
220 MaskIn.zextOrTrunc(SrcBitWidth);
221 KnownZero.zextOrTrunc(SrcBitWidth);
222 KnownOne.zextOrTrunc(SrcBitWidth);
223 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
225 KnownZero.zextOrTrunc(BitWidth);
226 KnownOne.zextOrTrunc(BitWidth);
227 // Any top bits are known to be zero.
228 if (BitWidth > SrcBitWidth)
229 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
232 case Instruction::BitCast: {
233 const Type *SrcTy = I->getOperand(0)->getType();
234 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
235 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
241 case Instruction::SExt: {
242 // Compute the bits in the result that are not present in the input.
243 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
244 uint32_t SrcBitWidth = SrcTy->getBitWidth();
247 MaskIn.trunc(SrcBitWidth);
248 KnownZero.trunc(SrcBitWidth);
249 KnownOne.trunc(SrcBitWidth);
250 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
252 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
253 KnownZero.zext(BitWidth);
254 KnownOne.zext(BitWidth);
256 // If the sign bit of the input is known set or clear, then we know the
257 // top bits of the result.
258 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
259 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
260 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
261 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
264 case Instruction::Shl:
265 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
266 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
267 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
268 APInt Mask2(Mask.lshr(ShiftAmt));
269 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
272 KnownZero <<= ShiftAmt;
273 KnownOne <<= ShiftAmt;
274 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
278 case Instruction::LShr:
279 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
280 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
281 // Compute the new bits that are at the top now.
282 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
284 // Unsigned shift right.
285 APInt Mask2(Mask.shl(ShiftAmt));
286 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
288 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
289 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
290 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
291 // high bits known zero.
292 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
296 case Instruction::AShr:
297 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
299 // Compute the new bits that are at the top now.
300 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
302 // Signed shift right.
303 APInt Mask2(Mask.shl(ShiftAmt));
304 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
306 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
307 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
308 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
310 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
311 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
312 KnownZero |= HighBits;
313 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
314 KnownOne |= HighBits;
318 case Instruction::Sub: {
319 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
320 // We know that the top bits of C-X are clear if X contains less bits
321 // than C (i.e. no wrap-around can happen). For example, 20-X is
322 // positive if we can prove that X is >= 0 and < 16.
323 if (!CLHS->getValue().isNegative()) {
324 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
325 // NLZ can't be BitWidth with no sign bit
326 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
327 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
330 // If all of the MaskV bits are known to be zero, then we know the
331 // output top bits are zero, because we now know that the output is
333 if ((KnownZero2 & MaskV) == MaskV) {
334 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
335 // Top bits known zero.
336 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
342 case Instruction::Add: {
343 // Output known-0 bits are known if clear or set in both the low clear bits
344 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
346 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
347 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
349 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
350 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
352 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
354 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
355 KnownZeroOut = std::min(KnownZeroOut,
356 KnownZero2.countTrailingOnes());
358 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
361 case Instruction::SRem:
362 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
363 APInt RA = Rem->getValue();
364 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
365 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
366 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
367 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
370 // The sign of a remainder is equal to the sign of the first
371 // operand (zero being positive).
372 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
373 KnownZero2 |= ~LowBits;
374 else if (KnownOne2[BitWidth-1])
375 KnownOne2 |= ~LowBits;
377 KnownZero |= KnownZero2 & Mask;
378 KnownOne |= KnownOne2 & Mask;
380 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
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,
393 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
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,
403 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
406 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
407 KnownZero2.countLeadingOnes());
409 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
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->getPrefTypeAlignment(AI->getType()->getElementType());
420 else if (isa<MallocInst>(AI)) {
421 // Malloc returns maximally aligned memory.
422 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
425 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
428 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
433 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
434 CountTrailingZeros_32(Align));
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();
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.
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));
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->getABITypeSize(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());
473 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
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);
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.
506 // Ok, we have a PHI of the form L op= R. Check for low
508 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
509 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
510 Mask2 = APInt::getLowBitsSet(BitWidth,
511 KnownZero2.countTrailingOnes());
514 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
516 APInt::getLowBitsSet(BitWidth,
517 KnownZero2.countTrailingOnes());
524 case Instruction::Call:
525 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
526 switch (II->getIntrinsicID()) {
528 case Intrinsic::ctpop:
529 case Intrinsic::ctlz:
530 case Intrinsic::cttz: {
531 unsigned LowBits = Log2_32(BitWidth)+1;
532 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
541 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
542 /// this predicate to simplify operations downstream. Mask is known to be zero
543 /// for bits that V cannot have.
544 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
545 TargetData *TD, unsigned Depth) {
546 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
547 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
548 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
549 return (KnownZero & Mask) == Mask;
554 /// ComputeNumSignBits - Return the number of times the sign bit of the
555 /// register is replicated into the other bits. We know that at least 1 bit
556 /// is always equal to the sign bit (itself), but other cases can give us
557 /// information. For example, immediately after an "ashr X, 2", we know that
558 /// the top 3 bits are all equal to each other, so we return 3.
560 /// 'Op' must have a scalar integer type.
562 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
563 const IntegerType *Ty = cast<IntegerType>(V->getType());
564 unsigned TyBits = Ty->getBitWidth();
566 unsigned FirstAnswer = 1;
568 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
569 if (CI->getValue().isNegative())
570 return CI->getValue().countLeadingOnes();
571 return CI->getValue().countLeadingZeros();
575 return 1; // Limit search depth.
577 User *U = dyn_cast<User>(V);
578 switch (getOpcode(V)) {
580 case Instruction::SExt:
581 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
582 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
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;
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();
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);
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.
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);
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.
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,
635 // If the input is known to be 0 or 1, the output is 0/-1, which is all
637 if ((KnownZero | APInt(TyBits, 1)) == Mask)
640 // If we are subtracting one from a positive number, there is no carry
641 // out of the result.
642 if (KnownZero.isNegative())
646 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
647 if (Tmp2 == 1) return 1;
648 return std::min(Tmp, Tmp2)-1;
651 case Instruction::Sub:
652 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
653 if (Tmp2 == 1) return 1;
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,
662 // If the input is known to be 0 or 1, the output is 0/-1, which is all
664 if ((KnownZero | APInt(TyBits, 1)) == Mask)
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())
672 // Otherwise, we treat this like a SUB.
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;
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.
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);
693 if (KnownZero.isNegative()) { // sign bit is 0
695 } else if (KnownOne.isNegative()) { // sign bit is 1;
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.
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()));