blob: f2740a6ceb41b5b2311f0bfa3f007b516a3c7f6a [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.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000037static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
Duncan Sandsd70d1a52011-01-25 09:38:29 +000038 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()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000106 Type *ObjectType = GV->getType()->getElementType();
Dan Gohman00407252009-08-11 15:50:03 +0000107 // 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 Lattnerb3f06732011-05-23 00:03:39 +0000134
135 if (Argument *A = dyn_cast<Argument>(V)) {
136 // Get alignment information off byval arguments if specified in the IR.
137 if (A->hasByValAttr())
138 if (unsigned Align = A->getParamAlignment())
139 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
140 CountTrailingZeros_32(Align));
141 return;
142 }
Chris Lattner173234a2008-06-02 01:18:21 +0000143
Chris Lattnerb3f06732011-05-23 00:03:39 +0000144 // Start out not knowing anything.
145 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000146
Dan Gohman9004c8a2009-05-21 02:28:33 +0000147 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000148 return; // Limit search depth.
149
Dan Gohmanca178902009-07-17 20:47:02 +0000150 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000151 if (!I) return;
152
153 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000154 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000155 default: break;
156 case Instruction::And: {
157 // If either the LHS or the RHS are Zero, the result is zero.
158 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
159 APInt Mask2(Mask & ~KnownZero);
160 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
161 Depth+1);
162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
163 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
164
165 // Output known-1 bits are only known if set in both the LHS & RHS.
166 KnownOne &= KnownOne2;
167 // Output known-0 are known to be clear if zero in either the LHS | RHS.
168 KnownZero |= KnownZero2;
169 return;
170 }
171 case Instruction::Or: {
172 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
173 APInt Mask2(Mask & ~KnownOne);
174 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
175 Depth+1);
176 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
177 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
178
179 // Output known-0 bits are only known if clear in both the LHS & RHS.
180 KnownZero &= KnownZero2;
181 // Output known-1 are known to be set if set in either the LHS | RHS.
182 KnownOne |= KnownOne2;
183 return;
184 }
185 case Instruction::Xor: {
186 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
187 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
188 Depth+1);
189 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
190 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
191
192 // Output known-0 bits are known if clear or set in both the LHS & RHS.
193 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
194 // Output known-1 are known to be set if set in only one of the LHS, RHS.
195 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
196 KnownZero = KnownZeroOut;
197 return;
198 }
199 case Instruction::Mul: {
200 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
201 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
202 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
203 Depth+1);
Duncan Sandse8ec2252011-10-26 15:31:51 +0000204 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
205 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
206
207 bool isKnownNegative = false;
208 bool isKnownNonNegative = false;
209 // If the multiplication is known not to overflow, compute the sign bit.
210 if (Mask.isNegative() && cast<BinaryOperator>(I)->hasNoSignedWrap()) {
211 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
212 if (Op1 == Op2) {
213 // The product of a number with itself is non-negative.
214 isKnownNonNegative = true;
215 } else {
216 bool isKnownNonNegative1 = KnownZero.isNegative();
217 bool isKnownNonNegative2 = KnownZero2.isNegative();
218 bool isKnownNegative1 = KnownOne.isNegative();
219 bool isKnownNegative2 = KnownOne2.isNegative();
220 // The product of two numbers with the same sign is non-negative.
221 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
222 (isKnownNonNegative1 && isKnownNonNegative2);
223 // The product of a negative number and a non-negative number is either
224 // negative or zero.
225 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
226 isKnownNonZero(Op2, TD, Depth)) ||
227 (isKnownNegative2 && isKnownNonNegative1 &&
228 isKnownNonZero(Op1, TD, Depth));
229 assert(!(isKnownNegative && isKnownNonNegative) &&
230 "Sign bit both zero and one?");
231 }
232 }
233
Chris Lattner173234a2008-06-02 01:18:21 +0000234 // If low bits are zero in either operand, output low known-0 bits.
235 // Also compute a conserative estimate for high known-0 bits.
236 // More trickiness is possible, but this is sufficient for the
237 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000238 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000239 unsigned TrailZ = KnownZero.countTrailingOnes() +
240 KnownZero2.countTrailingOnes();
241 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
242 KnownZero2.countLeadingOnes(),
243 BitWidth) - BitWidth;
244
245 TrailZ = std::min(TrailZ, BitWidth);
246 LeadZ = std::min(LeadZ, BitWidth);
247 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
248 APInt::getHighBitsSet(BitWidth, LeadZ);
249 KnownZero &= Mask;
Duncan Sandse8ec2252011-10-26 15:31:51 +0000250
251 if (isKnownNonNegative)
252 KnownZero.setBit(BitWidth - 1);
253 else if (isKnownNegative)
254 KnownOne.setBit(BitWidth - 1);
255
Chris Lattner173234a2008-06-02 01:18:21 +0000256 return;
257 }
258 case Instruction::UDiv: {
259 // For the purposes of computing leading zeros we can conservatively
260 // treat a udiv as a logical right shift by the power of 2 known to
261 // be less than the denominator.
262 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
263 ComputeMaskedBits(I->getOperand(0),
264 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
265 unsigned LeadZ = KnownZero2.countLeadingOnes();
266
Jay Foad7a874dd2010-12-01 08:53:58 +0000267 KnownOne2.clearAllBits();
268 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000269 ComputeMaskedBits(I->getOperand(1),
270 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
271 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
272 if (RHSUnknownLeadingOnes != BitWidth)
273 LeadZ = std::min(BitWidth,
274 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
275
276 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
277 return;
278 }
279 case Instruction::Select:
280 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
281 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
282 Depth+1);
283 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
284 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
285
286 // Only known if known in both the LHS and RHS.
287 KnownOne &= KnownOne2;
288 KnownZero &= KnownZero2;
289 return;
290 case Instruction::FPTrunc:
291 case Instruction::FPExt:
292 case Instruction::FPToUI:
293 case Instruction::FPToSI:
294 case Instruction::SIToFP:
295 case Instruction::UIToFP:
296 return; // Can't work with floating point.
297 case Instruction::PtrToInt:
298 case Instruction::IntToPtr:
299 // We can't handle these if we don't know the pointer size.
300 if (!TD) return;
301 // FALL THROUGH and handle them the same as zext/trunc.
302 case Instruction::ZExt:
303 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000304 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000305
306 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000307 // Note that we handle pointer operands here because of inttoptr/ptrtoint
308 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000309 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000310 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
311 else
312 SrcBitWidth = SrcTy->getScalarSizeInBits();
313
Jay Foad40f8f622010-12-07 08:25:19 +0000314 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
315 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
316 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000317 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
318 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000319 KnownZero = KnownZero.zextOrTrunc(BitWidth);
320 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000321 // Any top bits are known to be zero.
322 if (BitWidth > SrcBitWidth)
323 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
324 return;
325 }
326 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000327 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000328 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000329 // TODO: For now, not handling conversions like:
330 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000331 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000332 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
333 Depth+1);
334 return;
335 }
336 break;
337 }
338 case Instruction::SExt: {
339 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000340 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000341
Jay Foad40f8f622010-12-07 08:25:19 +0000342 APInt MaskIn = Mask.trunc(SrcBitWidth);
343 KnownZero = KnownZero.trunc(SrcBitWidth);
344 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000345 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
346 Depth+1);
347 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000348 KnownZero = KnownZero.zext(BitWidth);
349 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000350
351 // If the sign bit of the input is known set or clear, then we know the
352 // top bits of the result.
353 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
354 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
355 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
356 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
357 return;
358 }
359 case Instruction::Shl:
360 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
361 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
362 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
363 APInt Mask2(Mask.lshr(ShiftAmt));
364 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
365 Depth+1);
366 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
367 KnownZero <<= ShiftAmt;
368 KnownOne <<= ShiftAmt;
369 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
370 return;
371 }
372 break;
373 case Instruction::LShr:
374 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
375 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
376 // Compute the new bits that are at the top now.
377 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
378
379 // Unsigned shift right.
380 APInt Mask2(Mask.shl(ShiftAmt));
381 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
382 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000383 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000384 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
385 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
386 // high bits known zero.
387 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
388 return;
389 }
390 break;
391 case Instruction::AShr:
392 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
393 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
394 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000395 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000396
397 // Signed shift right.
398 APInt Mask2(Mask.shl(ShiftAmt));
399 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
400 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000401 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000402 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
403 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
404
405 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
406 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
407 KnownZero |= HighBits;
408 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
409 KnownOne |= HighBits;
410 return;
411 }
412 break;
413 case Instruction::Sub: {
414 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
415 // We know that the top bits of C-X are clear if X contains less bits
416 // than C (i.e. no wrap-around can happen). For example, 20-X is
417 // positive if we can prove that X is >= 0 and < 16.
418 if (!CLHS->getValue().isNegative()) {
419 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
420 // NLZ can't be BitWidth with no sign bit
421 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
422 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
423 TD, Depth+1);
424
425 // If all of the MaskV bits are known to be zero, then we know the
426 // output top bits are zero, because we now know that the output is
427 // from [0-C].
428 if ((KnownZero2 & MaskV) == MaskV) {
429 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
430 // Top bits known zero.
431 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
432 }
433 }
434 }
435 }
436 // fall through
437 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000438 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000439 // other operand has in those bit positions will be preserved in the
440 // result. For an add, this works with either operand. For a subtract,
441 // this only works if the known zeros are in the right operand.
442 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
443 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
444 BitWidth - Mask.countLeadingZeros());
445 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000446 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000447 assert((LHSKnownZero & LHSKnownOne) == 0 &&
448 "Bits known to be one AND zero?");
449 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000450
451 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
452 Depth+1);
453 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000454 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000455
Dan Gohman39250432009-05-24 18:02:35 +0000456 // Determine which operand has more trailing zeros, and use that
457 // many bits from the other operand.
458 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000459 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000460 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
461 KnownZero |= KnownZero2 & Mask;
462 KnownOne |= KnownOne2 & Mask;
463 } else {
464 // If the known zeros are in the left operand for a subtract,
465 // fall back to the minimum known zeros in both operands.
466 KnownZero |= APInt::getLowBitsSet(BitWidth,
467 std::min(LHSKnownZeroOut,
468 RHSKnownZeroOut));
469 }
470 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
471 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
472 KnownZero |= LHSKnownZero & Mask;
473 KnownOne |= LHSKnownOne & Mask;
474 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000475
476 // Are we still trying to solve for the sign bit?
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000477 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000478 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
479 if (OBO->hasNoSignedWrap()) {
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000480 if (I->getOpcode() == Instruction::Add) {
481 // Adding two positive numbers can't wrap into negative
482 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
483 KnownZero |= APInt::getSignBit(BitWidth);
484 // and adding two negative numbers can't wrap into positive.
485 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
486 KnownOne |= APInt::getSignBit(BitWidth);
487 } else {
488 // Subtracting a negative number from a positive one can't wrap
489 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
490 KnownZero |= APInt::getSignBit(BitWidth);
491 // neither can subtracting a positive number from a negative one.
492 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
493 KnownOne |= APInt::getSignBit(BitWidth);
494 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000495 }
496 }
497
Chris Lattner173234a2008-06-02 01:18:21 +0000498 return;
499 }
500 case Instruction::SRem:
501 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000502 APInt RA = Rem->getValue().abs();
503 if (RA.isPowerOf2()) {
504 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000505 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
506 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
507 Depth+1);
508
Duncan Sandscfd54182010-01-29 06:18:37 +0000509 // The low bits of the first operand are unchanged by the srem.
510 KnownZero = KnownZero2 & LowBits;
511 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000512
Duncan Sandscfd54182010-01-29 06:18:37 +0000513 // If the first operand is non-negative or has all low bits zero, then
514 // the upper bits are all zero.
515 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
516 KnownZero |= ~LowBits;
517
518 // If the first operand is negative and not all low bits are zero, then
519 // the upper bits are all one.
520 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
521 KnownOne |= ~LowBits;
522
523 KnownZero &= Mask;
524 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000525
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000526 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000527 }
528 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000529
530 // The sign bit is the LHS's sign bit, except when the result of the
531 // remainder is zero.
532 if (Mask.isNegative() && KnownZero.isNonNegative()) {
533 APInt Mask2 = APInt::getSignBit(BitWidth);
534 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
535 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
536 Depth+1);
537 // If it's known zero, our sign bit is also zero.
538 if (LHSKnownZero.isNegative())
539 KnownZero |= LHSKnownZero;
540 }
541
Chris Lattner173234a2008-06-02 01:18:21 +0000542 break;
543 case Instruction::URem: {
544 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
545 APInt RA = Rem->getValue();
546 if (RA.isPowerOf2()) {
547 APInt LowBits = (RA - 1);
548 APInt Mask2 = LowBits & Mask;
549 KnownZero |= ~LowBits & Mask;
550 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
551 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000552 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000553 break;
554 }
555 }
556
557 // Since the result is less than or equal to either operand, any leading
558 // zero bits in either operand must also exist in the result.
559 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
560 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
561 TD, Depth+1);
562 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
563 TD, Depth+1);
564
Chris Lattner79abedb2009-01-20 18:22:57 +0000565 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000566 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000567 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000568 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
569 break;
570 }
571
Victor Hernandeza276c602009-10-17 01:18:07 +0000572 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000573 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000574 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000575 if (Align == 0 && TD)
576 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000577
578 if (Align > 0)
579 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
580 CountTrailingZeros_32(Align));
581 break;
582 }
583 case Instruction::GetElementPtr: {
584 // Analyze all of the subscripts of this getelementptr instruction
585 // to determine if we can prove known low zero bits.
586 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
587 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
588 ComputeMaskedBits(I->getOperand(0), LocalMask,
589 LocalKnownZero, LocalKnownOne, TD, Depth+1);
590 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
591
592 gep_type_iterator GTI = gep_type_begin(I);
593 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
594 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000595 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000596 // Handle struct member offset arithmetic.
597 if (!TD) return;
598 const StructLayout *SL = TD->getStructLayout(STy);
599 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
600 uint64_t Offset = SL->getElementOffset(Idx);
601 TrailZ = std::min(TrailZ,
602 CountTrailingZeros_64(Offset));
603 } else {
604 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000606 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000607 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000608 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000609 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
610 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
611 ComputeMaskedBits(Index, LocalMask,
612 LocalKnownZero, LocalKnownOne, TD, Depth+1);
613 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000614 unsigned(CountTrailingZeros_64(TypeSize) +
615 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000616 }
617 }
618
619 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
620 break;
621 }
622 case Instruction::PHI: {
623 PHINode *P = cast<PHINode>(I);
624 // Handle the case of a simple two-predecessor recurrence PHI.
625 // There's a lot more that could theoretically be done here, but
626 // this is sufficient to catch some interesting cases.
627 if (P->getNumIncomingValues() == 2) {
628 for (unsigned i = 0; i != 2; ++i) {
629 Value *L = P->getIncomingValue(i);
630 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000631 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000632 if (!LU)
633 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000634 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000635 // Check for operations that have the property that if
636 // both their operands have low zero bits, the result
637 // will have low zero bits.
638 if (Opcode == Instruction::Add ||
639 Opcode == Instruction::Sub ||
640 Opcode == Instruction::And ||
641 Opcode == Instruction::Or ||
642 Opcode == Instruction::Mul) {
643 Value *LL = LU->getOperand(0);
644 Value *LR = LU->getOperand(1);
645 // Find a recurrence.
646 if (LL == I)
647 L = LR;
648 else if (LR == I)
649 L = LL;
650 else
651 break;
652 // Ok, we have a PHI of the form L op= R. Check for low
653 // zero bits.
654 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
655 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
656 Mask2 = APInt::getLowBitsSet(BitWidth,
657 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000658
659 // We need to take the minimum number of known bits
660 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
661 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
662
Chris Lattner173234a2008-06-02 01:18:21 +0000663 KnownZero = Mask &
664 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000665 std::min(KnownZero2.countTrailingOnes(),
666 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000667 break;
668 }
669 }
670 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000671
Nick Lewycky3b739d22011-02-10 23:54:10 +0000672 // Unreachable blocks may have zero-operand PHI nodes.
673 if (P->getNumIncomingValues() == 0)
674 return;
675
Dan Gohman9004c8a2009-05-21 02:28:33 +0000676 // Otherwise take the unions of the known bit sets of the operands,
677 // taking conservative care to avoid excessive recursion.
678 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000679 // Skip if every incoming value references to ourself.
680 if (P->hasConstantValue() == P)
681 break;
682
Dan Gohman9004c8a2009-05-21 02:28:33 +0000683 KnownZero = APInt::getAllOnesValue(BitWidth);
684 KnownOne = APInt::getAllOnesValue(BitWidth);
685 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
686 // Skip direct self references.
687 if (P->getIncomingValue(i) == P) continue;
688
689 KnownZero2 = APInt(BitWidth, 0);
690 KnownOne2 = APInt(BitWidth, 0);
691 // Recurse, but cap the recursion to one level, because we don't
692 // want to waste time spinning around in loops.
693 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
694 KnownZero2, KnownOne2, TD, MaxDepth-1);
695 KnownZero &= KnownZero2;
696 KnownOne &= KnownOne2;
697 // If all bits have been ruled out, there's no need to check
698 // more operands.
699 if (!KnownZero && !KnownOne)
700 break;
701 }
702 }
Chris Lattner173234a2008-06-02 01:18:21 +0000703 break;
704 }
705 case Instruction::Call:
706 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
707 switch (II->getIntrinsicID()) {
708 default: break;
709 case Intrinsic::ctpop:
710 case Intrinsic::ctlz:
711 case Intrinsic::cttz: {
712 unsigned LowBits = Log2_32(BitWidth)+1;
713 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
714 break;
715 }
Chad Rosier62660312011-05-26 23:13:19 +0000716 case Intrinsic::x86_sse42_crc32_64_8:
717 case Intrinsic::x86_sse42_crc32_64_64:
Evan Chengcb559c12011-05-22 18:25:30 +0000718 KnownZero = APInt::getHighBitsSet(64, 32);
719 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000720 }
721 }
722 break;
723 }
724}
725
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000726/// ComputeSignBit - Determine whether the sign bit is known to be zero or
727/// one. Convenience wrapper around ComputeMaskedBits.
728void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
729 const TargetData *TD, unsigned Depth) {
730 unsigned BitWidth = getBitWidth(V->getType(), TD);
731 if (!BitWidth) {
732 KnownZero = false;
733 KnownOne = false;
734 return;
735 }
736 APInt ZeroBits(BitWidth, 0);
737 APInt OneBits(BitWidth, 0);
738 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
739 Depth);
740 KnownOne = OneBits[BitWidth - 1];
741 KnownZero = ZeroBits[BitWidth - 1];
742}
743
744/// isPowerOfTwo - Return true if the given value is known to have exactly one
745/// bit set when defined. For vectors return true if every element is known to
746/// be a power of two when defined. Supports values with integer or pointer
747/// types and vectors of integers.
748bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, unsigned Depth) {
749 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Duncan Sands464a4f32011-01-26 08:44:16 +0000750 return CI->getValue().isPowerOf2();
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000751 // TODO: Handle vector constants.
752
753 // 1 << X is clearly a power of two if the one is not shifted off the end. If
754 // it is shifted off the end then the result is undefined.
755 if (match(V, m_Shl(m_One(), m_Value())))
756 return true;
757
758 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
759 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000760 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000761 return true;
762
763 // The remaining tests are all recursive, so bail out if we hit the limit.
764 if (Depth++ == MaxDepth)
765 return false;
766
767 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
768 return isPowerOfTwo(ZI->getOperand(0), TD, Depth);
769
770 if (SelectInst *SI = dyn_cast<SelectInst>(V))
771 return isPowerOfTwo(SI->getTrueValue(), TD, Depth) &&
772 isPowerOfTwo(SI->getFalseValue(), TD, Depth);
773
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000774 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000775 // is a power of two only if the first operand is a power of two and not
776 // copying a sign bit (sdiv int_min, 2).
777 if (match(V, m_LShr(m_Value(), m_Value())) ||
778 match(V, m_UDiv(m_Value(), m_Value()))) {
Eli Friedman6bdd2612011-04-02 22:11:56 +0000779 PossiblyExactOperator *PEO = cast<PossiblyExactOperator>(V);
780 if (PEO->isExact())
781 return isPowerOfTwo(PEO->getOperand(0), TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000782 }
783
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000784 return false;
785}
786
787/// isKnownNonZero - Return true if the given value is known to be non-zero
788/// when defined. For vectors return true if every element is known to be
789/// non-zero when defined. Supports values with integer or pointer type and
790/// vectors of integers.
791bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
792 if (Constant *C = dyn_cast<Constant>(V)) {
793 if (C->isNullValue())
794 return false;
795 if (isa<ConstantInt>(C))
796 // Must be non-zero due to null test above.
797 return true;
798 // TODO: Handle vectors
799 return false;
800 }
801
802 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sandse8ec2252011-10-26 15:31:51 +0000803 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000804 return false;
805
806 unsigned BitWidth = getBitWidth(V->getType(), TD);
807
808 // X | Y != 0 if X != 0 or Y != 0.
809 Value *X = 0, *Y = 0;
810 if (match(V, m_Or(m_Value(X), m_Value(Y))))
811 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
812
813 // ext X != 0 if X != 0.
814 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
815 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
816
Duncan Sands91367822011-01-29 13:27:00 +0000817 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000818 // if the lowest bit is shifted off the end.
819 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000820 // shl nuw can't remove any non-zero bits.
821 BinaryOperator *BO = cast<BinaryOperator>(V);
822 if (BO->hasNoUnsignedWrap())
823 return isKnownNonZero(X, TD, Depth);
824
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000825 APInt KnownZero(BitWidth, 0);
826 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000827 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000828 if (KnownOne[0])
829 return true;
830 }
Duncan Sands91367822011-01-29 13:27:00 +0000831 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000832 // defined if the sign bit is shifted off the end.
833 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000834 // shr exact can only shift out zero bits.
835 BinaryOperator *BO = cast<BinaryOperator>(V);
836 if (BO->isExact())
837 return isKnownNonZero(X, TD, Depth);
838
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000839 bool XKnownNonNegative, XKnownNegative;
840 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
841 if (XKnownNegative)
842 return true;
843 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000844 // div exact can only produce a zero if the dividend is zero.
845 else if (match(V, m_IDiv(m_Value(X), m_Value()))) {
846 BinaryOperator *BO = cast<BinaryOperator>(V);
847 if (BO->isExact())
848 return isKnownNonZero(X, TD, Depth);
849 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000850 // X + Y.
851 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
852 bool XKnownNonNegative, XKnownNegative;
853 bool YKnownNonNegative, YKnownNegative;
854 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
855 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
856
857 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000858 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000859 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000860 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
861 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000862
863 // If X and Y are both negative (as signed values) then their sum is not
864 // zero unless both X and Y equal INT_MIN.
865 if (BitWidth && XKnownNegative && YKnownNegative) {
866 APInt KnownZero(BitWidth, 0);
867 APInt KnownOne(BitWidth, 0);
868 APInt Mask = APInt::getSignedMaxValue(BitWidth);
869 // The sign bit of X is set. If some other bit is set then X is not equal
870 // to INT_MIN.
871 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
872 if ((KnownOne & Mask) != 0)
873 return true;
874 // The sign bit of Y is set. If some other bit is set then Y is not equal
875 // to INT_MIN.
876 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
877 if ((KnownOne & Mask) != 0)
878 return true;
879 }
880
881 // The sum of a non-negative number and a power of two is not zero.
882 if (XKnownNonNegative && isPowerOfTwo(Y, TD, Depth))
883 return true;
884 if (YKnownNonNegative && isPowerOfTwo(X, TD, Depth))
885 return true;
886 }
Duncan Sandse8ec2252011-10-26 15:31:51 +0000887 // X * Y.
888 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
889 BinaryOperator *BO = cast<BinaryOperator>(V);
890 // If X and Y are non-zero then so is X * Y as long as the multiplication
891 // does not overflow.
892 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
893 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
894 return true;
895 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000896 // (C ? X : Y) != 0 if X != 0 and Y != 0.
897 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
898 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
899 isKnownNonZero(SI->getFalseValue(), TD, Depth))
900 return true;
901 }
902
903 if (!BitWidth) return false;
904 APInt KnownZero(BitWidth, 0);
905 APInt KnownOne(BitWidth, 0);
906 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
907 TD, Depth);
908 return KnownOne != 0;
909}
910
Chris Lattner173234a2008-06-02 01:18:21 +0000911/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
912/// this predicate to simplify operations downstream. Mask is known to be zero
913/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000914///
915/// This function is defined on values with integer type, values with pointer
916/// type (but only if TD is non-null), and vectors of integers. In the case
917/// where V is a vector, the mask, known zero, and known one values are the
918/// same width as the vector element, and the bit is set only if it is true
919/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000920bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000921 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000922 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
923 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 return (KnownZero & Mask) == Mask;
926}
927
928
929
930/// ComputeNumSignBits - Return the number of times the sign bit of the
931/// register is replicated into the other bits. We know that at least 1 bit
932/// is always equal to the sign bit (itself), but other cases can give us
933/// information. For example, immediately after an "ashr X, 2", we know that
934/// the top 3 bits are all equal to each other, so we return 3.
935///
936/// 'Op' must have a scalar integer type.
937///
Dan Gohman846a2f22009-08-27 17:51:25 +0000938unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
939 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000940 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000941 "ComputeNumSignBits requires a TargetData object to operate "
942 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000943 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000944 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
945 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000946 unsigned Tmp, Tmp2;
947 unsigned FirstAnswer = 1;
948
Chris Lattnerd82e5112008-06-02 18:39:07 +0000949 // Note that ConstantInt is handled by the general ComputeMaskedBits case
950 // below.
951
Chris Lattner173234a2008-06-02 01:18:21 +0000952 if (Depth == 6)
953 return 1; // Limit search depth.
954
Dan Gohmanca178902009-07-17 20:47:02 +0000955 Operator *U = dyn_cast<Operator>(V);
956 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000957 default: break;
958 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000959 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000960 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
961
962 case Instruction::AShr:
963 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
964 // ashr X, C -> adds C sign bits.
965 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
966 Tmp += C->getZExtValue();
967 if (Tmp > TyBits) Tmp = TyBits;
968 }
Nate Begeman9a3dc552010-12-17 23:12:19 +0000969 // vector ashr X, <C, C, C, C> -> adds C sign bits
970 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
971 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
972 Tmp += CI->getZExtValue();
973 if (Tmp > TyBits) Tmp = TyBits;
974 }
975 }
Chris Lattner173234a2008-06-02 01:18:21 +0000976 return Tmp;
977 case Instruction::Shl:
978 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
979 // shl destroys sign bits.
980 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
981 if (C->getZExtValue() >= TyBits || // Bad shift.
982 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
983 return Tmp - C->getZExtValue();
984 }
985 break;
986 case Instruction::And:
987 case Instruction::Or:
988 case Instruction::Xor: // NOT is handled here.
989 // Logical binary ops preserve the number of sign bits at the worst.
990 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
991 if (Tmp != 1) {
992 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
993 FirstAnswer = std::min(Tmp, Tmp2);
994 // We computed what we know about the sign bits as our first
995 // answer. Now proceed to the generic code that uses
996 // ComputeMaskedBits, and pick whichever answer is better.
997 }
998 break;
999
1000 case Instruction::Select:
1001 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1002 if (Tmp == 1) return 1; // Early out.
1003 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1004 return std::min(Tmp, Tmp2);
1005
1006 case Instruction::Add:
1007 // Add can have at most one carry bit. Thus we know that the output
1008 // is, at worst, one more bit than the inputs.
1009 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1010 if (Tmp == 1) return 1; // Early out.
1011
1012 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001013 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001014 if (CRHS->isAllOnesValue()) {
1015 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1016 APInt Mask = APInt::getAllOnesValue(TyBits);
1017 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1018 Depth+1);
1019
1020 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1021 // sign bits set.
1022 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1023 return TyBits;
1024
1025 // If we are subtracting one from a positive number, there is no carry
1026 // out of the result.
1027 if (KnownZero.isNegative())
1028 return Tmp;
1029 }
1030
1031 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1032 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001033 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001034
1035 case Instruction::Sub:
1036 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1037 if (Tmp2 == 1) return 1;
1038
1039 // Handle NEG.
1040 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1041 if (CLHS->isNullValue()) {
1042 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1043 APInt Mask = APInt::getAllOnesValue(TyBits);
1044 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1045 TD, Depth+1);
1046 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1047 // sign bits set.
1048 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1049 return TyBits;
1050
1051 // If the input is known to be positive (the sign bit is known clear),
1052 // the output of the NEG has the same number of sign bits as the input.
1053 if (KnownZero.isNegative())
1054 return Tmp2;
1055
1056 // Otherwise, we treat this like a SUB.
1057 }
1058
1059 // Sub can have at most one carry bit. Thus we know that the output
1060 // is, at worst, one more bit than the inputs.
1061 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1062 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001063 return std::min(Tmp, Tmp2)-1;
1064
1065 case Instruction::PHI: {
1066 PHINode *PN = cast<PHINode>(U);
1067 // Don't analyze large in-degree PHIs.
1068 if (PN->getNumIncomingValues() > 4) break;
1069
1070 // Take the minimum of all incoming values. This can't infinitely loop
1071 // because of our depth threshold.
1072 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1073 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1074 if (Tmp == 1) return Tmp;
1075 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001076 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001077 }
1078 return Tmp;
1079 }
1080
Chris Lattner173234a2008-06-02 01:18:21 +00001081 case Instruction::Trunc:
1082 // FIXME: it's tricky to do anything useful for this, but it is an important
1083 // case for targets like X86.
1084 break;
1085 }
1086
1087 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1088 // use this information.
1089 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1090 APInt Mask = APInt::getAllOnesValue(TyBits);
1091 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1092
1093 if (KnownZero.isNegative()) { // sign bit is 0
1094 Mask = KnownZero;
1095 } else if (KnownOne.isNegative()) { // sign bit is 1;
1096 Mask = KnownOne;
1097 } else {
1098 // Nothing known.
1099 return FirstAnswer;
1100 }
1101
1102 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1103 // the number of identical bits in the top of the input value.
1104 Mask = ~Mask;
1105 Mask <<= Mask.getBitWidth()-TyBits;
1106 // Return # leading zeros. We use 'min' here in case Val was zero before
1107 // shifting. We don't want to return '64' as for an i32 "0".
1108 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1109}
Chris Lattner833f25d2008-06-02 01:29:46 +00001110
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001111/// ComputeMultiple - This function computes the integer multiple of Base that
1112/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001113/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001114/// through SExt instructions only if LookThroughSExt is true.
1115bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001116 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001117 const unsigned MaxDepth = 6;
1118
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001119 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001120 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001121 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001122
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001123 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001124
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001125 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001126
1127 if (Base == 0)
1128 return false;
1129
1130 if (Base == 1) {
1131 Multiple = V;
1132 return true;
1133 }
1134
1135 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1136 Constant *BaseVal = ConstantInt::get(T, Base);
1137 if (CO && CO == BaseVal) {
1138 // Multiple is 1.
1139 Multiple = ConstantInt::get(T, 1);
1140 return true;
1141 }
1142
1143 if (CI && CI->getZExtValue() % Base == 0) {
1144 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1145 return true;
1146 }
1147
1148 if (Depth == MaxDepth) return false; // Limit search depth.
1149
1150 Operator *I = dyn_cast<Operator>(V);
1151 if (!I) return false;
1152
1153 switch (I->getOpcode()) {
1154 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001155 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001156 if (!LookThroughSExt) return false;
1157 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001158 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001159 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1160 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001161 case Instruction::Shl:
1162 case Instruction::Mul: {
1163 Value *Op0 = I->getOperand(0);
1164 Value *Op1 = I->getOperand(1);
1165
1166 if (I->getOpcode() == Instruction::Shl) {
1167 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1168 if (!Op1CI) return false;
1169 // Turn Op0 << Op1 into Op0 * 2^Op1
1170 APInt Op1Int = Op1CI->getValue();
1171 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001172 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001173 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001174 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001175 }
1176
1177 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001178 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1179 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1180 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1181 if (Op1C->getType()->getPrimitiveSizeInBits() <
1182 MulC->getType()->getPrimitiveSizeInBits())
1183 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1184 if (Op1C->getType()->getPrimitiveSizeInBits() >
1185 MulC->getType()->getPrimitiveSizeInBits())
1186 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1187
1188 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1189 Multiple = ConstantExpr::getMul(MulC, Op1C);
1190 return true;
1191 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001192
1193 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1194 if (Mul0CI->getValue() == 1) {
1195 // V == Base * Op1, so return Op1
1196 Multiple = Op1;
1197 return true;
1198 }
1199 }
1200
Chris Lattnere9711312010-09-05 17:20:46 +00001201 Value *Mul1 = NULL;
1202 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1203 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1204 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1205 if (Op0C->getType()->getPrimitiveSizeInBits() <
1206 MulC->getType()->getPrimitiveSizeInBits())
1207 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1208 if (Op0C->getType()->getPrimitiveSizeInBits() >
1209 MulC->getType()->getPrimitiveSizeInBits())
1210 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1211
1212 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1213 Multiple = ConstantExpr::getMul(MulC, Op0C);
1214 return true;
1215 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001216
1217 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1218 if (Mul1CI->getValue() == 1) {
1219 // V == Base * Op0, so return Op0
1220 Multiple = Op0;
1221 return true;
1222 }
1223 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001224 }
1225 }
1226
1227 // We could not determine if V is a multiple of Base.
1228 return false;
1229}
1230
Chris Lattner833f25d2008-06-02 01:29:46 +00001231/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1232/// value is never equal to -0.0.
1233///
1234/// NOTE: this function will need to be revisited when we support non-default
1235/// rounding modes!
1236///
1237bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1238 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1239 return !CFP->getValueAPF().isNegZero();
1240
1241 if (Depth == 6)
1242 return 1; // Limit search depth.
1243
Dan Gohmanca178902009-07-17 20:47:02 +00001244 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001245 if (I == 0) return false;
1246
1247 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001248 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001249 isa<ConstantFP>(I->getOperand(1)) &&
1250 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1251 return true;
1252
1253 // sitofp and uitofp turn into +0.0 for zero.
1254 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1255 return true;
1256
1257 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1258 // sqrt(-0.0) = -0.0, no other negative results are possible.
1259 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001260 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001261
1262 if (const CallInst *CI = dyn_cast<CallInst>(I))
1263 if (const Function *F = CI->getCalledFunction()) {
1264 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001265 // abs(x) != -0.0
1266 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001267 // fabs[lf](x) != -0.0
1268 if (F->getName() == "fabs") return true;
1269 if (F->getName() == "fabsf") return true;
1270 if (F->getName() == "fabsl") return true;
1271 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1272 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001273 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001274 }
1275 }
1276
1277 return false;
1278}
1279
Chris Lattnerbb897102010-12-26 20:15:01 +00001280/// isBytewiseValue - If the specified value can be set by repeating the same
1281/// byte in memory, return the i8 value that it is represented with. This is
1282/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1283/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1284/// byte store (e.g. i16 0x1234), return null.
1285Value *llvm::isBytewiseValue(Value *V) {
1286 // All byte-wide stores are splatable, even of arbitrary variables.
1287 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001288
1289 // Handle 'null' ConstantArrayZero etc.
1290 if (Constant *C = dyn_cast<Constant>(V))
1291 if (C->isNullValue())
1292 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001293
1294 // Constant float and double values can be handled as integer values if the
1295 // corresponding integer value is "byteable". An important case is 0.0.
1296 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1297 if (CFP->getType()->isFloatTy())
1298 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1299 if (CFP->getType()->isDoubleTy())
1300 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1301 // Don't handle long double formats, which have strange constraints.
1302 }
1303
1304 // We can handle constant integers that are power of two in size and a
1305 // multiple of 8 bits.
1306 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1307 unsigned Width = CI->getBitWidth();
1308 if (isPowerOf2_32(Width) && Width > 8) {
1309 // We can handle this value if the recursive binary decomposition is the
1310 // same at all levels.
1311 APInt Val = CI->getValue();
1312 APInt Val2;
1313 while (Val.getBitWidth() != 8) {
1314 unsigned NextWidth = Val.getBitWidth()/2;
1315 Val2 = Val.lshr(NextWidth);
1316 Val2 = Val2.trunc(Val.getBitWidth()/2);
1317 Val = Val.trunc(Val.getBitWidth()/2);
1318
1319 // If the top/bottom halves aren't the same, reject it.
1320 if (Val != Val2)
1321 return 0;
1322 }
1323 return ConstantInt::get(V->getContext(), Val);
1324 }
1325 }
1326
1327 // A ConstantArray is splatable if all its members are equal and also
1328 // splatable.
1329 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1330 if (CA->getNumOperands() == 0)
1331 return 0;
1332
1333 Value *Val = isBytewiseValue(CA->getOperand(0));
1334 if (!Val)
1335 return 0;
1336
1337 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1338 if (CA->getOperand(I-1) != CA->getOperand(I))
1339 return 0;
1340
1341 return Val;
1342 }
1343
1344 // Conceptually, we could handle things like:
1345 // %a = zext i8 %X to i16
1346 // %b = shl i16 %a, 8
1347 // %c = or i16 %a, %b
1348 // but until there is an example that actually needs this, it doesn't seem
1349 // worth worrying about.
1350 return 0;
1351}
1352
1353
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001354// This is the recursive version of BuildSubAggregate. It takes a few different
1355// arguments. Idxs is the index within the nested struct From that we are
1356// looking at now (which is of type IndexedType). IdxSkip is the number of
1357// indices from Idxs that should be left out when inserting into the resulting
1358// struct. To is the result struct built so far, new insertvalue instructions
1359// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001360static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001361 SmallVector<unsigned, 10> &Idxs,
1362 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001363 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001364 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001365 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001366 // Save the original To argument so we can modify it
1367 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001368 // General case, the type indexed by Idxs is a struct
1369 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1370 // Process each struct element recursively
1371 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001372 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001373 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001374 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001375 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001376 if (!To) {
1377 // Couldn't find any inserted value for this index? Cleanup
1378 while (PrevTo != OrigTo) {
1379 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1380 PrevTo = Del->getAggregateOperand();
1381 Del->eraseFromParent();
1382 }
1383 // Stop processing elements
1384 break;
1385 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001386 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001387 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001388 if (To)
1389 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001390 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001391 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1392 // the struct's elements had a value that was inserted directly. In the latter
1393 // case, perhaps we can't determine each of the subelements individually, but
1394 // we might be able to find the complete struct somewhere.
1395
1396 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001397 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001398
1399 if (!V)
1400 return NULL;
1401
1402 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001403 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001404 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001405}
1406
1407// This helper takes a nested struct and extracts a part of it (which is again a
1408// struct) into a new value. For example, given the struct:
1409// { a, { b, { c, d }, e } }
1410// and the indices "1, 1" this returns
1411// { c, d }.
1412//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001413// It does this by inserting an insertvalue for each element in the resulting
1414// struct, as opposed to just inserting a single struct. This will only work if
1415// each of the elements of the substruct are known (ie, inserted into From by an
1416// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001417//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001418// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001419static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001420 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001421 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001422 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001423 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001424 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001425 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001426 unsigned IdxSkip = Idxs.size();
1427
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001428 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001429}
1430
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001431/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1432/// the scalar value indexed is already around as a register, for example if it
1433/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001434///
1435/// If InsertBefore is not null, this function will duplicate (modified)
1436/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001437Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1438 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001439 // Nothing to index? Just return V then (this is useful at the end of our
1440 // recursion)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001441 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001442 return V;
1443 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001444 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001445 && "Not looking at a struct or array?");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001446 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range)
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001447 && "Invalid indices for type?");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001448 CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001449
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001450 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001451 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001452 idx_range));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001453 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001454 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001455 idx_range));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001456 else if (Constant *C = dyn_cast<Constant>(V)) {
1457 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1458 // Recursively process this constant
Jay Foadfc6d3a42011-07-13 10:26:04 +00001459 return FindInsertedValue(C->getOperand(idx_range[0]), idx_range.slice(1),
1460 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001461 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1462 // Loop the indices for the insertvalue instruction in parallel with the
1463 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001464 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001465 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1466 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001467 if (req_idx == idx_range.end()) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001468 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001469 // The requested index identifies a part of a nested aggregate. Handle
1470 // this specially. For example,
1471 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1472 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1473 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1474 // This can be changed into
1475 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1476 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1477 // which allows the unused 0,0 element from the nested struct to be
1478 // removed.
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001479 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001480 InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001481 else
1482 // We can't handle this without inserting insertvalues
1483 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001484 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001485
1486 // This insert value inserts something else than what we are looking for.
1487 // See if the (aggregrate) value inserted into has the value we are
1488 // looking for, then.
1489 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001490 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001491 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001492 }
1493 // If we end up here, the indices of the insertvalue match with those
1494 // requested (though possibly only partially). Now we recursively look at
1495 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001496 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001497 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001498 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001499 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1500 // If we're extracting a value from an aggregrate that was extracted from
1501 // something else, we can extract from that something else directly instead.
1502 // However, we will need to chain I's indices with the requested indices.
1503
1504 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001505 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001506 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001507 SmallVector<unsigned, 5> Idxs;
1508 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001509 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001510 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001511
1512 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001513 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001514
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001515 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001516 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001517
Jay Foadfc6d3a42011-07-13 10:26:04 +00001518 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001519 }
1520 // Otherwise, we don't know (such as, extracting from a function return value
1521 // or load instruction)
1522 return 0;
1523}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001524
Chris Lattnered58a6f2010-11-30 22:25:26 +00001525/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1526/// it can be expressed as a base pointer plus a constant offset. Return the
1527/// base and offset to the caller.
1528Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1529 const TargetData &TD) {
1530 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1531 if (PtrOp == 0) return Ptr;
1532
1533 // Just look through bitcasts.
1534 if (PtrOp->getOpcode() == Instruction::BitCast)
1535 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1536
1537 // If this is a GEP with constant indices, we can look through it.
1538 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1539 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1540
1541 gep_type_iterator GTI = gep_type_begin(GEP);
1542 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1543 ++I, ++GTI) {
1544 ConstantInt *OpC = cast<ConstantInt>(*I);
1545 if (OpC->isZero()) continue;
1546
1547 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001548 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001549 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1550 } else {
1551 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1552 Offset += OpC->getSExtValue()*Size;
1553 }
1554 }
1555
1556 // Re-sign extend from the pointer size if needed to get overflow edge cases
1557 // right.
1558 unsigned PtrSize = TD.getPointerSizeInBits();
1559 if (PtrSize < 64)
1560 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1561
1562 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1563}
1564
1565
Evan Cheng0ff39b32008-06-30 07:31:25 +00001566/// GetConstantStringInfo - This function computes the length of a
1567/// null-terminated C string pointed to by V. If successful, it returns true
1568/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001569bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001570 uint64_t Offset, bool StopAtNul) {
Bill Wendling0582ae92009-03-13 04:39:26 +00001571 // If V is NULL then return false;
1572 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001573
1574 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001575 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001576 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1577
Evan Cheng0ff39b32008-06-30 07:31:25 +00001578 // If the value is not a GEP instruction nor a constant expression with a
1579 // GEP instruction, then return false because ConstantArray can't occur
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001580 // any other way.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001581 const User *GEP = 0;
1582 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001583 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001584 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001585 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001586 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1587 if (CE->getOpcode() != Instruction::GetElementPtr)
1588 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001589 GEP = CE;
1590 }
1591
1592 if (GEP) {
1593 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001594 if (GEP->getNumOperands() != 3)
1595 return false;
1596
Evan Cheng0ff39b32008-06-30 07:31:25 +00001597 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001598 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1599 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001600 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001601 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001602
1603 // Check to make sure that the first operand of the GEP is an integer and
1604 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001605 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001606 if (FirstIdx == 0 || !FirstIdx->isZero())
1607 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001608
1609 // If the second index isn't a ConstantInt, then this is a variable index
1610 // into the array. If this occurs, we can't say anything meaningful about
1611 // the string.
1612 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001613 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001614 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001615 else
1616 return false;
1617 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001618 StopAtNul);
1619 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001620
Evan Cheng0ff39b32008-06-30 07:31:25 +00001621 // The GEP instruction, constant or instruction, must reference a global
1622 // variable that is a constant and is initialized. The referenced constant
1623 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001624 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001625 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001626 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001627 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001628
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001629 // Handle the all-zeros case
1630 if (GlobalInit->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001631 // This is a degenerate case. The initializer is constant zero so the
1632 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001633 Str.clear();
1634 return true;
1635 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001636
1637 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001638 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001639 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001640 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001641
1642 // Get the number of elements in the array
1643 uint64_t NumElts = Array->getType()->getNumElements();
1644
Bill Wendling0582ae92009-03-13 04:39:26 +00001645 if (Offset > NumElts)
1646 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001647
1648 // Traverse the constant array from 'Offset' which is the place the GEP refers
1649 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001650 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001651 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001652 const Constant *Elt = Array->getOperand(i);
1653 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001654 if (!CI) // This array isn't suitable, non-int initializer.
1655 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001656 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001657 return true; // we found end of string, success!
1658 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001659 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001660
Evan Cheng0ff39b32008-06-30 07:31:25 +00001661 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001662 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001663}
Eric Christopher25ec4832010-03-05 06:58:57 +00001664
1665// These next two are very similar to the above, but also look through PHI
1666// nodes.
1667// TODO: See if we can integrate these two together.
1668
1669/// GetStringLengthH - If we can compute the length of the string pointed to by
1670/// the specified pointer, return 'len+1'. If we can't, return 0.
1671static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1672 // Look through noop bitcast instructions.
1673 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1674 return GetStringLengthH(BCI->getOperand(0), PHIs);
1675
1676 // If this is a PHI node, there are two cases: either we have already seen it
1677 // or we haven't.
1678 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1679 if (!PHIs.insert(PN))
1680 return ~0ULL; // already in the set.
1681
1682 // If it was new, see if all the input strings are the same length.
1683 uint64_t LenSoFar = ~0ULL;
1684 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1685 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1686 if (Len == 0) return 0; // Unknown length -> unknown.
1687
1688 if (Len == ~0ULL) continue;
1689
1690 if (Len != LenSoFar && LenSoFar != ~0ULL)
1691 return 0; // Disagree -> unknown.
1692 LenSoFar = Len;
1693 }
1694
1695 // Success, all agree.
1696 return LenSoFar;
1697 }
1698
1699 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1700 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1701 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1702 if (Len1 == 0) return 0;
1703 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1704 if (Len2 == 0) return 0;
1705 if (Len1 == ~0ULL) return Len2;
1706 if (Len2 == ~0ULL) return Len1;
1707 if (Len1 != Len2) return 0;
1708 return Len1;
1709 }
1710
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001711 // As a special-case, "@string = constant i8 0" is also a string with zero
1712 // length, not wrapped in a bitcast or GEP.
1713 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
1714 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1715 if (GV->getInitializer()->isNullValue()) return 1;
1716 return 0;
1717 }
1718
Eric Christopher25ec4832010-03-05 06:58:57 +00001719 // If the value is not a GEP instruction nor a constant expression with a
1720 // GEP instruction, then return unknown.
1721 User *GEP = 0;
1722 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1723 GEP = GEPI;
1724 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1725 if (CE->getOpcode() != Instruction::GetElementPtr)
1726 return 0;
1727 GEP = CE;
1728 } else {
1729 return 0;
1730 }
1731
1732 // Make sure the GEP has exactly three arguments.
1733 if (GEP->getNumOperands() != 3)
1734 return 0;
1735
1736 // Check to make sure that the first operand of the GEP is an integer and
1737 // has value 0 so that we are sure we're indexing into the initializer.
1738 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1739 if (!Idx->isZero())
1740 return 0;
1741 } else
1742 return 0;
1743
1744 // If the second index isn't a ConstantInt, then this is a variable index
1745 // into the array. If this occurs, we can't say anything meaningful about
1746 // the string.
1747 uint64_t StartIdx = 0;
1748 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1749 StartIdx = CI->getZExtValue();
1750 else
1751 return 0;
1752
1753 // The GEP instruction, constant or instruction, must reference a global
1754 // variable that is a constant and is initialized. The referenced constant
1755 // initializer is the array that we'll use for optimization.
1756 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1757 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1758 GV->mayBeOverridden())
1759 return 0;
1760 Constant *GlobalInit = GV->getInitializer();
1761
1762 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1763 // initializer is constant zero so the length of the string must be zero.
1764 if (isa<ConstantAggregateZero>(GlobalInit))
1765 return 1; // Len = 0 offset by 1.
1766
1767 // Must be a Constant Array
1768 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1769 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1770 return false;
1771
1772 // Get the number of elements in the array
1773 uint64_t NumElts = Array->getType()->getNumElements();
1774
1775 // Traverse the constant array from StartIdx (derived above) which is
1776 // the place the GEP refers to in the array.
1777 for (unsigned i = StartIdx; i != NumElts; ++i) {
1778 Constant *Elt = Array->getOperand(i);
1779 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1780 if (!CI) // This array isn't suitable, non-int initializer.
1781 return 0;
1782 if (CI->isZero())
1783 return i-StartIdx+1; // We found end of string, success!
1784 }
1785
1786 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1787}
1788
1789/// GetStringLength - If we can compute the length of the string pointed to by
1790/// the specified pointer, return 'len+1'. If we can't, return 0.
1791uint64_t llvm::GetStringLength(Value *V) {
1792 if (!V->getType()->isPointerTy()) return 0;
1793
1794 SmallPtrSet<PHINode*, 32> PHIs;
1795 uint64_t Len = GetStringLengthH(V, PHIs);
1796 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1797 // an empty string as a length.
1798 return Len == ~0ULL ? 1 : Len;
1799}
Dan Gohman5034dd32010-12-15 20:02:24 +00001800
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001801Value *
1802llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001803 if (!V->getType()->isPointerTy())
1804 return V;
1805 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1806 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1807 V = GEP->getPointerOperand();
1808 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1809 V = cast<Operator>(V)->getOperand(0);
1810 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1811 if (GA->mayBeOverridden())
1812 return V;
1813 V = GA->getAliasee();
1814 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001815 // See if InstructionSimplify knows any relevant tricks.
1816 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001817 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001818 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001819 V = Simplified;
1820 continue;
1821 }
1822
Dan Gohman5034dd32010-12-15 20:02:24 +00001823 return V;
1824 }
1825 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1826 }
1827 return V;
1828}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001829
1830/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1831/// are lifetime markers.
1832///
1833bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1834 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1835 UI != UE; ++UI) {
1836 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1837 if (!II) return false;
1838
1839 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1840 II->getIntrinsicID() != Intrinsic::lifetime_end)
1841 return false;
1842 }
1843 return true;
1844}