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/GlobalVariable.h"
19 #include "llvm/GlobalAlias.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Operator.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/MathExtras.h"
29 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
30 /// known to be either zero or one and return them in the KnownZero/KnownOne
31 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
33 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
34 /// we cannot optimize based on the assumption that it is zero without changing
35 /// it to be an explicit zero. If we don't change it to zero, other code could
36 /// optimized based on the contradictory assumption that it is non-zero.
37 /// Because instcombine aggressively folds operations with undef args anyway,
38 /// this won't lose us code quality.
40 /// This function is defined on values with integer type, values with pointer
41 /// type (but only if TD is non-null), and vectors of integers. In the case
42 /// where V is a vector, the mask, known zero, and known one values are the
43 /// same width as the vector element, and the bit is set only if it is true
44 /// for all of the elements in the vector.
45 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
46 APInt &KnownZero, APInt &KnownOne,
47 const TargetData *TD, unsigned Depth) {
48 const unsigned MaxDepth = 6;
49 assert(V && "No Value?");
50 assert(Depth <= MaxDepth && "Limit Search Depth");
51 unsigned BitWidth = Mask.getBitWidth();
52 assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) &&
53 "Not integer or pointer type!");
55 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
56 (!V->getType()->isIntOrIntVector() ||
57 V->getType()->getScalarSizeInBits() == BitWidth) &&
58 KnownZero.getBitWidth() == BitWidth &&
59 KnownOne.getBitWidth() == BitWidth &&
60 "V, Mask, KnownOne and KnownZero should have same BitWidth");
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;
68 // Null and aggregate-zero are all-zeros.
69 if (isa<ConstantPointerNull>(V) ||
70 isa<ConstantAggregateZero>(V)) {
75 // Handle a constant vector by taking the intersection of the known bits of
77 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
78 KnownZero.set(); KnownOne.set();
79 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
80 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
81 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
83 KnownZero &= KnownZero2;
84 KnownOne &= KnownOne2;
88 // The address of an aligned GlobalValue has trailing zeros.
89 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
90 unsigned Align = GV->getAlignment();
91 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
92 const Type *ObjectType = GV->getType()->getElementType();
93 // If the object is defined in the current Module, we'll be giving
94 // it the preferred alignment. Otherwise, we have to assume that it
95 // may only have the minimum ABI alignment.
96 if (!GV->isDeclaration() && !GV->mayBeOverridden())
97 Align = TD->getPrefTypeAlignment(ObjectType);
99 Align = TD->getABITypeAlignment(ObjectType);
102 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
103 CountTrailingZeros_32(Align));
109 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
110 // the bits of its aliasee.
111 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
112 if (GA->mayBeOverridden()) {
113 KnownZero.clear(); KnownOne.clear();
115 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
121 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
123 if (Depth == MaxDepth || Mask == 0)
124 return; // Limit search depth.
126 Operator *I = dyn_cast<Operator>(V);
129 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
130 switch (I->getOpcode()) {
132 case Instruction::And: {
133 // If either the LHS or the RHS are Zero, the result is zero.
134 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
135 APInt Mask2(Mask & ~KnownZero);
136 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
138 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
139 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
141 // Output known-1 bits are only known if set in both the LHS & RHS.
142 KnownOne &= KnownOne2;
143 // Output known-0 are known to be clear if zero in either the LHS | RHS.
144 KnownZero |= KnownZero2;
147 case Instruction::Or: {
148 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
149 APInt Mask2(Mask & ~KnownOne);
150 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
152 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
155 // Output known-0 bits are only known if clear in both the LHS & RHS.
156 KnownZero &= KnownZero2;
157 // Output known-1 are known to be set if set in either the LHS | RHS.
158 KnownOne |= KnownOne2;
161 case Instruction::Xor: {
162 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
163 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
166 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
168 // Output known-0 bits are known if clear or set in both the LHS & RHS.
169 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
170 // Output known-1 are known to be set if set in only one of the LHS, RHS.
171 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
172 KnownZero = KnownZeroOut;
175 case Instruction::Mul: {
176 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
177 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
178 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
180 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
181 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
183 // If low bits are zero in either operand, output low known-0 bits.
184 // Also compute a conserative estimate for high known-0 bits.
185 // More trickiness is possible, but this is sufficient for the
186 // interesting case of alignment computation.
188 unsigned TrailZ = KnownZero.countTrailingOnes() +
189 KnownZero2.countTrailingOnes();
190 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
191 KnownZero2.countLeadingOnes(),
192 BitWidth) - BitWidth;
194 TrailZ = std::min(TrailZ, BitWidth);
195 LeadZ = std::min(LeadZ, BitWidth);
196 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
197 APInt::getHighBitsSet(BitWidth, LeadZ);
201 case Instruction::UDiv: {
202 // For the purposes of computing leading zeros we can conservatively
203 // treat a udiv as a logical right shift by the power of 2 known to
204 // be less than the denominator.
205 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
206 ComputeMaskedBits(I->getOperand(0),
207 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
208 unsigned LeadZ = KnownZero2.countLeadingOnes();
212 ComputeMaskedBits(I->getOperand(1),
213 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
214 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
215 if (RHSUnknownLeadingOnes != BitWidth)
216 LeadZ = std::min(BitWidth,
217 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
219 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
222 case Instruction::Select:
223 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
224 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
226 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
227 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
229 // Only known if known in both the LHS and RHS.
230 KnownOne &= KnownOne2;
231 KnownZero &= KnownZero2;
233 case Instruction::FPTrunc:
234 case Instruction::FPExt:
235 case Instruction::FPToUI:
236 case Instruction::FPToSI:
237 case Instruction::SIToFP:
238 case Instruction::UIToFP:
239 return; // Can't work with floating point.
240 case Instruction::PtrToInt:
241 case Instruction::IntToPtr:
242 // We can't handle these if we don't know the pointer size.
244 // FALL THROUGH and handle them the same as zext/trunc.
245 case Instruction::ZExt:
246 case Instruction::Trunc: {
247 const Type *SrcTy = I->getOperand(0)->getType();
249 unsigned SrcBitWidth;
250 // Note that we handle pointer operands here because of inttoptr/ptrtoint
251 // which fall through here.
252 if (isa<PointerType>(SrcTy))
253 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
255 SrcBitWidth = SrcTy->getScalarSizeInBits();
258 MaskIn.zextOrTrunc(SrcBitWidth);
259 KnownZero.zextOrTrunc(SrcBitWidth);
260 KnownOne.zextOrTrunc(SrcBitWidth);
261 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
263 KnownZero.zextOrTrunc(BitWidth);
264 KnownOne.zextOrTrunc(BitWidth);
265 // Any top bits are known to be zero.
266 if (BitWidth > SrcBitWidth)
267 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
270 case Instruction::BitCast: {
271 const Type *SrcTy = I->getOperand(0)->getType();
272 if ((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
273 // TODO: For now, not handling conversions like:
274 // (bitcast i64 %x to <2 x i32>)
275 !isa<VectorType>(I->getType())) {
276 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
282 case Instruction::SExt: {
283 // Compute the bits in the result that are not present in the input.
284 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
287 MaskIn.trunc(SrcBitWidth);
288 KnownZero.trunc(SrcBitWidth);
289 KnownOne.trunc(SrcBitWidth);
290 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
293 KnownZero.zext(BitWidth);
294 KnownOne.zext(BitWidth);
296 // If the sign bit of the input is known set or clear, then we know the
297 // top bits of the result.
298 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
299 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
300 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
301 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
304 case Instruction::Shl:
305 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
307 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
308 APInt Mask2(Mask.lshr(ShiftAmt));
309 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
312 KnownZero <<= ShiftAmt;
313 KnownOne <<= ShiftAmt;
314 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
318 case Instruction::LShr:
319 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
321 // Compute the new bits that are at the top now.
322 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
324 // Unsigned shift right.
325 APInt Mask2(Mask.shl(ShiftAmt));
326 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
328 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
329 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
330 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
331 // high bits known zero.
332 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
336 case Instruction::AShr:
337 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
338 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
339 // Compute the new bits that are at the top now.
340 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
342 // Signed shift right.
343 APInt Mask2(Mask.shl(ShiftAmt));
344 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
346 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
347 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
348 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
350 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
351 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
352 KnownZero |= HighBits;
353 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
354 KnownOne |= HighBits;
358 case Instruction::Sub: {
359 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
360 // We know that the top bits of C-X are clear if X contains less bits
361 // than C (i.e. no wrap-around can happen). For example, 20-X is
362 // positive if we can prove that X is >= 0 and < 16.
363 if (!CLHS->getValue().isNegative()) {
364 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
365 // NLZ can't be BitWidth with no sign bit
366 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
367 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
370 // If all of the MaskV bits are known to be zero, then we know the
371 // output top bits are zero, because we now know that the output is
373 if ((KnownZero2 & MaskV) == MaskV) {
374 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
375 // Top bits known zero.
376 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
382 case Instruction::Add: {
383 // If one of the operands has trailing zeros, than the bits that the
384 // other operand has in those bit positions will be preserved in the
385 // result. For an add, this works with either operand. For a subtract,
386 // this only works if the known zeros are in the right operand.
387 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
388 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
389 BitWidth - Mask.countLeadingZeros());
390 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
392 assert((LHSKnownZero & LHSKnownOne) == 0 &&
393 "Bits known to be one AND zero?");
394 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
396 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
398 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
399 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
401 // Determine which operand has more trailing zeros, and use that
402 // many bits from the other operand.
403 if (LHSKnownZeroOut > RHSKnownZeroOut) {
404 if (I->getOpcode() == Instruction::Add) {
405 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
406 KnownZero |= KnownZero2 & Mask;
407 KnownOne |= KnownOne2 & Mask;
409 // If the known zeros are in the left operand for a subtract,
410 // fall back to the minimum known zeros in both operands.
411 KnownZero |= APInt::getLowBitsSet(BitWidth,
412 std::min(LHSKnownZeroOut,
415 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
416 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
417 KnownZero |= LHSKnownZero & Mask;
418 KnownOne |= LHSKnownOne & Mask;
422 case Instruction::SRem:
423 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
424 APInt RA = Rem->getValue();
425 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
426 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
427 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
428 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
431 // If the sign bit of the first operand is zero, the sign bit of
432 // the result is zero. If the first operand has no one bits below
433 // the second operand's single 1 bit, its sign will be zero.
434 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
435 KnownZero2 |= ~LowBits;
437 KnownZero |= KnownZero2 & Mask;
439 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
443 case Instruction::URem: {
444 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
445 APInt RA = Rem->getValue();
446 if (RA.isPowerOf2()) {
447 APInt LowBits = (RA - 1);
448 APInt Mask2 = LowBits & Mask;
449 KnownZero |= ~LowBits & Mask;
450 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
452 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
457 // Since the result is less than or equal to either operand, any leading
458 // zero bits in either operand must also exist in the result.
459 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
460 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
462 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
465 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
466 KnownZero2.countLeadingOnes());
468 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
472 case Instruction::Alloca: {
473 AllocaInst *AI = cast<AllocaInst>(V);
474 unsigned Align = AI->getAlignment();
475 if (Align == 0 && TD)
476 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
479 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
480 CountTrailingZeros_32(Align));
483 case Instruction::GetElementPtr: {
484 // Analyze all of the subscripts of this getelementptr instruction
485 // to determine if we can prove known low zero bits.
486 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
487 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
488 ComputeMaskedBits(I->getOperand(0), LocalMask,
489 LocalKnownZero, LocalKnownOne, TD, Depth+1);
490 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
492 gep_type_iterator GTI = gep_type_begin(I);
493 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
494 Value *Index = I->getOperand(i);
495 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
496 // Handle struct member offset arithmetic.
498 const StructLayout *SL = TD->getStructLayout(STy);
499 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
500 uint64_t Offset = SL->getElementOffset(Idx);
501 TrailZ = std::min(TrailZ,
502 CountTrailingZeros_64(Offset));
504 // Handle array index arithmetic.
505 const Type *IndexedTy = GTI.getIndexedType();
506 if (!IndexedTy->isSized()) return;
507 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
508 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
509 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
510 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
511 ComputeMaskedBits(Index, LocalMask,
512 LocalKnownZero, LocalKnownOne, TD, Depth+1);
513 TrailZ = std::min(TrailZ,
514 unsigned(CountTrailingZeros_64(TypeSize) +
515 LocalKnownZero.countTrailingOnes()));
519 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
522 case Instruction::PHI: {
523 PHINode *P = cast<PHINode>(I);
524 // Handle the case of a simple two-predecessor recurrence PHI.
525 // There's a lot more that could theoretically be done here, but
526 // this is sufficient to catch some interesting cases.
527 if (P->getNumIncomingValues() == 2) {
528 for (unsigned i = 0; i != 2; ++i) {
529 Value *L = P->getIncomingValue(i);
530 Value *R = P->getIncomingValue(!i);
531 Operator *LU = dyn_cast<Operator>(L);
534 unsigned Opcode = LU->getOpcode();
535 // Check for operations that have the property that if
536 // both their operands have low zero bits, the result
537 // will have low zero bits.
538 if (Opcode == Instruction::Add ||
539 Opcode == Instruction::Sub ||
540 Opcode == Instruction::And ||
541 Opcode == Instruction::Or ||
542 Opcode == Instruction::Mul) {
543 Value *LL = LU->getOperand(0);
544 Value *LR = LU->getOperand(1);
545 // Find a recurrence.
552 // Ok, we have a PHI of the form L op= R. Check for low
554 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
555 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
556 Mask2 = APInt::getLowBitsSet(BitWidth,
557 KnownZero2.countTrailingOnes());
559 // We need to take the minimum number of known bits
560 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
561 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
564 APInt::getLowBitsSet(BitWidth,
565 std::min(KnownZero2.countTrailingOnes(),
566 KnownZero3.countTrailingOnes()));
572 // Otherwise take the unions of the known bit sets of the operands,
573 // taking conservative care to avoid excessive recursion.
574 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
575 KnownZero = APInt::getAllOnesValue(BitWidth);
576 KnownOne = APInt::getAllOnesValue(BitWidth);
577 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
578 // Skip direct self references.
579 if (P->getIncomingValue(i) == P) continue;
581 KnownZero2 = APInt(BitWidth, 0);
582 KnownOne2 = APInt(BitWidth, 0);
583 // Recurse, but cap the recursion to one level, because we don't
584 // want to waste time spinning around in loops.
585 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
586 KnownZero2, KnownOne2, TD, MaxDepth-1);
587 KnownZero &= KnownZero2;
588 KnownOne &= KnownOne2;
589 // If all bits have been ruled out, there's no need to check
591 if (!KnownZero && !KnownOne)
597 case Instruction::Call:
598 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
599 switch (II->getIntrinsicID()) {
601 case Intrinsic::ctpop:
602 case Intrinsic::ctlz:
603 case Intrinsic::cttz: {
604 unsigned LowBits = Log2_32(BitWidth)+1;
605 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
614 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
615 /// this predicate to simplify operations downstream. Mask is known to be zero
616 /// for bits that V cannot have.
618 /// This function is defined on values with integer type, values with pointer
619 /// type (but only if TD is non-null), and vectors of integers. In the case
620 /// where V is a vector, the mask, known zero, and known one values are the
621 /// same width as the vector element, and the bit is set only if it is true
622 /// for all of the elements in the vector.
623 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
624 const TargetData *TD, unsigned Depth) {
625 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
626 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
628 return (KnownZero & Mask) == Mask;
633 /// ComputeNumSignBits - Return the number of times the sign bit of the
634 /// register is replicated into the other bits. We know that at least 1 bit
635 /// is always equal to the sign bit (itself), but other cases can give us
636 /// information. For example, immediately after an "ashr X, 2", we know that
637 /// the top 3 bits are all equal to each other, so we return 3.
639 /// 'Op' must have a scalar integer type.
641 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
643 assert((TD || V->getType()->isIntOrIntVector()) &&
644 "ComputeNumSignBits requires a TargetData object to operate "
645 "on non-integer values!");
646 const Type *Ty = V->getType();
647 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
648 Ty->getScalarSizeInBits();
650 unsigned FirstAnswer = 1;
652 // Note that ConstantInt is handled by the general ComputeMaskedBits case
656 return 1; // Limit search depth.
658 Operator *U = dyn_cast<Operator>(V);
659 switch (Operator::getOpcode(V)) {
661 case Instruction::SExt:
662 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
663 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
665 case Instruction::AShr:
666 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
667 // ashr X, C -> adds C sign bits.
668 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
669 Tmp += C->getZExtValue();
670 if (Tmp > TyBits) Tmp = TyBits;
673 case Instruction::Shl:
674 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
675 // shl destroys sign bits.
676 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
677 if (C->getZExtValue() >= TyBits || // Bad shift.
678 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
679 return Tmp - C->getZExtValue();
682 case Instruction::And:
683 case Instruction::Or:
684 case Instruction::Xor: // NOT is handled here.
685 // Logical binary ops preserve the number of sign bits at the worst.
686 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
688 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
689 FirstAnswer = std::min(Tmp, Tmp2);
690 // We computed what we know about the sign bits as our first
691 // answer. Now proceed to the generic code that uses
692 // ComputeMaskedBits, and pick whichever answer is better.
696 case Instruction::Select:
697 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
698 if (Tmp == 1) return 1; // Early out.
699 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
700 return std::min(Tmp, Tmp2);
702 case Instruction::Add:
703 // Add can have at most one carry bit. Thus we know that the output
704 // is, at worst, one more bit than the inputs.
705 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
706 if (Tmp == 1) return 1; // Early out.
708 // Special case decrementing a value (ADD X, -1):
709 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
710 if (CRHS->isAllOnesValue()) {
711 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
712 APInt Mask = APInt::getAllOnesValue(TyBits);
713 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
716 // If the input is known to be 0 or 1, the output is 0/-1, which is all
718 if ((KnownZero | APInt(TyBits, 1)) == Mask)
721 // If we are subtracting one from a positive number, there is no carry
722 // out of the result.
723 if (KnownZero.isNegative())
727 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
728 if (Tmp2 == 1) return 1;
729 return std::min(Tmp, Tmp2)-1;
732 case Instruction::Sub:
733 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
734 if (Tmp2 == 1) return 1;
737 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
738 if (CLHS->isNullValue()) {
739 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
740 APInt Mask = APInt::getAllOnesValue(TyBits);
741 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
743 // If the input is known to be 0 or 1, the output is 0/-1, which is all
745 if ((KnownZero | APInt(TyBits, 1)) == Mask)
748 // If the input is known to be positive (the sign bit is known clear),
749 // the output of the NEG has the same number of sign bits as the input.
750 if (KnownZero.isNegative())
753 // Otherwise, we treat this like a SUB.
756 // Sub can have at most one carry bit. Thus we know that the output
757 // is, at worst, one more bit than the inputs.
758 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
759 if (Tmp == 1) return 1; // Early out.
760 return std::min(Tmp, Tmp2)-1;
762 case Instruction::Trunc:
763 // FIXME: it's tricky to do anything useful for this, but it is an important
764 // case for targets like X86.
768 // Finally, if we can prove that the top bits of the result are 0's or 1's,
769 // use this information.
770 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
771 APInt Mask = APInt::getAllOnesValue(TyBits);
772 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
774 if (KnownZero.isNegative()) { // sign bit is 0
776 } else if (KnownOne.isNegative()) { // sign bit is 1;
783 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
784 // the number of identical bits in the top of the input value.
786 Mask <<= Mask.getBitWidth()-TyBits;
787 // Return # leading zeros. We use 'min' here in case Val was zero before
788 // shifting. We don't want to return '64' as for an i32 "0".
789 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
792 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
793 /// value is never equal to -0.0.
795 /// NOTE: this function will need to be revisited when we support non-default
798 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
799 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
800 return !CFP->getValueAPF().isNegZero();
803 return 1; // Limit search depth.
805 const Operator *I = dyn_cast<Operator>(V);
806 if (I == 0) return false;
808 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
809 if (I->getOpcode() == Instruction::FAdd &&
810 isa<ConstantFP>(I->getOperand(1)) &&
811 cast<ConstantFP>(I->getOperand(1))->isNullValue())
814 // sitofp and uitofp turn into +0.0 for zero.
815 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
818 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
819 // sqrt(-0.0) = -0.0, no other negative results are possible.
820 if (II->getIntrinsicID() == Intrinsic::sqrt)
821 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
823 if (const CallInst *CI = dyn_cast<CallInst>(I))
824 if (const Function *F = CI->getCalledFunction()) {
825 if (F->isDeclaration()) {
827 if (F->getName() == "abs") return true;
828 // fabs[lf](x) != -0.0
829 if (F->getName() == "fabs") return true;
830 if (F->getName() == "fabsf") return true;
831 if (F->getName() == "fabsl") return true;
832 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
833 F->getName() == "sqrtl")
834 return CannotBeNegativeZero(CI->getOperand(1), Depth+1);
841 // This is the recursive version of BuildSubAggregate. It takes a few different
842 // arguments. Idxs is the index within the nested struct From that we are
843 // looking at now (which is of type IndexedType). IdxSkip is the number of
844 // indices from Idxs that should be left out when inserting into the resulting
845 // struct. To is the result struct built so far, new insertvalue instructions
847 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
848 SmallVector<unsigned, 10> &Idxs,
850 LLVMContext &Context,
851 Instruction *InsertBefore) {
852 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
854 // Save the original To argument so we can modify it
856 // General case, the type indexed by Idxs is a struct
857 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
858 // Process each struct element recursively
861 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
862 Context, InsertBefore);
865 // Couldn't find any inserted value for this index? Cleanup
866 while (PrevTo != OrigTo) {
867 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
868 PrevTo = Del->getAggregateOperand();
869 Del->eraseFromParent();
871 // Stop processing elements
875 // If we succesfully found a value for each of our subaggregates
879 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
880 // the struct's elements had a value that was inserted directly. In the latter
881 // case, perhaps we can't determine each of the subelements individually, but
882 // we might be able to find the complete struct somewhere.
884 // Find the value that is at that particular spot
885 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end(), Context);
890 // Insert the value in the new (sub) aggregrate
891 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
892 Idxs.end(), "tmp", InsertBefore);
895 // This helper takes a nested struct and extracts a part of it (which is again a
896 // struct) into a new value. For example, given the struct:
897 // { a, { b, { c, d }, e } }
898 // and the indices "1, 1" this returns
901 // It does this by inserting an insertvalue for each element in the resulting
902 // struct, as opposed to just inserting a single struct. This will only work if
903 // each of the elements of the substruct are known (ie, inserted into From by an
904 // insertvalue instruction somewhere).
906 // All inserted insertvalue instructions are inserted before InsertBefore
907 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
908 const unsigned *idx_end, LLVMContext &Context,
909 Instruction *InsertBefore) {
910 assert(InsertBefore && "Must have someplace to insert!");
911 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
914 Value *To = UndefValue::get(IndexedType);
915 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
916 unsigned IdxSkip = Idxs.size();
918 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip,
919 Context, InsertBefore);
922 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
923 /// the scalar value indexed is already around as a register, for example if it
924 /// were inserted directly into the aggregrate.
926 /// If InsertBefore is not null, this function will duplicate (modified)
927 /// insertvalues when a part of a nested struct is extracted.
928 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
929 const unsigned *idx_end, LLVMContext &Context,
930 Instruction *InsertBefore) {
931 // Nothing to index? Just return V then (this is useful at the end of our
933 if (idx_begin == idx_end)
935 // We have indices, so V should have an indexable type
936 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
937 && "Not looking at a struct or array?");
938 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
939 && "Invalid indices for type?");
940 const CompositeType *PTy = cast<CompositeType>(V->getType());
942 if (isa<UndefValue>(V))
943 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
946 else if (isa<ConstantAggregateZero>(V))
947 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
950 else if (Constant *C = dyn_cast<Constant>(V)) {
951 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
952 // Recursively process this constant
953 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
954 idx_end, Context, InsertBefore);
955 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
956 // Loop the indices for the insertvalue instruction in parallel with the
958 const unsigned *req_idx = idx_begin;
959 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
960 i != e; ++i, ++req_idx) {
961 if (req_idx == idx_end) {
963 // The requested index identifies a part of a nested aggregate. Handle
964 // this specially. For example,
965 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
966 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
967 // %C = extractvalue {i32, { i32, i32 } } %B, 1
968 // This can be changed into
969 // %A = insertvalue {i32, i32 } undef, i32 10, 0
970 // %C = insertvalue {i32, i32 } %A, i32 11, 1
971 // which allows the unused 0,0 element from the nested struct to be
973 return BuildSubAggregate(V, idx_begin, req_idx,
974 Context, InsertBefore);
976 // We can't handle this without inserting insertvalues
980 // This insert value inserts something else than what we are looking for.
981 // See if the (aggregrate) value inserted into has the value we are
982 // looking for, then.
984 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
985 Context, InsertBefore);
987 // If we end up here, the indices of the insertvalue match with those
988 // requested (though possibly only partially). Now we recursively look at
989 // the inserted value, passing any remaining indices.
990 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
991 Context, InsertBefore);
992 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
993 // If we're extracting a value from an aggregrate that was extracted from
994 // something else, we can extract from that something else directly instead.
995 // However, we will need to chain I's indices with the requested indices.
997 // Calculate the number of indices required
998 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
999 // Allocate some space to put the new indices in
1000 SmallVector<unsigned, 5> Idxs;
1002 // Add indices from the extract value instruction
1003 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1007 // Add requested indices
1008 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1011 assert(Idxs.size() == size
1012 && "Number of indices added not correct?");
1014 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
1015 Context, InsertBefore);
1017 // Otherwise, we don't know (such as, extracting from a function return value
1018 // or load instruction)
1022 /// GetConstantStringInfo - This function computes the length of a
1023 /// null-terminated C string pointed to by V. If successful, it returns true
1024 /// and returns the string in Str. If unsuccessful, it returns false.
1025 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
1027 // If V is NULL then return false;
1028 if (V == NULL) return false;
1030 // Look through bitcast instructions.
1031 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1032 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1034 // If the value is not a GEP instruction nor a constant expression with a
1035 // GEP instruction, then return false because ConstantArray can't occur
1038 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1040 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1041 if (CE->getOpcode() == Instruction::BitCast)
1042 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1043 if (CE->getOpcode() != Instruction::GetElementPtr)
1049 // Make sure the GEP has exactly three arguments.
1050 if (GEP->getNumOperands() != 3)
1053 // Make sure the index-ee is a pointer to array of i8.
1054 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1055 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1056 if (AT == 0 || AT->getElementType() != Type::getInt8Ty(V->getContext()))
1059 // Check to make sure that the first operand of the GEP is an integer and
1060 // has value 0 so that we are sure we're indexing into the initializer.
1061 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1062 if (FirstIdx == 0 || !FirstIdx->isZero())
1065 // If the second index isn't a ConstantInt, then this is a variable index
1066 // into the array. If this occurs, we can't say anything meaningful about
1068 uint64_t StartIdx = 0;
1069 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1070 StartIdx = CI->getZExtValue();
1073 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1077 if (MDString *MDStr = dyn_cast<MDString>(V)) {
1078 Str = MDStr->getString();
1082 // The GEP instruction, constant or instruction, must reference a global
1083 // variable that is a constant and is initialized. The referenced constant
1084 // initializer is the array that we'll use for optimization.
1085 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1086 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1088 Constant *GlobalInit = GV->getInitializer();
1090 // Handle the ConstantAggregateZero case
1091 if (isa<ConstantAggregateZero>(GlobalInit)) {
1092 // This is a degenerate case. The initializer is constant zero so the
1093 // length of the string must be zero.
1098 // Must be a Constant Array
1099 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1101 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
1104 // Get the number of elements in the array
1105 uint64_t NumElts = Array->getType()->getNumElements();
1107 if (Offset > NumElts)
1110 // Traverse the constant array from 'Offset' which is the place the GEP refers
1112 Str.reserve(NumElts-Offset);
1113 for (unsigned i = Offset; i != NumElts; ++i) {
1114 Constant *Elt = Array->getOperand(i);
1115 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1116 if (!CI) // This array isn't suitable, non-int initializer.
1118 if (StopAtNul && CI->isZero())
1119 return true; // we found end of string, success!
1120 Str += (char)CI->getZExtValue();
1123 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.