blob: f8145cd0e3d9bca93a01d84a281112ea8b2b22eb [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"
Dan Gohman24371272010-12-15 20:10:26 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner173234a2008-06-02 01:18:21 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000019#include "llvm/GlobalVariable.h"
Dan Gohman307a7c42009-09-15 16:14:44 +000020#include "llvm/GlobalAlias.h"
Chris Lattner173234a2008-06-02 01:18:21 +000021#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000022#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000023#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000024#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000025#include "llvm/Support/GetElementPtrTypeIterator.h"
26#include "llvm/Support/MathExtras.h"
Eric Christopher25ec4832010-03-05 06:58:57 +000027#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000028#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000029using namespace llvm;
30
Chris Lattner173234a2008-06-02 01:18:21 +000031/// ComputeMaskedBits - Determine which of the bits specified in Mask are
32/// known to be either zero or one and return them in the KnownZero/KnownOne
33/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
34/// processing.
35/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
36/// we cannot optimize based on the assumption that it is zero without changing
37/// it to be an explicit zero. If we don't change it to zero, other code could
38/// optimized based on the contradictory assumption that it is non-zero.
39/// Because instcombine aggressively folds operations with undef args anyway,
40/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +000041///
42/// This function is defined on values with integer type, values with pointer
43/// type (but only if TD is non-null), and vectors of integers. In the case
44/// where V is a vector, the mask, known zero, and known one values are the
45/// same width as the vector element, and the bit is set only if it is true
46/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +000047void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
48 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +000049 const TargetData *TD, unsigned Depth) {
Dan Gohman9004c8a2009-05-21 02:28:33 +000050 const unsigned MaxDepth = 6;
Chris Lattner173234a2008-06-02 01:18:21 +000051 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000052 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000053 unsigned BitWidth = Mask.getBitWidth();
Duncan Sands1df98592010-02-16 11:11:14 +000054 assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000055 && "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000056 assert((!TD ||
57 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000058 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +000059 V->getType()->getScalarSizeInBits() == BitWidth) &&
Chris Lattner173234a2008-06-02 01:18:21 +000060 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 }
Dan Gohman6de29f82009-06-15 22:12:54 +000070 // Null and aggregate-zero are all-zeros.
71 if (isa<ConstantPointerNull>(V) ||
72 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000073 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +000074 KnownZero = Mask;
75 return;
76 }
Dan Gohman6de29f82009-06-15 22:12:54 +000077 // Handle a constant vector by taking the intersection of the known bits of
78 // each element.
79 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000080 KnownZero.setAllBits(); KnownOne.setAllBits();
Dan Gohman6de29f82009-06-15 22:12:54 +000081 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
82 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
83 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
84 TD, Depth);
85 KnownZero &= KnownZero2;
86 KnownOne &= KnownOne2;
87 }
88 return;
89 }
Chris Lattner173234a2008-06-02 01:18:21 +000090 // The address of an aligned GlobalValue has trailing zeros.
91 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
92 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +000093 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
94 const Type *ObjectType = GV->getType()->getElementType();
95 // If the object is defined in the current Module, we'll be giving
96 // it the preferred alignment. Otherwise, we have to assume that it
97 // may only have the minimum ABI alignment.
98 if (!GV->isDeclaration() && !GV->mayBeOverridden())
99 Align = TD->getPrefTypeAlignment(ObjectType);
100 else
101 Align = TD->getABITypeAlignment(ObjectType);
102 }
Chris Lattner173234a2008-06-02 01:18:21 +0000103 if (Align > 0)
104 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
105 CountTrailingZeros_32(Align));
106 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000107 KnownZero.clearAllBits();
108 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000109 return;
110 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000111 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
112 // the bits of its aliasee.
113 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
114 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000115 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000116 } else {
117 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
118 TD, Depth+1);
119 }
120 return;
121 }
Chris Lattner173234a2008-06-02 01:18:21 +0000122
Jay Foad7a874dd2010-12-01 08:53:58 +0000123 KnownZero.clearAllBits(); KnownOne.clearAllBits(); // Start out not knowing anything.
Chris Lattner173234a2008-06-02 01:18:21 +0000124
Dan Gohman9004c8a2009-05-21 02:28:33 +0000125 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000126 return; // Limit search depth.
127
Dan Gohmanca178902009-07-17 20:47:02 +0000128 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000129 if (!I) return;
130
131 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000132 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000133 default: break;
134 case Instruction::And: {
135 // If either the LHS or the RHS are Zero, the result is zero.
136 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
137 APInt Mask2(Mask & ~KnownZero);
138 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
139 Depth+1);
140 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
141 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
142
143 // Output known-1 bits are only known if set in both the LHS & RHS.
144 KnownOne &= KnownOne2;
145 // Output known-0 are known to be clear if zero in either the LHS | RHS.
146 KnownZero |= KnownZero2;
147 return;
148 }
149 case Instruction::Or: {
150 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
151 APInt Mask2(Mask & ~KnownOne);
152 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
153 Depth+1);
154 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
155 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
156
157 // Output known-0 bits are only known if clear in both the LHS & RHS.
158 KnownZero &= KnownZero2;
159 // Output known-1 are known to be set if set in either the LHS | RHS.
160 KnownOne |= KnownOne2;
161 return;
162 }
163 case Instruction::Xor: {
164 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
165 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
166 Depth+1);
167 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
168 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
169
170 // Output known-0 bits are known if clear or set in both the LHS & RHS.
171 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
172 // Output known-1 are known to be set if set in only one of the LHS, RHS.
173 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
174 KnownZero = KnownZeroOut;
175 return;
176 }
177 case Instruction::Mul: {
178 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
179 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
180 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
181 Depth+1);
182 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
183 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
184
185 // If low bits are zero in either operand, output low known-0 bits.
186 // Also compute a conserative estimate for high known-0 bits.
187 // More trickiness is possible, but this is sufficient for the
188 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000189 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000190 unsigned TrailZ = KnownZero.countTrailingOnes() +
191 KnownZero2.countTrailingOnes();
192 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
193 KnownZero2.countLeadingOnes(),
194 BitWidth) - BitWidth;
195
196 TrailZ = std::min(TrailZ, BitWidth);
197 LeadZ = std::min(LeadZ, BitWidth);
198 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
199 APInt::getHighBitsSet(BitWidth, LeadZ);
200 KnownZero &= Mask;
201 return;
202 }
203 case Instruction::UDiv: {
204 // For the purposes of computing leading zeros we can conservatively
205 // treat a udiv as a logical right shift by the power of 2 known to
206 // be less than the denominator.
207 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
208 ComputeMaskedBits(I->getOperand(0),
209 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
210 unsigned LeadZ = KnownZero2.countLeadingOnes();
211
Jay Foad7a874dd2010-12-01 08:53:58 +0000212 KnownOne2.clearAllBits();
213 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000214 ComputeMaskedBits(I->getOperand(1),
215 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
216 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
217 if (RHSUnknownLeadingOnes != BitWidth)
218 LeadZ = std::min(BitWidth,
219 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
220
221 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
222 return;
223 }
224 case Instruction::Select:
225 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
226 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
227 Depth+1);
228 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
229 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
230
231 // Only known if known in both the LHS and RHS.
232 KnownOne &= KnownOne2;
233 KnownZero &= KnownZero2;
234 return;
235 case Instruction::FPTrunc:
236 case Instruction::FPExt:
237 case Instruction::FPToUI:
238 case Instruction::FPToSI:
239 case Instruction::SIToFP:
240 case Instruction::UIToFP:
241 return; // Can't work with floating point.
242 case Instruction::PtrToInt:
243 case Instruction::IntToPtr:
244 // We can't handle these if we don't know the pointer size.
245 if (!TD) return;
246 // FALL THROUGH and handle them the same as zext/trunc.
247 case Instruction::ZExt:
248 case Instruction::Trunc: {
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000249 const Type *SrcTy = I->getOperand(0)->getType();
250
251 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000252 // Note that we handle pointer operands here because of inttoptr/ptrtoint
253 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000254 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000255 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
256 else
257 SrcBitWidth = SrcTy->getScalarSizeInBits();
258
Jay Foad40f8f622010-12-07 08:25:19 +0000259 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
260 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
261 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000262 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
263 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000264 KnownZero = KnownZero.zextOrTrunc(BitWidth);
265 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000266 // Any top bits are known to be zero.
267 if (BitWidth > SrcBitWidth)
268 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
269 return;
270 }
271 case Instruction::BitCast: {
272 const Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000273 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000274 // TODO: For now, not handling conversions like:
275 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000276 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000277 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
278 Depth+1);
279 return;
280 }
281 break;
282 }
283 case Instruction::SExt: {
284 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000285 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000286
Jay Foad40f8f622010-12-07 08:25:19 +0000287 APInt MaskIn = Mask.trunc(SrcBitWidth);
288 KnownZero = KnownZero.trunc(SrcBitWidth);
289 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000290 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
291 Depth+1);
292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000293 KnownZero = KnownZero.zext(BitWidth);
294 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000295
296 // If the sign bit of the input is known set or clear, then we know the
297 // top bits of the result.
298 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
299 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
300 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
301 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
302 return;
303 }
304 case Instruction::Shl:
305 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
307 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
308 APInt Mask2(Mask.lshr(ShiftAmt));
309 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
310 Depth+1);
311 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
312 KnownZero <<= ShiftAmt;
313 KnownOne <<= ShiftAmt;
314 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
315 return;
316 }
317 break;
318 case Instruction::LShr:
319 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
321 // Compute the new bits that are at the top now.
322 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
323
324 // Unsigned shift right.
325 APInt Mask2(Mask.shl(ShiftAmt));
326 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
327 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000328 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000329 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
330 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
331 // high bits known zero.
332 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
333 return;
334 }
335 break;
336 case Instruction::AShr:
337 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
338 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
339 // Compute the new bits that are at the top now.
340 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
341
342 // Signed shift right.
343 APInt Mask2(Mask.shl(ShiftAmt));
344 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
345 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000346 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000347 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
348 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
349
350 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
351 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
352 KnownZero |= HighBits;
353 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
354 KnownOne |= HighBits;
355 return;
356 }
357 break;
358 case Instruction::Sub: {
359 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
360 // We know that the top bits of C-X are clear if X contains less bits
361 // than C (i.e. no wrap-around can happen). For example, 20-X is
362 // positive if we can prove that X is >= 0 and < 16.
363 if (!CLHS->getValue().isNegative()) {
364 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
365 // NLZ can't be BitWidth with no sign bit
366 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
367 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
368 TD, Depth+1);
369
370 // If all of the MaskV bits are known to be zero, then we know the
371 // output top bits are zero, because we now know that the output is
372 // from [0-C].
373 if ((KnownZero2 & MaskV) == MaskV) {
374 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
375 // Top bits known zero.
376 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
377 }
378 }
379 }
380 }
381 // fall through
382 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000383 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000384 // other operand has in those bit positions will be preserved in the
385 // result. For an add, this works with either operand. For a subtract,
386 // this only works if the known zeros are in the right operand.
387 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
388 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
389 BitWidth - Mask.countLeadingZeros());
390 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000391 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000392 assert((LHSKnownZero & LHSKnownOne) == 0 &&
393 "Bits known to be one AND zero?");
394 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000395
396 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
397 Depth+1);
398 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000399 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000400
Dan Gohman39250432009-05-24 18:02:35 +0000401 // Determine which operand has more trailing zeros, and use that
402 // many bits from the other operand.
403 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000404 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000405 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
406 KnownZero |= KnownZero2 & Mask;
407 KnownOne |= KnownOne2 & Mask;
408 } else {
409 // If the known zeros are in the left operand for a subtract,
410 // fall back to the minimum known zeros in both operands.
411 KnownZero |= APInt::getLowBitsSet(BitWidth,
412 std::min(LHSKnownZeroOut,
413 RHSKnownZeroOut));
414 }
415 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
416 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
417 KnownZero |= LHSKnownZero & Mask;
418 KnownOne |= LHSKnownOne & Mask;
419 }
Chris Lattner173234a2008-06-02 01:18:21 +0000420 return;
421 }
422 case Instruction::SRem:
423 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000424 APInt RA = Rem->getValue().abs();
425 if (RA.isPowerOf2()) {
426 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000427 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
428 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
429 Depth+1);
430
Duncan Sandscfd54182010-01-29 06:18:37 +0000431 // The low bits of the first operand are unchanged by the srem.
432 KnownZero = KnownZero2 & LowBits;
433 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000434
Duncan Sandscfd54182010-01-29 06:18:37 +0000435 // If the first operand is non-negative or has all low bits zero, then
436 // the upper bits are all zero.
437 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
438 KnownZero |= ~LowBits;
439
440 // If the first operand is negative and not all low bits are zero, then
441 // the upper bits are all one.
442 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
443 KnownOne |= ~LowBits;
444
445 KnownZero &= Mask;
446 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000447
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000448 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000449 }
450 }
451 break;
452 case Instruction::URem: {
453 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
454 APInt RA = Rem->getValue();
455 if (RA.isPowerOf2()) {
456 APInt LowBits = (RA - 1);
457 APInt Mask2 = LowBits & Mask;
458 KnownZero |= ~LowBits & Mask;
459 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
460 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000461 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000462 break;
463 }
464 }
465
466 // Since the result is less than or equal to either operand, any leading
467 // zero bits in either operand must also exist in the result.
468 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
469 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
470 TD, Depth+1);
471 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
472 TD, Depth+1);
473
Chris Lattner79abedb2009-01-20 18:22:57 +0000474 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000475 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000476 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000477 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
478 break;
479 }
480
Victor Hernandeza276c602009-10-17 01:18:07 +0000481 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000482 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000483 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000484 if (Align == 0 && TD)
485 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000486
487 if (Align > 0)
488 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
489 CountTrailingZeros_32(Align));
490 break;
491 }
492 case Instruction::GetElementPtr: {
493 // Analyze all of the subscripts of this getelementptr instruction
494 // to determine if we can prove known low zero bits.
495 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
496 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
497 ComputeMaskedBits(I->getOperand(0), LocalMask,
498 LocalKnownZero, LocalKnownOne, TD, Depth+1);
499 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
500
501 gep_type_iterator GTI = gep_type_begin(I);
502 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
503 Value *Index = I->getOperand(i);
504 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
505 // Handle struct member offset arithmetic.
506 if (!TD) return;
507 const StructLayout *SL = TD->getStructLayout(STy);
508 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
509 uint64_t Offset = SL->getElementOffset(Idx);
510 TrailZ = std::min(TrailZ,
511 CountTrailingZeros_64(Offset));
512 } else {
513 // Handle array index arithmetic.
514 const Type *IndexedTy = GTI.getIndexedType();
515 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000516 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000517 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000518 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
519 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
520 ComputeMaskedBits(Index, LocalMask,
521 LocalKnownZero, LocalKnownOne, TD, Depth+1);
522 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000523 unsigned(CountTrailingZeros_64(TypeSize) +
524 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000525 }
526 }
527
528 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
529 break;
530 }
531 case Instruction::PHI: {
532 PHINode *P = cast<PHINode>(I);
533 // Handle the case of a simple two-predecessor recurrence PHI.
534 // There's a lot more that could theoretically be done here, but
535 // this is sufficient to catch some interesting cases.
536 if (P->getNumIncomingValues() == 2) {
537 for (unsigned i = 0; i != 2; ++i) {
538 Value *L = P->getIncomingValue(i);
539 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000540 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000541 if (!LU)
542 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000543 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000544 // Check for operations that have the property that if
545 // both their operands have low zero bits, the result
546 // will have low zero bits.
547 if (Opcode == Instruction::Add ||
548 Opcode == Instruction::Sub ||
549 Opcode == Instruction::And ||
550 Opcode == Instruction::Or ||
551 Opcode == Instruction::Mul) {
552 Value *LL = LU->getOperand(0);
553 Value *LR = LU->getOperand(1);
554 // Find a recurrence.
555 if (LL == I)
556 L = LR;
557 else if (LR == I)
558 L = LL;
559 else
560 break;
561 // Ok, we have a PHI of the form L op= R. Check for low
562 // zero bits.
563 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
564 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
565 Mask2 = APInt::getLowBitsSet(BitWidth,
566 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000567
568 // We need to take the minimum number of known bits
569 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
570 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
571
Chris Lattner173234a2008-06-02 01:18:21 +0000572 KnownZero = Mask &
573 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000574 std::min(KnownZero2.countTrailingOnes(),
575 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000576 break;
577 }
578 }
579 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000580
581 // Otherwise take the unions of the known bit sets of the operands,
582 // taking conservative care to avoid excessive recursion.
583 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
584 KnownZero = APInt::getAllOnesValue(BitWidth);
585 KnownOne = APInt::getAllOnesValue(BitWidth);
586 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
587 // Skip direct self references.
588 if (P->getIncomingValue(i) == P) continue;
589
590 KnownZero2 = APInt(BitWidth, 0);
591 KnownOne2 = APInt(BitWidth, 0);
592 // Recurse, but cap the recursion to one level, because we don't
593 // want to waste time spinning around in loops.
594 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
595 KnownZero2, KnownOne2, TD, MaxDepth-1);
596 KnownZero &= KnownZero2;
597 KnownOne &= KnownOne2;
598 // If all bits have been ruled out, there's no need to check
599 // more operands.
600 if (!KnownZero && !KnownOne)
601 break;
602 }
603 }
Chris Lattner173234a2008-06-02 01:18:21 +0000604 break;
605 }
606 case Instruction::Call:
607 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
608 switch (II->getIntrinsicID()) {
609 default: break;
610 case Intrinsic::ctpop:
611 case Intrinsic::ctlz:
612 case Intrinsic::cttz: {
613 unsigned LowBits = Log2_32(BitWidth)+1;
614 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
615 break;
616 }
617 }
618 }
619 break;
620 }
621}
622
623/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
624/// this predicate to simplify operations downstream. Mask is known to be zero
625/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000626///
627/// This function is defined on values with integer type, values with pointer
628/// type (but only if TD is non-null), and vectors of integers. In the case
629/// where V is a vector, the mask, known zero, and known one values are the
630/// same width as the vector element, and the bit is set only if it is true
631/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000632bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000633 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000634 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
635 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
636 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
637 return (KnownZero & Mask) == Mask;
638}
639
640
641
642/// ComputeNumSignBits - Return the number of times the sign bit of the
643/// register is replicated into the other bits. We know that at least 1 bit
644/// is always equal to the sign bit (itself), but other cases can give us
645/// information. For example, immediately after an "ashr X, 2", we know that
646/// the top 3 bits are all equal to each other, so we return 3.
647///
648/// 'Op' must have a scalar integer type.
649///
Dan Gohman846a2f22009-08-27 17:51:25 +0000650unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
651 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000652 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000653 "ComputeNumSignBits requires a TargetData object to operate "
654 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000655 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000656 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
657 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000658 unsigned Tmp, Tmp2;
659 unsigned FirstAnswer = 1;
660
Chris Lattnerd82e5112008-06-02 18:39:07 +0000661 // Note that ConstantInt is handled by the general ComputeMaskedBits case
662 // below.
663
Chris Lattner173234a2008-06-02 01:18:21 +0000664 if (Depth == 6)
665 return 1; // Limit search depth.
666
Dan Gohmanca178902009-07-17 20:47:02 +0000667 Operator *U = dyn_cast<Operator>(V);
668 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000669 default: break;
670 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000671 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000672 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
673
674 case Instruction::AShr:
675 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
676 // ashr X, C -> adds C sign bits.
677 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
678 Tmp += C->getZExtValue();
679 if (Tmp > TyBits) Tmp = TyBits;
680 }
Nate Begeman9a3dc552010-12-17 23:12:19 +0000681 // vector ashr X, <C, C, C, C> -> adds C sign bits
682 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
683 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
684 Tmp += CI->getZExtValue();
685 if (Tmp > TyBits) Tmp = TyBits;
686 }
687 }
Chris Lattner173234a2008-06-02 01:18:21 +0000688 return Tmp;
689 case Instruction::Shl:
690 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
691 // shl destroys sign bits.
692 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
693 if (C->getZExtValue() >= TyBits || // Bad shift.
694 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
695 return Tmp - C->getZExtValue();
696 }
697 break;
698 case Instruction::And:
699 case Instruction::Or:
700 case Instruction::Xor: // NOT is handled here.
701 // Logical binary ops preserve the number of sign bits at the worst.
702 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
703 if (Tmp != 1) {
704 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
705 FirstAnswer = std::min(Tmp, Tmp2);
706 // We computed what we know about the sign bits as our first
707 // answer. Now proceed to the generic code that uses
708 // ComputeMaskedBits, and pick whichever answer is better.
709 }
710 break;
711
712 case Instruction::Select:
713 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
714 if (Tmp == 1) return 1; // Early out.
715 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
716 return std::min(Tmp, Tmp2);
717
718 case Instruction::Add:
719 // Add can have at most one carry bit. Thus we know that the output
720 // is, at worst, one more bit than the inputs.
721 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
722 if (Tmp == 1) return 1; // Early out.
723
724 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000725 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000726 if (CRHS->isAllOnesValue()) {
727 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
728 APInt Mask = APInt::getAllOnesValue(TyBits);
729 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
730 Depth+1);
731
732 // If the input is known to be 0 or 1, the output is 0/-1, which is all
733 // sign bits set.
734 if ((KnownZero | APInt(TyBits, 1)) == Mask)
735 return TyBits;
736
737 // If we are subtracting one from a positive number, there is no carry
738 // out of the result.
739 if (KnownZero.isNegative())
740 return Tmp;
741 }
742
743 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
744 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000745 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +0000746
747 case Instruction::Sub:
748 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
749 if (Tmp2 == 1) return 1;
750
751 // Handle NEG.
752 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
753 if (CLHS->isNullValue()) {
754 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
755 APInt Mask = APInt::getAllOnesValue(TyBits);
756 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
757 TD, Depth+1);
758 // If the input is known to be 0 or 1, the output is 0/-1, which is all
759 // sign bits set.
760 if ((KnownZero | APInt(TyBits, 1)) == Mask)
761 return TyBits;
762
763 // If the input is known to be positive (the sign bit is known clear),
764 // the output of the NEG has the same number of sign bits as the input.
765 if (KnownZero.isNegative())
766 return Tmp2;
767
768 // Otherwise, we treat this like a SUB.
769 }
770
771 // Sub can have at most one carry bit. Thus we know that the output
772 // is, at worst, one more bit than the inputs.
773 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
774 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000775 return std::min(Tmp, Tmp2)-1;
776
777 case Instruction::PHI: {
778 PHINode *PN = cast<PHINode>(U);
779 // Don't analyze large in-degree PHIs.
780 if (PN->getNumIncomingValues() > 4) break;
781
782 // Take the minimum of all incoming values. This can't infinitely loop
783 // because of our depth threshold.
784 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
785 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
786 if (Tmp == 1) return Tmp;
787 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +0000788 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000789 }
790 return Tmp;
791 }
792
Chris Lattner173234a2008-06-02 01:18:21 +0000793 case Instruction::Trunc:
794 // FIXME: it's tricky to do anything useful for this, but it is an important
795 // case for targets like X86.
796 break;
797 }
798
799 // Finally, if we can prove that the top bits of the result are 0's or 1's,
800 // use this information.
801 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
802 APInt Mask = APInt::getAllOnesValue(TyBits);
803 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
804
805 if (KnownZero.isNegative()) { // sign bit is 0
806 Mask = KnownZero;
807 } else if (KnownOne.isNegative()) { // sign bit is 1;
808 Mask = KnownOne;
809 } else {
810 // Nothing known.
811 return FirstAnswer;
812 }
813
814 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
815 // the number of identical bits in the top of the input value.
816 Mask = ~Mask;
817 Mask <<= Mask.getBitWidth()-TyBits;
818 // Return # leading zeros. We use 'min' here in case Val was zero before
819 // shifting. We don't want to return '64' as for an i32 "0".
820 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
821}
Chris Lattner833f25d2008-06-02 01:29:46 +0000822
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000823/// ComputeMultiple - This function computes the integer multiple of Base that
824/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000825/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000826/// through SExt instructions only if LookThroughSExt is true.
827bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000828 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000829 const unsigned MaxDepth = 6;
830
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000831 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000832 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000833 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000834
835 const Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000836
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000837 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000838
839 if (Base == 0)
840 return false;
841
842 if (Base == 1) {
843 Multiple = V;
844 return true;
845 }
846
847 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
848 Constant *BaseVal = ConstantInt::get(T, Base);
849 if (CO && CO == BaseVal) {
850 // Multiple is 1.
851 Multiple = ConstantInt::get(T, 1);
852 return true;
853 }
854
855 if (CI && CI->getZExtValue() % Base == 0) {
856 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
857 return true;
858 }
859
860 if (Depth == MaxDepth) return false; // Limit search depth.
861
862 Operator *I = dyn_cast<Operator>(V);
863 if (!I) return false;
864
865 switch (I->getOpcode()) {
866 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +0000867 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000868 if (!LookThroughSExt) return false;
869 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +0000870 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000871 return ComputeMultiple(I->getOperand(0), Base, Multiple,
872 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000873 case Instruction::Shl:
874 case Instruction::Mul: {
875 Value *Op0 = I->getOperand(0);
876 Value *Op1 = I->getOperand(1);
877
878 if (I->getOpcode() == Instruction::Shl) {
879 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
880 if (!Op1CI) return false;
881 // Turn Op0 << Op1 into Op0 * 2^Op1
882 APInt Op1Int = Op1CI->getValue();
883 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +0000884 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +0000885 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +0000886 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000887 }
888
889 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +0000890 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
891 if (Constant *Op1C = dyn_cast<Constant>(Op1))
892 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
893 if (Op1C->getType()->getPrimitiveSizeInBits() <
894 MulC->getType()->getPrimitiveSizeInBits())
895 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
896 if (Op1C->getType()->getPrimitiveSizeInBits() >
897 MulC->getType()->getPrimitiveSizeInBits())
898 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
899
900 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
901 Multiple = ConstantExpr::getMul(MulC, Op1C);
902 return true;
903 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000904
905 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
906 if (Mul0CI->getValue() == 1) {
907 // V == Base * Op1, so return Op1
908 Multiple = Op1;
909 return true;
910 }
911 }
912
Chris Lattnere9711312010-09-05 17:20:46 +0000913 Value *Mul1 = NULL;
914 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
915 if (Constant *Op0C = dyn_cast<Constant>(Op0))
916 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
917 if (Op0C->getType()->getPrimitiveSizeInBits() <
918 MulC->getType()->getPrimitiveSizeInBits())
919 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
920 if (Op0C->getType()->getPrimitiveSizeInBits() >
921 MulC->getType()->getPrimitiveSizeInBits())
922 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
923
924 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
925 Multiple = ConstantExpr::getMul(MulC, Op0C);
926 return true;
927 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000928
929 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
930 if (Mul1CI->getValue() == 1) {
931 // V == Base * Op0, so return Op0
932 Multiple = Op0;
933 return true;
934 }
935 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +0000936 }
937 }
938
939 // We could not determine if V is a multiple of Base.
940 return false;
941}
942
Chris Lattner833f25d2008-06-02 01:29:46 +0000943/// CannotBeNegativeZero - Return true if we can prove that the specified FP
944/// value is never equal to -0.0.
945///
946/// NOTE: this function will need to be revisited when we support non-default
947/// rounding modes!
948///
949bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
950 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
951 return !CFP->getValueAPF().isNegZero();
952
953 if (Depth == 6)
954 return 1; // Limit search depth.
955
Dan Gohmanca178902009-07-17 20:47:02 +0000956 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +0000957 if (I == 0) return false;
958
959 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000960 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +0000961 isa<ConstantFP>(I->getOperand(1)) &&
962 cast<ConstantFP>(I->getOperand(1))->isNullValue())
963 return true;
964
965 // sitofp and uitofp turn into +0.0 for zero.
966 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
967 return true;
968
969 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
970 // sqrt(-0.0) = -0.0, no other negative results are possible.
971 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +0000972 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000973
974 if (const CallInst *CI = dyn_cast<CallInst>(I))
975 if (const Function *F = CI->getCalledFunction()) {
976 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +0000977 // abs(x) != -0.0
978 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +0000979 // fabs[lf](x) != -0.0
980 if (F->getName() == "fabs") return true;
981 if (F->getName() == "fabsf") return true;
982 if (F->getName() == "fabsl") return true;
983 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
984 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +0000985 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +0000986 }
987 }
988
989 return false;
990}
991
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +0000992// This is the recursive version of BuildSubAggregate. It takes a few different
993// arguments. Idxs is the index within the nested struct From that we are
994// looking at now (which is of type IndexedType). IdxSkip is the number of
995// indices from Idxs that should be left out when inserting into the resulting
996// struct. To is the result struct built so far, new insertvalue instructions
997// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +0000998static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
999 SmallVector<unsigned, 10> &Idxs,
1000 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001001 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001002 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1003 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001004 // Save the original To argument so we can modify it
1005 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001006 // General case, the type indexed by Idxs is a struct
1007 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1008 // Process each struct element recursively
1009 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001010 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001011 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001012 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001013 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001014 if (!To) {
1015 // Couldn't find any inserted value for this index? Cleanup
1016 while (PrevTo != OrigTo) {
1017 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1018 PrevTo = Del->getAggregateOperand();
1019 Del->eraseFromParent();
1020 }
1021 // Stop processing elements
1022 break;
1023 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001024 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001025 // If we succesfully found a value for each of our subaggregates
1026 if (To)
1027 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001028 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001029 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1030 // the struct's elements had a value that was inserted directly. In the latter
1031 // case, perhaps we can't determine each of the subelements individually, but
1032 // we might be able to find the complete struct somewhere.
1033
1034 // Find the value that is at that particular spot
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001035 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001036
1037 if (!V)
1038 return NULL;
1039
1040 // Insert the value in the new (sub) aggregrate
1041 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1042 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001043}
1044
1045// This helper takes a nested struct and extracts a part of it (which is again a
1046// struct) into a new value. For example, given the struct:
1047// { a, { b, { c, d }, e } }
1048// and the indices "1, 1" this returns
1049// { c, d }.
1050//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001051// It does this by inserting an insertvalue for each element in the resulting
1052// struct, as opposed to just inserting a single struct. This will only work if
1053// each of the elements of the substruct are known (ie, inserted into From by an
1054// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001055//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001056// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +00001057static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001058 const unsigned *idx_end,
Dan Gohman7db949d2009-08-07 01:32:21 +00001059 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001060 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001061 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1062 idx_begin,
1063 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001064 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001065 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1066 unsigned IdxSkip = Idxs.size();
1067
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001068 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001069}
1070
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001071/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1072/// the scalar value indexed is already around as a register, for example if it
1073/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001074///
1075/// If InsertBefore is not null, this function will duplicate (modified)
1076/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001077Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001078 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001079 // Nothing to index? Just return V then (this is useful at the end of our
1080 // recursion)
1081 if (idx_begin == idx_end)
1082 return V;
1083 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001084 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001085 && "Not looking at a struct or array?");
1086 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1087 && "Invalid indices for type?");
1088 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001089
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001090 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001091 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001092 idx_begin,
1093 idx_end));
1094 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001095 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +00001096 idx_begin,
1097 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001098 else if (Constant *C = dyn_cast<Constant>(V)) {
1099 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1100 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +00001101 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001102 idx_end, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001103 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1104 // Loop the indices for the insertvalue instruction in parallel with the
1105 // requested indices
1106 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001107 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1108 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +00001109 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001110 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001111 // The requested index identifies a part of a nested aggregate. Handle
1112 // this specially. For example,
1113 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1114 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1115 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1116 // This can be changed into
1117 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1118 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1119 // which allows the unused 0,0 element from the nested struct to be
1120 // removed.
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001121 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001122 else
1123 // We can't handle this without inserting insertvalues
1124 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001125 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001126
1127 // This insert value inserts something else than what we are looking for.
1128 // See if the (aggregrate) value inserted into has the value we are
1129 // looking for, then.
1130 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001131 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001132 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001133 }
1134 // If we end up here, the indices of the insertvalue match with those
1135 // requested (though possibly only partially). Now we recursively look at
1136 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001137 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001138 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001139 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1140 // If we're extracting a value from an aggregrate that was extracted from
1141 // something else, we can extract from that something else directly instead.
1142 // However, we will need to chain I's indices with the requested indices.
1143
1144 // Calculate the number of indices required
1145 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1146 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001147 SmallVector<unsigned, 5> Idxs;
1148 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001149 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001150 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001151 i != e; ++i)
1152 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001153
1154 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001155 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1156 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001157
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001158 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001159 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001160
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001161 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001162 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001163 }
1164 // Otherwise, we don't know (such as, extracting from a function return value
1165 // or load instruction)
1166 return 0;
1167}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001168
Chris Lattnered58a6f2010-11-30 22:25:26 +00001169/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1170/// it can be expressed as a base pointer plus a constant offset. Return the
1171/// base and offset to the caller.
1172Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1173 const TargetData &TD) {
1174 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1175 if (PtrOp == 0) return Ptr;
1176
1177 // Just look through bitcasts.
1178 if (PtrOp->getOpcode() == Instruction::BitCast)
1179 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1180
1181 // If this is a GEP with constant indices, we can look through it.
1182 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1183 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1184
1185 gep_type_iterator GTI = gep_type_begin(GEP);
1186 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1187 ++I, ++GTI) {
1188 ConstantInt *OpC = cast<ConstantInt>(*I);
1189 if (OpC->isZero()) continue;
1190
1191 // Handle a struct and array indices which add their offset to the pointer.
1192 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1193 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1194 } else {
1195 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1196 Offset += OpC->getSExtValue()*Size;
1197 }
1198 }
1199
1200 // Re-sign extend from the pointer size if needed to get overflow edge cases
1201 // right.
1202 unsigned PtrSize = TD.getPointerSizeInBits();
1203 if (PtrSize < 64)
1204 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1205
1206 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1207}
1208
1209
Evan Cheng0ff39b32008-06-30 07:31:25 +00001210/// GetConstantStringInfo - This function computes the length of a
1211/// null-terminated C string pointed to by V. If successful, it returns true
1212/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001213bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1214 uint64_t Offset,
Bill Wendling0582ae92009-03-13 04:39:26 +00001215 bool StopAtNul) {
1216 // If V is NULL then return false;
1217 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001218
1219 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001220 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001221 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1222
Evan Cheng0ff39b32008-06-30 07:31:25 +00001223 // If the value is not a GEP instruction nor a constant expression with a
1224 // GEP instruction, then return false because ConstantArray can't occur
1225 // any other way
Dan Gohman0a60fa32010-04-14 22:20:45 +00001226 const User *GEP = 0;
1227 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001228 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001229 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001230 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001231 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1232 if (CE->getOpcode() != Instruction::GetElementPtr)
1233 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001234 GEP = CE;
1235 }
1236
1237 if (GEP) {
1238 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001239 if (GEP->getNumOperands() != 3)
1240 return false;
1241
Evan Cheng0ff39b32008-06-30 07:31:25 +00001242 // Make sure the index-ee is a pointer to array of i8.
1243 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1244 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001245 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001246 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001247
1248 // Check to make sure that the first operand of the GEP is an integer and
1249 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001250 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001251 if (FirstIdx == 0 || !FirstIdx->isZero())
1252 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001253
1254 // If the second index isn't a ConstantInt, then this is a variable index
1255 // into the array. If this occurs, we can't say anything meaningful about
1256 // the string.
1257 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001258 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001259 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001260 else
1261 return false;
1262 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001263 StopAtNul);
1264 }
1265
1266 // The GEP instruction, constant or instruction, must reference a global
1267 // variable that is a constant and is initialized. The referenced constant
1268 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001269 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001270 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001271 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001272 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001273
1274 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001275 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001276 // This is a degenerate case. The initializer is constant zero so the
1277 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001278 Str.clear();
1279 return true;
1280 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001281
1282 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001283 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001284 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001285 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001286
1287 // Get the number of elements in the array
1288 uint64_t NumElts = Array->getType()->getNumElements();
1289
Bill Wendling0582ae92009-03-13 04:39:26 +00001290 if (Offset > NumElts)
1291 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001292
1293 // Traverse the constant array from 'Offset' which is the place the GEP refers
1294 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001295 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001296 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001297 const Constant *Elt = Array->getOperand(i);
1298 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001299 if (!CI) // This array isn't suitable, non-int initializer.
1300 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001301 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001302 return true; // we found end of string, success!
1303 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001304 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001305
Evan Cheng0ff39b32008-06-30 07:31:25 +00001306 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001307 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001308}
Eric Christopher25ec4832010-03-05 06:58:57 +00001309
1310// These next two are very similar to the above, but also look through PHI
1311// nodes.
1312// TODO: See if we can integrate these two together.
1313
1314/// GetStringLengthH - If we can compute the length of the string pointed to by
1315/// the specified pointer, return 'len+1'. If we can't, return 0.
1316static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1317 // Look through noop bitcast instructions.
1318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1319 return GetStringLengthH(BCI->getOperand(0), PHIs);
1320
1321 // If this is a PHI node, there are two cases: either we have already seen it
1322 // or we haven't.
1323 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1324 if (!PHIs.insert(PN))
1325 return ~0ULL; // already in the set.
1326
1327 // If it was new, see if all the input strings are the same length.
1328 uint64_t LenSoFar = ~0ULL;
1329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1330 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1331 if (Len == 0) return 0; // Unknown length -> unknown.
1332
1333 if (Len == ~0ULL) continue;
1334
1335 if (Len != LenSoFar && LenSoFar != ~0ULL)
1336 return 0; // Disagree -> unknown.
1337 LenSoFar = Len;
1338 }
1339
1340 // Success, all agree.
1341 return LenSoFar;
1342 }
1343
1344 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1345 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1346 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1347 if (Len1 == 0) return 0;
1348 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1349 if (Len2 == 0) return 0;
1350 if (Len1 == ~0ULL) return Len2;
1351 if (Len2 == ~0ULL) return Len1;
1352 if (Len1 != Len2) return 0;
1353 return Len1;
1354 }
1355
1356 // If the value is not a GEP instruction nor a constant expression with a
1357 // GEP instruction, then return unknown.
1358 User *GEP = 0;
1359 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1360 GEP = GEPI;
1361 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1362 if (CE->getOpcode() != Instruction::GetElementPtr)
1363 return 0;
1364 GEP = CE;
1365 } else {
1366 return 0;
1367 }
1368
1369 // Make sure the GEP has exactly three arguments.
1370 if (GEP->getNumOperands() != 3)
1371 return 0;
1372
1373 // Check to make sure that the first operand of the GEP is an integer and
1374 // has value 0 so that we are sure we're indexing into the initializer.
1375 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1376 if (!Idx->isZero())
1377 return 0;
1378 } else
1379 return 0;
1380
1381 // If the second index isn't a ConstantInt, then this is a variable index
1382 // into the array. If this occurs, we can't say anything meaningful about
1383 // the string.
1384 uint64_t StartIdx = 0;
1385 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1386 StartIdx = CI->getZExtValue();
1387 else
1388 return 0;
1389
1390 // The GEP instruction, constant or instruction, must reference a global
1391 // variable that is a constant and is initialized. The referenced constant
1392 // initializer is the array that we'll use for optimization.
1393 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1394 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1395 GV->mayBeOverridden())
1396 return 0;
1397 Constant *GlobalInit = GV->getInitializer();
1398
1399 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1400 // initializer is constant zero so the length of the string must be zero.
1401 if (isa<ConstantAggregateZero>(GlobalInit))
1402 return 1; // Len = 0 offset by 1.
1403
1404 // Must be a Constant Array
1405 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1406 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1407 return false;
1408
1409 // Get the number of elements in the array
1410 uint64_t NumElts = Array->getType()->getNumElements();
1411
1412 // Traverse the constant array from StartIdx (derived above) which is
1413 // the place the GEP refers to in the array.
1414 for (unsigned i = StartIdx; i != NumElts; ++i) {
1415 Constant *Elt = Array->getOperand(i);
1416 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1417 if (!CI) // This array isn't suitable, non-int initializer.
1418 return 0;
1419 if (CI->isZero())
1420 return i-StartIdx+1; // We found end of string, success!
1421 }
1422
1423 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1424}
1425
1426/// GetStringLength - If we can compute the length of the string pointed to by
1427/// the specified pointer, return 'len+1'. If we can't, return 0.
1428uint64_t llvm::GetStringLength(Value *V) {
1429 if (!V->getType()->isPointerTy()) return 0;
1430
1431 SmallPtrSet<PHINode*, 32> PHIs;
1432 uint64_t Len = GetStringLengthH(V, PHIs);
1433 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1434 // an empty string as a length.
1435 return Len == ~0ULL ? 1 : Len;
1436}
Dan Gohman5034dd32010-12-15 20:02:24 +00001437
1438Value *llvm::GetUnderlyingObject(Value *V, unsigned MaxLookup) {
1439 if (!V->getType()->isPointerTy())
1440 return V;
1441 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1442 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1443 V = GEP->getPointerOperand();
1444 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1445 V = cast<Operator>(V)->getOperand(0);
1446 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1447 if (GA->mayBeOverridden())
1448 return V;
1449 V = GA->getAliasee();
1450 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001451 // See if InstructionSimplify knows any relevant tricks.
1452 if (Instruction *I = dyn_cast<Instruction>(V))
1453 // TODO: Aquire TargetData and DominatorTree and use them.
1454 if (Value *Simplified = SimplifyInstruction(I, 0, 0)) {
1455 V = Simplified;
1456 continue;
1457 }
1458
Dan Gohman5034dd32010-12-15 20:02:24 +00001459 return V;
1460 }
1461 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1462 }
1463 return V;
1464}