blob: 604d10c68b94df42e889a4e1a4dcfd48998a8356 [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"
Owen Anderson76f600b2009-07-06 22:37:39 +000020#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000021#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000022#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000023#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000025#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000026using namespace llvm;
27
Chris Lattner173234a2008-06-02 01:18:21 +000028/// ComputeMaskedBits - Determine which of the bits specified in Mask are
29/// known to be either zero or one and return them in the KnownZero/KnownOne
30/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
31/// processing.
32/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
33/// we cannot optimize based on the assumption that it is zero without changing
34/// it to be an explicit zero. If we don't change it to zero, other code could
35/// optimized based on the contradictory assumption that it is non-zero.
36/// Because instcombine aggressively folds operations with undef args anyway,
37/// this won't lose us code quality.
38void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
39 APInt &KnownZero, APInt &KnownOne,
40 TargetData *TD, unsigned Depth) {
Dan Gohman9004c8a2009-05-21 02:28:33 +000041 const unsigned MaxDepth = 6;
Chris Lattner173234a2008-06-02 01:18:21 +000042 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000043 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000044 unsigned BitWidth = Mask.getBitWidth();
Dan Gohman6de29f82009-06-15 22:12:54 +000045 assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) &&
Chris Lattner173234a2008-06-02 01:18:21 +000046 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000047 assert((!TD ||
48 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
49 (!V->getType()->isIntOrIntVector() ||
50 V->getType()->getScalarSizeInBits() == BitWidth) &&
Chris Lattner173234a2008-06-02 01:18:21 +000051 KnownZero.getBitWidth() == BitWidth &&
52 KnownOne.getBitWidth() == BitWidth &&
53 "V, Mask, KnownOne and KnownZero should have same BitWidth");
54
55 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
56 // We know all of the bits for a constant!
57 KnownOne = CI->getValue() & Mask;
58 KnownZero = ~KnownOne & Mask;
59 return;
60 }
Dan Gohman6de29f82009-06-15 22:12:54 +000061 // Null and aggregate-zero are all-zeros.
62 if (isa<ConstantPointerNull>(V) ||
63 isa<ConstantAggregateZero>(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +000064 KnownOne.clear();
65 KnownZero = Mask;
66 return;
67 }
Dan Gohman6de29f82009-06-15 22:12:54 +000068 // Handle a constant vector by taking the intersection of the known bits of
69 // each element.
70 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
71 KnownZero.set(); KnownOne.set();
72 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
73 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
74 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
75 TD, Depth);
76 KnownZero &= KnownZero2;
77 KnownOne &= KnownOne2;
78 }
79 return;
80 }
Chris Lattner173234a2008-06-02 01:18:21 +000081 // The address of an aligned GlobalValue has trailing zeros.
82 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
83 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +000084 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
85 const Type *ObjectType = GV->getType()->getElementType();
86 // If the object is defined in the current Module, we'll be giving
87 // it the preferred alignment. Otherwise, we have to assume that it
88 // may only have the minimum ABI alignment.
89 if (!GV->isDeclaration() && !GV->mayBeOverridden())
90 Align = TD->getPrefTypeAlignment(ObjectType);
91 else
92 Align = TD->getABITypeAlignment(ObjectType);
93 }
Chris Lattner173234a2008-06-02 01:18:21 +000094 if (Align > 0)
95 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
96 CountTrailingZeros_32(Align));
97 else
98 KnownZero.clear();
99 KnownOne.clear();
100 return;
101 }
102
103 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
104
Dan Gohman9004c8a2009-05-21 02:28:33 +0000105 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000106 return; // Limit search depth.
107
Dan Gohmanca178902009-07-17 20:47:02 +0000108 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000109 if (!I) return;
110
111 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000112 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000113 default: break;
114 case Instruction::And: {
115 // If either the LHS or the RHS are Zero, the result is zero.
116 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
117 APInt Mask2(Mask & ~KnownZero);
118 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
119 Depth+1);
120 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
121 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
122
123 // Output known-1 bits are only known if set in both the LHS & RHS.
124 KnownOne &= KnownOne2;
125 // Output known-0 are known to be clear if zero in either the LHS | RHS.
126 KnownZero |= KnownZero2;
127 return;
128 }
129 case Instruction::Or: {
130 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
131 APInt Mask2(Mask & ~KnownOne);
132 ComputeMaskedBits(I->getOperand(0), Mask2, 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 only known if clear in both the LHS & RHS.
138 KnownZero &= KnownZero2;
139 // Output known-1 are known to be set if set in either the LHS | RHS.
140 KnownOne |= KnownOne2;
141 return;
142 }
143 case Instruction::Xor: {
144 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
145 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
146 Depth+1);
147 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
148 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
149
150 // Output known-0 bits are known if clear or set in both the LHS & RHS.
151 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
152 // Output known-1 are known to be set if set in only one of the LHS, RHS.
153 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
154 KnownZero = KnownZeroOut;
155 return;
156 }
157 case Instruction::Mul: {
158 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
159 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
160 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
161 Depth+1);
162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
163 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
164
165 // If low bits are zero in either operand, output low known-0 bits.
166 // Also compute a conserative estimate for high known-0 bits.
167 // More trickiness is possible, but this is sufficient for the
168 // interesting case of alignment computation.
169 KnownOne.clear();
170 unsigned TrailZ = KnownZero.countTrailingOnes() +
171 KnownZero2.countTrailingOnes();
172 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
173 KnownZero2.countLeadingOnes(),
174 BitWidth) - BitWidth;
175
176 TrailZ = std::min(TrailZ, BitWidth);
177 LeadZ = std::min(LeadZ, BitWidth);
178 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
179 APInt::getHighBitsSet(BitWidth, LeadZ);
180 KnownZero &= Mask;
181 return;
182 }
183 case Instruction::UDiv: {
184 // For the purposes of computing leading zeros we can conservatively
185 // treat a udiv as a logical right shift by the power of 2 known to
186 // be less than the denominator.
187 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
188 ComputeMaskedBits(I->getOperand(0),
189 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
190 unsigned LeadZ = KnownZero2.countLeadingOnes();
191
192 KnownOne2.clear();
193 KnownZero2.clear();
194 ComputeMaskedBits(I->getOperand(1),
195 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
196 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
197 if (RHSUnknownLeadingOnes != BitWidth)
198 LeadZ = std::min(BitWidth,
199 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
200
201 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
202 return;
203 }
204 case Instruction::Select:
205 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
206 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
207 Depth+1);
208 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
209 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
210
211 // Only known if known in both the LHS and RHS.
212 KnownOne &= KnownOne2;
213 KnownZero &= KnownZero2;
214 return;
215 case Instruction::FPTrunc:
216 case Instruction::FPExt:
217 case Instruction::FPToUI:
218 case Instruction::FPToSI:
219 case Instruction::SIToFP:
220 case Instruction::UIToFP:
221 return; // Can't work with floating point.
222 case Instruction::PtrToInt:
223 case Instruction::IntToPtr:
224 // We can't handle these if we don't know the pointer size.
225 if (!TD) return;
226 // FALL THROUGH and handle them the same as zext/trunc.
227 case Instruction::ZExt:
228 case Instruction::Trunc: {
229 // Note that we handle pointer operands here because of inttoptr/ptrtoint
230 // which fall through here.
231 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner79abedb2009-01-20 18:22:57 +0000232 unsigned SrcBitWidth = TD ?
Chris Lattner173234a2008-06-02 01:18:21 +0000233 TD->getTypeSizeInBits(SrcTy) :
Dan Gohman6de29f82009-06-15 22:12:54 +0000234 SrcTy->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000235 APInt MaskIn(Mask);
236 MaskIn.zextOrTrunc(SrcBitWidth);
237 KnownZero.zextOrTrunc(SrcBitWidth);
238 KnownOne.zextOrTrunc(SrcBitWidth);
239 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
240 Depth+1);
241 KnownZero.zextOrTrunc(BitWidth);
242 KnownOne.zextOrTrunc(BitWidth);
243 // Any top bits are known to be zero.
244 if (BitWidth > SrcBitWidth)
245 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
246 return;
247 }
248 case Instruction::BitCast: {
249 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000250 if ((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
251 // TODO: For now, not handling conversions like:
252 // (bitcast i64 %x to <2 x i32>)
253 !isa<VectorType>(I->getType())) {
Chris Lattner173234a2008-06-02 01:18:21 +0000254 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
255 Depth+1);
256 return;
257 }
258 break;
259 }
260 case Instruction::SExt: {
261 // Compute the bits in the result that are not present in the input.
262 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Chris Lattner79abedb2009-01-20 18:22:57 +0000263 unsigned SrcBitWidth = SrcTy->getBitWidth();
Chris Lattner173234a2008-06-02 01:18:21 +0000264
265 APInt MaskIn(Mask);
266 MaskIn.trunc(SrcBitWidth);
267 KnownZero.trunc(SrcBitWidth);
268 KnownOne.trunc(SrcBitWidth);
269 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
270 Depth+1);
271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
272 KnownZero.zext(BitWidth);
273 KnownOne.zext(BitWidth);
274
275 // If the sign bit of the input is known set or clear, then we know the
276 // top bits of the result.
277 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
278 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
279 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
280 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
281 return;
282 }
283 case Instruction::Shl:
284 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
285 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
286 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
287 APInt Mask2(Mask.lshr(ShiftAmt));
288 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
289 Depth+1);
290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
291 KnownZero <<= ShiftAmt;
292 KnownOne <<= ShiftAmt;
293 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
294 return;
295 }
296 break;
297 case Instruction::LShr:
298 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
300 // Compute the new bits that are at the top now.
301 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
302
303 // Unsigned shift right.
304 APInt Mask2(Mask.shl(ShiftAmt));
305 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
306 Depth+1);
307 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
308 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
309 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
310 // high bits known zero.
311 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
312 return;
313 }
314 break;
315 case Instruction::AShr:
316 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
317 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
318 // Compute the new bits that are at the top now.
319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
320
321 // Signed shift right.
322 APInt Mask2(Mask.shl(ShiftAmt));
323 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
324 Depth+1);
325 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
326 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
327 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
328
329 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
330 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
331 KnownZero |= HighBits;
332 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
333 KnownOne |= HighBits;
334 return;
335 }
336 break;
337 case Instruction::Sub: {
338 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
339 // We know that the top bits of C-X are clear if X contains less bits
340 // than C (i.e. no wrap-around can happen). For example, 20-X is
341 // positive if we can prove that X is >= 0 and < 16.
342 if (!CLHS->getValue().isNegative()) {
343 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
344 // NLZ can't be BitWidth with no sign bit
345 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
346 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
347 TD, Depth+1);
348
349 // If all of the MaskV bits are known to be zero, then we know the
350 // output top bits are zero, because we now know that the output is
351 // from [0-C].
352 if ((KnownZero2 & MaskV) == MaskV) {
353 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
354 // Top bits known zero.
355 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
356 }
357 }
358 }
359 }
360 // fall through
361 case Instruction::Add: {
Dan Gohman39250432009-05-24 18:02:35 +0000362 // If one of the operands has trailing zeros, than the bits that the
363 // other operand has in those bit positions will be preserved in the
364 // result. For an add, this works with either operand. For a subtract,
365 // this only works if the known zeros are in the right operand.
366 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
367 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
368 BitWidth - Mask.countLeadingZeros());
369 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000370 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000371 assert((LHSKnownZero & LHSKnownOne) == 0 &&
372 "Bits known to be one AND zero?");
373 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000374
375 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
376 Depth+1);
377 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000378 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000379
Dan Gohman39250432009-05-24 18:02:35 +0000380 // Determine which operand has more trailing zeros, and use that
381 // many bits from the other operand.
382 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000383 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000384 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
385 KnownZero |= KnownZero2 & Mask;
386 KnownOne |= KnownOne2 & Mask;
387 } else {
388 // If the known zeros are in the left operand for a subtract,
389 // fall back to the minimum known zeros in both operands.
390 KnownZero |= APInt::getLowBitsSet(BitWidth,
391 std::min(LHSKnownZeroOut,
392 RHSKnownZeroOut));
393 }
394 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
395 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
396 KnownZero |= LHSKnownZero & Mask;
397 KnownOne |= LHSKnownOne & Mask;
398 }
Chris Lattner173234a2008-06-02 01:18:21 +0000399 return;
400 }
401 case Instruction::SRem:
402 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
403 APInt RA = Rem->getValue();
404 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
405 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
406 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
407 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
408 Depth+1);
409
Dan Gohmana60832b2008-08-13 23:12:35 +0000410 // If the sign bit of the first operand is zero, the sign bit of
411 // the result is zero. If the first operand has no one bits below
412 // the second operand's single 1 bit, its sign will be zero.
Chris Lattner173234a2008-06-02 01:18:21 +0000413 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
414 KnownZero2 |= ~LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000415
416 KnownZero |= KnownZero2 & Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000417
418 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
419 }
420 }
421 break;
422 case Instruction::URem: {
423 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
424 APInt RA = Rem->getValue();
425 if (RA.isPowerOf2()) {
426 APInt LowBits = (RA - 1);
427 APInt Mask2 = LowBits & Mask;
428 KnownZero |= ~LowBits & Mask;
429 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
430 Depth+1);
431 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
432 break;
433 }
434 }
435
436 // Since the result is less than or equal to either operand, any leading
437 // zero bits in either operand must also exist in the result.
438 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
439 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
440 TD, Depth+1);
441 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
442 TD, Depth+1);
443
Chris Lattner79abedb2009-01-20 18:22:57 +0000444 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000445 KnownZero2.countLeadingOnes());
446 KnownOne.clear();
447 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
448 break;
449 }
450
451 case Instruction::Alloca:
452 case Instruction::Malloc: {
453 AllocationInst *AI = cast<AllocationInst>(V);
454 unsigned Align = AI->getAlignment();
455 if (Align == 0 && TD) {
456 if (isa<AllocaInst>(AI))
Chris Lattner0f2831c2009-01-08 19:28:38 +0000457 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000458 else if (isa<MallocInst>(AI)) {
459 // Malloc returns maximally aligned memory.
460 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
461 Align =
462 std::max(Align,
Owen Anderson1d0be152009-08-13 21:58:54 +0000463 (unsigned)TD->getABITypeAlignment(
464 Type::getDoubleTy(V->getContext())));
Chris Lattner173234a2008-06-02 01:18:21 +0000465 Align =
466 std::max(Align,
Owen Anderson1d0be152009-08-13 21:58:54 +0000467 (unsigned)TD->getABITypeAlignment(
468 Type::getInt64Ty(V->getContext())));
Chris Lattner173234a2008-06-02 01:18:21 +0000469 }
470 }
471
472 if (Align > 0)
473 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
474 CountTrailingZeros_32(Align));
475 break;
476 }
477 case Instruction::GetElementPtr: {
478 // Analyze all of the subscripts of this getelementptr instruction
479 // to determine if we can prove known low zero bits.
480 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
481 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
482 ComputeMaskedBits(I->getOperand(0), LocalMask,
483 LocalKnownZero, LocalKnownOne, TD, Depth+1);
484 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
485
486 gep_type_iterator GTI = gep_type_begin(I);
487 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
488 Value *Index = I->getOperand(i);
489 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
490 // Handle struct member offset arithmetic.
491 if (!TD) return;
492 const StructLayout *SL = TD->getStructLayout(STy);
493 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
494 uint64_t Offset = SL->getElementOffset(Idx);
495 TrailZ = std::min(TrailZ,
496 CountTrailingZeros_64(Offset));
497 } else {
498 // Handle array index arithmetic.
499 const Type *IndexedTy = GTI.getIndexedType();
500 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000501 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000502 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000503 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
504 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
505 ComputeMaskedBits(Index, LocalMask,
506 LocalKnownZero, LocalKnownOne, TD, Depth+1);
507 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000508 unsigned(CountTrailingZeros_64(TypeSize) +
509 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000510 }
511 }
512
513 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
514 break;
515 }
516 case Instruction::PHI: {
517 PHINode *P = cast<PHINode>(I);
518 // Handle the case of a simple two-predecessor recurrence PHI.
519 // There's a lot more that could theoretically be done here, but
520 // this is sufficient to catch some interesting cases.
521 if (P->getNumIncomingValues() == 2) {
522 for (unsigned i = 0; i != 2; ++i) {
523 Value *L = P->getIncomingValue(i);
524 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000525 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000526 if (!LU)
527 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000528 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000529 // Check for operations that have the property that if
530 // both their operands have low zero bits, the result
531 // will have low zero bits.
532 if (Opcode == Instruction::Add ||
533 Opcode == Instruction::Sub ||
534 Opcode == Instruction::And ||
535 Opcode == Instruction::Or ||
536 Opcode == Instruction::Mul) {
537 Value *LL = LU->getOperand(0);
538 Value *LR = LU->getOperand(1);
539 // Find a recurrence.
540 if (LL == I)
541 L = LR;
542 else if (LR == I)
543 L = LL;
544 else
545 break;
546 // Ok, we have a PHI of the form L op= R. Check for low
547 // zero bits.
548 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
549 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
550 Mask2 = APInt::getLowBitsSet(BitWidth,
551 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000552
553 // We need to take the minimum number of known bits
554 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
555 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
556
Chris Lattner173234a2008-06-02 01:18:21 +0000557 KnownZero = Mask &
558 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000559 std::min(KnownZero2.countTrailingOnes(),
560 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000561 break;
562 }
563 }
564 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000565
566 // Otherwise take the unions of the known bit sets of the operands,
567 // taking conservative care to avoid excessive recursion.
568 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
569 KnownZero = APInt::getAllOnesValue(BitWidth);
570 KnownOne = APInt::getAllOnesValue(BitWidth);
571 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
572 // Skip direct self references.
573 if (P->getIncomingValue(i) == P) continue;
574
575 KnownZero2 = APInt(BitWidth, 0);
576 KnownOne2 = APInt(BitWidth, 0);
577 // Recurse, but cap the recursion to one level, because we don't
578 // want to waste time spinning around in loops.
579 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
580 KnownZero2, KnownOne2, TD, MaxDepth-1);
581 KnownZero &= KnownZero2;
582 KnownOne &= KnownOne2;
583 // If all bits have been ruled out, there's no need to check
584 // more operands.
585 if (!KnownZero && !KnownOne)
586 break;
587 }
588 }
Chris Lattner173234a2008-06-02 01:18:21 +0000589 break;
590 }
591 case Instruction::Call:
592 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
593 switch (II->getIntrinsicID()) {
594 default: break;
595 case Intrinsic::ctpop:
596 case Intrinsic::ctlz:
597 case Intrinsic::cttz: {
598 unsigned LowBits = Log2_32(BitWidth)+1;
599 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
600 break;
601 }
602 }
603 }
604 break;
605 }
606}
607
608/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
609/// this predicate to simplify operations downstream. Mask is known to be zero
610/// for bits that V cannot have.
611bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
612 TargetData *TD, unsigned Depth) {
613 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
614 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 return (KnownZero & Mask) == Mask;
617}
618
619
620
621/// ComputeNumSignBits - Return the number of times the sign bit of the
622/// register is replicated into the other bits. We know that at least 1 bit
623/// is always equal to the sign bit (itself), but other cases can give us
624/// information. For example, immediately after an "ashr X, 2", we know that
625/// the top 3 bits are all equal to each other, so we return 3.
626///
627/// 'Op' must have a scalar integer type.
628///
629unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) {
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000630 assert((TD || V->getType()->isIntOrIntVector()) &&
631 "ComputeNumSignBits requires a TargetData object to operate "
632 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000633 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000634 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
635 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000636 unsigned Tmp, Tmp2;
637 unsigned FirstAnswer = 1;
638
Chris Lattnerd82e5112008-06-02 18:39:07 +0000639 // Note that ConstantInt is handled by the general ComputeMaskedBits case
640 // below.
641
Chris Lattner173234a2008-06-02 01:18:21 +0000642 if (Depth == 6)
643 return 1; // Limit search depth.
644
Dan Gohmanca178902009-07-17 20:47:02 +0000645 Operator *U = dyn_cast<Operator>(V);
646 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000647 default: break;
648 case Instruction::SExt:
649 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
650 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
651
652 case Instruction::AShr:
653 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
654 // ashr X, C -> adds C sign bits.
655 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
656 Tmp += C->getZExtValue();
657 if (Tmp > TyBits) Tmp = TyBits;
658 }
659 return Tmp;
660 case Instruction::Shl:
661 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
662 // shl destroys sign bits.
663 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
664 if (C->getZExtValue() >= TyBits || // Bad shift.
665 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
666 return Tmp - C->getZExtValue();
667 }
668 break;
669 case Instruction::And:
670 case Instruction::Or:
671 case Instruction::Xor: // NOT is handled here.
672 // Logical binary ops preserve the number of sign bits at the worst.
673 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
674 if (Tmp != 1) {
675 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
676 FirstAnswer = std::min(Tmp, Tmp2);
677 // We computed what we know about the sign bits as our first
678 // answer. Now proceed to the generic code that uses
679 // ComputeMaskedBits, and pick whichever answer is better.
680 }
681 break;
682
683 case Instruction::Select:
684 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
685 if (Tmp == 1) return 1; // Early out.
686 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
687 return std::min(Tmp, Tmp2);
688
689 case Instruction::Add:
690 // Add can have at most one carry bit. Thus we know that the output
691 // is, at worst, one more bit than the inputs.
692 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
693 if (Tmp == 1) return 1; // Early out.
694
695 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000696 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000697 if (CRHS->isAllOnesValue()) {
698 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
699 APInt Mask = APInt::getAllOnesValue(TyBits);
700 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
701 Depth+1);
702
703 // If the input is known to be 0 or 1, the output is 0/-1, which is all
704 // sign bits set.
705 if ((KnownZero | APInt(TyBits, 1)) == Mask)
706 return TyBits;
707
708 // If we are subtracting one from a positive number, there is no carry
709 // out of the result.
710 if (KnownZero.isNegative())
711 return Tmp;
712 }
713
714 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
715 if (Tmp2 == 1) return 1;
716 return std::min(Tmp, Tmp2)-1;
717 break;
718
719 case Instruction::Sub:
720 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
721 if (Tmp2 == 1) return 1;
722
723 // Handle NEG.
724 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
725 if (CLHS->isNullValue()) {
726 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
727 APInt Mask = APInt::getAllOnesValue(TyBits);
728 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
729 TD, Depth+1);
730 // If the input is known to be 0 or 1, the output is 0/-1, which is all
731 // sign bits set.
732 if ((KnownZero | APInt(TyBits, 1)) == Mask)
733 return TyBits;
734
735 // If the input is known to be positive (the sign bit is known clear),
736 // the output of the NEG has the same number of sign bits as the input.
737 if (KnownZero.isNegative())
738 return Tmp2;
739
740 // Otherwise, we treat this like a SUB.
741 }
742
743 // Sub can have at most one carry bit. Thus we know that the output
744 // is, at worst, one more bit than the inputs.
745 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
746 if (Tmp == 1) return 1; // Early out.
747 return std::min(Tmp, Tmp2)-1;
748 break;
749 case Instruction::Trunc:
750 // FIXME: it's tricky to do anything useful for this, but it is an important
751 // case for targets like X86.
752 break;
753 }
754
755 // Finally, if we can prove that the top bits of the result are 0's or 1's,
756 // use this information.
757 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
758 APInt Mask = APInt::getAllOnesValue(TyBits);
759 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
760
761 if (KnownZero.isNegative()) { // sign bit is 0
762 Mask = KnownZero;
763 } else if (KnownOne.isNegative()) { // sign bit is 1;
764 Mask = KnownOne;
765 } else {
766 // Nothing known.
767 return FirstAnswer;
768 }
769
770 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
771 // the number of identical bits in the top of the input value.
772 Mask = ~Mask;
773 Mask <<= Mask.getBitWidth()-TyBits;
774 // Return # leading zeros. We use 'min' here in case Val was zero before
775 // shifting. We don't want to return '64' as for an i32 "0".
776 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
777}
Chris Lattner833f25d2008-06-02 01:29:46 +0000778
779/// CannotBeNegativeZero - Return true if we can prove that the specified FP
780/// value is never equal to -0.0.
781///
782/// NOTE: this function will need to be revisited when we support non-default
783/// rounding modes!
784///
785bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
786 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
787 return !CFP->getValueAPF().isNegZero();
788
789 if (Depth == 6)
790 return 1; // Limit search depth.
791
Dan Gohmanca178902009-07-17 20:47:02 +0000792 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +0000793 if (I == 0) return false;
794
795 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000796 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +0000797 isa<ConstantFP>(I->getOperand(1)) &&
798 cast<ConstantFP>(I->getOperand(1))->isNullValue())
799 return true;
800
801 // sitofp and uitofp turn into +0.0 for zero.
802 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
803 return true;
804
805 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
806 // sqrt(-0.0) = -0.0, no other negative results are possible.
807 if (II->getIntrinsicID() == Intrinsic::sqrt)
808 return CannotBeNegativeZero(II->getOperand(1), Depth+1);
809
810 if (const CallInst *CI = dyn_cast<CallInst>(I))
811 if (const Function *F = CI->getCalledFunction()) {
812 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000813 // abs(x) != -0.0
814 if (F->getName() == "abs") return true;
815 // abs[lf](x) != -0.0
816 if (F->getName() == "absf") return true;
817 if (F->getName() == "absl") return true;
Chris Lattner833f25d2008-06-02 01:29:46 +0000818 }
819 }
820
821 return false;
822}
823
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000824// This is the recursive version of BuildSubAggregate. It takes a few different
825// arguments. Idxs is the index within the nested struct From that we are
826// looking at now (which is of type IndexedType). IdxSkip is the number of
827// indices from Idxs that should be left out when inserting into the resulting
828// struct. To is the result struct built so far, new insertvalue instructions
829// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +0000830static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
831 SmallVector<unsigned, 10> &Idxs,
832 unsigned IdxSkip,
833 LLVMContext &Context,
834 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000835 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
836 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000837 // Save the original To argument so we can modify it
838 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000839 // General case, the type indexed by Idxs is a struct
840 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
841 // Process each struct element recursively
842 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000843 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000844 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Owen Anderson76f600b2009-07-06 22:37:39 +0000845 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000846 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000847 if (!To) {
848 // Couldn't find any inserted value for this index? Cleanup
849 while (PrevTo != OrigTo) {
850 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
851 PrevTo = Del->getAggregateOperand();
852 Del->eraseFromParent();
853 }
854 // Stop processing elements
855 break;
856 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000857 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000858 // If we succesfully found a value for each of our subaggregates
859 if (To)
860 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000861 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000862 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
863 // the struct's elements had a value that was inserted directly. In the latter
864 // case, perhaps we can't determine each of the subelements individually, but
865 // we might be able to find the complete struct somewhere.
866
867 // Find the value that is at that particular spot
Owen Anderson76f600b2009-07-06 22:37:39 +0000868 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end(), Context);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000869
870 if (!V)
871 return NULL;
872
873 // Insert the value in the new (sub) aggregrate
874 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
875 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000876}
877
878// This helper takes a nested struct and extracts a part of it (which is again a
879// struct) into a new value. For example, given the struct:
880// { a, { b, { c, d }, e } }
881// and the indices "1, 1" this returns
882// { c, d }.
883//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000884// It does this by inserting an insertvalue for each element in the resulting
885// struct, as opposed to just inserting a single struct. This will only work if
886// each of the elements of the substruct are known (ie, inserted into From by an
887// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000888//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000889// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +0000890static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
891 const unsigned *idx_end, LLVMContext &Context,
892 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000893 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000894 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
895 idx_begin,
896 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000897 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000898 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
899 unsigned IdxSkip = Idxs.size();
900
Owen Anderson76f600b2009-07-06 22:37:39 +0000901 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip,
902 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000903}
904
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000905/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
906/// the scalar value indexed is already around as a register, for example if it
907/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000908///
909/// If InsertBefore is not null, this function will duplicate (modified)
910/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000911Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Owen Andersone922c022009-07-22 00:24:57 +0000912 const unsigned *idx_end, LLVMContext &Context,
Owen Anderson76f600b2009-07-06 22:37:39 +0000913 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000914 // Nothing to index? Just return V then (this is useful at the end of our
915 // recursion)
916 if (idx_begin == idx_end)
917 return V;
918 // We have indices, so V should have an indexable type
919 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
920 && "Not looking at a struct or array?");
921 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
922 && "Invalid indices for type?");
923 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +0000924
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000925 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000926 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000927 idx_begin,
928 idx_end));
929 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +0000930 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +0000931 idx_begin,
932 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000933 else if (Constant *C = dyn_cast<Constant>(V)) {
934 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
935 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +0000936 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
937 idx_end, Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000938 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
939 // Loop the indices for the insertvalue instruction in parallel with the
940 // requested indices
941 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000942 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
943 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +0000944 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +0000945 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +0000946 // The requested index identifies a part of a nested aggregate. Handle
947 // this specially. For example,
948 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
949 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
950 // %C = extractvalue {i32, { i32, i32 } } %B, 1
951 // This can be changed into
952 // %A = insertvalue {i32, i32 } undef, i32 10, 0
953 // %C = insertvalue {i32, i32 } %A, i32 11, 1
954 // which allows the unused 0,0 element from the nested struct to be
955 // removed.
Owen Anderson76f600b2009-07-06 22:37:39 +0000956 return BuildSubAggregate(V, idx_begin, req_idx,
957 Context, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +0000958 else
959 // We can't handle this without inserting insertvalues
960 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +0000961 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000962
963 // This insert value inserts something else than what we are looking for.
964 // See if the (aggregrate) value inserted into has the value we are
965 // looking for, then.
966 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000967 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Owen Anderson76f600b2009-07-06 22:37:39 +0000968 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000969 }
970 // If we end up here, the indices of the insertvalue match with those
971 // requested (though possibly only partially). Now we recursively look at
972 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000973 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Owen Anderson76f600b2009-07-06 22:37:39 +0000974 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000975 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
976 // If we're extracting a value from an aggregrate that was extracted from
977 // something else, we can extract from that something else directly instead.
978 // However, we will need to chain I's indices with the requested indices.
979
980 // Calculate the number of indices required
981 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
982 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000983 SmallVector<unsigned, 5> Idxs;
984 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000985 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000986 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000987 i != e; ++i)
988 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000989
990 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000991 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
992 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000993
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000994 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +0000995 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000996
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +0000997 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Owen Anderson76f600b2009-07-06 22:37:39 +0000998 Context, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000999 }
1000 // Otherwise, we don't know (such as, extracting from a function return value
1001 // or load instruction)
1002 return 0;
1003}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001004
1005/// GetConstantStringInfo - This function computes the length of a
1006/// null-terminated C string pointed to by V. If successful, it returns true
1007/// and returns the string in Str. If unsuccessful, it returns false.
Bill Wendling0582ae92009-03-13 04:39:26 +00001008bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset,
1009 bool StopAtNul) {
1010 // If V is NULL then return false;
1011 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001012
1013 // Look through bitcast instructions.
1014 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001015 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1016
Evan Cheng0ff39b32008-06-30 07:31:25 +00001017 // If the value is not a GEP instruction nor a constant expression with a
1018 // GEP instruction, then return false because ConstantArray can't occur
1019 // any other way
1020 User *GEP = 0;
1021 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1022 GEP = GEPI;
1023 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1024 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001025 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1026 if (CE->getOpcode() != Instruction::GetElementPtr)
1027 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001028 GEP = CE;
1029 }
1030
1031 if (GEP) {
1032 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001033 if (GEP->getNumOperands() != 3)
1034 return false;
1035
Evan Cheng0ff39b32008-06-30 07:31:25 +00001036 // Make sure the index-ee is a pointer to array of i8.
1037 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1038 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001039 if (AT == 0 || AT->getElementType() != Type::getInt8Ty(V->getContext()))
Bill Wendling0582ae92009-03-13 04:39:26 +00001040 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001041
1042 // Check to make sure that the first operand of the GEP is an integer and
1043 // has value 0 so that we are sure we're indexing into the initializer.
1044 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001045 if (FirstIdx == 0 || !FirstIdx->isZero())
1046 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001047
1048 // If the second index isn't a ConstantInt, then this is a variable index
1049 // into the array. If this occurs, we can't say anything meaningful about
1050 // the string.
1051 uint64_t StartIdx = 0;
Bill Wendling0582ae92009-03-13 04:39:26 +00001052 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001053 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001054 else
1055 return false;
1056 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001057 StopAtNul);
1058 }
1059
1060 // The GEP instruction, constant or instruction, must reference a global
1061 // variable that is a constant and is initialized. The referenced constant
1062 // initializer is the array that we'll use for optimization.
1063 GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Bill Wendling0582ae92009-03-13 04:39:26 +00001064 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1065 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001066 Constant *GlobalInit = GV->getInitializer();
1067
1068 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001069 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001070 // This is a degenerate case. The initializer is constant zero so the
1071 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001072 Str.clear();
1073 return true;
1074 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001075
1076 // Must be a Constant Array
1077 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +00001078 if (Array == 0 ||
1079 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Bill Wendling0582ae92009-03-13 04:39:26 +00001080 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001081
1082 // Get the number of elements in the array
1083 uint64_t NumElts = Array->getType()->getNumElements();
1084
Bill Wendling0582ae92009-03-13 04:39:26 +00001085 if (Offset > NumElts)
1086 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001087
1088 // Traverse the constant array from 'Offset' which is the place the GEP refers
1089 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001090 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001091 for (unsigned i = Offset; i != NumElts; ++i) {
1092 Constant *Elt = Array->getOperand(i);
1093 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001094 if (!CI) // This array isn't suitable, non-int initializer.
1095 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001096 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001097 return true; // we found end of string, success!
1098 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001099 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001100
Evan Cheng0ff39b32008-06-30 07:31:25 +00001101 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001102 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001103}