Fixed some bugs.
[llvm/zpu.git] / lib / Analysis / ValueTracking.cpp
blob181c9b01980c33c7bdbff2fc76064c60470bfc61
1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines that help analyze properties that chains of
11 // computations have.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/GlobalAlias.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Operator.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/GetElementPtrTypeIterator.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include <cstring>
28 using namespace llvm;
30 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
31 /// known to be either zero or one and return them in the KnownZero/KnownOne
32 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
33 /// processing.
34 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
35 /// we cannot optimize based on the assumption that it is zero without changing
36 /// it to be an explicit zero. If we don't change it to zero, other code could
37 /// optimized based on the contradictory assumption that it is non-zero.
38 /// Because instcombine aggressively folds operations with undef args anyway,
39 /// this won't lose us code quality.
40 ///
41 /// This function is defined on values with integer type, values with pointer
42 /// type (but only if TD is non-null), and vectors of integers. In the case
43 /// where V is a vector, the mask, known zero, and known one values are the
44 /// same width as the vector element, and the bit is set only if it is true
45 /// for all of the elements in the vector.
46 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
47 APInt &KnownZero, APInt &KnownOne,
48 const TargetData *TD, unsigned Depth) {
49 const unsigned MaxDepth = 6;
50 assert(V && "No Value?");
51 assert(Depth <= MaxDepth && "Limit Search Depth");
52 unsigned BitWidth = Mask.getBitWidth();
53 assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
54 && "Not integer or pointer type!");
55 assert((!TD ||
56 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
57 (!V->getType()->isIntOrIntVectorTy() ||
58 V->getType()->getScalarSizeInBits() == BitWidth) &&
59 KnownZero.getBitWidth() == BitWidth &&
60 KnownOne.getBitWidth() == BitWidth &&
61 "V, Mask, KnownOne and KnownZero should have same BitWidth");
63 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
64 // We know all of the bits for a constant!
65 KnownOne = CI->getValue() & Mask;
66 KnownZero = ~KnownOne & Mask;
67 return;
69 // Null and aggregate-zero are all-zeros.
70 if (isa<ConstantPointerNull>(V) ||
71 isa<ConstantAggregateZero>(V)) {
72 KnownOne.clear();
73 KnownZero = Mask;
74 return;
76 // Handle a constant vector by taking the intersection of the known bits of
77 // each element.
78 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
79 KnownZero.set(); KnownOne.set();
80 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
81 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
82 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
83 TD, Depth);
84 KnownZero &= KnownZero2;
85 KnownOne &= KnownOne2;
87 return;
89 // The address of an aligned GlobalValue has trailing zeros.
90 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
91 unsigned Align = GV->getAlignment();
92 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
93 const Type *ObjectType = GV->getType()->getElementType();
94 // If the object is defined in the current Module, we'll be giving
95 // it the preferred alignment. Otherwise, we have to assume that it
96 // may only have the minimum ABI alignment.
97 if (!GV->isDeclaration() && !GV->mayBeOverridden())
98 Align = TD->getPrefTypeAlignment(ObjectType);
99 else
100 Align = TD->getABITypeAlignment(ObjectType);
102 if (Align > 0)
103 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
104 CountTrailingZeros_32(Align));
105 else
106 KnownZero.clear();
107 KnownOne.clear();
108 return;
110 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
111 // the bits of its aliasee.
112 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
113 if (GA->mayBeOverridden()) {
114 KnownZero.clear(); KnownOne.clear();
115 } else {
116 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
117 TD, Depth+1);
119 return;
122 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
124 if (Depth == MaxDepth || Mask == 0)
125 return; // Limit search depth.
127 Operator *I = dyn_cast<Operator>(V);
128 if (!I) return;
130 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
131 switch (I->getOpcode()) {
132 default: break;
133 case Instruction::And: {
134 // If either the LHS or the RHS are Zero, the result is zero.
135 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
136 APInt Mask2(Mask & ~KnownZero);
137 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
138 Depth+1);
139 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
140 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
142 // Output known-1 bits are only known if set in both the LHS & RHS.
143 KnownOne &= KnownOne2;
144 // Output known-0 are known to be clear if zero in either the LHS | RHS.
145 KnownZero |= KnownZero2;
146 return;
148 case Instruction::Or: {
149 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
150 APInt Mask2(Mask & ~KnownOne);
151 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
152 Depth+1);
153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
154 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
156 // Output known-0 bits are only known if clear in both the LHS & RHS.
157 KnownZero &= KnownZero2;
158 // Output known-1 are known to be set if set in either the LHS | RHS.
159 KnownOne |= KnownOne2;
160 return;
162 case Instruction::Xor: {
163 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
164 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
165 Depth+1);
166 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
167 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
169 // Output known-0 bits are known if clear or set in both the LHS & RHS.
170 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
171 // Output known-1 are known to be set if set in only one of the LHS, RHS.
172 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
173 KnownZero = KnownZeroOut;
174 return;
176 case Instruction::Mul: {
177 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
178 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
179 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
180 Depth+1);
181 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
182 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
184 // If low bits are zero in either operand, output low known-0 bits.
185 // Also compute a conserative estimate for high known-0 bits.
186 // More trickiness is possible, but this is sufficient for the
187 // interesting case of alignment computation.
188 KnownOne.clear();
189 unsigned TrailZ = KnownZero.countTrailingOnes() +
190 KnownZero2.countTrailingOnes();
191 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
192 KnownZero2.countLeadingOnes(),
193 BitWidth) - BitWidth;
195 TrailZ = std::min(TrailZ, BitWidth);
196 LeadZ = std::min(LeadZ, BitWidth);
197 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
198 APInt::getHighBitsSet(BitWidth, LeadZ);
199 KnownZero &= Mask;
200 return;
202 case Instruction::UDiv: {
203 // For the purposes of computing leading zeros we can conservatively
204 // treat a udiv as a logical right shift by the power of 2 known to
205 // be less than the denominator.
206 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
207 ComputeMaskedBits(I->getOperand(0),
208 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
209 unsigned LeadZ = KnownZero2.countLeadingOnes();
211 KnownOne2.clear();
212 KnownZero2.clear();
213 ComputeMaskedBits(I->getOperand(1),
214 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
215 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
216 if (RHSUnknownLeadingOnes != BitWidth)
217 LeadZ = std::min(BitWidth,
218 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
220 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
221 return;
223 case Instruction::Select:
224 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
225 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
226 Depth+1);
227 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
228 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
230 // Only known if known in both the LHS and RHS.
231 KnownOne &= KnownOne2;
232 KnownZero &= KnownZero2;
233 return;
234 case Instruction::FPTrunc:
235 case Instruction::FPExt:
236 case Instruction::FPToUI:
237 case Instruction::FPToSI:
238 case Instruction::SIToFP:
239 case Instruction::UIToFP:
240 return; // Can't work with floating point.
241 case Instruction::PtrToInt:
242 case Instruction::IntToPtr:
243 // We can't handle these if we don't know the pointer size.
244 if (!TD) return;
245 // FALL THROUGH and handle them the same as zext/trunc.
246 case Instruction::ZExt:
247 case Instruction::Trunc: {
248 const Type *SrcTy = I->getOperand(0)->getType();
250 unsigned SrcBitWidth;
251 // Note that we handle pointer operands here because of inttoptr/ptrtoint
252 // which fall through here.
253 if (SrcTy->isPointerTy())
254 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
255 else
256 SrcBitWidth = SrcTy->getScalarSizeInBits();
258 APInt MaskIn(Mask);
259 MaskIn.zextOrTrunc(SrcBitWidth);
260 KnownZero.zextOrTrunc(SrcBitWidth);
261 KnownOne.zextOrTrunc(SrcBitWidth);
262 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
263 Depth+1);
264 KnownZero.zextOrTrunc(BitWidth);
265 KnownOne.zextOrTrunc(BitWidth);
266 // Any top bits are known to be zero.
267 if (BitWidth > SrcBitWidth)
268 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
269 return;
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,
278 Depth+1);
279 return;
281 break;
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);
288 MaskIn.trunc(SrcBitWidth);
289 KnownZero.trunc(SrcBitWidth);
290 KnownOne.trunc(SrcBitWidth);
291 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
292 Depth+1);
293 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
294 KnownZero.zext(BitWidth);
295 KnownOne.zext(BitWidth);
297 // If the sign bit of the input is known set or clear, then we know the
298 // top bits of the result.
299 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
300 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
301 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
302 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
303 return;
305 case Instruction::Shl:
306 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
308 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
309 APInt Mask2(Mask.lshr(ShiftAmt));
310 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
311 Depth+1);
312 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
313 KnownZero <<= ShiftAmt;
314 KnownOne <<= ShiftAmt;
315 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
316 return;
318 break;
319 case Instruction::LShr:
320 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
321 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
322 // Compute the new bits that are at the top now.
323 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
325 // Unsigned shift right.
326 APInt Mask2(Mask.shl(ShiftAmt));
327 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
328 Depth+1);
329 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
330 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
331 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
332 // high bits known zero.
333 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
334 return;
336 break;
337 case Instruction::AShr:
338 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
339 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
340 // Compute the new bits that are at the top now.
341 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
343 // Signed shift right.
344 APInt Mask2(Mask.shl(ShiftAmt));
345 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
346 Depth+1);
347 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
348 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
349 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
351 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
352 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
353 KnownZero |= HighBits;
354 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
355 KnownOne |= HighBits;
356 return;
358 break;
359 case Instruction::Sub: {
360 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
361 // We know that the top bits of C-X are clear if X contains less bits
362 // than C (i.e. no wrap-around can happen). For example, 20-X is
363 // positive if we can prove that X is >= 0 and < 16.
364 if (!CLHS->getValue().isNegative()) {
365 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
366 // NLZ can't be BitWidth with no sign bit
367 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
368 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
369 TD, Depth+1);
371 // If all of the MaskV bits are known to be zero, then we know the
372 // output top bits are zero, because we now know that the output is
373 // from [0-C].
374 if ((KnownZero2 & MaskV) == MaskV) {
375 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
376 // Top bits known zero.
377 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
382 // fall through
383 case Instruction::Add: {
384 // If one of the operands has trailing zeros, then the bits that the
385 // other operand has in those bit positions will be preserved in the
386 // result. For an add, this works with either operand. For a subtract,
387 // this only works if the known zeros are in the right operand.
388 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
389 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
390 BitWidth - Mask.countLeadingZeros());
391 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
392 Depth+1);
393 assert((LHSKnownZero & LHSKnownOne) == 0 &&
394 "Bits known to be one AND zero?");
395 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
397 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
398 Depth+1);
399 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
400 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
402 // Determine which operand has more trailing zeros, and use that
403 // many bits from the other operand.
404 if (LHSKnownZeroOut > RHSKnownZeroOut) {
405 if (I->getOpcode() == Instruction::Add) {
406 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
407 KnownZero |= KnownZero2 & Mask;
408 KnownOne |= KnownOne2 & Mask;
409 } else {
410 // If the known zeros are in the left operand for a subtract,
411 // fall back to the minimum known zeros in both operands.
412 KnownZero |= APInt::getLowBitsSet(BitWidth,
413 std::min(LHSKnownZeroOut,
414 RHSKnownZeroOut));
416 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
417 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
418 KnownZero |= LHSKnownZero & Mask;
419 KnownOne |= LHSKnownOne & Mask;
421 return;
423 case Instruction::SRem:
424 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
425 APInt RA = Rem->getValue().abs();
426 if (RA.isPowerOf2()) {
427 APInt LowBits = RA - 1;
428 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
429 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
430 Depth+1);
432 // The low bits of the first operand are unchanged by the srem.
433 KnownZero = KnownZero2 & LowBits;
434 KnownOne = KnownOne2 & LowBits;
436 // If the first operand is non-negative or has all low bits zero, then
437 // the upper bits are all zero.
438 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
439 KnownZero |= ~LowBits;
441 // If the first operand is negative and not all low bits are zero, then
442 // the upper bits are all one.
443 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
444 KnownOne |= ~LowBits;
446 KnownZero &= Mask;
447 KnownOne &= Mask;
449 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
452 break;
453 case Instruction::URem: {
454 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
455 APInt RA = Rem->getValue();
456 if (RA.isPowerOf2()) {
457 APInt LowBits = (RA - 1);
458 APInt Mask2 = LowBits & Mask;
459 KnownZero |= ~LowBits & Mask;
460 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
461 Depth+1);
462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
463 break;
467 // Since the result is less than or equal to either operand, any leading
468 // zero bits in either operand must also exist in the result.
469 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
470 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
471 TD, Depth+1);
472 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
473 TD, Depth+1);
475 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
476 KnownZero2.countLeadingOnes());
477 KnownOne.clear();
478 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
479 break;
482 case Instruction::Alloca: {
483 AllocaInst *AI = cast<AllocaInst>(V);
484 unsigned Align = AI->getAlignment();
485 if (Align == 0 && TD)
486 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
488 if (Align > 0)
489 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
490 CountTrailingZeros_32(Align));
491 break;
493 case Instruction::GetElementPtr: {
494 // Analyze all of the subscripts of this getelementptr instruction
495 // to determine if we can prove known low zero bits.
496 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
497 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
498 ComputeMaskedBits(I->getOperand(0), LocalMask,
499 LocalKnownZero, LocalKnownOne, TD, Depth+1);
500 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
502 gep_type_iterator GTI = gep_type_begin(I);
503 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
504 Value *Index = I->getOperand(i);
505 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
506 // Handle struct member offset arithmetic.
507 if (!TD) return;
508 const StructLayout *SL = TD->getStructLayout(STy);
509 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
510 uint64_t Offset = SL->getElementOffset(Idx);
511 TrailZ = std::min(TrailZ,
512 CountTrailingZeros_64(Offset));
513 } else {
514 // Handle array index arithmetic.
515 const Type *IndexedTy = GTI.getIndexedType();
516 if (!IndexedTy->isSized()) return;
517 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
518 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
519 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
520 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
521 ComputeMaskedBits(Index, LocalMask,
522 LocalKnownZero, LocalKnownOne, TD, Depth+1);
523 TrailZ = std::min(TrailZ,
524 unsigned(CountTrailingZeros_64(TypeSize) +
525 LocalKnownZero.countTrailingOnes()));
529 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
530 break;
532 case Instruction::PHI: {
533 PHINode *P = cast<PHINode>(I);
534 // Handle the case of a simple two-predecessor recurrence PHI.
535 // There's a lot more that could theoretically be done here, but
536 // this is sufficient to catch some interesting cases.
537 if (P->getNumIncomingValues() == 2) {
538 for (unsigned i = 0; i != 2; ++i) {
539 Value *L = P->getIncomingValue(i);
540 Value *R = P->getIncomingValue(!i);
541 Operator *LU = dyn_cast<Operator>(L);
542 if (!LU)
543 continue;
544 unsigned Opcode = LU->getOpcode();
545 // Check for operations that have the property that if
546 // both their operands have low zero bits, the result
547 // will have low zero bits.
548 if (Opcode == Instruction::Add ||
549 Opcode == Instruction::Sub ||
550 Opcode == Instruction::And ||
551 Opcode == Instruction::Or ||
552 Opcode == Instruction::Mul) {
553 Value *LL = LU->getOperand(0);
554 Value *LR = LU->getOperand(1);
555 // Find a recurrence.
556 if (LL == I)
557 L = LR;
558 else if (LR == I)
559 L = LL;
560 else
561 break;
562 // Ok, we have a PHI of the form L op= R. Check for low
563 // zero bits.
564 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
565 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
566 Mask2 = APInt::getLowBitsSet(BitWidth,
567 KnownZero2.countTrailingOnes());
569 // We need to take the minimum number of known bits
570 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
571 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
573 KnownZero = Mask &
574 APInt::getLowBitsSet(BitWidth,
575 std::min(KnownZero2.countTrailingOnes(),
576 KnownZero3.countTrailingOnes()));
577 break;
582 // Otherwise take the unions of the known bit sets of the operands,
583 // taking conservative care to avoid excessive recursion.
584 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
585 KnownZero = APInt::getAllOnesValue(BitWidth);
586 KnownOne = APInt::getAllOnesValue(BitWidth);
587 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
588 // Skip direct self references.
589 if (P->getIncomingValue(i) == P) continue;
591 KnownZero2 = APInt(BitWidth, 0);
592 KnownOne2 = APInt(BitWidth, 0);
593 // Recurse, but cap the recursion to one level, because we don't
594 // want to waste time spinning around in loops.
595 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
596 KnownZero2, KnownOne2, TD, MaxDepth-1);
597 KnownZero &= KnownZero2;
598 KnownOne &= KnownOne2;
599 // If all bits have been ruled out, there's no need to check
600 // more operands.
601 if (!KnownZero && !KnownOne)
602 break;
605 break;
607 case Instruction::Call:
608 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
609 switch (II->getIntrinsicID()) {
610 default: break;
611 case Intrinsic::ctpop:
612 case Intrinsic::ctlz:
613 case Intrinsic::cttz: {
614 unsigned LowBits = Log2_32(BitWidth)+1;
615 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
616 break;
620 break;
624 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
625 /// this predicate to simplify operations downstream. Mask is known to be zero
626 /// for bits that V cannot have.
628 /// This function is defined on values with integer type, values with pointer
629 /// type (but only if TD is non-null), and vectors of integers. In the case
630 /// where V is a vector, the mask, known zero, and known one values are the
631 /// same width as the vector element, and the bit is set only if it is true
632 /// for all of the elements in the vector.
633 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
634 const TargetData *TD, unsigned Depth) {
635 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
636 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 return (KnownZero & Mask) == Mask;
643 /// ComputeNumSignBits - Return the number of times the sign bit of the
644 /// register is replicated into the other bits. We know that at least 1 bit
645 /// is always equal to the sign bit (itself), but other cases can give us
646 /// information. For example, immediately after an "ashr X, 2", we know that
647 /// the top 3 bits are all equal to each other, so we return 3.
649 /// 'Op' must have a scalar integer type.
651 unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
652 unsigned Depth) {
653 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
654 "ComputeNumSignBits requires a TargetData object to operate "
655 "on non-integer values!");
656 const Type *Ty = V->getType();
657 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
658 Ty->getScalarSizeInBits();
659 unsigned Tmp, Tmp2;
660 unsigned FirstAnswer = 1;
662 // Note that ConstantInt is handled by the general ComputeMaskedBits case
663 // below.
665 if (Depth == 6)
666 return 1; // Limit search depth.
668 Operator *U = dyn_cast<Operator>(V);
669 switch (Operator::getOpcode(V)) {
670 default: break;
671 case Instruction::SExt:
672 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
673 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
675 case Instruction::AShr:
676 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
677 // ashr X, C -> adds C sign bits.
678 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
679 Tmp += C->getZExtValue();
680 if (Tmp > TyBits) Tmp = TyBits;
682 return Tmp;
683 case Instruction::Shl:
684 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
685 // shl destroys sign bits.
686 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
687 if (C->getZExtValue() >= TyBits || // Bad shift.
688 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
689 return Tmp - C->getZExtValue();
691 break;
692 case Instruction::And:
693 case Instruction::Or:
694 case Instruction::Xor: // NOT is handled here.
695 // Logical binary ops preserve the number of sign bits at the worst.
696 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
697 if (Tmp != 1) {
698 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
699 FirstAnswer = std::min(Tmp, Tmp2);
700 // We computed what we know about the sign bits as our first
701 // answer. Now proceed to the generic code that uses
702 // ComputeMaskedBits, and pick whichever answer is better.
704 break;
706 case Instruction::Select:
707 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
708 if (Tmp == 1) return 1; // Early out.
709 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
710 return std::min(Tmp, Tmp2);
712 case Instruction::Add:
713 // Add can have at most one carry bit. Thus we know that the output
714 // is, at worst, one more bit than the inputs.
715 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
716 if (Tmp == 1) return 1; // Early out.
718 // Special case decrementing a value (ADD X, -1):
719 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
720 if (CRHS->isAllOnesValue()) {
721 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
722 APInt Mask = APInt::getAllOnesValue(TyBits);
723 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
724 Depth+1);
726 // If the input is known to be 0 or 1, the output is 0/-1, which is all
727 // sign bits set.
728 if ((KnownZero | APInt(TyBits, 1)) == Mask)
729 return TyBits;
731 // If we are subtracting one from a positive number, there is no carry
732 // out of the result.
733 if (KnownZero.isNegative())
734 return Tmp;
737 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
738 if (Tmp2 == 1) return 1;
739 return std::min(Tmp, Tmp2)-1;
741 case Instruction::Sub:
742 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
743 if (Tmp2 == 1) return 1;
745 // Handle NEG.
746 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
747 if (CLHS->isNullValue()) {
748 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
749 APInt Mask = APInt::getAllOnesValue(TyBits);
750 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
751 TD, Depth+1);
752 // If the input is known to be 0 or 1, the output is 0/-1, which is all
753 // sign bits set.
754 if ((KnownZero | APInt(TyBits, 1)) == Mask)
755 return TyBits;
757 // If the input is known to be positive (the sign bit is known clear),
758 // the output of the NEG has the same number of sign bits as the input.
759 if (KnownZero.isNegative())
760 return Tmp2;
762 // Otherwise, we treat this like a SUB.
765 // Sub can have at most one carry bit. Thus we know that the output
766 // is, at worst, one more bit than the inputs.
767 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
768 if (Tmp == 1) return 1; // Early out.
769 return std::min(Tmp, Tmp2)-1;
771 case Instruction::PHI: {
772 PHINode *PN = cast<PHINode>(U);
773 // Don't analyze large in-degree PHIs.
774 if (PN->getNumIncomingValues() > 4) break;
776 // Take the minimum of all incoming values. This can't infinitely loop
777 // because of our depth threshold.
778 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
779 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
780 if (Tmp == 1) return Tmp;
781 Tmp = std::min(Tmp,
782 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
784 return Tmp;
787 case Instruction::Trunc:
788 // FIXME: it's tricky to do anything useful for this, but it is an important
789 // case for targets like X86.
790 break;
793 // Finally, if we can prove that the top bits of the result are 0's or 1's,
794 // use this information.
795 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
796 APInt Mask = APInt::getAllOnesValue(TyBits);
797 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
799 if (KnownZero.isNegative()) { // sign bit is 0
800 Mask = KnownZero;
801 } else if (KnownOne.isNegative()) { // sign bit is 1;
802 Mask = KnownOne;
803 } else {
804 // Nothing known.
805 return FirstAnswer;
808 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
809 // the number of identical bits in the top of the input value.
810 Mask = ~Mask;
811 Mask <<= Mask.getBitWidth()-TyBits;
812 // Return # leading zeros. We use 'min' here in case Val was zero before
813 // shifting. We don't want to return '64' as for an i32 "0".
814 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
817 /// ComputeMultiple - This function computes the integer multiple of Base that
818 /// equals V. If successful, it returns true and returns the multiple in
819 /// Multiple. If unsuccessful, it returns false. It looks
820 /// through SExt instructions only if LookThroughSExt is true.
821 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
822 bool LookThroughSExt, unsigned Depth) {
823 const unsigned MaxDepth = 6;
825 assert(V && "No Value?");
826 assert(Depth <= MaxDepth && "Limit Search Depth");
827 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
829 const Type *T = V->getType();
831 ConstantInt *CI = dyn_cast<ConstantInt>(V);
833 if (Base == 0)
834 return false;
836 if (Base == 1) {
837 Multiple = V;
838 return true;
841 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
842 Constant *BaseVal = ConstantInt::get(T, Base);
843 if (CO && CO == BaseVal) {
844 // Multiple is 1.
845 Multiple = ConstantInt::get(T, 1);
846 return true;
849 if (CI && CI->getZExtValue() % Base == 0) {
850 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
851 return true;
854 if (Depth == MaxDepth) return false; // Limit search depth.
856 Operator *I = dyn_cast<Operator>(V);
857 if (!I) return false;
859 switch (I->getOpcode()) {
860 default: break;
861 case Instruction::SExt:
862 if (!LookThroughSExt) return false;
863 // otherwise fall through to ZExt
864 case Instruction::ZExt:
865 return ComputeMultiple(I->getOperand(0), Base, Multiple,
866 LookThroughSExt, Depth+1);
867 case Instruction::Shl:
868 case Instruction::Mul: {
869 Value *Op0 = I->getOperand(0);
870 Value *Op1 = I->getOperand(1);
872 if (I->getOpcode() == Instruction::Shl) {
873 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
874 if (!Op1CI) return false;
875 // Turn Op0 << Op1 into Op0 * 2^Op1
876 APInt Op1Int = Op1CI->getValue();
877 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
878 Op1 = ConstantInt::get(V->getContext(),
879 APInt(Op1Int.getBitWidth(), 0).set(BitToSet));
882 Value *Mul0 = NULL;
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);
895 return true;
898 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
899 if (Mul0CI->getValue() == 1) {
900 // V == Base * Op1, so return Op1
901 Multiple = Op1;
902 return true;
906 Value *Mul1 = NULL;
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);
919 return true;
922 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
923 if (Mul1CI->getValue() == 1) {
924 // V == Base * Op0, so return Op0
925 Multiple = Op0;
926 return true;
932 // We could not determine if V is a multiple of Base.
933 return false;
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
940 /// rounding modes!
942 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
943 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
944 return !CFP->getValueAPF().isNegZero();
946 if (Depth == 6)
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())
956 return true;
958 // sitofp and uitofp turn into +0.0 for zero.
959 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
960 return true;
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()) {
970 // abs(x) != -0.0
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);
982 return false;
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
990 // build on that.
991 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
992 SmallVector<unsigned, 10> &Idxs,
993 unsigned IdxSkip,
994 Instruction *InsertBefore) {
995 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
996 if (STy) {
997 // Save the original To argument so we can modify it
998 Value *OrigTo = To;
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
1002 Idxs.push_back(i);
1003 Value *PrevTo = To;
1004 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
1005 InsertBefore);
1006 Idxs.pop_back();
1007 if (!To) {
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
1015 break;
1018 // If we succesfully found a value for each of our subaggregates
1019 if (To)
1020 return To;
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());
1030 if (!V)
1031 return NULL;
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
1042 // { c, d }.
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(),
1055 idx_begin,
1056 idx_end);
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
1073 // recursion)
1074 if (idx_begin == idx_end)
1075 return V;
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,
1085 idx_begin,
1086 idx_end));
1087 else if (isa<ConstantAggregateZero>(V))
1088 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
1089 idx_begin,
1090 idx_end));
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) {
1103 if (InsertBefore)
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
1113 // removed.
1114 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
1115 else
1116 // We can't handle this without inserting insertvalues
1117 return 0;
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.
1123 if (*req_idx != *i)
1124 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
1125 InsertBefore);
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,
1131 InsertBefore);
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;
1141 Idxs.reserve(size);
1142 // Add indices from the extract value instruction
1143 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1144 i != e; ++i)
1145 Idxs.push_back(*i);
1147 // Add requested indices
1148 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1149 Idxs.push_back(*i);
1151 assert(Idxs.size() == size
1152 && "Number of indices added not correct?");
1154 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
1155 InsertBefore);
1157 // Otherwise, we don't know (such as, extracting from a function return value
1158 // or load instruction)
1159 return 0;
1162 /// GetConstantStringInfo - This function computes the length of a
1163 /// null-terminated C string pointed to by V. If successful, it returns true
1164 /// and returns the string in Str. If unsuccessful, it returns false.
1165 bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1166 uint64_t Offset,
1167 bool StopAtNul) {
1168 // If V is NULL then return false;
1169 if (V == NULL) return false;
1171 // Look through bitcast instructions.
1172 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1173 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1175 // If the value is not a GEP instruction nor a constant expression with a
1176 // GEP instruction, then return false because ConstantArray can't occur
1177 // any other way
1178 const User *GEP = 0;
1179 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1180 GEP = GEPI;
1181 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1182 if (CE->getOpcode() == Instruction::BitCast)
1183 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1184 if (CE->getOpcode() != Instruction::GetElementPtr)
1185 return false;
1186 GEP = CE;
1189 if (GEP) {
1190 // Make sure the GEP has exactly three arguments.
1191 if (GEP->getNumOperands() != 3)
1192 return false;
1194 // Make sure the index-ee is a pointer to array of i8.
1195 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1196 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
1197 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
1198 return false;
1200 // Check to make sure that the first operand of the GEP is an integer and
1201 // has value 0 so that we are sure we're indexing into the initializer.
1202 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
1203 if (FirstIdx == 0 || !FirstIdx->isZero())
1204 return false;
1206 // If the second index isn't a ConstantInt, then this is a variable index
1207 // into the array. If this occurs, we can't say anything meaningful about
1208 // the string.
1209 uint64_t StartIdx = 0;
1210 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1211 StartIdx = CI->getZExtValue();
1212 else
1213 return false;
1214 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
1215 StopAtNul);
1218 // The GEP instruction, constant or instruction, must reference a global
1219 // variable that is a constant and is initialized. The referenced constant
1220 // initializer is the array that we'll use for optimization.
1221 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
1222 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
1223 return false;
1224 const Constant *GlobalInit = GV->getInitializer();
1226 // Handle the ConstantAggregateZero case
1227 if (isa<ConstantAggregateZero>(GlobalInit)) {
1228 // This is a degenerate case. The initializer is constant zero so the
1229 // length of the string must be zero.
1230 Str.clear();
1231 return true;
1234 // Must be a Constant Array
1235 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1236 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
1237 return false;
1239 // Get the number of elements in the array
1240 uint64_t NumElts = Array->getType()->getNumElements();
1242 if (Offset > NumElts)
1243 return false;
1245 // Traverse the constant array from 'Offset' which is the place the GEP refers
1246 // to in the array.
1247 Str.reserve(NumElts-Offset);
1248 for (unsigned i = Offset; i != NumElts; ++i) {
1249 const Constant *Elt = Array->getOperand(i);
1250 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1251 if (!CI) // This array isn't suitable, non-int initializer.
1252 return false;
1253 if (StopAtNul && CI->isZero())
1254 return true; // we found end of string, success!
1255 Str += (char)CI->getZExtValue();
1258 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
1259 return true;
1262 // These next two are very similar to the above, but also look through PHI
1263 // nodes.
1264 // TODO: See if we can integrate these two together.
1266 /// GetStringLengthH - If we can compute the length of the string pointed to by
1267 /// the specified pointer, return 'len+1'. If we can't, return 0.
1268 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1269 // Look through noop bitcast instructions.
1270 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1271 return GetStringLengthH(BCI->getOperand(0), PHIs);
1273 // If this is a PHI node, there are two cases: either we have already seen it
1274 // or we haven't.
1275 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1276 if (!PHIs.insert(PN))
1277 return ~0ULL; // already in the set.
1279 // If it was new, see if all the input strings are the same length.
1280 uint64_t LenSoFar = ~0ULL;
1281 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1282 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1283 if (Len == 0) return 0; // Unknown length -> unknown.
1285 if (Len == ~0ULL) continue;
1287 if (Len != LenSoFar && LenSoFar != ~0ULL)
1288 return 0; // Disagree -> unknown.
1289 LenSoFar = Len;
1292 // Success, all agree.
1293 return LenSoFar;
1296 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1297 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1298 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1299 if (Len1 == 0) return 0;
1300 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1301 if (Len2 == 0) return 0;
1302 if (Len1 == ~0ULL) return Len2;
1303 if (Len2 == ~0ULL) return Len1;
1304 if (Len1 != Len2) return 0;
1305 return Len1;
1308 // If the value is not a GEP instruction nor a constant expression with a
1309 // GEP instruction, then return unknown.
1310 User *GEP = 0;
1311 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1312 GEP = GEPI;
1313 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1314 if (CE->getOpcode() != Instruction::GetElementPtr)
1315 return 0;
1316 GEP = CE;
1317 } else {
1318 return 0;
1321 // Make sure the GEP has exactly three arguments.
1322 if (GEP->getNumOperands() != 3)
1323 return 0;
1325 // Check to make sure that the first operand of the GEP is an integer and
1326 // has value 0 so that we are sure we're indexing into the initializer.
1327 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1328 if (!Idx->isZero())
1329 return 0;
1330 } else
1331 return 0;
1333 // If the second index isn't a ConstantInt, then this is a variable index
1334 // into the array. If this occurs, we can't say anything meaningful about
1335 // the string.
1336 uint64_t StartIdx = 0;
1337 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1338 StartIdx = CI->getZExtValue();
1339 else
1340 return 0;
1342 // The GEP instruction, constant or instruction, must reference a global
1343 // variable that is a constant and is initialized. The referenced constant
1344 // initializer is the array that we'll use for optimization.
1345 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1346 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1347 GV->mayBeOverridden())
1348 return 0;
1349 Constant *GlobalInit = GV->getInitializer();
1351 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1352 // initializer is constant zero so the length of the string must be zero.
1353 if (isa<ConstantAggregateZero>(GlobalInit))
1354 return 1; // Len = 0 offset by 1.
1356 // Must be a Constant Array
1357 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1358 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1359 return false;
1361 // Get the number of elements in the array
1362 uint64_t NumElts = Array->getType()->getNumElements();
1364 // Traverse the constant array from StartIdx (derived above) which is
1365 // the place the GEP refers to in the array.
1366 for (unsigned i = StartIdx; i != NumElts; ++i) {
1367 Constant *Elt = Array->getOperand(i);
1368 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1369 if (!CI) // This array isn't suitable, non-int initializer.
1370 return 0;
1371 if (CI->isZero())
1372 return i-StartIdx+1; // We found end of string, success!
1375 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1378 /// GetStringLength - If we can compute the length of the string pointed to by
1379 /// the specified pointer, return 'len+1'. If we can't, return 0.
1380 uint64_t llvm::GetStringLength(Value *V) {
1381 if (!V->getType()->isPointerTy()) return 0;
1383 SmallPtrSet<PHINode*, 32> PHIs;
1384 uint64_t Len = GetStringLengthH(V, PHIs);
1385 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1386 // an empty string as a length.
1387 return Len == ~0ULL ? 1 : Len;