blob: f05ad66b87d5d334e88a57d0f4d9e64d931e38a9 [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"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000027#include "llvm/Support/PatternMatch.h"
Eric Christopher25ec4832010-03-05 06:58:57 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000029#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000030using namespace llvm;
Duncan Sandsd70d1a52011-01-25 09:38:29 +000031using namespace llvm::PatternMatch;
32
33const unsigned MaxDepth = 6;
34
35/// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
36/// unknown returns 0). For vector types, returns the element type's bitwidth.
37static unsigned getBitWidth(const Type *Ty, const TargetData *TD) {
38 if (unsigned BitWidth = Ty->getScalarSizeInBits())
39 return BitWidth;
40 assert(isa<PointerType>(Ty) && "Expected a pointer type!");
41 return TD ? TD->getPointerSizeInBits() : 0;
42}
Chris Lattner173234a2008-06-02 01:18:21 +000043
Chris Lattner173234a2008-06-02 01:18:21 +000044/// ComputeMaskedBits - Determine which of the bits specified in Mask are
45/// known to be either zero or one and return them in the KnownZero/KnownOne
46/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
47/// processing.
48/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
49/// we cannot optimize based on the assumption that it is zero without changing
50/// it to be an explicit zero. If we don't change it to zero, other code could
51/// optimized based on the contradictory assumption that it is non-zero.
52/// Because instcombine aggressively folds operations with undef args anyway,
53/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +000054///
55/// This function is defined on values with integer type, values with pointer
56/// type (but only if TD is non-null), and vectors of integers. In the case
57/// where V is a vector, the mask, known zero, and known one values are the
58/// same width as the vector element, and the bit is set only if it is true
59/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +000060void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
61 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +000062 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +000063 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000064 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000065 unsigned BitWidth = Mask.getBitWidth();
Duncan Sands1df98592010-02-16 11:11:14 +000066 assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy())
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000067 && "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000068 assert((!TD ||
69 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000070 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +000071 V->getType()->getScalarSizeInBits() == BitWidth) &&
Chris Lattner173234a2008-06-02 01:18:21 +000072 KnownZero.getBitWidth() == BitWidth &&
73 KnownOne.getBitWidth() == BitWidth &&
74 "V, Mask, KnownOne and KnownZero should have same BitWidth");
75
76 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
77 // We know all of the bits for a constant!
78 KnownOne = CI->getValue() & Mask;
79 KnownZero = ~KnownOne & Mask;
80 return;
81 }
Dan Gohman6de29f82009-06-15 22:12:54 +000082 // Null and aggregate-zero are all-zeros.
83 if (isa<ConstantPointerNull>(V) ||
84 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000085 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +000086 KnownZero = Mask;
87 return;
88 }
Dan Gohman6de29f82009-06-15 22:12:54 +000089 // Handle a constant vector by taking the intersection of the known bits of
90 // each element.
91 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000092 KnownZero.setAllBits(); KnownOne.setAllBits();
Dan Gohman6de29f82009-06-15 22:12:54 +000093 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
94 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
95 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
96 TD, Depth);
97 KnownZero &= KnownZero2;
98 KnownOne &= KnownOne2;
99 }
100 return;
101 }
Chris Lattner173234a2008-06-02 01:18:21 +0000102 // The address of an aligned GlobalValue has trailing zeros.
103 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
104 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +0000105 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
106 const Type *ObjectType = GV->getType()->getElementType();
107 // If the object is defined in the current Module, we'll be giving
108 // it the preferred alignment. Otherwise, we have to assume that it
109 // may only have the minimum ABI alignment.
110 if (!GV->isDeclaration() && !GV->mayBeOverridden())
111 Align = TD->getPrefTypeAlignment(ObjectType);
112 else
113 Align = TD->getABITypeAlignment(ObjectType);
114 }
Chris Lattner173234a2008-06-02 01:18:21 +0000115 if (Align > 0)
116 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
117 CountTrailingZeros_32(Align));
118 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000119 KnownZero.clearAllBits();
120 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000121 return;
122 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000123 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
124 // the bits of its aliasee.
125 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
126 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000127 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000128 } else {
129 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
130 TD, Depth+1);
131 }
132 return;
133 }
Chris Lattner173234a2008-06-02 01:18:21 +0000134
Jay Foad7a874dd2010-12-01 08:53:58 +0000135 KnownZero.clearAllBits(); KnownOne.clearAllBits(); // Start out not knowing anything.
Chris Lattner173234a2008-06-02 01:18:21 +0000136
Dan Gohman9004c8a2009-05-21 02:28:33 +0000137 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000138 return; // Limit search depth.
139
Dan Gohmanca178902009-07-17 20:47:02 +0000140 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000141 if (!I) return;
142
143 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000144 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000145 default: break;
146 case Instruction::And: {
147 // If either the LHS or the RHS are Zero, the result is zero.
148 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
149 APInt Mask2(Mask & ~KnownZero);
150 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
151 Depth+1);
152 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
153 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
154
155 // Output known-1 bits are only known if set in both the LHS & RHS.
156 KnownOne &= KnownOne2;
157 // Output known-0 are known to be clear if zero in either the LHS | RHS.
158 KnownZero |= KnownZero2;
159 return;
160 }
161 case Instruction::Or: {
162 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
163 APInt Mask2(Mask & ~KnownOne);
164 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
165 Depth+1);
166 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
167 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
168
169 // Output known-0 bits are only known if clear in both the LHS & RHS.
170 KnownZero &= KnownZero2;
171 // Output known-1 are known to be set if set in either the LHS | RHS.
172 KnownOne |= KnownOne2;
173 return;
174 }
175 case Instruction::Xor: {
176 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
177 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
178 Depth+1);
179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
180 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
181
182 // Output known-0 bits are known if clear or set in both the LHS & RHS.
183 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
184 // Output known-1 are known to be set if set in only one of the LHS, RHS.
185 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
186 KnownZero = KnownZeroOut;
187 return;
188 }
189 case Instruction::Mul: {
190 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
191 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
192 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
193 Depth+1);
194 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
195 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
196
197 // If low bits are zero in either operand, output low known-0 bits.
198 // Also compute a conserative estimate for high known-0 bits.
199 // More trickiness is possible, but this is sufficient for the
200 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000201 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000202 unsigned TrailZ = KnownZero.countTrailingOnes() +
203 KnownZero2.countTrailingOnes();
204 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
205 KnownZero2.countLeadingOnes(),
206 BitWidth) - BitWidth;
207
208 TrailZ = std::min(TrailZ, BitWidth);
209 LeadZ = std::min(LeadZ, BitWidth);
210 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
211 APInt::getHighBitsSet(BitWidth, LeadZ);
212 KnownZero &= Mask;
213 return;
214 }
215 case Instruction::UDiv: {
216 // For the purposes of computing leading zeros we can conservatively
217 // treat a udiv as a logical right shift by the power of 2 known to
218 // be less than the denominator.
219 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
220 ComputeMaskedBits(I->getOperand(0),
221 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
222 unsigned LeadZ = KnownZero2.countLeadingOnes();
223
Jay Foad7a874dd2010-12-01 08:53:58 +0000224 KnownOne2.clearAllBits();
225 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000226 ComputeMaskedBits(I->getOperand(1),
227 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
228 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
229 if (RHSUnknownLeadingOnes != BitWidth)
230 LeadZ = std::min(BitWidth,
231 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
232
233 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
234 return;
235 }
236 case Instruction::Select:
237 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
238 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
239 Depth+1);
240 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
241 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
242
243 // Only known if known in both the LHS and RHS.
244 KnownOne &= KnownOne2;
245 KnownZero &= KnownZero2;
246 return;
247 case Instruction::FPTrunc:
248 case Instruction::FPExt:
249 case Instruction::FPToUI:
250 case Instruction::FPToSI:
251 case Instruction::SIToFP:
252 case Instruction::UIToFP:
253 return; // Can't work with floating point.
254 case Instruction::PtrToInt:
255 case Instruction::IntToPtr:
256 // We can't handle these if we don't know the pointer size.
257 if (!TD) return;
258 // FALL THROUGH and handle them the same as zext/trunc.
259 case Instruction::ZExt:
260 case Instruction::Trunc: {
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000261 const Type *SrcTy = I->getOperand(0)->getType();
262
263 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000264 // Note that we handle pointer operands here because of inttoptr/ptrtoint
265 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000266 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000267 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
268 else
269 SrcBitWidth = SrcTy->getScalarSizeInBits();
270
Jay Foad40f8f622010-12-07 08:25:19 +0000271 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
272 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
273 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000274 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
275 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000276 KnownZero = KnownZero.zextOrTrunc(BitWidth);
277 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000278 // Any top bits are known to be zero.
279 if (BitWidth > SrcBitWidth)
280 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
281 return;
282 }
283 case Instruction::BitCast: {
284 const Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000285 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000286 // TODO: For now, not handling conversions like:
287 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000288 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000289 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
290 Depth+1);
291 return;
292 }
293 break;
294 }
295 case Instruction::SExt: {
296 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000297 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000298
Jay Foad40f8f622010-12-07 08:25:19 +0000299 APInt MaskIn = Mask.trunc(SrcBitWidth);
300 KnownZero = KnownZero.trunc(SrcBitWidth);
301 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000302 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
303 Depth+1);
304 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000305 KnownZero = KnownZero.zext(BitWidth);
306 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000307
308 // If the sign bit of the input is known set or clear, then we know the
309 // top bits of the result.
310 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
311 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
312 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
313 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
314 return;
315 }
316 case Instruction::Shl:
317 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
320 APInt Mask2(Mask.lshr(ShiftAmt));
321 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
322 Depth+1);
323 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
324 KnownZero <<= ShiftAmt;
325 KnownOne <<= ShiftAmt;
326 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
327 return;
328 }
329 break;
330 case Instruction::LShr:
331 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
332 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
333 // Compute the new bits that are at the top now.
334 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
335
336 // Unsigned shift right.
337 APInt Mask2(Mask.shl(ShiftAmt));
338 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
339 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000340 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000341 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
342 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
343 // high bits known zero.
344 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
345 return;
346 }
347 break;
348 case Instruction::AShr:
349 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
350 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
351 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000352 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000353
354 // Signed shift right.
355 APInt Mask2(Mask.shl(ShiftAmt));
356 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
357 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000358 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000359 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
360 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
361
362 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
363 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
364 KnownZero |= HighBits;
365 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
366 KnownOne |= HighBits;
367 return;
368 }
369 break;
370 case Instruction::Sub: {
371 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
372 // We know that the top bits of C-X are clear if X contains less bits
373 // than C (i.e. no wrap-around can happen). For example, 20-X is
374 // positive if we can prove that X is >= 0 and < 16.
375 if (!CLHS->getValue().isNegative()) {
376 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
377 // NLZ can't be BitWidth with no sign bit
378 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
379 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
380 TD, Depth+1);
381
382 // If all of the MaskV bits are known to be zero, then we know the
383 // output top bits are zero, because we now know that the output is
384 // from [0-C].
385 if ((KnownZero2 & MaskV) == MaskV) {
386 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
387 // Top bits known zero.
388 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
389 }
390 }
391 }
392 }
393 // fall through
394 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000395 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000396 // other operand has in those bit positions will be preserved in the
397 // result. For an add, this works with either operand. For a subtract,
398 // this only works if the known zeros are in the right operand.
399 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
400 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
401 BitWidth - Mask.countLeadingZeros());
402 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000403 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000404 assert((LHSKnownZero & LHSKnownOne) == 0 &&
405 "Bits known to be one AND zero?");
406 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000407
408 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
409 Depth+1);
410 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000411 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000412
Dan Gohman39250432009-05-24 18:02:35 +0000413 // Determine which operand has more trailing zeros, and use that
414 // many bits from the other operand.
415 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000416 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000417 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
418 KnownZero |= KnownZero2 & Mask;
419 KnownOne |= KnownOne2 & Mask;
420 } else {
421 // If the known zeros are in the left operand for a subtract,
422 // fall back to the minimum known zeros in both operands.
423 KnownZero |= APInt::getLowBitsSet(BitWidth,
424 std::min(LHSKnownZeroOut,
425 RHSKnownZeroOut));
426 }
427 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
428 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
429 KnownZero |= LHSKnownZero & Mask;
430 KnownOne |= LHSKnownOne & Mask;
431 }
Chris Lattner173234a2008-06-02 01:18:21 +0000432 return;
433 }
434 case Instruction::SRem:
435 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000436 APInt RA = Rem->getValue().abs();
437 if (RA.isPowerOf2()) {
438 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000439 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
440 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
441 Depth+1);
442
Duncan Sandscfd54182010-01-29 06:18:37 +0000443 // The low bits of the first operand are unchanged by the srem.
444 KnownZero = KnownZero2 & LowBits;
445 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000446
Duncan Sandscfd54182010-01-29 06:18:37 +0000447 // If the first operand is non-negative or has all low bits zero, then
448 // the upper bits are all zero.
449 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
450 KnownZero |= ~LowBits;
451
452 // If the first operand is negative and not all low bits are zero, then
453 // the upper bits are all one.
454 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
455 KnownOne |= ~LowBits;
456
457 KnownZero &= Mask;
458 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000459
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000461 }
462 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000463
464 // The sign bit is the LHS's sign bit, except when the result of the
465 // remainder is zero.
466 if (Mask.isNegative() && KnownZero.isNonNegative()) {
467 APInt Mask2 = APInt::getSignBit(BitWidth);
468 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
469 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
470 Depth+1);
471 // If it's known zero, our sign bit is also zero.
472 if (LHSKnownZero.isNegative())
473 KnownZero |= LHSKnownZero;
474 }
475
Chris Lattner173234a2008-06-02 01:18:21 +0000476 break;
477 case Instruction::URem: {
478 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
479 APInt RA = Rem->getValue();
480 if (RA.isPowerOf2()) {
481 APInt LowBits = (RA - 1);
482 APInt Mask2 = LowBits & Mask;
483 KnownZero |= ~LowBits & Mask;
484 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
485 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000486 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000487 break;
488 }
489 }
490
491 // Since the result is less than or equal to either operand, any leading
492 // zero bits in either operand must also exist in the result.
493 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
494 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
495 TD, Depth+1);
496 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
497 TD, Depth+1);
498
Chris Lattner79abedb2009-01-20 18:22:57 +0000499 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000500 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000501 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000502 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
503 break;
504 }
505
Victor Hernandeza276c602009-10-17 01:18:07 +0000506 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000507 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000508 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000509 if (Align == 0 && TD)
510 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000511
512 if (Align > 0)
513 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
514 CountTrailingZeros_32(Align));
515 break;
516 }
517 case Instruction::GetElementPtr: {
518 // Analyze all of the subscripts of this getelementptr instruction
519 // to determine if we can prove known low zero bits.
520 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
521 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
522 ComputeMaskedBits(I->getOperand(0), LocalMask,
523 LocalKnownZero, LocalKnownOne, TD, Depth+1);
524 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
525
526 gep_type_iterator GTI = gep_type_begin(I);
527 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
528 Value *Index = I->getOperand(i);
529 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
530 // Handle struct member offset arithmetic.
531 if (!TD) return;
532 const StructLayout *SL = TD->getStructLayout(STy);
533 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
534 uint64_t Offset = SL->getElementOffset(Idx);
535 TrailZ = std::min(TrailZ,
536 CountTrailingZeros_64(Offset));
537 } else {
538 // Handle array index arithmetic.
539 const Type *IndexedTy = GTI.getIndexedType();
540 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000541 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000542 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000543 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
544 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
545 ComputeMaskedBits(Index, LocalMask,
546 LocalKnownZero, LocalKnownOne, TD, Depth+1);
547 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000548 unsigned(CountTrailingZeros_64(TypeSize) +
549 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000550 }
551 }
552
553 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
554 break;
555 }
556 case Instruction::PHI: {
557 PHINode *P = cast<PHINode>(I);
558 // Handle the case of a simple two-predecessor recurrence PHI.
559 // There's a lot more that could theoretically be done here, but
560 // this is sufficient to catch some interesting cases.
561 if (P->getNumIncomingValues() == 2) {
562 for (unsigned i = 0; i != 2; ++i) {
563 Value *L = P->getIncomingValue(i);
564 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000565 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000566 if (!LU)
567 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000568 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000569 // Check for operations that have the property that if
570 // both their operands have low zero bits, the result
571 // will have low zero bits.
572 if (Opcode == Instruction::Add ||
573 Opcode == Instruction::Sub ||
574 Opcode == Instruction::And ||
575 Opcode == Instruction::Or ||
576 Opcode == Instruction::Mul) {
577 Value *LL = LU->getOperand(0);
578 Value *LR = LU->getOperand(1);
579 // Find a recurrence.
580 if (LL == I)
581 L = LR;
582 else if (LR == I)
583 L = LL;
584 else
585 break;
586 // Ok, we have a PHI of the form L op= R. Check for low
587 // zero bits.
588 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
589 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
590 Mask2 = APInt::getLowBitsSet(BitWidth,
591 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000592
593 // We need to take the minimum number of known bits
594 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
595 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
596
Chris Lattner173234a2008-06-02 01:18:21 +0000597 KnownZero = Mask &
598 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000599 std::min(KnownZero2.countTrailingOnes(),
600 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000601 break;
602 }
603 }
604 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000605
Nick Lewycky3b739d22011-02-10 23:54:10 +0000606 // Unreachable blocks may have zero-operand PHI nodes.
607 if (P->getNumIncomingValues() == 0)
608 return;
609
Dan Gohman9004c8a2009-05-21 02:28:33 +0000610 // Otherwise take the unions of the known bit sets of the operands,
611 // taking conservative care to avoid excessive recursion.
612 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000613 // Skip if every incoming value references to ourself.
614 if (P->hasConstantValue() == P)
615 break;
616
Dan Gohman9004c8a2009-05-21 02:28:33 +0000617 KnownZero = APInt::getAllOnesValue(BitWidth);
618 KnownOne = APInt::getAllOnesValue(BitWidth);
619 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
620 // Skip direct self references.
621 if (P->getIncomingValue(i) == P) continue;
622
623 KnownZero2 = APInt(BitWidth, 0);
624 KnownOne2 = APInt(BitWidth, 0);
625 // Recurse, but cap the recursion to one level, because we don't
626 // want to waste time spinning around in loops.
627 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
628 KnownZero2, KnownOne2, TD, MaxDepth-1);
629 KnownZero &= KnownZero2;
630 KnownOne &= KnownOne2;
631 // If all bits have been ruled out, there's no need to check
632 // more operands.
633 if (!KnownZero && !KnownOne)
634 break;
635 }
636 }
Chris Lattner173234a2008-06-02 01:18:21 +0000637 break;
638 }
639 case Instruction::Call:
640 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
641 switch (II->getIntrinsicID()) {
642 default: break;
643 case Intrinsic::ctpop:
644 case Intrinsic::ctlz:
645 case Intrinsic::cttz: {
646 unsigned LowBits = Log2_32(BitWidth)+1;
647 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
648 break;
649 }
650 }
651 }
652 break;
653 }
654}
655
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000656/// ComputeSignBit - Determine whether the sign bit is known to be zero or
657/// one. Convenience wrapper around ComputeMaskedBits.
658void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
659 const TargetData *TD, unsigned Depth) {
660 unsigned BitWidth = getBitWidth(V->getType(), TD);
661 if (!BitWidth) {
662 KnownZero = false;
663 KnownOne = false;
664 return;
665 }
666 APInt ZeroBits(BitWidth, 0);
667 APInt OneBits(BitWidth, 0);
668 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
669 Depth);
670 KnownOne = OneBits[BitWidth - 1];
671 KnownZero = ZeroBits[BitWidth - 1];
672}
673
674/// isPowerOfTwo - Return true if the given value is known to have exactly one
675/// bit set when defined. For vectors return true if every element is known to
676/// be a power of two when defined. Supports values with integer or pointer
677/// types and vectors of integers.
678bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, unsigned Depth) {
679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Duncan Sands464a4f32011-01-26 08:44:16 +0000680 return CI->getValue().isPowerOf2();
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000681 // TODO: Handle vector constants.
682
683 // 1 << X is clearly a power of two if the one is not shifted off the end. If
684 // it is shifted off the end then the result is undefined.
685 if (match(V, m_Shl(m_One(), m_Value())))
686 return true;
687
688 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
689 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000690 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000691 return true;
692
693 // The remaining tests are all recursive, so bail out if we hit the limit.
694 if (Depth++ == MaxDepth)
695 return false;
696
697 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
698 return isPowerOfTwo(ZI->getOperand(0), TD, Depth);
699
700 if (SelectInst *SI = dyn_cast<SelectInst>(V))
701 return isPowerOfTwo(SI->getTrueValue(), TD, Depth) &&
702 isPowerOfTwo(SI->getFalseValue(), TD, Depth);
703
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000704 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyda834092011-02-28 09:18:11 +0000705 // is a power of two only if the first operand is a power of two.
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000706 if (match(V, m_Shr(m_Value(), m_Value())) ||
707 match(V, m_IDiv(m_Value(), m_Value()))) {
708 BinaryOperator *BO = cast<BinaryOperator>(V);
709 if (BO->isExact())
710 return isPowerOfTwo(BO->getOperand(0), TD, Depth);
711 }
712
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000713 return false;
714}
715
716/// isKnownNonZero - Return true if the given value is known to be non-zero
717/// when defined. For vectors return true if every element is known to be
718/// non-zero when defined. Supports values with integer or pointer type and
719/// vectors of integers.
720bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
721 if (Constant *C = dyn_cast<Constant>(V)) {
722 if (C->isNullValue())
723 return false;
724 if (isa<ConstantInt>(C))
725 // Must be non-zero due to null test above.
726 return true;
727 // TODO: Handle vectors
728 return false;
729 }
730
731 // The remaining tests are all recursive, so bail out if we hit the limit.
732 if (Depth++ == MaxDepth)
733 return false;
734
735 unsigned BitWidth = getBitWidth(V->getType(), TD);
736
737 // X | Y != 0 if X != 0 or Y != 0.
738 Value *X = 0, *Y = 0;
739 if (match(V, m_Or(m_Value(X), m_Value(Y))))
740 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
741
742 // ext X != 0 if X != 0.
743 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
744 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
745
Duncan Sands91367822011-01-29 13:27:00 +0000746 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000747 // if the lowest bit is shifted off the end.
748 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000749 // shl nuw can't remove any non-zero bits.
750 BinaryOperator *BO = cast<BinaryOperator>(V);
751 if (BO->hasNoUnsignedWrap())
752 return isKnownNonZero(X, TD, Depth);
753
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000754 APInt KnownZero(BitWidth, 0);
755 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000756 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000757 if (KnownOne[0])
758 return true;
759 }
Duncan Sands91367822011-01-29 13:27:00 +0000760 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000761 // defined if the sign bit is shifted off the end.
762 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000763 // shr exact can only shift out zero bits.
764 BinaryOperator *BO = cast<BinaryOperator>(V);
765 if (BO->isExact())
766 return isKnownNonZero(X, TD, Depth);
767
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000768 bool XKnownNonNegative, XKnownNegative;
769 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
770 if (XKnownNegative)
771 return true;
772 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000773 // div exact can only produce a zero if the dividend is zero.
774 else if (match(V, m_IDiv(m_Value(X), m_Value()))) {
775 BinaryOperator *BO = cast<BinaryOperator>(V);
776 if (BO->isExact())
777 return isKnownNonZero(X, TD, Depth);
778 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000779 // X + Y.
780 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
781 bool XKnownNonNegative, XKnownNegative;
782 bool YKnownNonNegative, YKnownNegative;
783 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
784 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
785
786 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000787 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000788 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000789 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
790 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000791
792 // If X and Y are both negative (as signed values) then their sum is not
793 // zero unless both X and Y equal INT_MIN.
794 if (BitWidth && XKnownNegative && YKnownNegative) {
795 APInt KnownZero(BitWidth, 0);
796 APInt KnownOne(BitWidth, 0);
797 APInt Mask = APInt::getSignedMaxValue(BitWidth);
798 // The sign bit of X is set. If some other bit is set then X is not equal
799 // to INT_MIN.
800 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
801 if ((KnownOne & Mask) != 0)
802 return true;
803 // The sign bit of Y is set. If some other bit is set then Y is not equal
804 // to INT_MIN.
805 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
806 if ((KnownOne & Mask) != 0)
807 return true;
808 }
809
810 // The sum of a non-negative number and a power of two is not zero.
811 if (XKnownNonNegative && isPowerOfTwo(Y, TD, Depth))
812 return true;
813 if (YKnownNonNegative && isPowerOfTwo(X, TD, Depth))
814 return true;
815 }
816 // (C ? X : Y) != 0 if X != 0 and Y != 0.
817 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
818 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
819 isKnownNonZero(SI->getFalseValue(), TD, Depth))
820 return true;
821 }
822
823 if (!BitWidth) return false;
824 APInt KnownZero(BitWidth, 0);
825 APInt KnownOne(BitWidth, 0);
826 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
827 TD, Depth);
828 return KnownOne != 0;
829}
830
Chris Lattner173234a2008-06-02 01:18:21 +0000831/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
832/// this predicate to simplify operations downstream. Mask is known to be zero
833/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000834///
835/// This function is defined on values with integer type, values with pointer
836/// type (but only if TD is non-null), and vectors of integers. In the case
837/// where V is a vector, the mask, known zero, and known one values are the
838/// same width as the vector element, and the bit is set only if it is true
839/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000840bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000841 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000842 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
843 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
844 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
845 return (KnownZero & Mask) == Mask;
846}
847
848
849
850/// ComputeNumSignBits - Return the number of times the sign bit of the
851/// register is replicated into the other bits. We know that at least 1 bit
852/// is always equal to the sign bit (itself), but other cases can give us
853/// information. For example, immediately after an "ashr X, 2", we know that
854/// the top 3 bits are all equal to each other, so we return 3.
855///
856/// 'Op' must have a scalar integer type.
857///
Dan Gohman846a2f22009-08-27 17:51:25 +0000858unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
859 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000860 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000861 "ComputeNumSignBits requires a TargetData object to operate "
862 "on non-integer values!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000863 const Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000864 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
865 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000866 unsigned Tmp, Tmp2;
867 unsigned FirstAnswer = 1;
868
Chris Lattnerd82e5112008-06-02 18:39:07 +0000869 // Note that ConstantInt is handled by the general ComputeMaskedBits case
870 // below.
871
Chris Lattner173234a2008-06-02 01:18:21 +0000872 if (Depth == 6)
873 return 1; // Limit search depth.
874
Dan Gohmanca178902009-07-17 20:47:02 +0000875 Operator *U = dyn_cast<Operator>(V);
876 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000877 default: break;
878 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000879 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000880 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
881
882 case Instruction::AShr:
883 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
884 // ashr X, C -> adds C sign bits.
885 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
886 Tmp += C->getZExtValue();
887 if (Tmp > TyBits) Tmp = TyBits;
888 }
Nate Begeman9a3dc552010-12-17 23:12:19 +0000889 // vector ashr X, <C, C, C, C> -> adds C sign bits
890 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
891 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
892 Tmp += CI->getZExtValue();
893 if (Tmp > TyBits) Tmp = TyBits;
894 }
895 }
Chris Lattner173234a2008-06-02 01:18:21 +0000896 return Tmp;
897 case Instruction::Shl:
898 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
899 // shl destroys sign bits.
900 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
901 if (C->getZExtValue() >= TyBits || // Bad shift.
902 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
903 return Tmp - C->getZExtValue();
904 }
905 break;
906 case Instruction::And:
907 case Instruction::Or:
908 case Instruction::Xor: // NOT is handled here.
909 // Logical binary ops preserve the number of sign bits at the worst.
910 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
911 if (Tmp != 1) {
912 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
913 FirstAnswer = std::min(Tmp, Tmp2);
914 // We computed what we know about the sign bits as our first
915 // answer. Now proceed to the generic code that uses
916 // ComputeMaskedBits, and pick whichever answer is better.
917 }
918 break;
919
920 case Instruction::Select:
921 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
922 if (Tmp == 1) return 1; // Early out.
923 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
924 return std::min(Tmp, Tmp2);
925
926 case Instruction::Add:
927 // Add can have at most one carry bit. Thus we know that the output
928 // is, at worst, one more bit than the inputs.
929 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
930 if (Tmp == 1) return 1; // Early out.
931
932 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +0000933 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +0000934 if (CRHS->isAllOnesValue()) {
935 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
936 APInt Mask = APInt::getAllOnesValue(TyBits);
937 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
938 Depth+1);
939
940 // If the input is known to be 0 or 1, the output is 0/-1, which is all
941 // sign bits set.
942 if ((KnownZero | APInt(TyBits, 1)) == Mask)
943 return TyBits;
944
945 // If we are subtracting one from a positive number, there is no carry
946 // out of the result.
947 if (KnownZero.isNegative())
948 return Tmp;
949 }
950
951 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
952 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000953 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +0000954
955 case Instruction::Sub:
956 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
957 if (Tmp2 == 1) return 1;
958
959 // Handle NEG.
960 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
961 if (CLHS->isNullValue()) {
962 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
963 APInt Mask = APInt::getAllOnesValue(TyBits);
964 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
965 TD, Depth+1);
966 // If the input is known to be 0 or 1, the output is 0/-1, which is all
967 // sign bits set.
968 if ((KnownZero | APInt(TyBits, 1)) == Mask)
969 return TyBits;
970
971 // If the input is known to be positive (the sign bit is known clear),
972 // the output of the NEG has the same number of sign bits as the input.
973 if (KnownZero.isNegative())
974 return Tmp2;
975
976 // Otherwise, we treat this like a SUB.
977 }
978
979 // Sub can have at most one carry bit. Thus we know that the output
980 // is, at worst, one more bit than the inputs.
981 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
982 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000983 return std::min(Tmp, Tmp2)-1;
984
985 case Instruction::PHI: {
986 PHINode *PN = cast<PHINode>(U);
987 // Don't analyze large in-degree PHIs.
988 if (PN->getNumIncomingValues() > 4) break;
989
990 // Take the minimum of all incoming values. This can't infinitely loop
991 // because of our depth threshold.
992 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
993 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
994 if (Tmp == 1) return Tmp;
995 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +0000996 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +0000997 }
998 return Tmp;
999 }
1000
Chris Lattner173234a2008-06-02 01:18:21 +00001001 case Instruction::Trunc:
1002 // FIXME: it's tricky to do anything useful for this, but it is an important
1003 // case for targets like X86.
1004 break;
1005 }
1006
1007 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1008 // use this information.
1009 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1010 APInt Mask = APInt::getAllOnesValue(TyBits);
1011 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1012
1013 if (KnownZero.isNegative()) { // sign bit is 0
1014 Mask = KnownZero;
1015 } else if (KnownOne.isNegative()) { // sign bit is 1;
1016 Mask = KnownOne;
1017 } else {
1018 // Nothing known.
1019 return FirstAnswer;
1020 }
1021
1022 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1023 // the number of identical bits in the top of the input value.
1024 Mask = ~Mask;
1025 Mask <<= Mask.getBitWidth()-TyBits;
1026 // Return # leading zeros. We use 'min' here in case Val was zero before
1027 // shifting. We don't want to return '64' as for an i32 "0".
1028 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1029}
Chris Lattner833f25d2008-06-02 01:29:46 +00001030
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001031/// ComputeMultiple - This function computes the integer multiple of Base that
1032/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001033/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001034/// through SExt instructions only if LookThroughSExt is true.
1035bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001036 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001037 const unsigned MaxDepth = 6;
1038
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001039 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001040 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001041 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001042
1043 const Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001044
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001045 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001046
1047 if (Base == 0)
1048 return false;
1049
1050 if (Base == 1) {
1051 Multiple = V;
1052 return true;
1053 }
1054
1055 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1056 Constant *BaseVal = ConstantInt::get(T, Base);
1057 if (CO && CO == BaseVal) {
1058 // Multiple is 1.
1059 Multiple = ConstantInt::get(T, 1);
1060 return true;
1061 }
1062
1063 if (CI && CI->getZExtValue() % Base == 0) {
1064 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1065 return true;
1066 }
1067
1068 if (Depth == MaxDepth) return false; // Limit search depth.
1069
1070 Operator *I = dyn_cast<Operator>(V);
1071 if (!I) return false;
1072
1073 switch (I->getOpcode()) {
1074 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001075 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001076 if (!LookThroughSExt) return false;
1077 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001078 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001079 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1080 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001081 case Instruction::Shl:
1082 case Instruction::Mul: {
1083 Value *Op0 = I->getOperand(0);
1084 Value *Op1 = I->getOperand(1);
1085
1086 if (I->getOpcode() == Instruction::Shl) {
1087 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1088 if (!Op1CI) return false;
1089 // Turn Op0 << Op1 into Op0 * 2^Op1
1090 APInt Op1Int = Op1CI->getValue();
1091 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001092 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001093 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001094 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001095 }
1096
1097 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001098 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1099 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1100 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1101 if (Op1C->getType()->getPrimitiveSizeInBits() <
1102 MulC->getType()->getPrimitiveSizeInBits())
1103 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1104 if (Op1C->getType()->getPrimitiveSizeInBits() >
1105 MulC->getType()->getPrimitiveSizeInBits())
1106 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1107
1108 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1109 Multiple = ConstantExpr::getMul(MulC, Op1C);
1110 return true;
1111 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001112
1113 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1114 if (Mul0CI->getValue() == 1) {
1115 // V == Base * Op1, so return Op1
1116 Multiple = Op1;
1117 return true;
1118 }
1119 }
1120
Chris Lattnere9711312010-09-05 17:20:46 +00001121 Value *Mul1 = NULL;
1122 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1123 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1124 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1125 if (Op0C->getType()->getPrimitiveSizeInBits() <
1126 MulC->getType()->getPrimitiveSizeInBits())
1127 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1128 if (Op0C->getType()->getPrimitiveSizeInBits() >
1129 MulC->getType()->getPrimitiveSizeInBits())
1130 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1131
1132 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1133 Multiple = ConstantExpr::getMul(MulC, Op0C);
1134 return true;
1135 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001136
1137 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1138 if (Mul1CI->getValue() == 1) {
1139 // V == Base * Op0, so return Op0
1140 Multiple = Op0;
1141 return true;
1142 }
1143 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001144 }
1145 }
1146
1147 // We could not determine if V is a multiple of Base.
1148 return false;
1149}
1150
Chris Lattner833f25d2008-06-02 01:29:46 +00001151/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1152/// value is never equal to -0.0.
1153///
1154/// NOTE: this function will need to be revisited when we support non-default
1155/// rounding modes!
1156///
1157bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1158 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1159 return !CFP->getValueAPF().isNegZero();
1160
1161 if (Depth == 6)
1162 return 1; // Limit search depth.
1163
Dan Gohmanca178902009-07-17 20:47:02 +00001164 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001165 if (I == 0) return false;
1166
1167 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001168 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001169 isa<ConstantFP>(I->getOperand(1)) &&
1170 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1171 return true;
1172
1173 // sitofp and uitofp turn into +0.0 for zero.
1174 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1175 return true;
1176
1177 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1178 // sqrt(-0.0) = -0.0, no other negative results are possible.
1179 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001180 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001181
1182 if (const CallInst *CI = dyn_cast<CallInst>(I))
1183 if (const Function *F = CI->getCalledFunction()) {
1184 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001185 // abs(x) != -0.0
1186 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001187 // fabs[lf](x) != -0.0
1188 if (F->getName() == "fabs") return true;
1189 if (F->getName() == "fabsf") return true;
1190 if (F->getName() == "fabsl") return true;
1191 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1192 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001193 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001194 }
1195 }
1196
1197 return false;
1198}
1199
Chris Lattnerbb897102010-12-26 20:15:01 +00001200/// isBytewiseValue - If the specified value can be set by repeating the same
1201/// byte in memory, return the i8 value that it is represented with. This is
1202/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1203/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1204/// byte store (e.g. i16 0x1234), return null.
1205Value *llvm::isBytewiseValue(Value *V) {
1206 // All byte-wide stores are splatable, even of arbitrary variables.
1207 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001208
1209 // Handle 'null' ConstantArrayZero etc.
1210 if (Constant *C = dyn_cast<Constant>(V))
1211 if (C->isNullValue())
1212 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001213
1214 // Constant float and double values can be handled as integer values if the
1215 // corresponding integer value is "byteable". An important case is 0.0.
1216 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1217 if (CFP->getType()->isFloatTy())
1218 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1219 if (CFP->getType()->isDoubleTy())
1220 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1221 // Don't handle long double formats, which have strange constraints.
1222 }
1223
1224 // We can handle constant integers that are power of two in size and a
1225 // multiple of 8 bits.
1226 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1227 unsigned Width = CI->getBitWidth();
1228 if (isPowerOf2_32(Width) && Width > 8) {
1229 // We can handle this value if the recursive binary decomposition is the
1230 // same at all levels.
1231 APInt Val = CI->getValue();
1232 APInt Val2;
1233 while (Val.getBitWidth() != 8) {
1234 unsigned NextWidth = Val.getBitWidth()/2;
1235 Val2 = Val.lshr(NextWidth);
1236 Val2 = Val2.trunc(Val.getBitWidth()/2);
1237 Val = Val.trunc(Val.getBitWidth()/2);
1238
1239 // If the top/bottom halves aren't the same, reject it.
1240 if (Val != Val2)
1241 return 0;
1242 }
1243 return ConstantInt::get(V->getContext(), Val);
1244 }
1245 }
1246
1247 // A ConstantArray is splatable if all its members are equal and also
1248 // splatable.
1249 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1250 if (CA->getNumOperands() == 0)
1251 return 0;
1252
1253 Value *Val = isBytewiseValue(CA->getOperand(0));
1254 if (!Val)
1255 return 0;
1256
1257 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1258 if (CA->getOperand(I-1) != CA->getOperand(I))
1259 return 0;
1260
1261 return Val;
1262 }
1263
1264 // Conceptually, we could handle things like:
1265 // %a = zext i8 %X to i16
1266 // %b = shl i16 %a, 8
1267 // %c = or i16 %a, %b
1268 // but until there is an example that actually needs this, it doesn't seem
1269 // worth worrying about.
1270 return 0;
1271}
1272
1273
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001274// This is the recursive version of BuildSubAggregate. It takes a few different
1275// arguments. Idxs is the index within the nested struct From that we are
1276// looking at now (which is of type IndexedType). IdxSkip is the number of
1277// indices from Idxs that should be left out when inserting into the resulting
1278// struct. To is the result struct built so far, new insertvalue instructions
1279// build on that.
Dan Gohman7db949d2009-08-07 01:32:21 +00001280static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
1281 SmallVector<unsigned, 10> &Idxs,
1282 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001283 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001284 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
1285 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001286 // Save the original To argument so we can modify it
1287 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001288 // General case, the type indexed by Idxs is a struct
1289 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1290 // Process each struct element recursively
1291 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001292 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001293 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001294 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001295 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001296 if (!To) {
1297 // Couldn't find any inserted value for this index? Cleanup
1298 while (PrevTo != OrigTo) {
1299 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1300 PrevTo = Del->getAggregateOperand();
1301 Del->eraseFromParent();
1302 }
1303 // Stop processing elements
1304 break;
1305 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001306 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001307 // If we succesfully found a value for each of our subaggregates
1308 if (To)
1309 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001310 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001311 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1312 // the struct's elements had a value that was inserted directly. In the latter
1313 // case, perhaps we can't determine each of the subelements individually, but
1314 // we might be able to find the complete struct somewhere.
1315
1316 // Find the value that is at that particular spot
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001317 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end());
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001318
1319 if (!V)
1320 return NULL;
1321
1322 // Insert the value in the new (sub) aggregrate
1323 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip,
1324 Idxs.end(), "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001325}
1326
1327// This helper takes a nested struct and extracts a part of it (which is again a
1328// struct) into a new value. For example, given the struct:
1329// { a, { b, { c, d }, e } }
1330// and the indices "1, 1" this returns
1331// { c, d }.
1332//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001333// It does this by inserting an insertvalue for each element in the resulting
1334// struct, as opposed to just inserting a single struct. This will only work if
1335// each of the elements of the substruct are known (ie, inserted into From by an
1336// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001337//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001338// All inserted insertvalue instructions are inserted before InsertBefore
Dan Gohman7db949d2009-08-07 01:32:21 +00001339static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001340 const unsigned *idx_end,
Dan Gohman7db949d2009-08-07 01:32:21 +00001341 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001342 assert(InsertBefore && "Must have someplace to insert!");
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001343 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
1344 idx_begin,
1345 idx_end);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001346 Value *To = UndefValue::get(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001347 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
1348 unsigned IdxSkip = Idxs.size();
1349
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001350 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001351}
1352
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001353/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1354/// the scalar value indexed is already around as a register, for example if it
1355/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001356///
1357/// If InsertBefore is not null, this function will duplicate (modified)
1358/// insertvalues when a part of a nested struct is extracted.
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001359Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001360 const unsigned *idx_end, Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001361 // Nothing to index? Just return V then (this is useful at the end of our
1362 // recursion)
1363 if (idx_begin == idx_end)
1364 return V;
1365 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001366 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001367 && "Not looking at a struct or array?");
1368 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
1369 && "Invalid indices for type?");
1370 const CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001371
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001372 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001373 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001374 idx_begin,
1375 idx_end));
1376 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001377 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Owen Anderson76f600b2009-07-06 22:37:39 +00001378 idx_begin,
1379 idx_end));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001380 else if (Constant *C = dyn_cast<Constant>(V)) {
1381 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1382 // Recursively process this constant
Owen Anderson76f600b2009-07-06 22:37:39 +00001383 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001384 idx_end, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001385 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1386 // Loop the indices for the insertvalue instruction in parallel with the
1387 // requested indices
1388 const unsigned *req_idx = idx_begin;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001389 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1390 i != e; ++i, ++req_idx) {
Duncan Sands9954c762008-06-19 08:47:31 +00001391 if (req_idx == idx_end) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001392 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001393 // The requested index identifies a part of a nested aggregate. Handle
1394 // this specially. For example,
1395 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1396 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1397 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1398 // This can be changed into
1399 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1400 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1401 // which allows the unused 0,0 element from the nested struct to be
1402 // removed.
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001403 return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001404 else
1405 // We can't handle this without inserting insertvalues
1406 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001407 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001408
1409 // This insert value inserts something else than what we are looking for.
1410 // See if the (aggregrate) value inserted into has the value we are
1411 // looking for, then.
1412 if (*req_idx != *i)
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001413 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001414 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001415 }
1416 // If we end up here, the indices of the insertvalue match with those
1417 // requested (though possibly only partially). Now we recursively look at
1418 // the inserted value, passing any remaining indices.
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001419 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001420 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001421 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1422 // If we're extracting a value from an aggregrate that was extracted from
1423 // something else, we can extract from that something else directly instead.
1424 // However, we will need to chain I's indices with the requested indices.
1425
1426 // Calculate the number of indices required
1427 unsigned size = I->getNumIndices() + (idx_end - idx_begin);
1428 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001429 SmallVector<unsigned, 5> Idxs;
1430 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001431 // Add indices from the extract value instruction
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001432 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001433 i != e; ++i)
1434 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001435
1436 // Add requested indices
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001437 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i)
1438 Idxs.push_back(*i);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001439
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001440 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001441 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001442
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001443 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001444 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001445 }
1446 // Otherwise, we don't know (such as, extracting from a function return value
1447 // or load instruction)
1448 return 0;
1449}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001450
Chris Lattnered58a6f2010-11-30 22:25:26 +00001451/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1452/// it can be expressed as a base pointer plus a constant offset. Return the
1453/// base and offset to the caller.
1454Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1455 const TargetData &TD) {
1456 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1457 if (PtrOp == 0) return Ptr;
1458
1459 // Just look through bitcasts.
1460 if (PtrOp->getOpcode() == Instruction::BitCast)
1461 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1462
1463 // If this is a GEP with constant indices, we can look through it.
1464 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1465 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1466
1467 gep_type_iterator GTI = gep_type_begin(GEP);
1468 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1469 ++I, ++GTI) {
1470 ConstantInt *OpC = cast<ConstantInt>(*I);
1471 if (OpC->isZero()) continue;
1472
1473 // Handle a struct and array indices which add their offset to the pointer.
1474 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1475 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1476 } else {
1477 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1478 Offset += OpC->getSExtValue()*Size;
1479 }
1480 }
1481
1482 // Re-sign extend from the pointer size if needed to get overflow edge cases
1483 // right.
1484 unsigned PtrSize = TD.getPointerSizeInBits();
1485 if (PtrSize < 64)
1486 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1487
1488 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1489}
1490
1491
Evan Cheng0ff39b32008-06-30 07:31:25 +00001492/// GetConstantStringInfo - This function computes the length of a
1493/// null-terminated C string pointed to by V. If successful, it returns true
1494/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001495bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
1496 uint64_t Offset,
Bill Wendling0582ae92009-03-13 04:39:26 +00001497 bool StopAtNul) {
1498 // If V is NULL then return false;
1499 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001500
1501 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001502 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001503 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1504
Evan Cheng0ff39b32008-06-30 07:31:25 +00001505 // If the value is not a GEP instruction nor a constant expression with a
1506 // GEP instruction, then return false because ConstantArray can't occur
1507 // any other way
Dan Gohman0a60fa32010-04-14 22:20:45 +00001508 const User *GEP = 0;
1509 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001510 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001511 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001512 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001513 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1514 if (CE->getOpcode() != Instruction::GetElementPtr)
1515 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001516 GEP = CE;
1517 }
1518
1519 if (GEP) {
1520 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001521 if (GEP->getNumOperands() != 3)
1522 return false;
1523
Evan Cheng0ff39b32008-06-30 07:31:25 +00001524 // Make sure the index-ee is a pointer to array of i8.
1525 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1526 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001527 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001528 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001529
1530 // Check to make sure that the first operand of the GEP is an integer and
1531 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001532 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001533 if (FirstIdx == 0 || !FirstIdx->isZero())
1534 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001535
1536 // If the second index isn't a ConstantInt, then this is a variable index
1537 // into the array. If this occurs, we can't say anything meaningful about
1538 // the string.
1539 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001540 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001541 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001542 else
1543 return false;
1544 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001545 StopAtNul);
1546 }
1547
1548 // The GEP instruction, constant or instruction, must reference a global
1549 // variable that is a constant and is initialized. The referenced constant
1550 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001551 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001552 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001553 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001554 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001555
1556 // Handle the ConstantAggregateZero case
Bill Wendling0582ae92009-03-13 04:39:26 +00001557 if (isa<ConstantAggregateZero>(GlobalInit)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001558 // This is a degenerate case. The initializer is constant zero so the
1559 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001560 Str.clear();
1561 return true;
1562 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001563
1564 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001565 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001566 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001567 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001568
1569 // Get the number of elements in the array
1570 uint64_t NumElts = Array->getType()->getNumElements();
1571
Bill Wendling0582ae92009-03-13 04:39:26 +00001572 if (Offset > NumElts)
1573 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001574
1575 // Traverse the constant array from 'Offset' which is the place the GEP refers
1576 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001577 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001578 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001579 const Constant *Elt = Array->getOperand(i);
1580 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001581 if (!CI) // This array isn't suitable, non-int initializer.
1582 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001583 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001584 return true; // we found end of string, success!
1585 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001586 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001587
Evan Cheng0ff39b32008-06-30 07:31:25 +00001588 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001589 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001590}
Eric Christopher25ec4832010-03-05 06:58:57 +00001591
1592// These next two are very similar to the above, but also look through PHI
1593// nodes.
1594// TODO: See if we can integrate these two together.
1595
1596/// GetStringLengthH - If we can compute the length of the string pointed to by
1597/// the specified pointer, return 'len+1'. If we can't, return 0.
1598static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1599 // Look through noop bitcast instructions.
1600 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1601 return GetStringLengthH(BCI->getOperand(0), PHIs);
1602
1603 // If this is a PHI node, there are two cases: either we have already seen it
1604 // or we haven't.
1605 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1606 if (!PHIs.insert(PN))
1607 return ~0ULL; // already in the set.
1608
1609 // If it was new, see if all the input strings are the same length.
1610 uint64_t LenSoFar = ~0ULL;
1611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1612 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1613 if (Len == 0) return 0; // Unknown length -> unknown.
1614
1615 if (Len == ~0ULL) continue;
1616
1617 if (Len != LenSoFar && LenSoFar != ~0ULL)
1618 return 0; // Disagree -> unknown.
1619 LenSoFar = Len;
1620 }
1621
1622 // Success, all agree.
1623 return LenSoFar;
1624 }
1625
1626 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1627 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1628 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1629 if (Len1 == 0) return 0;
1630 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1631 if (Len2 == 0) return 0;
1632 if (Len1 == ~0ULL) return Len2;
1633 if (Len2 == ~0ULL) return Len1;
1634 if (Len1 != Len2) return 0;
1635 return Len1;
1636 }
1637
1638 // If the value is not a GEP instruction nor a constant expression with a
1639 // GEP instruction, then return unknown.
1640 User *GEP = 0;
1641 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1642 GEP = GEPI;
1643 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1644 if (CE->getOpcode() != Instruction::GetElementPtr)
1645 return 0;
1646 GEP = CE;
1647 } else {
1648 return 0;
1649 }
1650
1651 // Make sure the GEP has exactly three arguments.
1652 if (GEP->getNumOperands() != 3)
1653 return 0;
1654
1655 // Check to make sure that the first operand of the GEP is an integer and
1656 // has value 0 so that we are sure we're indexing into the initializer.
1657 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1658 if (!Idx->isZero())
1659 return 0;
1660 } else
1661 return 0;
1662
1663 // If the second index isn't a ConstantInt, then this is a variable index
1664 // into the array. If this occurs, we can't say anything meaningful about
1665 // the string.
1666 uint64_t StartIdx = 0;
1667 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1668 StartIdx = CI->getZExtValue();
1669 else
1670 return 0;
1671
1672 // The GEP instruction, constant or instruction, must reference a global
1673 // variable that is a constant and is initialized. The referenced constant
1674 // initializer is the array that we'll use for optimization.
1675 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1676 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1677 GV->mayBeOverridden())
1678 return 0;
1679 Constant *GlobalInit = GV->getInitializer();
1680
1681 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1682 // initializer is constant zero so the length of the string must be zero.
1683 if (isa<ConstantAggregateZero>(GlobalInit))
1684 return 1; // Len = 0 offset by 1.
1685
1686 // Must be a Constant Array
1687 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1688 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1689 return false;
1690
1691 // Get the number of elements in the array
1692 uint64_t NumElts = Array->getType()->getNumElements();
1693
1694 // Traverse the constant array from StartIdx (derived above) which is
1695 // the place the GEP refers to in the array.
1696 for (unsigned i = StartIdx; i != NumElts; ++i) {
1697 Constant *Elt = Array->getOperand(i);
1698 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1699 if (!CI) // This array isn't suitable, non-int initializer.
1700 return 0;
1701 if (CI->isZero())
1702 return i-StartIdx+1; // We found end of string, success!
1703 }
1704
1705 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1706}
1707
1708/// GetStringLength - If we can compute the length of the string pointed to by
1709/// the specified pointer, return 'len+1'. If we can't, return 0.
1710uint64_t llvm::GetStringLength(Value *V) {
1711 if (!V->getType()->isPointerTy()) return 0;
1712
1713 SmallPtrSet<PHINode*, 32> PHIs;
1714 uint64_t Len = GetStringLengthH(V, PHIs);
1715 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1716 // an empty string as a length.
1717 return Len == ~0ULL ? 1 : Len;
1718}
Dan Gohman5034dd32010-12-15 20:02:24 +00001719
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001720Value *
1721llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001722 if (!V->getType()->isPointerTy())
1723 return V;
1724 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1725 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1726 V = GEP->getPointerOperand();
1727 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1728 V = cast<Operator>(V)->getOperand(0);
1729 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1730 if (GA->mayBeOverridden())
1731 return V;
1732 V = GA->getAliasee();
1733 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001734 // See if InstructionSimplify knows any relevant tricks.
1735 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001736 // TODO: Aquire a DominatorTree and use it.
1737 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001738 V = Simplified;
1739 continue;
1740 }
1741
Dan Gohman5034dd32010-12-15 20:02:24 +00001742 return V;
1743 }
1744 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1745 }
1746 return V;
1747}