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;
681 // vector ashr X, <C, C, C, C> -> adds C sign bits
682 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
683 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
684 Tmp += CI->getZExtValue();
685 if (Tmp > TyBits) Tmp = TyBits;
689 case Instruction::Shl:
690 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
691 // shl destroys sign bits.
692 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
693 if (C->getZExtValue() >= TyBits || // Bad shift.
694 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
695 return Tmp - C->getZExtValue();
698 case Instruction::And:
699 case Instruction::Or:
700 case Instruction::Xor: // NOT is handled here.
701 // Logical binary ops preserve the number of sign bits at the worst.
702 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
704 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
705 FirstAnswer = std::min(Tmp, Tmp2);
706 // We computed what we know about the sign bits as our first
707 // answer. Now proceed to the generic code that uses
708 // ComputeMaskedBits, and pick whichever answer is better.
712 case Instruction::Select:
713 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
714 if (Tmp == 1) return 1; // Early out.
715 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
716 return std::min(Tmp, Tmp2);
718 case Instruction::Add:
719 // Add can have at most one carry bit. Thus we know that the output
720 // is, at worst, one more bit than the inputs.
721 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
722 if (Tmp == 1) return 1; // Early out.
724 // Special case decrementing a value (ADD X, -1):
725 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
726 if (CRHS->isAllOnesValue()) {
727 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
728 APInt Mask = APInt::getAllOnesValue(TyBits);
729 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
732 // If the input is known to be 0 or 1, the output is 0/-1, which is all
734 if ((KnownZero | APInt(TyBits, 1)) == Mask)
737 // If we are subtracting one from a positive number, there is no carry
738 // out of the result.
739 if (KnownZero.isNegative())
743 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
744 if (Tmp2 == 1) return 1;
745 return std::min(Tmp, Tmp2)-1;
747 case Instruction::Sub:
748 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
749 if (Tmp2 == 1) return 1;
752 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
753 if (CLHS->isNullValue()) {
754 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
755 APInt Mask = APInt::getAllOnesValue(TyBits);
756 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
758 // If the input is known to be 0 or 1, the output is 0/-1, which is all
760 if ((KnownZero | APInt(TyBits, 1)) == Mask)
763 // If the input is known to be positive (the sign bit is known clear),
764 // the output of the NEG has the same number of sign bits as the input.
765 if (KnownZero.isNegative())
768 // Otherwise, we treat this like a SUB.
771 // Sub can have at most one carry bit. Thus we know that the output
772 // is, at worst, one more bit than the inputs.
773 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
774 if (Tmp == 1) return 1; // Early out.
775 return std::min(Tmp, Tmp2)-1;
777 case Instruction::PHI: {
778 PHINode *PN = cast<PHINode>(U);
779 // Don't analyze large in-degree PHIs.
780 if (PN->getNumIncomingValues() > 4) break;
782 // Take the minimum of all incoming values. This can't infinitely loop
783 // because of our depth threshold.
784 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
785 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
786 if (Tmp == 1) return Tmp;
788 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
793 case Instruction::Trunc:
794 // FIXME: it's tricky to do anything useful for this, but it is an important
795 // case for targets like X86.
799 // Finally, if we can prove that the top bits of the result are 0's or 1's,
800 // use this information.
801 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
802 APInt Mask = APInt::getAllOnesValue(TyBits);
803 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
805 if (KnownZero.isNegative()) { // sign bit is 0
807 } else if (KnownOne.isNegative()) { // sign bit is 1;
814 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
815 // the number of identical bits in the top of the input value.
817 Mask <<= Mask.getBitWidth()-TyBits;
818 // Return # leading zeros. We use 'min' here in case Val was zero before
819 // shifting. We don't want to return '64' as for an i32 "0".
820 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
823 /// ComputeMultiple - This function computes the integer multiple of Base that
824 /// equals V. If successful, it returns true and returns the multiple in
825 /// Multiple. If unsuccessful, it returns false. It looks
826 /// through SExt instructions only if LookThroughSExt is true.
827 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
828 bool LookThroughSExt, unsigned Depth) {
829 const unsigned MaxDepth = 6;
831 assert(V && "No Value?");
832 assert(Depth <= MaxDepth && "Limit Search Depth");
833 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
835 const Type *T = V->getType();
837 ConstantInt *CI = dyn_cast<ConstantInt>(V);
847 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
848 Constant *BaseVal = ConstantInt::get(T, Base);
849 if (CO && CO == BaseVal) {
851 Multiple = ConstantInt::get(T, 1);
855 if (CI && CI->getZExtValue() % Base == 0) {
856 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
860 if (Depth == MaxDepth) return false; // Limit search depth.
862 Operator *I = dyn_cast<Operator>(V);
863 if (!I) return false;
865 switch (I->getOpcode()) {
867 case Instruction::SExt:
868 if (!LookThroughSExt) return false;
869 // otherwise fall through to ZExt
870 case Instruction::ZExt:
871 return ComputeMultiple(I->getOperand(0), Base, Multiple,
872 LookThroughSExt, Depth+1);
873 case Instruction::Shl:
874 case Instruction::Mul: {
875 Value *Op0 = I->getOperand(0);
876 Value *Op1 = I->getOperand(1);
878 if (I->getOpcode() == Instruction::Shl) {
879 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
880 if (!Op1CI) return false;
881 // Turn Op0 << Op1 into Op0 * 2^Op1
882 APInt Op1Int = Op1CI->getValue();
883 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
884 APInt API(Op1Int.getBitWidth(), 0);
885 API.setBit(BitToSet);
886 Op1 = ConstantInt::get(V->getContext(), API);
890 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
891 if (Constant *Op1C = dyn_cast<Constant>(Op1))
892 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
893 if (Op1C->getType()->getPrimitiveSizeInBits() <
894 MulC->getType()->getPrimitiveSizeInBits())
895 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
896 if (Op1C->getType()->getPrimitiveSizeInBits() >
897 MulC->getType()->getPrimitiveSizeInBits())
898 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
900 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
901 Multiple = ConstantExpr::getMul(MulC, Op1C);
905 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
906 if (Mul0CI->getValue() == 1) {
907 // V == Base * Op1, so return Op1
914 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
915 if (Constant *Op0C = dyn_cast<Constant>(Op0))
916 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
917 if (Op0C->getType()->getPrimitiveSizeInBits() <
918 MulC->getType()->getPrimitiveSizeInBits())
919 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
920 if (Op0C->getType()->getPrimitiveSizeInBits() >
921 MulC->getType()->getPrimitiveSizeInBits())
922 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
924 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
925 Multiple = ConstantExpr::getMul(MulC, Op0C);
929 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
930 if (Mul1CI->getValue() == 1) {
931 // V == Base * Op0, so return Op0
939 // We could not determine if V is a multiple of Base.
943 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
944 /// value is never equal to -0.0.
946 /// NOTE: this function will need to be revisited when we support non-default
949 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
950 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
951 return !CFP->getValueAPF().isNegZero();
954 return 1; // Limit search depth.
956 const Operator *I = dyn_cast<Operator>(V);
957 if (I == 0) return false;
959 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
960 if (I->getOpcode() == Instruction::FAdd &&
961 isa<ConstantFP>(I->getOperand(1)) &&
962 cast<ConstantFP>(I->getOperand(1))->isNullValue())
965 // sitofp and uitofp turn into +0.0 for zero.
966 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
969 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
970 // sqrt(-0.0) = -0.0, no other negative results are possible.
971 if (II->getIntrinsicID() == Intrinsic::sqrt)
972 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
974 if (const CallInst *CI = dyn_cast<CallInst>(I))
975 if (const Function *F = CI->getCalledFunction()) {
976 if (F->isDeclaration()) {
978 if (F->getName() == "abs") return true;
979 // fabs[lf](x) != -0.0
980 if (F->getName() == "fabs") return true;
981 if (F->getName() == "fabsf") return true;
982 if (F->getName() == "fabsl") return true;
983 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
984 F->getName() == "sqrtl")
985 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
992 /// isBytewiseValue - If the specified value can be set by repeating the same
993 /// byte in memory, return the i8 value that it is represented with. This is
994 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
995 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
996 /// byte store (e.g. i16 0x1234), return null.
997 Value *llvm::isBytewiseValue(Value *V) {
998 // All byte-wide stores are splatable, even of arbitrary variables.
999 if (V->getType()->isIntegerTy(8)) return V;
1001 // Constant float and double values can be handled as integer values if the
1002 // corresponding integer value is "byteable". An important case is 0.0.
1003 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1004 if (CFP->getType()->isFloatTy())
1005 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1006 if (CFP->getType()->isDoubleTy())
1007 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1008 // Don't handle long double formats, which have strange constraints.
1011 // We can handle constant integers that are power of two in size and a
1012 // multiple of 8 bits.
1013 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1014 unsigned Width = CI->getBitWidth();
1015 if (isPowerOf2_32(Width) && Width > 8) {
1016 // We can handle this value if the recursive binary decomposition is the
1017 // same at all levels.
1018 APInt Val = CI->getValue();
1020 while (Val.getBitWidth() != 8) {
1021 unsigned NextWidth = Val.getBitWidth()/2;
1022 Val2 = Val.lshr(NextWidth);
1023 Val2 = Val2.trunc(Val.getBitWidth()/2);
1024 Val = Val.trunc(Val.getBitWidth()/2);
1026 // If the top/bottom halves aren't the same, reject it.
1030 return ConstantInt::get(V->getContext(), Val);
1034 // A ConstantArray is splatable if all its members are equal and also
1036 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1037 if (CA->getNumOperands() == 0)
1040 Value *Val = isBytewiseValue(CA->getOperand(0));
1044 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1045 if (CA->getOperand(I-1) != CA->getOperand(I))
1051 // Conceptually, we could handle things like:
1052 // %a = zext i8 %X to i16
1053 // %b = shl i16 %a, 8
1054 // %c = or i16 %a, %b
1055 // but until there is an example that actually needs this, it doesn't seem
1056 // worth worrying about.
1061 // This is the recursive version of BuildSubAggregate. It takes a few different
1062 // arguments. Idxs is the index within the nested struct From that we are
1063 // looking at now (which is of type IndexedType). IdxSkip is the number of
1064 // indices from Idxs that should be left out when inserting into the resulting
1065 // struct. To is the result struct built so far, new insertvalue instructions
1067 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
1068 SmallVector<unsigned, 10> &Idxs,
1070 Instruction *InsertBefore) {
1071 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1073 // Save the original To argument so we can modify it
1075 // General case, the type indexed by Idxs is a struct
1076 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1077 // Process each struct element recursively
1080 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1084 // Couldn't find any inserted value for this index? Cleanup
1085 while (PrevTo != OrigTo) {
1086 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1087 PrevTo = Del->getAggregateOperand();
1088 Del->eraseFromParent();
1090 // Stop processing elements
1094 // If we succesfully found a value for each of our subaggregates
1098 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1099 // the struct's elements had a value that was inserted directly. In the latter
1100 // case, perhaps we can't determine each of the subelements individually, but
1101 // we might be able to find the complete struct somewhere.
1103 // Find the value that is at that particular spot
1104 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
1109 // Insert the value in the new (sub) aggregrate
1110 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1111 Idxs.end(), "tmp", InsertBefore);
1114 // This helper takes a nested struct and extracts a part of it (which is again a
1115 // struct) into a new value. For example, given the struct:
1116 // { a, { b, { c, d }, e } }
1117 // and the indices "1, 1" this returns
1120 // It does this by inserting an insertvalue for each element in the resulting
1121 // struct, as opposed to just inserting a single struct. This will only work if
1122 // each of the elements of the substruct are known (ie, inserted into From by an
1123 // insertvalue instruction somewhere).
1125 // All inserted insertvalue instructions are inserted before InsertBefore
1126 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
1127 const unsigned *idx_end,
1128 Instruction *InsertBefore) {
1129 assert(InsertBefore && "Must have someplace to insert!");
1130 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1133 Value *To = UndefValue::get(IndexedType);
1134 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1135 unsigned IdxSkip = Idxs.size();
1137 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
1140 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1141 /// the scalar value indexed is already around as a register, for example if it
1142 /// were inserted directly into the aggregrate.
1144 /// If InsertBefore is not null, this function will duplicate (modified)
1145 /// insertvalues when a part of a nested struct is extracted.
1146 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
1147 const unsigned *idx_end, Instruction *InsertBefore) {
1148 // Nothing to index? Just return V then (this is useful at the end of our
1150 if (idx_begin == idx_end)
1152 // We have indices, so V should have an indexable type
1153 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
1154 && "Not looking at a struct or array?");
1155 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1156 && "Invalid indices for type?");
1157 const CompositeType *PTy = cast<CompositeType>(V->getType());
1159 if (isa<UndefValue>(V))
1160 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
1163 else if (isa<ConstantAggregateZero>(V))
1164 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
1167 else if (Constant *C = dyn_cast<Constant>(V)) {
1168 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1169 // Recursively process this constant
1170 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
1171 idx_end, InsertBefore);
1172 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1173 // Loop the indices for the insertvalue instruction in parallel with the
1174 // requested indices
1175 const unsigned *req_idx = idx_begin;
1176 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1177 i != e; ++i, ++req_idx) {
1178 if (req_idx == idx_end) {
1180 // The requested index identifies a part of a nested aggregate. Handle
1181 // this specially. For example,
1182 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1183 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1184 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1185 // This can be changed into
1186 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1187 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1188 // which allows the unused 0,0 element from the nested struct to be
1190 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
1192 // We can't handle this without inserting insertvalues
1196 // This insert value inserts something else than what we are looking for.
1197 // See if the (aggregrate) value inserted into has the value we are
1198 // looking for, then.
1200 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
1203 // If we end up here, the indices of the insertvalue match with those
1204 // requested (though possibly only partially). Now we recursively look at
1205 // the inserted value, passing any remaining indices.
1206 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
1208 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1209 // If we're extracting a value from an aggregrate that was extracted from
1210 // something else, we can extract from that something else directly instead.
1211 // However, we will need to chain I's indices with the requested indices.
1213 // Calculate the number of indices required
1214 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1215 // Allocate some space to put the new indices in
1216 SmallVector<unsigned, 5> Idxs;
1218 // Add indices from the extract value instruction
1219 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1223 // Add requested indices
1224 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1227 assert(Idxs.size() == size
1228 && "Number of indices added not correct?");
1230 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
1233 // Otherwise, we don't know (such as, extracting from a function return value
1234 // or load instruction)
1238 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1239 /// it can be expressed as a base pointer plus a constant offset. Return the
1240 /// base and offset to the caller.
1241 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1242 const TargetData &TD) {
1243 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1244 if (PtrOp == 0) return Ptr;
1246 // Just look through bitcasts.
1247 if (PtrOp->getOpcode() == Instruction::BitCast)
1248 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1250 // If this is a GEP with constant indices, we can look through it.
1251 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1252 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1254 gep_type_iterator GTI = gep_type_begin(GEP);
1255 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1257 ConstantInt *OpC = cast<ConstantInt>(*I);
1258 if (OpC->isZero()) continue;
1260 // Handle a struct and array indices which add their offset to the pointer.
1261 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1262 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1264 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1265 Offset += OpC->getSExtValue()*Size;
1269 // Re-sign extend from the pointer size if needed to get overflow edge cases
1271 unsigned PtrSize = TD.getPointerSizeInBits();
1273 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1275 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1279 /// GetConstantStringInfo - This function computes the length of a
1280 /// null-terminated C string pointed to by V. If successful, it returns true
1281 /// and returns the string in Str. If unsuccessful, it returns false.
1282 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1285 // If V is NULL then return false;
1286 if (V == NULL) return false;
1288 // Look through bitcast instructions.
1289 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1290 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1292 // If the value is not a GEP instruction nor a constant expression with a
1293 // GEP instruction, then return false because ConstantArray can't occur
1295 const User *GEP = 0;
1296 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1298 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1299 if (CE->getOpcode() == Instruction::BitCast)
1300 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1301 if (CE->getOpcode() != Instruction::GetElementPtr)
1307 // Make sure the GEP has exactly three arguments.
1308 if (GEP->getNumOperands() != 3)
1311 // Make sure the index-ee is a pointer to array of i8.
1312 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1313 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1314 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1317 // Check to make sure that the first operand of the GEP is an integer and
1318 // has value 0 so that we are sure we're indexing into the initializer.
1319 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1320 if (FirstIdx == 0 || !FirstIdx->isZero())
1323 // If the second index isn't a ConstantInt, then this is a variable index
1324 // into the array. If this occurs, we can't say anything meaningful about
1326 uint64_t StartIdx = 0;
1327 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1328 StartIdx = CI->getZExtValue();
1331 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1335 // The GEP instruction, constant or instruction, must reference a global
1336 // variable that is a constant and is initialized. The referenced constant
1337 // initializer is the array that we'll use for optimization.
1338 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1339 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1341 const Constant *GlobalInit = GV->getInitializer();
1343 // Handle the ConstantAggregateZero case
1344 if (isa<ConstantAggregateZero>(GlobalInit)) {
1345 // This is a degenerate case. The initializer is constant zero so the
1346 // length of the string must be zero.
1351 // Must be a Constant Array
1352 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1353 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
1356 // Get the number of elements in the array
1357 uint64_t NumElts = Array->getType()->getNumElements();
1359 if (Offset > NumElts)
1362 // Traverse the constant array from 'Offset' which is the place the GEP refers
1364 Str.reserve(NumElts-Offset);
1365 for (unsigned i = Offset; i != NumElts; ++i) {
1366 const Constant *Elt = Array->getOperand(i);
1367 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1368 if (!CI) // This array isn't suitable, non-int initializer.
1370 if (StopAtNul && CI->isZero())
1371 return true; // we found end of string, success!
1372 Str += (char)CI->getZExtValue();
1375 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1379 // These next two are very similar to the above, but also look through PHI
1381 // TODO: See if we can integrate these two together.
1383 /// GetStringLengthH - If we can compute the length of the string pointed to by
1384 /// the specified pointer, return 'len+1'. If we can't, return 0.
1385 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1386 // Look through noop bitcast instructions.
1387 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1388 return GetStringLengthH(BCI->getOperand(0), PHIs);
1390 // If this is a PHI node, there are two cases: either we have already seen it
1392 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1393 if (!PHIs.insert(PN))
1394 return ~0ULL; // already in the set.
1396 // If it was new, see if all the input strings are the same length.
1397 uint64_t LenSoFar = ~0ULL;
1398 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1399 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1400 if (Len == 0) return 0; // Unknown length -> unknown.
1402 if (Len == ~0ULL) continue;
1404 if (Len != LenSoFar && LenSoFar != ~0ULL)
1405 return 0; // Disagree -> unknown.
1409 // Success, all agree.
1413 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1414 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1415 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1416 if (Len1 == 0) return 0;
1417 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1418 if (Len2 == 0) return 0;
1419 if (Len1 == ~0ULL) return Len2;
1420 if (Len2 == ~0ULL) return Len1;
1421 if (Len1 != Len2) return 0;
1425 // If the value is not a GEP instruction nor a constant expression with a
1426 // GEP instruction, then return unknown.
1428 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1430 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1431 if (CE->getOpcode() != Instruction::GetElementPtr)
1438 // Make sure the GEP has exactly three arguments.
1439 if (GEP->getNumOperands() != 3)
1442 // Check to make sure that the first operand of the GEP is an integer and
1443 // has value 0 so that we are sure we're indexing into the initializer.
1444 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1450 // If the second index isn't a ConstantInt, then this is a variable index
1451 // into the array. If this occurs, we can't say anything meaningful about
1453 uint64_t StartIdx = 0;
1454 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1455 StartIdx = CI->getZExtValue();
1459 // The GEP instruction, constant or instruction, must reference a global
1460 // variable that is a constant and is initialized. The referenced constant
1461 // initializer is the array that we'll use for optimization.
1462 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1463 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1464 GV->mayBeOverridden())
1466 Constant *GlobalInit = GV->getInitializer();
1468 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1469 // initializer is constant zero so the length of the string must be zero.
1470 if (isa<ConstantAggregateZero>(GlobalInit))
1471 return 1; // Len = 0 offset by 1.
1473 // Must be a Constant Array
1474 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1475 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1478 // Get the number of elements in the array
1479 uint64_t NumElts = Array->getType()->getNumElements();
1481 // Traverse the constant array from StartIdx (derived above) which is
1482 // the place the GEP refers to in the array.
1483 for (unsigned i = StartIdx; i != NumElts; ++i) {
1484 Constant *Elt = Array->getOperand(i);
1485 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1486 if (!CI) // This array isn't suitable, non-int initializer.
1489 return i-StartIdx+1; // We found end of string, success!
1492 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1495 /// GetStringLength - If we can compute the length of the string pointed to by
1496 /// the specified pointer, return 'len+1'. If we can't, return 0.
1497 uint64_t llvm::GetStringLength(Value *V) {
1498 if (!V->getType()->isPointerTy()) return 0;
1500 SmallPtrSet<PHINode*, 32> PHIs;
1501 uint64_t Len = GetStringLengthH(V, PHIs);
1502 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1503 // an empty string as a length.
1504 return Len == ~0ULL ? 1 : Len;
1507 Value *llvm::GetUnderlyingObject(Value *V, unsigned MaxLookup) {
1508 if (!V->getType()->isPointerTy())
1510 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1511 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1512 V = GEP->getPointerOperand();
1513 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1514 V = cast<Operator>(V)->getOperand(0);
1515 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1516 if (GA->mayBeOverridden())
1518 V = GA->getAliasee();
1520 // See if InstructionSimplify knows any relevant tricks.
1521 if (Instruction *I = dyn_cast<Instruction>(V))
1522 // TODO: Aquire TargetData and DominatorTree and use them.
1523 if (Value *Simplified = SimplifyInstruction(I, 0, 0)) {
1530 assert(V->getType()->isPointerTy() && "Unexpected operand type!");