blob: 58adc26a1d7543589b770c52bd251744bb47e06b [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()) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000106 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
107 Type *ObjectType = GVar->getType()->getElementType();
108 // If the object is defined in the current Module, we'll be giving
109 // it the preferred alignment. Otherwise, we have to assume that it
110 // may only have the minimum ABI alignment.
Duncan Sandsd3a38cc2011-11-29 18:26:38 +0000111 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000112 Align = TD->getPreferredAlignment(GVar);
113 else
114 Align = TD->getABITypeAlignment(ObjectType);
115 }
Dan Gohman00407252009-08-11 15:50:03 +0000116 }
Chris Lattner173234a2008-06-02 01:18:21 +0000117 if (Align > 0)
118 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
119 CountTrailingZeros_32(Align));
120 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000121 KnownZero.clearAllBits();
122 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000123 return;
124 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000125 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
126 // the bits of its aliasee.
127 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
128 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000129 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000130 } else {
131 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
132 TD, Depth+1);
133 }
134 return;
135 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000136
137 if (Argument *A = dyn_cast<Argument>(V)) {
138 // Get alignment information off byval arguments if specified in the IR.
139 if (A->hasByValAttr())
140 if (unsigned Align = A->getParamAlignment())
141 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
142 CountTrailingZeros_32(Align));
143 return;
144 }
Chris Lattner173234a2008-06-02 01:18:21 +0000145
Chris Lattnerb3f06732011-05-23 00:03:39 +0000146 // Start out not knowing anything.
147 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000148
Dan Gohman9004c8a2009-05-21 02:28:33 +0000149 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000150 return; // Limit search depth.
151
Dan Gohmanca178902009-07-17 20:47:02 +0000152 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000153 if (!I) return;
154
155 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000156 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000157 default: break;
158 case Instruction::And: {
159 // If either the LHS or the RHS are Zero, the result is zero.
160 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
161 APInt Mask2(Mask & ~KnownZero);
162 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
163 Depth+1);
164 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
165 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
166
167 // Output known-1 bits are only known if set in both the LHS & RHS.
168 KnownOne &= KnownOne2;
169 // Output known-0 are known to be clear if zero in either the LHS | RHS.
170 KnownZero |= KnownZero2;
171 return;
172 }
173 case Instruction::Or: {
174 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
175 APInt Mask2(Mask & ~KnownOne);
176 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
177 Depth+1);
178 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
179 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
180
181 // Output known-0 bits are only known if clear in both the LHS & RHS.
182 KnownZero &= KnownZero2;
183 // Output known-1 are known to be set if set in either the LHS | RHS.
184 KnownOne |= KnownOne2;
185 return;
186 }
187 case Instruction::Xor: {
188 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
189 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
190 Depth+1);
191 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
192 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
193
194 // Output known-0 bits are known if clear or set in both the LHS & RHS.
195 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
196 // Output known-1 are known to be set if set in only one of the LHS, RHS.
197 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
198 KnownZero = KnownZeroOut;
199 return;
200 }
201 case Instruction::Mul: {
202 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
203 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
204 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
205 Depth+1);
Duncan Sands32a43cc2011-10-27 19:16:21 +0000206 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
207 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
208
209 bool isKnownNegative = false;
210 bool isKnownNonNegative = false;
211 // If the multiplication is known not to overflow, compute the sign bit.
212 if (Mask.isNegative() &&
213 cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) {
214 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
215 if (Op1 == Op2) {
216 // The product of a number with itself is non-negative.
217 isKnownNonNegative = true;
218 } else {
219 bool isKnownNonNegative1 = KnownZero.isNegative();
220 bool isKnownNonNegative2 = KnownZero2.isNegative();
221 bool isKnownNegative1 = KnownOne.isNegative();
222 bool isKnownNegative2 = KnownOne2.isNegative();
223 // The product of two numbers with the same sign is non-negative.
224 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
225 (isKnownNonNegative1 && isKnownNonNegative2);
226 // The product of a negative number and a non-negative number is either
227 // negative or zero.
228 if (!isKnownNonNegative)
229 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
230 isKnownNonZero(Op2, TD, Depth)) ||
231 (isKnownNegative2 && isKnownNonNegative1 &&
232 isKnownNonZero(Op1, TD, Depth));
233 }
234 }
235
Chris Lattner173234a2008-06-02 01:18:21 +0000236 // If low bits are zero in either operand, output low known-0 bits.
237 // Also compute a conserative estimate for high known-0 bits.
238 // More trickiness is possible, but this is sufficient for the
239 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000240 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000241 unsigned TrailZ = KnownZero.countTrailingOnes() +
242 KnownZero2.countTrailingOnes();
243 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
244 KnownZero2.countLeadingOnes(),
245 BitWidth) - BitWidth;
246
247 TrailZ = std::min(TrailZ, BitWidth);
248 LeadZ = std::min(LeadZ, BitWidth);
249 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
250 APInt::getHighBitsSet(BitWidth, LeadZ);
251 KnownZero &= Mask;
Duncan Sands32a43cc2011-10-27 19:16:21 +0000252
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000253 // Only make use of no-wrap flags if we failed to compute the sign bit
254 // directly. This matters if the multiplication always overflows, in
255 // which case we prefer to follow the result of the direct computation,
256 // though as the program is invoking undefined behaviour we can choose
257 // whatever we like here.
258 if (isKnownNonNegative && !KnownOne.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000259 KnownZero.setBit(BitWidth - 1);
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000260 else if (isKnownNegative && !KnownZero.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000261 KnownOne.setBit(BitWidth - 1);
262
Chris Lattner173234a2008-06-02 01:18:21 +0000263 return;
264 }
265 case Instruction::UDiv: {
266 // For the purposes of computing leading zeros we can conservatively
267 // treat a udiv as a logical right shift by the power of 2 known to
268 // be less than the denominator.
269 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
270 ComputeMaskedBits(I->getOperand(0),
271 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
272 unsigned LeadZ = KnownZero2.countLeadingOnes();
273
Jay Foad7a874dd2010-12-01 08:53:58 +0000274 KnownOne2.clearAllBits();
275 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000276 ComputeMaskedBits(I->getOperand(1),
277 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
278 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
279 if (RHSUnknownLeadingOnes != BitWidth)
280 LeadZ = std::min(BitWidth,
281 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
282
283 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
284 return;
285 }
286 case Instruction::Select:
287 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
288 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
289 Depth+1);
290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
291 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
292
293 // Only known if known in both the LHS and RHS.
294 KnownOne &= KnownOne2;
295 KnownZero &= KnownZero2;
296 return;
297 case Instruction::FPTrunc:
298 case Instruction::FPExt:
299 case Instruction::FPToUI:
300 case Instruction::FPToSI:
301 case Instruction::SIToFP:
302 case Instruction::UIToFP:
303 return; // Can't work with floating point.
304 case Instruction::PtrToInt:
305 case Instruction::IntToPtr:
306 // We can't handle these if we don't know the pointer size.
307 if (!TD) return;
308 // FALL THROUGH and handle them the same as zext/trunc.
309 case Instruction::ZExt:
310 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000311 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000312
313 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000314 // Note that we handle pointer operands here because of inttoptr/ptrtoint
315 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000316 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000317 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
318 else
319 SrcBitWidth = SrcTy->getScalarSizeInBits();
320
Jay Foad40f8f622010-12-07 08:25:19 +0000321 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
322 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
323 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000324 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
325 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000326 KnownZero = KnownZero.zextOrTrunc(BitWidth);
327 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000328 // Any top bits are known to be zero.
329 if (BitWidth > SrcBitWidth)
330 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
331 return;
332 }
333 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000334 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000335 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000336 // TODO: For now, not handling conversions like:
337 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000338 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000339 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
340 Depth+1);
341 return;
342 }
343 break;
344 }
345 case Instruction::SExt: {
346 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000347 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000348
Jay Foad40f8f622010-12-07 08:25:19 +0000349 APInt MaskIn = Mask.trunc(SrcBitWidth);
350 KnownZero = KnownZero.trunc(SrcBitWidth);
351 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000352 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
353 Depth+1);
354 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000355 KnownZero = KnownZero.zext(BitWidth);
356 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000357
358 // If the sign bit of the input is known set or clear, then we know the
359 // top bits of the result.
360 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
361 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
362 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
363 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
364 return;
365 }
366 case Instruction::Shl:
367 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
368 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
369 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
370 APInt Mask2(Mask.lshr(ShiftAmt));
371 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
372 Depth+1);
373 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
374 KnownZero <<= ShiftAmt;
375 KnownOne <<= ShiftAmt;
376 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
377 return;
378 }
379 break;
380 case Instruction::LShr:
381 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
382 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
383 // Compute the new bits that are at the top now.
384 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
385
386 // Unsigned shift right.
387 APInt Mask2(Mask.shl(ShiftAmt));
388 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
389 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000390 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000391 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
392 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
393 // high bits known zero.
394 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
395 return;
396 }
397 break;
398 case Instruction::AShr:
399 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
400 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
401 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000402 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000403
404 // Signed shift right.
405 APInt Mask2(Mask.shl(ShiftAmt));
406 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
407 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000408 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000409 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
410 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
411
412 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
413 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
414 KnownZero |= HighBits;
415 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
416 KnownOne |= HighBits;
417 return;
418 }
419 break;
420 case Instruction::Sub: {
421 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
422 // We know that the top bits of C-X are clear if X contains less bits
423 // than C (i.e. no wrap-around can happen). For example, 20-X is
424 // positive if we can prove that X is >= 0 and < 16.
425 if (!CLHS->getValue().isNegative()) {
426 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
427 // NLZ can't be BitWidth with no sign bit
428 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
429 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
430 TD, Depth+1);
431
432 // If all of the MaskV bits are known to be zero, then we know the
433 // output top bits are zero, because we now know that the output is
434 // from [0-C].
435 if ((KnownZero2 & MaskV) == MaskV) {
436 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
437 // Top bits known zero.
438 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
439 }
440 }
441 }
442 }
443 // fall through
444 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000445 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000446 // other operand has in those bit positions will be preserved in the
447 // result. For an add, this works with either operand. For a subtract,
448 // this only works if the known zeros are in the right operand.
449 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
450 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
451 BitWidth - Mask.countLeadingZeros());
452 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000453 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000454 assert((LHSKnownZero & LHSKnownOne) == 0 &&
455 "Bits known to be one AND zero?");
456 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000457
458 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
459 Depth+1);
460 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000461 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000462
Dan Gohman39250432009-05-24 18:02:35 +0000463 // Determine which operand has more trailing zeros, and use that
464 // many bits from the other operand.
465 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000466 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000467 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
468 KnownZero |= KnownZero2 & Mask;
469 KnownOne |= KnownOne2 & Mask;
470 } else {
471 // If the known zeros are in the left operand for a subtract,
472 // fall back to the minimum known zeros in both operands.
473 KnownZero |= APInt::getLowBitsSet(BitWidth,
474 std::min(LHSKnownZeroOut,
475 RHSKnownZeroOut));
476 }
477 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
478 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
479 KnownZero |= LHSKnownZero & Mask;
480 KnownOne |= LHSKnownOne & Mask;
481 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000482
483 // Are we still trying to solve for the sign bit?
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000484 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000485 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
486 if (OBO->hasNoSignedWrap()) {
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000487 if (I->getOpcode() == Instruction::Add) {
488 // Adding two positive numbers can't wrap into negative
489 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
490 KnownZero |= APInt::getSignBit(BitWidth);
491 // and adding two negative numbers can't wrap into positive.
492 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
493 KnownOne |= APInt::getSignBit(BitWidth);
494 } else {
495 // Subtracting a negative number from a positive one can't wrap
496 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
497 KnownZero |= APInt::getSignBit(BitWidth);
498 // neither can subtracting a positive number from a negative one.
499 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
500 KnownOne |= APInt::getSignBit(BitWidth);
501 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000502 }
503 }
504
Chris Lattner173234a2008-06-02 01:18:21 +0000505 return;
506 }
507 case Instruction::SRem:
508 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000509 APInt RA = Rem->getValue().abs();
510 if (RA.isPowerOf2()) {
511 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000512 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
513 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
514 Depth+1);
515
Duncan Sandscfd54182010-01-29 06:18:37 +0000516 // The low bits of the first operand are unchanged by the srem.
517 KnownZero = KnownZero2 & LowBits;
518 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000519
Duncan Sandscfd54182010-01-29 06:18:37 +0000520 // If the first operand is non-negative or has all low bits zero, then
521 // the upper bits are all zero.
522 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
523 KnownZero |= ~LowBits;
524
525 // If the first operand is negative and not all low bits are zero, then
526 // the upper bits are all one.
527 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
528 KnownOne |= ~LowBits;
529
530 KnownZero &= Mask;
531 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000532
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000533 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000534 }
535 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000536
537 // The sign bit is the LHS's sign bit, except when the result of the
538 // remainder is zero.
539 if (Mask.isNegative() && KnownZero.isNonNegative()) {
540 APInt Mask2 = APInt::getSignBit(BitWidth);
541 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
542 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
543 Depth+1);
544 // If it's known zero, our sign bit is also zero.
545 if (LHSKnownZero.isNegative())
546 KnownZero |= LHSKnownZero;
547 }
548
Chris Lattner173234a2008-06-02 01:18:21 +0000549 break;
550 case Instruction::URem: {
551 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
552 APInt RA = Rem->getValue();
553 if (RA.isPowerOf2()) {
554 APInt LowBits = (RA - 1);
555 APInt Mask2 = LowBits & Mask;
556 KnownZero |= ~LowBits & Mask;
557 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
558 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000559 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000560 break;
561 }
562 }
563
564 // Since the result is less than or equal to either operand, any leading
565 // zero bits in either operand must also exist in the result.
566 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
567 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
568 TD, Depth+1);
569 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
570 TD, Depth+1);
571
Chris Lattner79abedb2009-01-20 18:22:57 +0000572 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000573 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000574 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000575 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
576 break;
577 }
578
Victor Hernandeza276c602009-10-17 01:18:07 +0000579 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000580 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000581 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000582 if (Align == 0 && TD)
583 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000584
585 if (Align > 0)
586 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
587 CountTrailingZeros_32(Align));
588 break;
589 }
590 case Instruction::GetElementPtr: {
591 // Analyze all of the subscripts of this getelementptr instruction
592 // to determine if we can prove known low zero bits.
593 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
594 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
595 ComputeMaskedBits(I->getOperand(0), LocalMask,
596 LocalKnownZero, LocalKnownOne, TD, Depth+1);
597 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
598
599 gep_type_iterator GTI = gep_type_begin(I);
600 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
601 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000602 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000603 // Handle struct member offset arithmetic.
604 if (!TD) return;
605 const StructLayout *SL = TD->getStructLayout(STy);
606 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
607 uint64_t Offset = SL->getElementOffset(Idx);
608 TrailZ = std::min(TrailZ,
609 CountTrailingZeros_64(Offset));
610 } else {
611 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000612 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000613 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000614 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000615 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000616 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
617 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
618 ComputeMaskedBits(Index, LocalMask,
619 LocalKnownZero, LocalKnownOne, TD, Depth+1);
620 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000621 unsigned(CountTrailingZeros_64(TypeSize) +
622 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000623 }
624 }
625
626 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
627 break;
628 }
629 case Instruction::PHI: {
630 PHINode *P = cast<PHINode>(I);
631 // Handle the case of a simple two-predecessor recurrence PHI.
632 // There's a lot more that could theoretically be done here, but
633 // this is sufficient to catch some interesting cases.
634 if (P->getNumIncomingValues() == 2) {
635 for (unsigned i = 0; i != 2; ++i) {
636 Value *L = P->getIncomingValue(i);
637 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000638 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000639 if (!LU)
640 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000641 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000642 // Check for operations that have the property that if
643 // both their operands have low zero bits, the result
644 // will have low zero bits.
645 if (Opcode == Instruction::Add ||
646 Opcode == Instruction::Sub ||
647 Opcode == Instruction::And ||
648 Opcode == Instruction::Or ||
649 Opcode == Instruction::Mul) {
650 Value *LL = LU->getOperand(0);
651 Value *LR = LU->getOperand(1);
652 // Find a recurrence.
653 if (LL == I)
654 L = LR;
655 else if (LR == I)
656 L = LL;
657 else
658 break;
659 // Ok, we have a PHI of the form L op= R. Check for low
660 // zero bits.
661 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
662 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
663 Mask2 = APInt::getLowBitsSet(BitWidth,
664 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000665
666 // We need to take the minimum number of known bits
667 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
668 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
669
Chris Lattner173234a2008-06-02 01:18:21 +0000670 KnownZero = Mask &
671 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000672 std::min(KnownZero2.countTrailingOnes(),
673 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000674 break;
675 }
676 }
677 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000678
Nick Lewycky3b739d22011-02-10 23:54:10 +0000679 // Unreachable blocks may have zero-operand PHI nodes.
680 if (P->getNumIncomingValues() == 0)
681 return;
682
Dan Gohman9004c8a2009-05-21 02:28:33 +0000683 // Otherwise take the unions of the known bit sets of the operands,
684 // taking conservative care to avoid excessive recursion.
685 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000686 // Skip if every incoming value references to ourself.
687 if (P->hasConstantValue() == P)
688 break;
689
Dan Gohman9004c8a2009-05-21 02:28:33 +0000690 KnownZero = APInt::getAllOnesValue(BitWidth);
691 KnownOne = APInt::getAllOnesValue(BitWidth);
692 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
693 // Skip direct self references.
694 if (P->getIncomingValue(i) == P) continue;
695
696 KnownZero2 = APInt(BitWidth, 0);
697 KnownOne2 = APInt(BitWidth, 0);
698 // Recurse, but cap the recursion to one level, because we don't
699 // want to waste time spinning around in loops.
700 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
701 KnownZero2, KnownOne2, TD, MaxDepth-1);
702 KnownZero &= KnownZero2;
703 KnownOne &= KnownOne2;
704 // If all bits have been ruled out, there's no need to check
705 // more operands.
706 if (!KnownZero && !KnownOne)
707 break;
708 }
709 }
Chris Lattner173234a2008-06-02 01:18:21 +0000710 break;
711 }
712 case Instruction::Call:
713 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
714 switch (II->getIntrinsicID()) {
715 default: break;
716 case Intrinsic::ctpop:
717 case Intrinsic::ctlz:
718 case Intrinsic::cttz: {
719 unsigned LowBits = Log2_32(BitWidth)+1;
720 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
721 break;
722 }
Chad Rosier62660312011-05-26 23:13:19 +0000723 case Intrinsic::x86_sse42_crc32_64_8:
724 case Intrinsic::x86_sse42_crc32_64_64:
Evan Chengcb559c12011-05-22 18:25:30 +0000725 KnownZero = APInt::getHighBitsSet(64, 32);
726 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000727 }
728 }
729 break;
730 }
731}
732
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000733/// ComputeSignBit - Determine whether the sign bit is known to be zero or
734/// one. Convenience wrapper around ComputeMaskedBits.
735void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
736 const TargetData *TD, unsigned Depth) {
737 unsigned BitWidth = getBitWidth(V->getType(), TD);
738 if (!BitWidth) {
739 KnownZero = false;
740 KnownOne = false;
741 return;
742 }
743 APInt ZeroBits(BitWidth, 0);
744 APInt OneBits(BitWidth, 0);
745 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
746 Depth);
747 KnownOne = OneBits[BitWidth - 1];
748 KnownZero = ZeroBits[BitWidth - 1];
749}
750
751/// isPowerOfTwo - Return true if the given value is known to have exactly one
752/// bit set when defined. For vectors return true if every element is known to
753/// be a power of two when defined. Supports values with integer or pointer
754/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000755bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
756 unsigned Depth) {
757 if (Constant *C = dyn_cast<Constant>(V)) {
758 if (C->isNullValue())
759 return OrZero;
760 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
761 return CI->getValue().isPowerOf2();
762 // TODO: Handle vector constants.
763 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000764
765 // 1 << X is clearly a power of two if the one is not shifted off the end. If
766 // it is shifted off the end then the result is undefined.
767 if (match(V, m_Shl(m_One(), m_Value())))
768 return true;
769
770 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
771 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000772 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000773 return true;
774
775 // The remaining tests are all recursive, so bail out if we hit the limit.
776 if (Depth++ == MaxDepth)
777 return false;
778
Duncan Sands4604fc72011-10-28 18:30:05 +0000779 Value *X = 0, *Y = 0;
780 // A shift of a power of two is a power of two or zero.
781 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
782 match(V, m_Shr(m_Value(X), m_Value()))))
783 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
784
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000785 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000786 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000787
788 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000789 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
790 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
791
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000792 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
793 // A power of two and'd with anything is a power of two or zero.
794 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
795 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
796 return true;
797 // X & (-X) is always a power of two or zero.
798 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
799 return true;
800 return false;
801 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000802
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000803 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000804 // is a power of two only if the first operand is a power of two and not
805 // copying a sign bit (sdiv int_min, 2).
806 if (match(V, m_LShr(m_Value(), m_Value())) ||
807 match(V, m_UDiv(m_Value(), m_Value()))) {
Eli Friedman6bdd2612011-04-02 22:11:56 +0000808 PossiblyExactOperator *PEO = cast<PossiblyExactOperator>(V);
809 if (PEO->isExact())
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000810 return isPowerOfTwo(PEO->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000811 }
812
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000813 return false;
814}
815
816/// isKnownNonZero - Return true if the given value is known to be non-zero
817/// when defined. For vectors return true if every element is known to be
818/// non-zero when defined. Supports values with integer or pointer type and
819/// vectors of integers.
820bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
821 if (Constant *C = dyn_cast<Constant>(V)) {
822 if (C->isNullValue())
823 return false;
824 if (isa<ConstantInt>(C))
825 // Must be non-zero due to null test above.
826 return true;
827 // TODO: Handle vectors
828 return false;
829 }
830
831 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000832 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000833 return false;
834
835 unsigned BitWidth = getBitWidth(V->getType(), TD);
836
837 // X | Y != 0 if X != 0 or Y != 0.
838 Value *X = 0, *Y = 0;
839 if (match(V, m_Or(m_Value(X), m_Value(Y))))
840 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
841
842 // ext X != 0 if X != 0.
843 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
844 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
845
Duncan Sands91367822011-01-29 13:27:00 +0000846 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000847 // if the lowest bit is shifted off the end.
848 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000849 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000850 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000851 if (BO->hasNoUnsignedWrap())
852 return isKnownNonZero(X, TD, Depth);
853
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000854 APInt KnownZero(BitWidth, 0);
855 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000856 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000857 if (KnownOne[0])
858 return true;
859 }
Duncan Sands91367822011-01-29 13:27:00 +0000860 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000861 // defined if the sign bit is shifted off the end.
862 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000863 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000864 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000865 if (BO->isExact())
866 return isKnownNonZero(X, TD, Depth);
867
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000868 bool XKnownNonNegative, XKnownNegative;
869 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
870 if (XKnownNegative)
871 return true;
872 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000873 // div exact can only produce a zero if the dividend is zero.
874 else if (match(V, m_IDiv(m_Value(X), m_Value()))) {
Duncan Sands32a43cc2011-10-27 19:16:21 +0000875 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000876 if (BO->isExact())
877 return isKnownNonZero(X, TD, Depth);
878 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000879 // X + Y.
880 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
881 bool XKnownNonNegative, XKnownNegative;
882 bool YKnownNonNegative, YKnownNegative;
883 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
884 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
885
886 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000887 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000888 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000889 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
890 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000891
892 // If X and Y are both negative (as signed values) then their sum is not
893 // zero unless both X and Y equal INT_MIN.
894 if (BitWidth && XKnownNegative && YKnownNegative) {
895 APInt KnownZero(BitWidth, 0);
896 APInt KnownOne(BitWidth, 0);
897 APInt Mask = APInt::getSignedMaxValue(BitWidth);
898 // The sign bit of X is set. If some other bit is set then X is not equal
899 // to INT_MIN.
900 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
901 if ((KnownOne & Mask) != 0)
902 return true;
903 // The sign bit of Y is set. If some other bit is set then Y is not equal
904 // to INT_MIN.
905 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
906 if ((KnownOne & Mask) != 0)
907 return true;
908 }
909
910 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000911 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000912 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000913 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000914 return true;
915 }
Duncan Sands32a43cc2011-10-27 19:16:21 +0000916 // X * Y.
917 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
918 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
919 // If X and Y are non-zero then so is X * Y as long as the multiplication
920 // does not overflow.
921 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
922 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
923 return true;
924 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000925 // (C ? X : Y) != 0 if X != 0 and Y != 0.
926 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
927 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
928 isKnownNonZero(SI->getFalseValue(), TD, Depth))
929 return true;
930 }
931
932 if (!BitWidth) return false;
933 APInt KnownZero(BitWidth, 0);
934 APInt KnownOne(BitWidth, 0);
935 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
936 TD, Depth);
937 return KnownOne != 0;
938}
939
Chris Lattner173234a2008-06-02 01:18:21 +0000940/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
941/// this predicate to simplify operations downstream. Mask is known to be zero
942/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000943///
944/// This function is defined on values with integer type, values with pointer
945/// type (but only if TD is non-null), and vectors of integers. In the case
946/// where V is a vector, the mask, known zero, and known one values are the
947/// same width as the vector element, and the bit is set only if it is true
948/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000949bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000950 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000951 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
952 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
953 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
954 return (KnownZero & Mask) == Mask;
955}
956
957
958
959/// ComputeNumSignBits - Return the number of times the sign bit of the
960/// register is replicated into the other bits. We know that at least 1 bit
961/// is always equal to the sign bit (itself), but other cases can give us
962/// information. For example, immediately after an "ashr X, 2", we know that
963/// the top 3 bits are all equal to each other, so we return 3.
964///
965/// 'Op' must have a scalar integer type.
966///
Dan Gohman846a2f22009-08-27 17:51:25 +0000967unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
968 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000969 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000970 "ComputeNumSignBits requires a TargetData object to operate "
971 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000972 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000973 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
974 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000975 unsigned Tmp, Tmp2;
976 unsigned FirstAnswer = 1;
977
Chris Lattnerd82e5112008-06-02 18:39:07 +0000978 // Note that ConstantInt is handled by the general ComputeMaskedBits case
979 // below.
980
Chris Lattner173234a2008-06-02 01:18:21 +0000981 if (Depth == 6)
982 return 1; // Limit search depth.
983
Dan Gohmanca178902009-07-17 20:47:02 +0000984 Operator *U = dyn_cast<Operator>(V);
985 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000986 default: break;
987 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000988 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000989 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
990
991 case Instruction::AShr:
992 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
993 // ashr X, C -> adds C sign bits.
994 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
995 Tmp += C->getZExtValue();
996 if (Tmp > TyBits) Tmp = TyBits;
997 }
Nate Begeman9a3dc552010-12-17 23:12:19 +0000998 // vector ashr X, <C, C, C, C> -> adds C sign bits
999 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
1000 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
1001 Tmp += CI->getZExtValue();
1002 if (Tmp > TyBits) Tmp = TyBits;
1003 }
1004 }
Chris Lattner173234a2008-06-02 01:18:21 +00001005 return Tmp;
1006 case Instruction::Shl:
1007 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
1008 // shl destroys sign bits.
1009 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1010 if (C->getZExtValue() >= TyBits || // Bad shift.
1011 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1012 return Tmp - C->getZExtValue();
1013 }
1014 break;
1015 case Instruction::And:
1016 case Instruction::Or:
1017 case Instruction::Xor: // NOT is handled here.
1018 // Logical binary ops preserve the number of sign bits at the worst.
1019 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1020 if (Tmp != 1) {
1021 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1022 FirstAnswer = std::min(Tmp, Tmp2);
1023 // We computed what we know about the sign bits as our first
1024 // answer. Now proceed to the generic code that uses
1025 // ComputeMaskedBits, and pick whichever answer is better.
1026 }
1027 break;
1028
1029 case Instruction::Select:
1030 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1031 if (Tmp == 1) return 1; // Early out.
1032 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1033 return std::min(Tmp, Tmp2);
1034
1035 case Instruction::Add:
1036 // Add can have at most one carry bit. Thus we know that the output
1037 // is, at worst, one more bit than the inputs.
1038 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1039 if (Tmp == 1) return 1; // Early out.
1040
1041 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001042 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001043 if (CRHS->isAllOnesValue()) {
1044 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1045 APInt Mask = APInt::getAllOnesValue(TyBits);
1046 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1047 Depth+1);
1048
1049 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1050 // sign bits set.
1051 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1052 return TyBits;
1053
1054 // If we are subtracting one from a positive number, there is no carry
1055 // out of the result.
1056 if (KnownZero.isNegative())
1057 return Tmp;
1058 }
1059
1060 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1061 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001062 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001063
1064 case Instruction::Sub:
1065 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1066 if (Tmp2 == 1) return 1;
1067
1068 // Handle NEG.
1069 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1070 if (CLHS->isNullValue()) {
1071 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1072 APInt Mask = APInt::getAllOnesValue(TyBits);
1073 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1074 TD, Depth+1);
1075 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1076 // sign bits set.
1077 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1078 return TyBits;
1079
1080 // If the input is known to be positive (the sign bit is known clear),
1081 // the output of the NEG has the same number of sign bits as the input.
1082 if (KnownZero.isNegative())
1083 return Tmp2;
1084
1085 // Otherwise, we treat this like a SUB.
1086 }
1087
1088 // Sub can have at most one carry bit. Thus we know that the output
1089 // is, at worst, one more bit than the inputs.
1090 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1091 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001092 return std::min(Tmp, Tmp2)-1;
1093
1094 case Instruction::PHI: {
1095 PHINode *PN = cast<PHINode>(U);
1096 // Don't analyze large in-degree PHIs.
1097 if (PN->getNumIncomingValues() > 4) break;
1098
1099 // Take the minimum of all incoming values. This can't infinitely loop
1100 // because of our depth threshold.
1101 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1102 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1103 if (Tmp == 1) return Tmp;
1104 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001105 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001106 }
1107 return Tmp;
1108 }
1109
Chris Lattner173234a2008-06-02 01:18:21 +00001110 case Instruction::Trunc:
1111 // FIXME: it's tricky to do anything useful for this, but it is an important
1112 // case for targets like X86.
1113 break;
1114 }
1115
1116 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1117 // use this information.
1118 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1119 APInt Mask = APInt::getAllOnesValue(TyBits);
1120 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1121
1122 if (KnownZero.isNegative()) { // sign bit is 0
1123 Mask = KnownZero;
1124 } else if (KnownOne.isNegative()) { // sign bit is 1;
1125 Mask = KnownOne;
1126 } else {
1127 // Nothing known.
1128 return FirstAnswer;
1129 }
1130
1131 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1132 // the number of identical bits in the top of the input value.
1133 Mask = ~Mask;
1134 Mask <<= Mask.getBitWidth()-TyBits;
1135 // Return # leading zeros. We use 'min' here in case Val was zero before
1136 // shifting. We don't want to return '64' as for an i32 "0".
1137 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1138}
Chris Lattner833f25d2008-06-02 01:29:46 +00001139
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001140/// ComputeMultiple - This function computes the integer multiple of Base that
1141/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001142/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001143/// through SExt instructions only if LookThroughSExt is true.
1144bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001145 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001146 const unsigned MaxDepth = 6;
1147
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001148 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001149 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001150 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001151
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001152 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001153
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001154 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001155
1156 if (Base == 0)
1157 return false;
1158
1159 if (Base == 1) {
1160 Multiple = V;
1161 return true;
1162 }
1163
1164 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1165 Constant *BaseVal = ConstantInt::get(T, Base);
1166 if (CO && CO == BaseVal) {
1167 // Multiple is 1.
1168 Multiple = ConstantInt::get(T, 1);
1169 return true;
1170 }
1171
1172 if (CI && CI->getZExtValue() % Base == 0) {
1173 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1174 return true;
1175 }
1176
1177 if (Depth == MaxDepth) return false; // Limit search depth.
1178
1179 Operator *I = dyn_cast<Operator>(V);
1180 if (!I) return false;
1181
1182 switch (I->getOpcode()) {
1183 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001184 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001185 if (!LookThroughSExt) return false;
1186 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001187 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001188 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1189 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001190 case Instruction::Shl:
1191 case Instruction::Mul: {
1192 Value *Op0 = I->getOperand(0);
1193 Value *Op1 = I->getOperand(1);
1194
1195 if (I->getOpcode() == Instruction::Shl) {
1196 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1197 if (!Op1CI) return false;
1198 // Turn Op0 << Op1 into Op0 * 2^Op1
1199 APInt Op1Int = Op1CI->getValue();
1200 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001201 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001202 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001203 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001204 }
1205
1206 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001207 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1208 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1209 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1210 if (Op1C->getType()->getPrimitiveSizeInBits() <
1211 MulC->getType()->getPrimitiveSizeInBits())
1212 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1213 if (Op1C->getType()->getPrimitiveSizeInBits() >
1214 MulC->getType()->getPrimitiveSizeInBits())
1215 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1216
1217 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1218 Multiple = ConstantExpr::getMul(MulC, Op1C);
1219 return true;
1220 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001221
1222 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1223 if (Mul0CI->getValue() == 1) {
1224 // V == Base * Op1, so return Op1
1225 Multiple = Op1;
1226 return true;
1227 }
1228 }
1229
Chris Lattnere9711312010-09-05 17:20:46 +00001230 Value *Mul1 = NULL;
1231 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1232 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1233 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1234 if (Op0C->getType()->getPrimitiveSizeInBits() <
1235 MulC->getType()->getPrimitiveSizeInBits())
1236 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1237 if (Op0C->getType()->getPrimitiveSizeInBits() >
1238 MulC->getType()->getPrimitiveSizeInBits())
1239 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1240
1241 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1242 Multiple = ConstantExpr::getMul(MulC, Op0C);
1243 return true;
1244 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001245
1246 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1247 if (Mul1CI->getValue() == 1) {
1248 // V == Base * Op0, so return Op0
1249 Multiple = Op0;
1250 return true;
1251 }
1252 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001253 }
1254 }
1255
1256 // We could not determine if V is a multiple of Base.
1257 return false;
1258}
1259
Chris Lattner833f25d2008-06-02 01:29:46 +00001260/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1261/// value is never equal to -0.0.
1262///
1263/// NOTE: this function will need to be revisited when we support non-default
1264/// rounding modes!
1265///
1266bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1267 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1268 return !CFP->getValueAPF().isNegZero();
1269
1270 if (Depth == 6)
1271 return 1; // Limit search depth.
1272
Dan Gohmanca178902009-07-17 20:47:02 +00001273 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001274 if (I == 0) return false;
1275
1276 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001277 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001278 isa<ConstantFP>(I->getOperand(1)) &&
1279 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1280 return true;
1281
1282 // sitofp and uitofp turn into +0.0 for zero.
1283 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1284 return true;
1285
1286 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1287 // sqrt(-0.0) = -0.0, no other negative results are possible.
1288 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001289 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001290
1291 if (const CallInst *CI = dyn_cast<CallInst>(I))
1292 if (const Function *F = CI->getCalledFunction()) {
1293 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001294 // abs(x) != -0.0
1295 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001296 // fabs[lf](x) != -0.0
1297 if (F->getName() == "fabs") return true;
1298 if (F->getName() == "fabsf") return true;
1299 if (F->getName() == "fabsl") return true;
1300 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1301 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001302 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001303 }
1304 }
1305
1306 return false;
1307}
1308
Chris Lattnerbb897102010-12-26 20:15:01 +00001309/// isBytewiseValue - If the specified value can be set by repeating the same
1310/// byte in memory, return the i8 value that it is represented with. This is
1311/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1312/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1313/// byte store (e.g. i16 0x1234), return null.
1314Value *llvm::isBytewiseValue(Value *V) {
1315 // All byte-wide stores are splatable, even of arbitrary variables.
1316 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001317
1318 // Handle 'null' ConstantArrayZero etc.
1319 if (Constant *C = dyn_cast<Constant>(V))
1320 if (C->isNullValue())
1321 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001322
1323 // Constant float and double values can be handled as integer values if the
1324 // corresponding integer value is "byteable". An important case is 0.0.
1325 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1326 if (CFP->getType()->isFloatTy())
1327 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1328 if (CFP->getType()->isDoubleTy())
1329 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1330 // Don't handle long double formats, which have strange constraints.
1331 }
1332
1333 // We can handle constant integers that are power of two in size and a
1334 // multiple of 8 bits.
1335 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1336 unsigned Width = CI->getBitWidth();
1337 if (isPowerOf2_32(Width) && Width > 8) {
1338 // We can handle this value if the recursive binary decomposition is the
1339 // same at all levels.
1340 APInt Val = CI->getValue();
1341 APInt Val2;
1342 while (Val.getBitWidth() != 8) {
1343 unsigned NextWidth = Val.getBitWidth()/2;
1344 Val2 = Val.lshr(NextWidth);
1345 Val2 = Val2.trunc(Val.getBitWidth()/2);
1346 Val = Val.trunc(Val.getBitWidth()/2);
1347
1348 // If the top/bottom halves aren't the same, reject it.
1349 if (Val != Val2)
1350 return 0;
1351 }
1352 return ConstantInt::get(V->getContext(), Val);
1353 }
1354 }
1355
1356 // A ConstantArray is splatable if all its members are equal and also
1357 // splatable.
1358 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1359 if (CA->getNumOperands() == 0)
1360 return 0;
1361
1362 Value *Val = isBytewiseValue(CA->getOperand(0));
1363 if (!Val)
1364 return 0;
1365
1366 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1367 if (CA->getOperand(I-1) != CA->getOperand(I))
1368 return 0;
1369
1370 return Val;
1371 }
1372
1373 // Conceptually, we could handle things like:
1374 // %a = zext i8 %X to i16
1375 // %b = shl i16 %a, 8
1376 // %c = or i16 %a, %b
1377 // but until there is an example that actually needs this, it doesn't seem
1378 // worth worrying about.
1379 return 0;
1380}
1381
1382
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001383// This is the recursive version of BuildSubAggregate. It takes a few different
1384// arguments. Idxs is the index within the nested struct From that we are
1385// looking at now (which is of type IndexedType). IdxSkip is the number of
1386// indices from Idxs that should be left out when inserting into the resulting
1387// struct. To is the result struct built so far, new insertvalue instructions
1388// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001389static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001390 SmallVector<unsigned, 10> &Idxs,
1391 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001392 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001393 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001394 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001395 // Save the original To argument so we can modify it
1396 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001397 // General case, the type indexed by Idxs is a struct
1398 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1399 // Process each struct element recursively
1400 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001401 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001402 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001403 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001404 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001405 if (!To) {
1406 // Couldn't find any inserted value for this index? Cleanup
1407 while (PrevTo != OrigTo) {
1408 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1409 PrevTo = Del->getAggregateOperand();
1410 Del->eraseFromParent();
1411 }
1412 // Stop processing elements
1413 break;
1414 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001415 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001416 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001417 if (To)
1418 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001419 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001420 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1421 // the struct's elements had a value that was inserted directly. In the latter
1422 // case, perhaps we can't determine each of the subelements individually, but
1423 // we might be able to find the complete struct somewhere.
1424
1425 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001426 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001427
1428 if (!V)
1429 return NULL;
1430
1431 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001432 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001433 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001434}
1435
1436// This helper takes a nested struct and extracts a part of it (which is again a
1437// struct) into a new value. For example, given the struct:
1438// { a, { b, { c, d }, e } }
1439// and the indices "1, 1" this returns
1440// { c, d }.
1441//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001442// It does this by inserting an insertvalue for each element in the resulting
1443// struct, as opposed to just inserting a single struct. This will only work if
1444// each of the elements of the substruct are known (ie, inserted into From by an
1445// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001446//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001447// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001448static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001449 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001450 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001451 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001452 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001453 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001454 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001455 unsigned IdxSkip = Idxs.size();
1456
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001457 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001458}
1459
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001460/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1461/// the scalar value indexed is already around as a register, for example if it
1462/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001463///
1464/// If InsertBefore is not null, this function will duplicate (modified)
1465/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001466Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1467 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001468 // Nothing to index? Just return V then (this is useful at the end of our
1469 // recursion)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001470 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001471 return V;
1472 // We have indices, so V should have an indexable type
Duncan Sands1df98592010-02-16 11:11:14 +00001473 assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001474 && "Not looking at a struct or array?");
Jay Foadfc6d3a42011-07-13 10:26:04 +00001475 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range)
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001476 && "Invalid indices for type?");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001477 CompositeType *PTy = cast<CompositeType>(V->getType());
Owen Anderson76f600b2009-07-06 22:37:39 +00001478
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001479 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001480 return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001481 idx_range));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001482 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +00001483 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,
Jay Foadfc6d3a42011-07-13 10:26:04 +00001484 idx_range));
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001485 else if (Constant *C = dyn_cast<Constant>(V)) {
1486 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
1487 // Recursively process this constant
Jay Foadfc6d3a42011-07-13 10:26:04 +00001488 return FindInsertedValue(C->getOperand(idx_range[0]), idx_range.slice(1),
1489 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001490 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
1491 // Loop the indices for the insertvalue instruction in parallel with the
1492 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001493 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001494 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1495 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001496 if (req_idx == idx_range.end()) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001497 if (InsertBefore)
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001498 // The requested index identifies a part of a nested aggregate. Handle
1499 // this specially. For example,
1500 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1501 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1502 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1503 // This can be changed into
1504 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1505 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1506 // which allows the unused 0,0 element from the nested struct to be
1507 // removed.
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001508 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001509 InsertBefore);
Matthijs Kooijman97728912008-06-16 13:28:31 +00001510 else
1511 // We can't handle this without inserting insertvalues
1512 return 0;
Duncan Sands9954c762008-06-19 08:47:31 +00001513 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001514
1515 // This insert value inserts something else than what we are looking for.
1516 // See if the (aggregrate) value inserted into has the value we are
1517 // looking for, then.
1518 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001519 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001520 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001521 }
1522 // If we end up here, the indices of the insertvalue match with those
1523 // requested (though possibly only partially). Now we recursively look at
1524 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001525 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001526 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001527 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001528 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
1529 // If we're extracting a value from an aggregrate that was extracted from
1530 // something else, we can extract from that something else directly instead.
1531 // However, we will need to chain I's indices with the requested indices.
1532
1533 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001534 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001535 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001536 SmallVector<unsigned, 5> Idxs;
1537 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001538 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001539 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001540
1541 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001542 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001543
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001544 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001545 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001546
Jay Foadfc6d3a42011-07-13 10:26:04 +00001547 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001548 }
1549 // Otherwise, we don't know (such as, extracting from a function return value
1550 // or load instruction)
1551 return 0;
1552}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001553
Chris Lattnered58a6f2010-11-30 22:25:26 +00001554/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1555/// it can be expressed as a base pointer plus a constant offset. Return the
1556/// base and offset to the caller.
1557Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1558 const TargetData &TD) {
1559 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1560 if (PtrOp == 0) return Ptr;
1561
1562 // Just look through bitcasts.
1563 if (PtrOp->getOpcode() == Instruction::BitCast)
1564 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1565
1566 // If this is a GEP with constant indices, we can look through it.
1567 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1568 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1569
1570 gep_type_iterator GTI = gep_type_begin(GEP);
1571 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1572 ++I, ++GTI) {
1573 ConstantInt *OpC = cast<ConstantInt>(*I);
1574 if (OpC->isZero()) continue;
1575
1576 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001577 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001578 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1579 } else {
1580 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1581 Offset += OpC->getSExtValue()*Size;
1582 }
1583 }
1584
1585 // Re-sign extend from the pointer size if needed to get overflow edge cases
1586 // right.
1587 unsigned PtrSize = TD.getPointerSizeInBits();
1588 if (PtrSize < 64)
1589 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1590
1591 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1592}
1593
1594
Evan Cheng0ff39b32008-06-30 07:31:25 +00001595/// GetConstantStringInfo - This function computes the length of a
1596/// null-terminated C string pointed to by V. If successful, it returns true
1597/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001598bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001599 uint64_t Offset, bool StopAtNul) {
Bill Wendling0582ae92009-03-13 04:39:26 +00001600 // If V is NULL then return false;
1601 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001602
1603 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001604 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001605 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1606
Evan Cheng0ff39b32008-06-30 07:31:25 +00001607 // If the value is not a GEP instruction nor a constant expression with a
1608 // GEP instruction, then return false because ConstantArray can't occur
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001609 // any other way.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001610 const User *GEP = 0;
1611 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001612 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001613 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001614 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001615 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1616 if (CE->getOpcode() != Instruction::GetElementPtr)
1617 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001618 GEP = CE;
1619 }
1620
1621 if (GEP) {
1622 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001623 if (GEP->getNumOperands() != 3)
1624 return false;
1625
Evan Cheng0ff39b32008-06-30 07:31:25 +00001626 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001627 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1628 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001629 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001630 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001631
1632 // Check to make sure that the first operand of the GEP is an integer and
1633 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001634 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001635 if (FirstIdx == 0 || !FirstIdx->isZero())
1636 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001637
1638 // If the second index isn't a ConstantInt, then this is a variable index
1639 // into the array. If this occurs, we can't say anything meaningful about
1640 // the string.
1641 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001642 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001643 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001644 else
1645 return false;
1646 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001647 StopAtNul);
1648 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001649
Evan Cheng0ff39b32008-06-30 07:31:25 +00001650 // The GEP instruction, constant or instruction, must reference a global
1651 // variable that is a constant and is initialized. The referenced constant
1652 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001653 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001654 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001655 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001656 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001657
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001658 // Handle the all-zeros case
1659 if (GlobalInit->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001660 // This is a degenerate case. The initializer is constant zero so the
1661 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001662 Str.clear();
1663 return true;
1664 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001665
1666 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001667 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001668 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001669 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001670
1671 // Get the number of elements in the array
1672 uint64_t NumElts = Array->getType()->getNumElements();
1673
Bill Wendling0582ae92009-03-13 04:39:26 +00001674 if (Offset > NumElts)
1675 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001676
1677 // Traverse the constant array from 'Offset' which is the place the GEP refers
1678 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001679 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001680 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001681 const Constant *Elt = Array->getOperand(i);
1682 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001683 if (!CI) // This array isn't suitable, non-int initializer.
1684 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001685 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001686 return true; // we found end of string, success!
1687 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001688 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001689
Evan Cheng0ff39b32008-06-30 07:31:25 +00001690 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001691 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001692}
Eric Christopher25ec4832010-03-05 06:58:57 +00001693
1694// These next two are very similar to the above, but also look through PHI
1695// nodes.
1696// TODO: See if we can integrate these two together.
1697
1698/// GetStringLengthH - If we can compute the length of the string pointed to by
1699/// the specified pointer, return 'len+1'. If we can't, return 0.
1700static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1701 // Look through noop bitcast instructions.
1702 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1703 return GetStringLengthH(BCI->getOperand(0), PHIs);
1704
1705 // If this is a PHI node, there are two cases: either we have already seen it
1706 // or we haven't.
1707 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1708 if (!PHIs.insert(PN))
1709 return ~0ULL; // already in the set.
1710
1711 // If it was new, see if all the input strings are the same length.
1712 uint64_t LenSoFar = ~0ULL;
1713 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1714 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1715 if (Len == 0) return 0; // Unknown length -> unknown.
1716
1717 if (Len == ~0ULL) continue;
1718
1719 if (Len != LenSoFar && LenSoFar != ~0ULL)
1720 return 0; // Disagree -> unknown.
1721 LenSoFar = Len;
1722 }
1723
1724 // Success, all agree.
1725 return LenSoFar;
1726 }
1727
1728 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1729 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1730 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1731 if (Len1 == 0) return 0;
1732 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1733 if (Len2 == 0) return 0;
1734 if (Len1 == ~0ULL) return Len2;
1735 if (Len2 == ~0ULL) return Len1;
1736 if (Len1 != Len2) return 0;
1737 return Len1;
1738 }
1739
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001740 // As a special-case, "@string = constant i8 0" is also a string with zero
1741 // length, not wrapped in a bitcast or GEP.
1742 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
1743 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1744 if (GV->getInitializer()->isNullValue()) return 1;
1745 return 0;
1746 }
1747
Eric Christopher25ec4832010-03-05 06:58:57 +00001748 // If the value is not a GEP instruction nor a constant expression with a
1749 // GEP instruction, then return unknown.
1750 User *GEP = 0;
1751 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1752 GEP = GEPI;
1753 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1754 if (CE->getOpcode() != Instruction::GetElementPtr)
1755 return 0;
1756 GEP = CE;
1757 } else {
1758 return 0;
1759 }
1760
1761 // Make sure the GEP has exactly three arguments.
1762 if (GEP->getNumOperands() != 3)
1763 return 0;
1764
1765 // Check to make sure that the first operand of the GEP is an integer and
1766 // has value 0 so that we are sure we're indexing into the initializer.
1767 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1768 if (!Idx->isZero())
1769 return 0;
1770 } else
1771 return 0;
1772
1773 // If the second index isn't a ConstantInt, then this is a variable index
1774 // into the array. If this occurs, we can't say anything meaningful about
1775 // the string.
1776 uint64_t StartIdx = 0;
1777 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1778 StartIdx = CI->getZExtValue();
1779 else
1780 return 0;
1781
1782 // The GEP instruction, constant or instruction, must reference a global
1783 // variable that is a constant and is initialized. The referenced constant
1784 // initializer is the array that we'll use for optimization.
1785 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1786 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1787 GV->mayBeOverridden())
1788 return 0;
1789 Constant *GlobalInit = GV->getInitializer();
1790
1791 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1792 // initializer is constant zero so the length of the string must be zero.
1793 if (isa<ConstantAggregateZero>(GlobalInit))
1794 return 1; // Len = 0 offset by 1.
1795
1796 // Must be a Constant Array
1797 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1798 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1799 return false;
1800
1801 // Get the number of elements in the array
1802 uint64_t NumElts = Array->getType()->getNumElements();
1803
1804 // Traverse the constant array from StartIdx (derived above) which is
1805 // the place the GEP refers to in the array.
1806 for (unsigned i = StartIdx; i != NumElts; ++i) {
1807 Constant *Elt = Array->getOperand(i);
1808 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1809 if (!CI) // This array isn't suitable, non-int initializer.
1810 return 0;
1811 if (CI->isZero())
1812 return i-StartIdx+1; // We found end of string, success!
1813 }
1814
1815 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1816}
1817
1818/// GetStringLength - If we can compute the length of the string pointed to by
1819/// the specified pointer, return 'len+1'. If we can't, return 0.
1820uint64_t llvm::GetStringLength(Value *V) {
1821 if (!V->getType()->isPointerTy()) return 0;
1822
1823 SmallPtrSet<PHINode*, 32> PHIs;
1824 uint64_t Len = GetStringLengthH(V, PHIs);
1825 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1826 // an empty string as a length.
1827 return Len == ~0ULL ? 1 : Len;
1828}
Dan Gohman5034dd32010-12-15 20:02:24 +00001829
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001830Value *
1831llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001832 if (!V->getType()->isPointerTy())
1833 return V;
1834 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1835 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1836 V = GEP->getPointerOperand();
1837 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1838 V = cast<Operator>(V)->getOperand(0);
1839 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1840 if (GA->mayBeOverridden())
1841 return V;
1842 V = GA->getAliasee();
1843 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001844 // See if InstructionSimplify knows any relevant tricks.
1845 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001846 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001847 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001848 V = Simplified;
1849 continue;
1850 }
1851
Dan Gohman5034dd32010-12-15 20:02:24 +00001852 return V;
1853 }
1854 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1855 }
1856 return V;
1857}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001858
1859/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1860/// are lifetime markers.
1861///
1862bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1863 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1864 UI != UE; ++UI) {
1865 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1866 if (!II) return false;
1867
1868 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1869 II->getIntrinsicID() != Intrinsic::lifetime_end)
1870 return false;
1871 }
1872 return true;
1873}