blob: 29ff8aa4f4d0a00143ed0669e662ad036d5a82d1 [file] [log] [blame]
Chris Lattner173234a2008-06-02 01:18:21 +00001//===- 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.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
16#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000018#include "llvm/GlobalVariable.h"
Chris Lattner173234a2008-06-02 01:18:21 +000019#include "llvm/IntrinsicInst.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000020#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000021#include "llvm/Support/GetElementPtrTypeIterator.h"
22#include "llvm/Support/MathExtras.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000023#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000024using namespace llvm;
25
26/// getOpcode - If this is an Instruction or a ConstantExpr, return the
27/// opcode value. Otherwise return UserOp1.
28static unsigned getOpcode(const Value *V) {
29 if (const Instruction *I = dyn_cast<Instruction>(V))
30 return I->getOpcode();
31 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
32 return CE->getOpcode();
33 // Use UserOp1 to mean there's no opcode.
34 return Instruction::UserOp1;
35}
36
37
38/// ComputeMaskedBits - Determine which of the bits specified in Mask are
39/// known to be either zero or one and return them in the KnownZero/KnownOne
40/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
41/// processing.
42/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
43/// we cannot optimize based on the assumption that it is zero without changing
44/// it to be an explicit zero. If we don't change it to zero, other code could
45/// optimized based on the contradictory assumption that it is non-zero.
46/// Because instcombine aggressively folds operations with undef args anyway,
47/// this won't lose us code quality.
48void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
49 APInt &KnownZero, APInt &KnownOne,
50 TargetData *TD, unsigned Depth) {
Dan Gohman9004c8a2009-05-21 02:28:33 +000051 const unsigned MaxDepth = 6;
Chris Lattner173234a2008-06-02 01:18:21 +000052 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000053 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000054 unsigned BitWidth = Mask.getBitWidth();
Chris Lattner173234a2008-06-02 01:18:21 +000055 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
56 "Not integer or pointer type!");
57 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
58 (!isa<IntegerType>(V->getType()) ||
59 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
60 KnownZero.getBitWidth() == BitWidth &&
61 KnownOne.getBitWidth() == BitWidth &&
62 "V, Mask, KnownOne and KnownZero should have same BitWidth");
63
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;
68 return;
69 }
70 // Null is all-zeros.
71 if (isa<ConstantPointerNull>(V)) {
72 KnownOne.clear();
73 KnownZero = Mask;
74 return;
75 }
76 // The address of an aligned GlobalValue has trailing zeros.
77 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
78 unsigned Align = GV->getAlignment();
79 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
80 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
81 if (Align > 0)
82 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
83 CountTrailingZeros_32(Align));
84 else
85 KnownZero.clear();
86 KnownOne.clear();
87 return;
88 }
89
90 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
91
Dan Gohman9004c8a2009-05-21 02:28:33 +000092 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +000093 return; // Limit search depth.
94
95 User *I = dyn_cast<User>(V);
96 if (!I) return;
97
98 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
99 switch (getOpcode(I)) {
100 default: break;
101 case Instruction::And: {
102 // If either the LHS or the RHS are Zero, the result is zero.
103 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
104 APInt Mask2(Mask & ~KnownZero);
105 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
106 Depth+1);
107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
108 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
109
110 // Output known-1 bits are only known if set in both the LHS & RHS.
111 KnownOne &= KnownOne2;
112 // Output known-0 are known to be clear if zero in either the LHS | RHS.
113 KnownZero |= KnownZero2;
114 return;
115 }
116 case Instruction::Or: {
117 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
118 APInt Mask2(Mask & ~KnownOne);
119 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
120 Depth+1);
121 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
122 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
123
124 // Output known-0 bits are only known if clear in both the LHS & RHS.
125 KnownZero &= KnownZero2;
126 // Output known-1 are known to be set if set in either the LHS | RHS.
127 KnownOne |= KnownOne2;
128 return;
129 }
130 case Instruction::Xor: {
131 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
132 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
133 Depth+1);
134 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
135 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
136
137 // Output known-0 bits are known if clear or set in both the LHS & RHS.
138 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
139 // Output known-1 are known to be set if set in only one of the LHS, RHS.
140 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
141 KnownZero = KnownZeroOut;
142 return;
143 }
144 case Instruction::Mul: {
145 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
146 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
147 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
148 Depth+1);
149 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
150 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
151
152 // If low bits are zero in either operand, output low known-0 bits.
153 // Also compute a conserative estimate for high known-0 bits.
154 // More trickiness is possible, but this is sufficient for the
155 // interesting case of alignment computation.
156 KnownOne.clear();
157 unsigned TrailZ = KnownZero.countTrailingOnes() +
158 KnownZero2.countTrailingOnes();
159 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
160 KnownZero2.countLeadingOnes(),
161 BitWidth) - BitWidth;
162
163 TrailZ = std::min(TrailZ, BitWidth);
164 LeadZ = std::min(LeadZ, BitWidth);
165 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
166 APInt::getHighBitsSet(BitWidth, LeadZ);
167 KnownZero &= Mask;
168 return;
169 }
170 case Instruction::UDiv: {
171 // For the purposes of computing leading zeros we can conservatively
172 // treat a udiv as a logical right shift by the power of 2 known to
173 // be less than the denominator.
174 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
175 ComputeMaskedBits(I->getOperand(0),
176 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
177 unsigned LeadZ = KnownZero2.countLeadingOnes();
178
179 KnownOne2.clear();
180 KnownZero2.clear();
181 ComputeMaskedBits(I->getOperand(1),
182 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
183 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
184 if (RHSUnknownLeadingOnes != BitWidth)
185 LeadZ = std::min(BitWidth,
186 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
187
188 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
189 return;
190 }
191 case Instruction::Select:
192 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
193 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
194 Depth+1);
195 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
196 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
197
198 // Only known if known in both the LHS and RHS.
199 KnownOne &= KnownOne2;
200 KnownZero &= KnownZero2;
201 return;
202 case Instruction::FPTrunc:
203 case Instruction::FPExt:
204 case Instruction::FPToUI:
205 case Instruction::FPToSI:
206 case Instruction::SIToFP:
207 case Instruction::UIToFP:
208 return; // Can't work with floating point.
209 case Instruction::PtrToInt:
210 case Instruction::IntToPtr:
211 // We can't handle these if we don't know the pointer size.
212 if (!TD) return;
213 // FALL THROUGH and handle them the same as zext/trunc.
214 case Instruction::ZExt:
215 case Instruction::Trunc: {
216 // Note that we handle pointer operands here because of inttoptr/ptrtoint
217 // which fall through here.
218 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner79abedb2009-01-20 18:22:57 +0000219 unsigned SrcBitWidth = TD ?
Chris Lattner173234a2008-06-02 01:18:21 +0000220 TD->getTypeSizeInBits(SrcTy) :
221 SrcTy->getPrimitiveSizeInBits();
222 APInt MaskIn(Mask);
223 MaskIn.zextOrTrunc(SrcBitWidth);
224 KnownZero.zextOrTrunc(SrcBitWidth);
225 KnownOne.zextOrTrunc(SrcBitWidth);
226 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
227 Depth+1);
228 KnownZero.zextOrTrunc(BitWidth);
229 KnownOne.zextOrTrunc(BitWidth);
230 // Any top bits are known to be zero.
231 if (BitWidth > SrcBitWidth)
232 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
233 return;
234 }
235 case Instruction::BitCast: {
236 const Type *SrcTy = I->getOperand(0)->getType();
237 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
238 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
239 Depth+1);
240 return;
241 }
242 break;
243 }
244 case Instruction::SExt: {
245 // Compute the bits in the result that are not present in the input.
246 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Chris Lattner79abedb2009-01-20 18:22:57 +0000247 unsigned SrcBitWidth = SrcTy->getBitWidth();
Chris Lattner173234a2008-06-02 01:18:21 +0000248
249 APInt MaskIn(Mask);
250 MaskIn.trunc(SrcBitWidth);
251 KnownZero.trunc(SrcBitWidth);
252 KnownOne.trunc(SrcBitWidth);
253 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
254 Depth+1);
255 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
256 KnownZero.zext(BitWidth);
257 KnownOne.zext(BitWidth);
258
259 // If the sign bit of the input is known set or clear, then we know the
260 // top bits of the result.
261 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
262 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
263 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
264 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
265 return;
266 }
267 case Instruction::Shl:
268 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
270 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
271 APInt Mask2(Mask.lshr(ShiftAmt));
272 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
273 Depth+1);
274 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
275 KnownZero <<= ShiftAmt;
276 KnownOne <<= ShiftAmt;
277 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
278 return;
279 }
280 break;
281 case Instruction::LShr:
282 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
283 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
284 // Compute the new bits that are at the top now.
285 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
286
287 // Unsigned shift right.
288 APInt Mask2(Mask.shl(ShiftAmt));
289 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
290 Depth+1);
291 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
292 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
293 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
294 // high bits known zero.
295 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
296 return;
297 }
298 break;
299 case Instruction::AShr:
300 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
301 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
302 // Compute the new bits that are at the top now.
303 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
304
305 // Signed shift right.
306 APInt Mask2(Mask.shl(ShiftAmt));
307 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
308 Depth+1);
309 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
310 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
311 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
312
313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
314 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
315 KnownZero |= HighBits;
316 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
317 KnownOne |= HighBits;
318 return;
319 }
320 break;
321 case Instruction::Sub: {
322 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
323 // We know that the top bits of C-X are clear if X contains less bits
324 // than C (i.e. no wrap-around can happen). For example, 20-X is
325 // positive if we can prove that X is >= 0 and < 16.
326 if (!CLHS->getValue().isNegative()) {
327 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
328 // NLZ can't be BitWidth with no sign bit
329 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
330 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
331 TD, Depth+1);
332
333 // If all of the MaskV bits are known to be zero, then we know the
334 // output top bits are zero, because we now know that the output is
335 // from [0-C].
336 if ((KnownZero2 & MaskV) == MaskV) {
337 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
338 // Top bits known zero.
339 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
340 }
341 }
342 }
343 }
344 // fall through
345 case Instruction::Add: {
Dan Gohman39250432009-05-24 18:02:35 +0000346 // If one of the operands has trailing zeros, than the bits that the
347 // other operand has in those bit positions will be preserved in the
348 // result. For an add, this works with either operand. For a subtract,
349 // this only works if the known zeros are in the right operand.
350 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
351 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
352 BitWidth - Mask.countLeadingZeros());
353 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000354 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000355 assert((LHSKnownZero & LHSKnownOne) == 0 &&
356 "Bits known to be one AND zero?");
357 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000358
359 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
360 Depth+1);
361 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000362 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000363
Dan Gohman39250432009-05-24 18:02:35 +0000364 // Determine which operand has more trailing zeros, and use that
365 // many bits from the other operand.
366 if (LHSKnownZeroOut > RHSKnownZeroOut) {
367 if (getOpcode(I) == Instruction::Add) {
368 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
369 KnownZero |= KnownZero2 & Mask;
370 KnownOne |= KnownOne2 & Mask;
371 } else {
372 // If the known zeros are in the left operand for a subtract,
373 // fall back to the minimum known zeros in both operands.
374 KnownZero |= APInt::getLowBitsSet(BitWidth,
375 std::min(LHSKnownZeroOut,
376 RHSKnownZeroOut));
377 }
378 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
379 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
380 KnownZero |= LHSKnownZero & Mask;
381 KnownOne |= LHSKnownOne & Mask;
382 }
Chris Lattner173234a2008-06-02 01:18:21 +0000383 return;
384 }
385 case Instruction::SRem:
386 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
387 APInt RA = Rem->getValue();
388 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
389 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
390 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
391 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
392 Depth+1);
393
Dan Gohmana60832b2008-08-13 23:12:35 +0000394 // If the sign bit of the first operand is zero, the sign bit of
395 // the result is zero. If the first operand has no one bits below
396 // the second operand's single 1 bit, its sign will be zero.
Chris Lattner173234a2008-06-02 01:18:21 +0000397 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
398 KnownZero2 |= ~LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000399
400 KnownZero |= KnownZero2 & Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000401
402 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
403 }
404 }
405 break;
406 case Instruction::URem: {
407 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
408 APInt RA = Rem->getValue();
409 if (RA.isPowerOf2()) {
410 APInt LowBits = (RA - 1);
411 APInt Mask2 = LowBits & Mask;
412 KnownZero |= ~LowBits & Mask;
413 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
414 Depth+1);
415 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
416 break;
417 }
418 }
419
420 // Since the result is less than or equal to either operand, any leading
421 // zero bits in either operand must also exist in the result.
422 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
423 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
424 TD, Depth+1);
425 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
426 TD, Depth+1);
427
Chris Lattner79abedb2009-01-20 18:22:57 +0000428 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000429 KnownZero2.countLeadingOnes());
430 KnownOne.clear();
431 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
432 break;
433 }
434
435 case Instruction::Alloca:
436 case Instruction::Malloc: {
437 AllocationInst *AI = cast<AllocationInst>(V);
438 unsigned Align = AI->getAlignment();
439 if (Align == 0 && TD) {
440 if (isa<AllocaInst>(AI))
Chris Lattner0f2831c2009-01-08 19:28:38 +0000441 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000442 else if (isa<MallocInst>(AI)) {
443 // Malloc returns maximally aligned memory.
444 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
445 Align =
446 std::max(Align,
447 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
448 Align =
449 std::max(Align,
450 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
451 }
452 }
453
454 if (Align > 0)
455 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
456 CountTrailingZeros_32(Align));
457 break;
458 }
459 case Instruction::GetElementPtr: {
460 // Analyze all of the subscripts of this getelementptr instruction
461 // to determine if we can prove known low zero bits.
462 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
463 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
464 ComputeMaskedBits(I->getOperand(0), LocalMask,
465 LocalKnownZero, LocalKnownOne, TD, Depth+1);
466 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
467
468 gep_type_iterator GTI = gep_type_begin(I);
469 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
470 Value *Index = I->getOperand(i);
471 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
472 // Handle struct member offset arithmetic.
473 if (!TD) return;
474 const StructLayout *SL = TD->getStructLayout(STy);
475 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
476 uint64_t Offset = SL->getElementOffset(Idx);
477 TrailZ = std::min(TrailZ,
478 CountTrailingZeros_64(Offset));
479 } else {
480 // Handle array index arithmetic.
481 const Type *IndexedTy = GTI.getIndexedType();
482 if (!IndexedTy->isSized()) return;
483 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000484 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000485 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
486 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
487 ComputeMaskedBits(Index, LocalMask,
488 LocalKnownZero, LocalKnownOne, TD, Depth+1);
489 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000490 unsigned(CountTrailingZeros_64(TypeSize) +
491 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000492 }
493 }
494
495 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
496 break;
497 }
498 case Instruction::PHI: {
499 PHINode *P = cast<PHINode>(I);
500 // Handle the case of a simple two-predecessor recurrence PHI.
501 // There's a lot more that could theoretically be done here, but
502 // this is sufficient to catch some interesting cases.
503 if (P->getNumIncomingValues() == 2) {
504 for (unsigned i = 0; i != 2; ++i) {
505 Value *L = P->getIncomingValue(i);
506 Value *R = P->getIncomingValue(!i);
507 User *LU = dyn_cast<User>(L);
508 if (!LU)
509 continue;
510 unsigned Opcode = getOpcode(LU);
511 // Check for operations that have the property that if
512 // both their operands have low zero bits, the result
513 // will have low zero bits.
514 if (Opcode == Instruction::Add ||
515 Opcode == Instruction::Sub ||
516 Opcode == Instruction::And ||
517 Opcode == Instruction::Or ||
518 Opcode == Instruction::Mul) {
519 Value *LL = LU->getOperand(0);
520 Value *LR = LU->getOperand(1);
521 // Find a recurrence.
522 if (LL == I)
523 L = LR;
524 else if (LR == I)
525 L = LL;
526 else
527 break;
528 // Ok, we have a PHI of the form L op= R. Check for low
529 // zero bits.
530 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
531 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
532 Mask2 = APInt::getLowBitsSet(BitWidth,
533 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000534
535 // We need to take the minimum number of known bits
536 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
537 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
538
Chris Lattner173234a2008-06-02 01:18:21 +0000539 KnownZero = Mask &
540 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000541 std::min(KnownZero2.countTrailingOnes(),
542 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000543 break;
544 }
545 }
546 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000547
548 // Otherwise take the unions of the known bit sets of the operands,
549 // taking conservative care to avoid excessive recursion.
550 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
551 KnownZero = APInt::getAllOnesValue(BitWidth);
552 KnownOne = APInt::getAllOnesValue(BitWidth);
553 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
554 // Skip direct self references.
555 if (P->getIncomingValue(i) == P) continue;
556
557 KnownZero2 = APInt(BitWidth, 0);
558 KnownOne2 = APInt(BitWidth, 0);
559 // Recurse, but cap the recursion to one level, because we don't
560 // want to waste time spinning around in loops.
561 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
562 KnownZero2, KnownOne2, TD, MaxDepth-1);
563 KnownZero &= KnownZero2;
564 KnownOne &= KnownOne2;
565 // If all bits have been ruled out, there's no need to check
566 // more operands.
567 if (!KnownZero && !KnownOne)
568 break;
569 }
570 }
Chris Lattner173234a2008-06-02 01:18:21 +0000571 break;
572 }
573 case Instruction::Call:
574 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
575 switch (II->getIntrinsicID()) {
576 default: break;
577 case Intrinsic::ctpop:
578 case Intrinsic::ctlz:
579 case Intrinsic::cttz: {
580 unsigned LowBits = Log2_32(BitWidth)+1;
581 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
582 break;
583 }
584 }
585 }
586 break;
587 }
588}
589
590/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
591/// this predicate to simplify operations downstream. Mask is known to be zero
592/// for bits that V cannot have.
593bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
594 TargetData *TD, unsigned Depth) {
595 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
596 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
597 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
598 return (KnownZero & Mask) == Mask;
599}
600
601
602
603/// ComputeNumSignBits - Return the number of times the sign bit of the
604/// register is replicated into the other bits. We know that at least 1 bit
605/// is always equal to the sign bit (itself), but other cases can give us
606/// information. For example, immediately after an "ashr X, 2", we know that
607/// the top 3 bits are all equal to each other, so we return 3.
608///
609/// 'Op' must have a scalar integer type.
610///
611unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
612 const IntegerType *Ty = cast<IntegerType>(V->getType());
613 unsigned TyBits = Ty->getBitWidth();
614 unsigned Tmp, Tmp2;
615 unsigned FirstAnswer = 1;
616
Chris Lattnerd82e5112008-06-02 18:39:07 +0000617 // Note that ConstantInt is handled by the general ComputeMaskedBits case
618 // below.
619
Chris Lattner173234a2008-06-02 01:18:21 +0000620 if (Depth == 6)
621 return 1; // Limit search depth.
622
623 User *U = dyn_cast<User>(V);
624 switch (getOpcode(V)) {
625 default: break;
626 case Instruction::SExt:
627 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
628 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
629
630 case Instruction::AShr:
631 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
632 // ashr X, C -> adds C sign bits.
633 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
634 Tmp += C->getZExtValue();
635 if (Tmp > TyBits) Tmp = TyBits;
636 }
637 return Tmp;
638 case Instruction::Shl:
639 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
640 // shl destroys sign bits.
641 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
642 if (C->getZExtValue() >= TyBits || // Bad shift.
643 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
644 return Tmp - C->getZExtValue();
645 }
646 break;
647 case Instruction::And:
648 case Instruction::Or:
649 case Instruction::Xor: // NOT is handled here.
650 // Logical binary ops preserve the number of sign bits at the worst.
651 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
652 if (Tmp != 1) {
653 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
654 FirstAnswer = std::min(Tmp, Tmp2);
655 // We computed what we know about the sign bits as our first
656 // answer. Now proceed to the generic code that uses
657 // ComputeMaskedBits, and pick whichever answer is better.
658 }
659 break;
660
661 case Instruction::Select:
662 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
663 if (Tmp == 1) return 1; // Early out.
664 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
665 return std::min(Tmp, Tmp2);
666
667 case Instruction::Add:
668 // Add can have at most one carry bit. Thus we know that the output
669 // is, at worst, one more bit than the inputs.
670 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
671 if (Tmp == 1) return 1; // Early out.
672
673 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000674 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000675 if (CRHS->isAllOnesValue()) {
676 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
677 APInt Mask = APInt::getAllOnesValue(TyBits);
678 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
679 Depth+1);
680
681 // If the input is known to be 0 or 1, the output is 0/-1, which is all
682 // sign bits set.
683 if ((KnownZero | APInt(TyBits, 1)) == Mask)
684 return TyBits;
685
686 // If we are subtracting one from a positive number, there is no carry
687 // out of the result.
688 if (KnownZero.isNegative())
689 return Tmp;
690 }
691
692 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
693 if (Tmp2 == 1) return 1;
694 return std::min(Tmp, Tmp2)-1;
695 break;
696
697 case Instruction::Sub:
698 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
699 if (Tmp2 == 1) return 1;
700
701 // Handle NEG.
702 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
703 if (CLHS->isNullValue()) {
704 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
705 APInt Mask = APInt::getAllOnesValue(TyBits);
706 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
707 TD, Depth+1);
708 // If the input is known to be 0 or 1, the output is 0/-1, which is all
709 // sign bits set.
710 if ((KnownZero | APInt(TyBits, 1)) == Mask)
711 return TyBits;
712
713 // If the input is known to be positive (the sign bit is known clear),
714 // the output of the NEG has the same number of sign bits as the input.
715 if (KnownZero.isNegative())
716 return Tmp2;
717
718 // Otherwise, we treat this like a SUB.
719 }
720
721 // Sub can have at most one carry bit. Thus we know that the output
722 // is, at worst, one more bit than the inputs.
723 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
724 if (Tmp == 1) return 1; // Early out.
725 return std::min(Tmp, Tmp2)-1;
726 break;
727 case Instruction::Trunc:
728 // FIXME: it's tricky to do anything useful for this, but it is an important
729 // case for targets like X86.
730 break;
731 }
732
733 // Finally, if we can prove that the top bits of the result are 0's or 1's,
734 // use this information.
735 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
736 APInt Mask = APInt::getAllOnesValue(TyBits);
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
738
739 if (KnownZero.isNegative()) { // sign bit is 0
740 Mask = KnownZero;
741 } else if (KnownOne.isNegative()) { // sign bit is 1;
742 Mask = KnownOne;
743 } else {
744 // Nothing known.
745 return FirstAnswer;
746 }
747
748 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
749 // the number of identical bits in the top of the input value.
750 Mask = ~Mask;
751 Mask <<= Mask.getBitWidth()-TyBits;
752 // Return # leading zeros. We use 'min' here in case Val was zero before
753 // shifting. We don't want to return '64' as for an i32 "0".
754 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
755}
Chris Lattner833f25d2008-06-02 01:29:46 +0000756
757/// CannotBeNegativeZero - Return true if we can prove that the specified FP
758/// value is never equal to -0.0.
759///
760/// NOTE: this function will need to be revisited when we support non-default
761/// rounding modes!
762///
763bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
764 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
765 return !CFP->getValueAPF().isNegZero();
766
767 if (Depth == 6)
768 return 1; // Limit search depth.
769
770 const Instruction *I = dyn_cast<Instruction>(V);
771 if (I == 0) return false;
772
773 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
774 if (I->getOpcode() == Instruction::Add &&
775 isa<ConstantFP>(I->getOperand(1)) &&
776 cast<ConstantFP>(I->getOperand(1))->isNullValue())
777 return true;
778
779 // sitofp and uitofp turn into +0.0 for zero.
780 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
781 return true;
782
783 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
784 // sqrt(-0.0) = -0.0, no other negative results are possible.
785 if (II->getIntrinsicID() == Intrinsic::sqrt)
786 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
787
788 if (const CallInst *CI = dyn_cast<CallInst>(I))
789 if (const Function *F = CI->getCalledFunction()) {
790 if (F->isDeclaration()) {
791 switch (F->getNameLen()) {
792 case 3: // abs(x) != -0.0
793 if (!strcmp(F->getNameStart(), "abs")) return true;
794 break;
795 case 4: // abs[lf](x) != -0.0
796 if (!strcmp(F->getNameStart(), "absf")) return true;
797 if (!strcmp(F->getNameStart(), "absl")) return true;
798 break;
799 }
800 }
801 }
802
803 return false;
804}
805
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000806// This is the recursive version of BuildSubAggregate. It takes a few different
807// arguments. Idxs is the index within the nested struct From that we are
808// looking at now (which is of type IndexedType). IdxSkip is the number of
809// indices from Idxs that should be left out when inserting into the resulting
810// struct. To is the result struct built so far, new insertvalue instructions
811// build on that.
812Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
813 SmallVector<unsigned, 10> &Idxs,
814 unsigned IdxSkip,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000815 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000816 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
817 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000818 // Save the original To argument so we can modify it
819 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000820 // General case, the type indexed by Idxs is a struct
821 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
822 // Process each struct element recursively
823 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000824 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000825 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
826 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000827 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000828 if (!To) {
829 // Couldn't find any inserted value for this index? Cleanup
830 while (PrevTo != OrigTo) {
831 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
832 PrevTo = Del->getAggregateOperand();
833 Del->eraseFromParent();
834 }
835 // Stop processing elements
836 break;
837 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000838 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000839 // If we succesfully found a value for each of our subaggregates
840 if (To)
841 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000842 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000843 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
844 // the struct's elements had a value that was inserted directly. In the latter
845 // case, perhaps we can't determine each of the subelements individually, but
846 // we might be able to find the complete struct somewhere.
847
848 // Find the value that is at that particular spot
849 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
850
851 if (!V)
852 return NULL;
853
854 // Insert the value in the new (sub) aggregrate
855 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
856 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000857}
858
859// This helper takes a nested struct and extracts a part of it (which is again a
860// struct) into a new value. For example, given the struct:
861// { a, { b, { c, d }, e } }
862// and the indices "1, 1" this returns
863// { c, d }.
864//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000865// It does this by inserting an insertvalue for each element in the resulting
866// struct, as opposed to just inserting a single struct. This will only work if
867// each of the elements of the substruct are known (ie, inserted into From by an
868// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000869//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000870// All inserted insertvalue instructions are inserted before InsertBefore
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000871Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000872 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000873 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000874 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
875 idx_begin,
876 idx_end);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000877 Value *To = UndefValue::get(IndexedType);
878 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
879 unsigned IdxSkip = Idxs.size();
880
881 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
882}
883
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000884/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
885/// the scalar value indexed is already around as a register, for example if it
886/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000887///
888/// If InsertBefore is not null, this function will duplicate (modified)
889/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000890Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Matthijs Kooijman0a7413d2008-06-16 13:13:08 +0000891 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000892 // Nothing to index? Just return V then (this is useful at the end of our
893 // recursion)
894 if (idx_begin == idx_end)
895 return V;
896 // We have indices, so V should have an indexable type
897 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
898 && "Not looking at a struct or array?");
899 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
900 && "Invalid indices for type?");
901 const CompositeType *PTy = cast<CompositeType>(V->getType());
902
903 if (isa<UndefValue>(V))
904 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
905 idx_begin,
906 idx_end));
907 else if (isa<ConstantAggregateZero>(V))
908 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
909 idx_begin,
910 idx_end));
911 else if (Constant *C = dyn_cast<Constant>(V)) {
912 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
913 // Recursively process this constant
Matthijs Kooijmandddc8272008-07-16 10:47:35 +0000914 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, idx_end,
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000915 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000916 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
917 // Loop the indices for the insertvalue instruction in parallel with the
918 // requested indices
919 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000920 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
921 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +0000922 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000923 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000924 // The requested index identifies a part of a nested aggregate. Handle
925 // this specially. For example,
926 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
927 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
928 // %C = extractvalue {i32, { i32, i32 } } %B, 1
929 // This can be changed into
930 // %A = insertvalue {i32, i32 } undef, i32 10, 0
931 // %C = insertvalue {i32, i32 } %A, i32 11, 1
932 // which allows the unused 0,0 element from the nested struct to be
933 // removed.
Matthijs Kooijman97728912008-06-16 13:28:31 +0000934 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
935 else
936 // We can't handle this without inserting insertvalues
937 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +0000938 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000939
940 // This insert value inserts something else than what we are looking for.
941 // See if the (aggregrate) value inserted into has the value we are
942 // looking for, then.
943 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000944 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
945 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000946 }
947 // If we end up here, the indices of the insertvalue match with those
948 // requested (though possibly only partially). Now we recursively look at
949 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000950 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
951 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000952 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
953 // If we're extracting a value from an aggregrate that was extracted from
954 // something else, we can extract from that something else directly instead.
955 // However, we will need to chain I's indices with the requested indices.
956
957 // Calculate the number of indices required
958 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
959 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000960 SmallVector<unsigned, 5> Idxs;
961 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000962 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000963 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000964 i != e; ++i)
965 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000966
967 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000968 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
969 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000970
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000971 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000972 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000973
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000974 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000975 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000976 }
977 // Otherwise, we don't know (such as, extracting from a function return value
978 // or load instruction)
979 return 0;
980}
Evan Cheng0ff39b32008-06-30 07:31:25 +0000981
982/// GetConstantStringInfo - This function computes the length of a
983/// null-terminated C string pointed to by V. If successful, it returns true
984/// and returns the string in Str. If unsuccessful, it returns false.
Bill Wendling0582ae92009-03-13 04:39:26 +0000985bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
986 bool StopAtNul) {
987 // If V is NULL then return false;
988 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +0000989
990 // Look through bitcast instructions.
991 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +0000992 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
993
Evan Cheng0ff39b32008-06-30 07:31:25 +0000994 // If the value is not a GEP instruction nor a constant expression with a
995 // GEP instruction, then return false because ConstantArray can't occur
996 // any other way
997 User *GEP = 0;
998 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
999 GEP = GEPI;
1000 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1001 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001002 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1003 if (CE->getOpcode() != Instruction::GetElementPtr)
1004 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001005 GEP = CE;
1006 }
1007
1008 if (GEP) {
1009 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001010 if (GEP->getNumOperands() != 3)
1011 return false;
1012
Evan Cheng0ff39b32008-06-30 07:31:25 +00001013 // Make sure the index-ee is a pointer to array of i8.
1014 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1015 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Bill Wendling0582ae92009-03-13 04:39:26 +00001016 if (AT == 0 || AT->getElementType() != Type::Int8Ty)
1017 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001018
1019 // Check to make sure that the first operand of the GEP is an integer and
1020 // has value 0 so that we are sure we're indexing into the initializer.
1021 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001022 if (FirstIdx == 0 || !FirstIdx->isZero())
1023 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001024
1025 // If the second index isn't a ConstantInt, then this is a variable index
1026 // into the array. If this occurs, we can't say anything meaningful about
1027 // the string.
1028 uint64_t StartIdx = 0;
Bill Wendling0582ae92009-03-13 04:39:26 +00001029 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001030 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001031 else
1032 return false;
1033 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001034 StopAtNul);
1035 }
1036
1037 // The GEP instruction, constant or instruction, must reference a global
1038 // variable that is a constant and is initialized. The referenced constant
1039 // initializer is the array that we'll use for optimization.
1040 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Bill Wendling0582ae92009-03-13 04:39:26 +00001041 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1042 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001043 Constant *GlobalInit = GV->getInitializer();
1044
1045 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001046 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001047 // This is a degenerate case. The initializer is constant zero so the
1048 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001049 Str.clear();
1050 return true;
1051 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001052
1053 // Must be a Constant Array
1054 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Bill Wendling0582ae92009-03-13 04:39:26 +00001055 if (Array == 0 || Array->getType()->getElementType() != Type::Int8Ty)
1056 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001057
1058 // Get the number of elements in the array
1059 uint64_t NumElts = Array->getType()->getNumElements();
1060
Bill Wendling0582ae92009-03-13 04:39:26 +00001061 if (Offset > NumElts)
1062 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001063
1064 // Traverse the constant array from 'Offset' which is the place the GEP refers
1065 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001066 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001067 for (unsigned i = Offset; i != NumElts; ++i) {
1068 Constant *Elt = Array->getOperand(i);
1069 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001070 if (!CI) // This array isn't suitable, non-int initializer.
1071 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001072 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001073 return true; // we found end of string, success!
1074 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001075 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001076
Evan Cheng0ff39b32008-06-30 07:31:25 +00001077 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001078 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001079}