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/Analysis/InstructionSimplify.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Operator.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/GetElementPtrTypeIterator.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
31 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
32 /// known to be either zero or one and return them in the KnownZero/KnownOne
33 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
35 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
36 /// we cannot optimize based on the assumption that it is zero without changing
37 /// it to be an explicit zero. If we don't change it to zero, other code could
38 /// optimized based on the contradictory assumption that it is non-zero.
39 /// Because instcombine aggressively folds operations with undef args anyway,
40 /// this won't lose us code quality.
42 /// This function is defined on values with integer type, values with pointer
43 /// type (but only if TD is non-null), and vectors of integers. In the case
44 /// where V is a vector, the mask, known zero, and known one values are the
45 /// same width as the vector element, and the bit is set only if it is true
46 /// for all of the elements in the vector.
47 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
48 APInt &KnownZero, APInt &KnownOne,
49 const TargetData *TD, unsigned Depth) {
50 const unsigned MaxDepth = 6;
51 assert(V && "No Value?");
52 assert(Depth <= MaxDepth && "Limit Search Depth");
53 unsigned BitWidth = Mask.getBitWidth();
54 assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
55 && "Not integer or pointer type!");
57 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
58 (!V->getType()->isIntOrIntVectorTy() ||
59 V->getType()->getScalarSizeInBits() == BitWidth) &&
60 KnownZero.getBitWidth() == BitWidth &&
61 KnownOne.getBitWidth() == BitWidth &&
62 "V, Mask, KnownOne and KnownZero should have same BitWidth");
64 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
65 // We know all of the bits for a constant!
66 KnownOne = CI->getValue() & Mask;
67 KnownZero = ~KnownOne & Mask;
70 // Null and aggregate-zero are all-zeros.
71 if (isa<ConstantPointerNull>(V) ||
72 isa<ConstantAggregateZero>(V)) {
73 KnownOne.clearAllBits();
77 // Handle a constant vector by taking the intersection of the known bits of
79 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
80 KnownZero.setAllBits(); KnownOne.setAllBits();
81 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
82 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
83 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
85 KnownZero &= KnownZero2;
86 KnownOne &= KnownOne2;
90 // The address of an aligned GlobalValue has trailing zeros.
91 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
92 unsigned Align = GV->getAlignment();
93 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
94 const Type *ObjectType = GV->getType()->getElementType();
95 // If the object is defined in the current Module, we'll be giving
96 // it the preferred alignment. Otherwise, we have to assume that it
97 // may only have the minimum ABI alignment.
98 if (!GV->isDeclaration() && !GV->mayBeOverridden())
99 Align = TD->getPrefTypeAlignment(ObjectType);
101 Align = TD->getABITypeAlignment(ObjectType);
104 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
105 CountTrailingZeros_32(Align));
107 KnownZero.clearAllBits();
108 KnownOne.clearAllBits();
111 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
112 // the bits of its aliasee.
113 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
114 if (GA->mayBeOverridden()) {
115 KnownZero.clearAllBits(); KnownOne.clearAllBits();
117 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
123 KnownZero.clearAllBits(); KnownOne.clearAllBits(); // Start out not knowing anything.
125 if (Depth == MaxDepth || Mask == 0)
126 return; // Limit search depth.
128 Operator *I = dyn_cast<Operator>(V);
131 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
132 switch (I->getOpcode()) {
134 case Instruction::And: {
135 // If either the LHS or the RHS are Zero, the result is zero.
136 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
137 APInt Mask2(Mask & ~KnownZero);
138 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
140 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
141 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
143 // Output known-1 bits are only known if set in both the LHS & RHS.
144 KnownOne &= KnownOne2;
145 // Output known-0 are known to be clear if zero in either the LHS | RHS.
146 KnownZero |= KnownZero2;
149 case Instruction::Or: {
150 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
151 APInt Mask2(Mask & ~KnownOne);
152 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
154 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
155 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
157 // Output known-0 bits are only known if clear in both the LHS & RHS.
158 KnownZero &= KnownZero2;
159 // Output known-1 are known to be set if set in either the LHS | RHS.
160 KnownOne |= KnownOne2;
163 case Instruction::Xor: {
164 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
165 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
167 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
168 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
170 // Output known-0 bits are known if clear or set in both the LHS & RHS.
171 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
172 // Output known-1 are known to be set if set in only one of the LHS, RHS.
173 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
174 KnownZero = KnownZeroOut;
177 case Instruction::Mul: {
178 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
179 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
180 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
182 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
183 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
185 // If low bits are zero in either operand, output low known-0 bits.
186 // Also compute a conserative estimate for high known-0 bits.
187 // More trickiness is possible, but this is sufficient for the
188 // interesting case of alignment computation.
189 KnownOne.clearAllBits();
190 unsigned TrailZ = KnownZero.countTrailingOnes() +
191 KnownZero2.countTrailingOnes();
192 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
193 KnownZero2.countLeadingOnes(),
194 BitWidth) - BitWidth;
196 TrailZ = std::min(TrailZ, BitWidth);
197 LeadZ = std::min(LeadZ, BitWidth);
198 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
199 APInt::getHighBitsSet(BitWidth, LeadZ);
203 case Instruction::UDiv: {
204 // For the purposes of computing leading zeros we can conservatively
205 // treat a udiv as a logical right shift by the power of 2 known to
206 // be less than the denominator.
207 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
208 ComputeMaskedBits(I->getOperand(0),
209 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
210 unsigned LeadZ = KnownZero2.countLeadingOnes();
212 KnownOne2.clearAllBits();
213 KnownZero2.clearAllBits();
214 ComputeMaskedBits(I->getOperand(1),
215 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
216 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
217 if (RHSUnknownLeadingOnes != BitWidth)
218 LeadZ = std::min(BitWidth,
219 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
221 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
224 case Instruction::Select:
225 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
226 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
228 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
229 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
231 // Only known if known in both the LHS and RHS.
232 KnownOne &= KnownOne2;
233 KnownZero &= KnownZero2;
235 case Instruction::FPTrunc:
236 case Instruction::FPExt:
237 case Instruction::FPToUI:
238 case Instruction::FPToSI:
239 case Instruction::SIToFP:
240 case Instruction::UIToFP:
241 return; // Can't work with floating point.
242 case Instruction::PtrToInt:
243 case Instruction::IntToPtr:
244 // We can't handle these if we don't know the pointer size.
246 // FALL THROUGH and handle them the same as zext/trunc.
247 case Instruction::ZExt:
248 case Instruction::Trunc: {
249 const Type *SrcTy = I->getOperand(0)->getType();
251 unsigned SrcBitWidth;
252 // Note that we handle pointer operands here because of inttoptr/ptrtoint
253 // which fall through here.
254 if (SrcTy->isPointerTy())
255 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
257 SrcBitWidth = SrcTy->getScalarSizeInBits();
259 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
260 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
261 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
262 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
264 KnownZero = KnownZero.zextOrTrunc(BitWidth);
265 KnownOne = KnownOne.zextOrTrunc(BitWidth);
266 // Any top bits are known to be zero.
267 if (BitWidth > SrcBitWidth)
268 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
271 case Instruction::BitCast: {
272 const Type *SrcTy = I->getOperand(0)->getType();
273 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
274 // TODO: For now, not handling conversions like:
275 // (bitcast i64 %x to <2 x i32>)
276 !I->getType()->isVectorTy()) {
277 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
283 case Instruction::SExt: {
284 // Compute the bits in the result that are not present in the input.
285 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
287 APInt MaskIn = Mask.trunc(SrcBitWidth);
288 KnownZero = KnownZero.trunc(SrcBitWidth);
289 KnownOne = 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 = KnownZero.zext(BitWidth);
294 KnownOne = 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, then 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().abs();
425 if (RA.isPowerOf2()) {
426 APInt LowBits = RA - 1;
427 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
428 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
431 // The low bits of the first operand are unchanged by the srem.
432 KnownZero = KnownZero2 & LowBits;
433 KnownOne = KnownOne2 & LowBits;
435 // If the first operand is non-negative or has all low bits zero, then
436 // the upper bits are all zero.
437 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
438 KnownZero |= ~LowBits;
440 // If the first operand is negative and not all low bits are zero, then
441 // the upper bits are all one.
442 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
443 KnownOne |= ~LowBits;
448 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
452 case Instruction::URem: {
453 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
454 APInt RA = Rem->getValue();
455 if (RA.isPowerOf2()) {
456 APInt LowBits = (RA - 1);
457 APInt Mask2 = LowBits & Mask;
458 KnownZero |= ~LowBits & Mask;
459 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
461 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
466 // Since the result is less than or equal to either operand, any leading
467 // zero bits in either operand must also exist in the result.
468 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
469 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
471 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
474 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
475 KnownZero2.countLeadingOnes());
476 KnownOne.clearAllBits();
477 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
481 case Instruction::Alloca: {
482 AllocaInst *AI = cast<AllocaInst>(V);
483 unsigned Align = AI->getAlignment();
484 if (Align == 0 && TD)
485 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
488 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
489 CountTrailingZeros_32(Align));
492 case Instruction::GetElementPtr: {
493 // Analyze all of the subscripts of this getelementptr instruction
494 // to determine if we can prove known low zero bits.
495 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
496 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
497 ComputeMaskedBits(I->getOperand(0), LocalMask,
498 LocalKnownZero, LocalKnownOne, TD, Depth+1);
499 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
501 gep_type_iterator GTI = gep_type_begin(I);
502 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
503 Value *Index = I->getOperand(i);
504 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
505 // Handle struct member offset arithmetic.
507 const StructLayout *SL = TD->getStructLayout(STy);
508 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
509 uint64_t Offset = SL->getElementOffset(Idx);
510 TrailZ = std::min(TrailZ,
511 CountTrailingZeros_64(Offset));
513 // Handle array index arithmetic.
514 const Type *IndexedTy = GTI.getIndexedType();
515 if (!IndexedTy->isSized()) return;
516 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
517 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
518 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
519 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
520 ComputeMaskedBits(Index, LocalMask,
521 LocalKnownZero, LocalKnownOne, TD, Depth+1);
522 TrailZ = std::min(TrailZ,
523 unsigned(CountTrailingZeros_64(TypeSize) +
524 LocalKnownZero.countTrailingOnes()));
528 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
531 case Instruction::PHI: {
532 PHINode *P = cast<PHINode>(I);
533 // Handle the case of a simple two-predecessor recurrence PHI.
534 // There's a lot more that could theoretically be done here, but
535 // this is sufficient to catch some interesting cases.
536 if (P->getNumIncomingValues() == 2) {
537 for (unsigned i = 0; i != 2; ++i) {
538 Value *L = P->getIncomingValue(i);
539 Value *R = P->getIncomingValue(!i);
540 Operator *LU = dyn_cast<Operator>(L);
543 unsigned Opcode = LU->getOpcode();
544 // Check for operations that have the property that if
545 // both their operands have low zero bits, the result
546 // will have low zero bits.
547 if (Opcode == Instruction::Add ||
548 Opcode == Instruction::Sub ||
549 Opcode == Instruction::And ||
550 Opcode == Instruction::Or ||
551 Opcode == Instruction::Mul) {
552 Value *LL = LU->getOperand(0);
553 Value *LR = LU->getOperand(1);
554 // Find a recurrence.
561 // Ok, we have a PHI of the form L op= R. Check for low
563 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
564 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
565 Mask2 = APInt::getLowBitsSet(BitWidth,
566 KnownZero2.countTrailingOnes());
568 // We need to take the minimum number of known bits
569 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
570 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
573 APInt::getLowBitsSet(BitWidth,
574 std::min(KnownZero2.countTrailingOnes(),
575 KnownZero3.countTrailingOnes()));
581 // Otherwise take the unions of the known bit sets of the operands,
582 // taking conservative care to avoid excessive recursion.
583 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
584 KnownZero = APInt::getAllOnesValue(BitWidth);
585 KnownOne = APInt::getAllOnesValue(BitWidth);
586 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
587 // Skip direct self references.
588 if (P->getIncomingValue(i) == P) continue;
590 KnownZero2 = APInt(BitWidth, 0);
591 KnownOne2 = APInt(BitWidth, 0);
592 // Recurse, but cap the recursion to one level, because we don't
593 // want to waste time spinning around in loops.
594 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
595 KnownZero2, KnownOne2, TD, MaxDepth-1);
596 KnownZero &= KnownZero2;
597 KnownOne &= KnownOne2;
598 // If all bits have been ruled out, there's no need to check
600 if (!KnownZero && !KnownOne)
606 case Instruction::Call:
607 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
608 switch (II->getIntrinsicID()) {
610 case Intrinsic::ctpop:
611 case Intrinsic::ctlz:
612 case Intrinsic::cttz: {
613 unsigned LowBits = Log2_32(BitWidth)+1;
614 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
623 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
624 /// this predicate to simplify operations downstream. Mask is known to be zero
625 /// for bits that V cannot have.
627 /// This function is defined on values with integer type, values with pointer
628 /// type (but only if TD is non-null), and vectors of integers. In the case
629 /// where V is a vector, the mask, known zero, and known one values are the
630 /// same width as the vector element, and the bit is set only if it is true
631 /// for all of the elements in the vector.
632 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
633 const TargetData *TD, unsigned Depth) {
634 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
635 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
637 return (KnownZero & Mask) == Mask;
642 /// ComputeNumSignBits - Return the number of times the sign bit of the
643 /// register is replicated into the other bits. We know that at least 1 bit
644 /// is always equal to the sign bit (itself), but other cases can give us
645 /// information. For example, immediately after an "ashr X, 2", we know that
646 /// the top 3 bits are all equal to each other, so we return 3.
648 /// 'Op' must have a scalar integer type.
650 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
652 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
653 "ComputeNumSignBits requires a TargetData object to operate "
654 "on non-integer values!");
655 const Type *Ty = V->getType();
656 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
657 Ty->getScalarSizeInBits();
659 unsigned FirstAnswer = 1;
661 // Note that ConstantInt is handled by the general ComputeMaskedBits case
665 return 1; // Limit search depth.
667 Operator *U = dyn_cast<Operator>(V);
668 switch (Operator::getOpcode(V)) {
670 case Instruction::SExt:
671 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
672 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
674 case Instruction::AShr:
675 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
676 // ashr X, C -> adds C sign bits.
677 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
678 Tmp += C->getZExtValue();
679 if (Tmp > TyBits) Tmp = TyBits;
682 case Instruction::Shl:
683 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
684 // shl destroys sign bits.
685 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
686 if (C->getZExtValue() >= TyBits || // Bad shift.
687 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
688 return Tmp - C->getZExtValue();
691 case Instruction::And:
692 case Instruction::Or:
693 case Instruction::Xor: // NOT is handled here.
694 // Logical binary ops preserve the number of sign bits at the worst.
695 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
697 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
698 FirstAnswer = std::min(Tmp, Tmp2);
699 // We computed what we know about the sign bits as our first
700 // answer. Now proceed to the generic code that uses
701 // ComputeMaskedBits, and pick whichever answer is better.
705 case Instruction::Select:
706 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
707 if (Tmp == 1) return 1; // Early out.
708 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
709 return std::min(Tmp, Tmp2);
711 case Instruction::Add:
712 // Add can have at most one carry bit. Thus we know that the output
713 // is, at worst, one more bit than the inputs.
714 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
715 if (Tmp == 1) return 1; // Early out.
717 // Special case decrementing a value (ADD X, -1):
718 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
719 if (CRHS->isAllOnesValue()) {
720 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
721 APInt Mask = APInt::getAllOnesValue(TyBits);
722 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
725 // If the input is known to be 0 or 1, the output is 0/-1, which is all
727 if ((KnownZero | APInt(TyBits, 1)) == Mask)
730 // If we are subtracting one from a positive number, there is no carry
731 // out of the result.
732 if (KnownZero.isNegative())
736 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
737 if (Tmp2 == 1) return 1;
738 return std::min(Tmp, Tmp2)-1;
740 case Instruction::Sub:
741 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
742 if (Tmp2 == 1) return 1;
745 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
746 if (CLHS->isNullValue()) {
747 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
748 APInt Mask = APInt::getAllOnesValue(TyBits);
749 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
751 // If the input is known to be 0 or 1, the output is 0/-1, which is all
753 if ((KnownZero | APInt(TyBits, 1)) == Mask)
756 // If the input is known to be positive (the sign bit is known clear),
757 // the output of the NEG has the same number of sign bits as the input.
758 if (KnownZero.isNegative())
761 // Otherwise, we treat this like a SUB.
764 // Sub can have at most one carry bit. Thus we know that the output
765 // is, at worst, one more bit than the inputs.
766 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
767 if (Tmp == 1) return 1; // Early out.
768 return std::min(Tmp, Tmp2)-1;
770 case Instruction::PHI: {
771 PHINode *PN = cast<PHINode>(U);
772 // Don't analyze large in-degree PHIs.
773 if (PN->getNumIncomingValues() > 4) break;
775 // Take the minimum of all incoming values. This can't infinitely loop
776 // because of our depth threshold.
777 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
778 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
779 if (Tmp == 1) return Tmp;
781 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
786 case Instruction::Trunc:
787 // FIXME: it's tricky to do anything useful for this, but it is an important
788 // case for targets like X86.
792 // Finally, if we can prove that the top bits of the result are 0's or 1's,
793 // use this information.
794 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
795 APInt Mask = APInt::getAllOnesValue(TyBits);
796 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
798 if (KnownZero.isNegative()) { // sign bit is 0
800 } else if (KnownOne.isNegative()) { // sign bit is 1;
807 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
808 // the number of identical bits in the top of the input value.
810 Mask <<= Mask.getBitWidth()-TyBits;
811 // Return # leading zeros. We use 'min' here in case Val was zero before
812 // shifting. We don't want to return '64' as for an i32 "0".
813 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
816 /// ComputeMultiple - This function computes the integer multiple of Base that
817 /// equals V. If successful, it returns true and returns the multiple in
818 /// Multiple. If unsuccessful, it returns false. It looks
819 /// through SExt instructions only if LookThroughSExt is true.
820 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
821 bool LookThroughSExt, unsigned Depth) {
822 const unsigned MaxDepth = 6;
824 assert(V && "No Value?");
825 assert(Depth <= MaxDepth && "Limit Search Depth");
826 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
828 const Type *T = V->getType();
830 ConstantInt *CI = dyn_cast<ConstantInt>(V);
840 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
841 Constant *BaseVal = ConstantInt::get(T, Base);
842 if (CO && CO == BaseVal) {
844 Multiple = ConstantInt::get(T, 1);
848 if (CI && CI->getZExtValue() % Base == 0) {
849 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
853 if (Depth == MaxDepth) return false; // Limit search depth.
855 Operator *I = dyn_cast<Operator>(V);
856 if (!I) return false;
858 switch (I->getOpcode()) {
860 case Instruction::SExt:
861 if (!LookThroughSExt) return false;
862 // otherwise fall through to ZExt
863 case Instruction::ZExt:
864 return ComputeMultiple(I->getOperand(0), Base, Multiple,
865 LookThroughSExt, Depth+1);
866 case Instruction::Shl:
867 case Instruction::Mul: {
868 Value *Op0 = I->getOperand(0);
869 Value *Op1 = I->getOperand(1);
871 if (I->getOpcode() == Instruction::Shl) {
872 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
873 if (!Op1CI) return false;
874 // Turn Op0 << Op1 into Op0 * 2^Op1
875 APInt Op1Int = Op1CI->getValue();
876 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
877 APInt API(Op1Int.getBitWidth(), 0);
878 API.setBit(BitToSet);
879 Op1 = ConstantInt::get(V->getContext(), API);
883 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
884 if (Constant *Op1C = dyn_cast<Constant>(Op1))
885 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
886 if (Op1C->getType()->getPrimitiveSizeInBits() <
887 MulC->getType()->getPrimitiveSizeInBits())
888 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
889 if (Op1C->getType()->getPrimitiveSizeInBits() >
890 MulC->getType()->getPrimitiveSizeInBits())
891 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
893 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
894 Multiple = ConstantExpr::getMul(MulC, Op1C);
898 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
899 if (Mul0CI->getValue() == 1) {
900 // V == Base * Op1, so return Op1
907 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
908 if (Constant *Op0C = dyn_cast<Constant>(Op0))
909 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
910 if (Op0C->getType()->getPrimitiveSizeInBits() <
911 MulC->getType()->getPrimitiveSizeInBits())
912 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
913 if (Op0C->getType()->getPrimitiveSizeInBits() >
914 MulC->getType()->getPrimitiveSizeInBits())
915 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
917 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
918 Multiple = ConstantExpr::getMul(MulC, Op0C);
922 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
923 if (Mul1CI->getValue() == 1) {
924 // V == Base * Op0, so return Op0
932 // We could not determine if V is a multiple of Base.
936 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
937 /// value is never equal to -0.0.
939 /// NOTE: this function will need to be revisited when we support non-default
942 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
943 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
944 return !CFP->getValueAPF().isNegZero();
947 return 1; // Limit search depth.
949 const Operator *I = dyn_cast<Operator>(V);
950 if (I == 0) return false;
952 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
953 if (I->getOpcode() == Instruction::FAdd &&
954 isa<ConstantFP>(I->getOperand(1)) &&
955 cast<ConstantFP>(I->getOperand(1))->isNullValue())
958 // sitofp and uitofp turn into +0.0 for zero.
959 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
962 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
963 // sqrt(-0.0) = -0.0, no other negative results are possible.
964 if (II->getIntrinsicID() == Intrinsic::sqrt)
965 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
967 if (const CallInst *CI = dyn_cast<CallInst>(I))
968 if (const Function *F = CI->getCalledFunction()) {
969 if (F->isDeclaration()) {
971 if (F->getName() == "abs") return true;
972 // fabs[lf](x) != -0.0
973 if (F->getName() == "fabs") return true;
974 if (F->getName() == "fabsf") return true;
975 if (F->getName() == "fabsl") return true;
976 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
977 F->getName() == "sqrtl")
978 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
985 // This is the recursive version of BuildSubAggregate. It takes a few different
986 // arguments. Idxs is the index within the nested struct From that we are
987 // looking at now (which is of type IndexedType). IdxSkip is the number of
988 // indices from Idxs that should be left out when inserting into the resulting
989 // struct. To is the result struct built so far, new insertvalue instructions
991 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
992 SmallVector<unsigned, 10> &Idxs,
994 Instruction *InsertBefore) {
995 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
997 // Save the original To argument so we can modify it
999 // General case, the type indexed by Idxs is a struct
1000 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1001 // Process each struct element recursively
1004 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1008 // Couldn't find any inserted value for this index? Cleanup
1009 while (PrevTo != OrigTo) {
1010 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1011 PrevTo = Del->getAggregateOperand();
1012 Del->eraseFromParent();
1014 // Stop processing elements
1018 // If we succesfully found a value for each of our subaggregates
1022 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1023 // the struct's elements had a value that was inserted directly. In the latter
1024 // case, perhaps we can't determine each of the subelements individually, but
1025 // we might be able to find the complete struct somewhere.
1027 // Find the value that is at that particular spot
1028 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
1033 // Insert the value in the new (sub) aggregrate
1034 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1035 Idxs.end(), "tmp", InsertBefore);
1038 // This helper takes a nested struct and extracts a part of it (which is again a
1039 // struct) into a new value. For example, given the struct:
1040 // { a, { b, { c, d }, e } }
1041 // and the indices "1, 1" this returns
1044 // It does this by inserting an insertvalue for each element in the resulting
1045 // struct, as opposed to just inserting a single struct. This will only work if
1046 // each of the elements of the substruct are known (ie, inserted into From by an
1047 // insertvalue instruction somewhere).
1049 // All inserted insertvalue instructions are inserted before InsertBefore
1050 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
1051 const unsigned *idx_end,
1052 Instruction *InsertBefore) {
1053 assert(InsertBefore && "Must have someplace to insert!");
1054 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1057 Value *To = UndefValue::get(IndexedType);
1058 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1059 unsigned IdxSkip = Idxs.size();
1061 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1064 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1065 /// the scalar value indexed is already around as a register, for example if it
1066 /// were inserted directly into the aggregrate.
1068 /// If InsertBefore is not null, this function will duplicate (modified)
1069 /// insertvalues when a part of a nested struct is extracted.
1070 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
1071 const unsigned *idx_end, Instruction *InsertBefore) {
1072 // Nothing to index? Just return V then (this is useful at the end of our
1074 if (idx_begin == idx_end)
1076 // We have indices, so V should have an indexable type
1077 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
1078 && "Not looking at a struct or array?");
1079 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1080 && "Invalid indices for type?");
1081 const CompositeType *PTy = cast<CompositeType>(V->getType());
1083 if (isa<UndefValue>(V))
1084 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
1087 else if (isa<ConstantAggregateZero>(V))
1088 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
1091 else if (Constant *C = dyn_cast<Constant>(V)) {
1092 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1093 // Recursively process this constant
1094 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
1095 idx_end, InsertBefore);
1096 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1097 // Loop the indices for the insertvalue instruction in parallel with the
1098 // requested indices
1099 const unsigned *req_idx = idx_begin;
1100 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1101 i != e; ++i, ++req_idx) {
1102 if (req_idx == idx_end) {
1104 // The requested index identifies a part of a nested aggregate. Handle
1105 // this specially. For example,
1106 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1107 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1108 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1109 // This can be changed into
1110 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1111 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1112 // which allows the unused 0,0 element from the nested struct to be
1114 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
1116 // We can't handle this without inserting insertvalues
1120 // This insert value inserts something else than what we are looking for.
1121 // See if the (aggregrate) value inserted into has the value we are
1122 // looking for, then.
1124 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
1127 // If we end up here, the indices of the insertvalue match with those
1128 // requested (though possibly only partially). Now we recursively look at
1129 // the inserted value, passing any remaining indices.
1130 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
1132 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1133 // If we're extracting a value from an aggregrate that was extracted from
1134 // something else, we can extract from that something else directly instead.
1135 // However, we will need to chain I's indices with the requested indices.
1137 // Calculate the number of indices required
1138 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1139 // Allocate some space to put the new indices in
1140 SmallVector<unsigned, 5> Idxs;
1142 // Add indices from the extract value instruction
1143 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1147 // Add requested indices
1148 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1151 assert(Idxs.size() == size
1152 && "Number of indices added not correct?");
1154 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
1157 // Otherwise, we don't know (such as, extracting from a function return value
1158 // or load instruction)
1162 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1163 /// it can be expressed as a base pointer plus a constant offset. Return the
1164 /// base and offset to the caller.
1165 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1166 const TargetData &TD) {
1167 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1168 if (PtrOp == 0) return Ptr;
1170 // Just look through bitcasts.
1171 if (PtrOp->getOpcode() == Instruction::BitCast)
1172 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1174 // If this is a GEP with constant indices, we can look through it.
1175 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1176 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1178 gep_type_iterator GTI = gep_type_begin(GEP);
1179 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1181 ConstantInt *OpC = cast<ConstantInt>(*I);
1182 if (OpC->isZero()) continue;
1184 // Handle a struct and array indices which add their offset to the pointer.
1185 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1186 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1188 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1189 Offset += OpC->getSExtValue()*Size;
1193 // Re-sign extend from the pointer size if needed to get overflow edge cases
1195 unsigned PtrSize = TD.getPointerSizeInBits();
1197 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1199 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1203 /// GetConstantStringInfo - This function computes the length of a
1204 /// null-terminated C string pointed to by V. If successful, it returns true
1205 /// and returns the string in Str. If unsuccessful, it returns false.
1206 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1209 // If V is NULL then return false;
1210 if (V == NULL) return false;
1212 // Look through bitcast instructions.
1213 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1214 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1216 // If the value is not a GEP instruction nor a constant expression with a
1217 // GEP instruction, then return false because ConstantArray can't occur
1219 const User *GEP = 0;
1220 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1222 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1223 if (CE->getOpcode() == Instruction::BitCast)
1224 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1225 if (CE->getOpcode() != Instruction::GetElementPtr)
1231 // Make sure the GEP has exactly three arguments.
1232 if (GEP->getNumOperands() != 3)
1235 // Make sure the index-ee is a pointer to array of i8.
1236 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1237 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1238 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1241 // Check to make sure that the first operand of the GEP is an integer and
1242 // has value 0 so that we are sure we're indexing into the initializer.
1243 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1244 if (FirstIdx == 0 || !FirstIdx->isZero())
1247 // If the second index isn't a ConstantInt, then this is a variable index
1248 // into the array. If this occurs, we can't say anything meaningful about
1250 uint64_t StartIdx = 0;
1251 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1252 StartIdx = CI->getZExtValue();
1255 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1259 // The GEP instruction, constant or instruction, must reference a global
1260 // variable that is a constant and is initialized. The referenced constant
1261 // initializer is the array that we'll use for optimization.
1262 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1263 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1265 const Constant *GlobalInit = GV->getInitializer();
1267 // Handle the ConstantAggregateZero case
1268 if (isa<ConstantAggregateZero>(GlobalInit)) {
1269 // This is a degenerate case. The initializer is constant zero so the
1270 // length of the string must be zero.
1275 // Must be a Constant Array
1276 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1277 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
1280 // Get the number of elements in the array
1281 uint64_t NumElts = Array->getType()->getNumElements();
1283 if (Offset > NumElts)
1286 // Traverse the constant array from 'Offset' which is the place the GEP refers
1288 Str.reserve(NumElts-Offset);
1289 for (unsigned i = Offset; i != NumElts; ++i) {
1290 const Constant *Elt = Array->getOperand(i);
1291 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1292 if (!CI) // This array isn't suitable, non-int initializer.
1294 if (StopAtNul && CI->isZero())
1295 return true; // we found end of string, success!
1296 Str += (char)CI->getZExtValue();
1299 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1303 // These next two are very similar to the above, but also look through PHI
1305 // TODO: See if we can integrate these two together.
1307 /// GetStringLengthH - If we can compute the length of the string pointed to by
1308 /// the specified pointer, return 'len+1'. If we can't, return 0.
1309 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1310 // Look through noop bitcast instructions.
1311 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1312 return GetStringLengthH(BCI->getOperand(0), PHIs);
1314 // If this is a PHI node, there are two cases: either we have already seen it
1316 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1317 if (!PHIs.insert(PN))
1318 return ~0ULL; // already in the set.
1320 // If it was new, see if all the input strings are the same length.
1321 uint64_t LenSoFar = ~0ULL;
1322 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1323 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1324 if (Len == 0) return 0; // Unknown length -> unknown.
1326 if (Len == ~0ULL) continue;
1328 if (Len != LenSoFar && LenSoFar != ~0ULL)
1329 return 0; // Disagree -> unknown.
1333 // Success, all agree.
1337 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1338 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1339 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1340 if (Len1 == 0) return 0;
1341 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1342 if (Len2 == 0) return 0;
1343 if (Len1 == ~0ULL) return Len2;
1344 if (Len2 == ~0ULL) return Len1;
1345 if (Len1 != Len2) return 0;
1349 // If the value is not a GEP instruction nor a constant expression with a
1350 // GEP instruction, then return unknown.
1352 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1354 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1355 if (CE->getOpcode() != Instruction::GetElementPtr)
1362 // Make sure the GEP has exactly three arguments.
1363 if (GEP->getNumOperands() != 3)
1366 // Check to make sure that the first operand of the GEP is an integer and
1367 // has value 0 so that we are sure we're indexing into the initializer.
1368 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1374 // If the second index isn't a ConstantInt, then this is a variable index
1375 // into the array. If this occurs, we can't say anything meaningful about
1377 uint64_t StartIdx = 0;
1378 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1379 StartIdx = CI->getZExtValue();
1383 // The GEP instruction, constant or instruction, must reference a global
1384 // variable that is a constant and is initialized. The referenced constant
1385 // initializer is the array that we'll use for optimization.
1386 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1387 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1388 GV->mayBeOverridden())
1390 Constant *GlobalInit = GV->getInitializer();
1392 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1393 // initializer is constant zero so the length of the string must be zero.
1394 if (isa<ConstantAggregateZero>(GlobalInit))
1395 return 1; // Len = 0 offset by 1.
1397 // Must be a Constant Array
1398 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1399 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1402 // Get the number of elements in the array
1403 uint64_t NumElts = Array->getType()->getNumElements();
1405 // Traverse the constant array from StartIdx (derived above) which is
1406 // the place the GEP refers to in the array.
1407 for (unsigned i = StartIdx; i != NumElts; ++i) {
1408 Constant *Elt = Array->getOperand(i);
1409 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1410 if (!CI) // This array isn't suitable, non-int initializer.
1413 return i-StartIdx+1; // We found end of string, success!
1416 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1419 /// GetStringLength - If we can compute the length of the string pointed to by
1420 /// the specified pointer, return 'len+1'. If we can't, return 0.
1421 uint64_t llvm::GetStringLength(Value *V) {
1422 if (!V->getType()->isPointerTy()) return 0;
1424 SmallPtrSet<PHINode*, 32> PHIs;
1425 uint64_t Len = GetStringLengthH(V, PHIs);
1426 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1427 // an empty string as a length.
1428 return Len == ~0ULL ? 1 : Len;
1431 Value *llvm::GetUnderlyingObject(Value *V, unsigned MaxLookup) {
1432 if (!V->getType()->isPointerTy())
1434 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1435 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1436 V = GEP->getPointerOperand();
1437 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1438 V = cast<Operator>(V)->getOperand(0);
1439 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1440 if (GA->mayBeOverridden())
1442 V = GA->getAliasee();
1444 // See if InstructionSimplify knows any relevant tricks.
1445 if (Instruction *I = dyn_cast<Instruction>(V))
1446 // TODO: Aquire TargetData and DominatorTree and use them.
1447 if (Value *Simplified = SimplifyInstruction(I, 0, 0)) {
1454 assert(V->getType()->isPointerTy() && "Unexpected operand type!");