blob: 1a18247fddb8148dbcbdba27d751ccf93d82c3b9 [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();
Nadav Rotem16087692011-12-05 06:29:09 +000066 assert((V->getType()->isIntOrIntVectorTy() ||
67 V->getType()->getScalarType()->isPointerTy()) &&
68 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000069 assert((!TD ||
70 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000071 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +000072 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem16087692011-12-05 06:29:09 +000073 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner173234a2008-06-02 01:18:21 +000074 KnownOne.getBitWidth() == BitWidth &&
75 "V, Mask, KnownOne and KnownZero should have same BitWidth");
76
77 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
78 // We know all of the bits for a constant!
79 KnownOne = CI->getValue() & Mask;
80 KnownZero = ~KnownOne & Mask;
81 return;
82 }
Dan Gohman6de29f82009-06-15 22:12:54 +000083 // Null and aggregate-zero are all-zeros.
84 if (isa<ConstantPointerNull>(V) ||
85 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000086 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +000087 KnownZero = Mask;
88 return;
89 }
Dan Gohman6de29f82009-06-15 22:12:54 +000090 // Handle a constant vector by taking the intersection of the known bits of
91 // each element.
Chris Lattner6b0dc922012-01-26 21:37:55 +000092 // FIXME: Remove.
Dan Gohman6de29f82009-06-15 22:12:54 +000093 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000094 KnownZero.setAllBits(); KnownOne.setAllBits();
Dan Gohman6de29f82009-06-15 22:12:54 +000095 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
96 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
97 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
98 TD, Depth);
99 KnownZero &= KnownZero2;
100 KnownOne &= KnownOne2;
101 }
102 return;
103 }
Chris Lattnerdf390282012-01-24 07:54:10 +0000104 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
105 // We know that CDS must be a vector of integers. Take the intersection of
106 // each element.
107 KnownZero.setAllBits(); KnownOne.setAllBits();
108 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner0f193b82012-01-25 01:27:20 +0000109 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerdf390282012-01-24 07:54:10 +0000110 Elt = CDS->getElementAsInteger(i);
111 KnownZero &= ~Elt;
112 KnownOne &= Elt;
113 }
114 return;
115 }
116
Chris Lattner173234a2008-06-02 01:18:21 +0000117 // The address of an aligned GlobalValue has trailing zeros.
118 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
119 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +0000120 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000121 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
122 Type *ObjectType = GVar->getType()->getElementType();
123 // If the object is defined in the current Module, we'll be giving
124 // it the preferred alignment. Otherwise, we have to assume that it
125 // may only have the minimum ABI alignment.
Duncan Sandsd3a38cc2011-11-29 18:26:38 +0000126 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000127 Align = TD->getPreferredAlignment(GVar);
128 else
129 Align = TD->getABITypeAlignment(ObjectType);
130 }
Dan Gohman00407252009-08-11 15:50:03 +0000131 }
Chris Lattner173234a2008-06-02 01:18:21 +0000132 if (Align > 0)
133 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
134 CountTrailingZeros_32(Align));
135 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000136 KnownZero.clearAllBits();
137 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000138 return;
139 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000140 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
141 // the bits of its aliasee.
142 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
143 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000144 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000145 } else {
146 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
147 TD, Depth+1);
148 }
149 return;
150 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000151
152 if (Argument *A = dyn_cast<Argument>(V)) {
153 // Get alignment information off byval arguments if specified in the IR.
154 if (A->hasByValAttr())
155 if (unsigned Align = A->getParamAlignment())
156 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
157 CountTrailingZeros_32(Align));
158 return;
159 }
Chris Lattner173234a2008-06-02 01:18:21 +0000160
Chris Lattnerb3f06732011-05-23 00:03:39 +0000161 // Start out not knowing anything.
162 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000163
Dan Gohman9004c8a2009-05-21 02:28:33 +0000164 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000165 return; // Limit search depth.
166
Dan Gohmanca178902009-07-17 20:47:02 +0000167 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000168 if (!I) return;
169
170 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000171 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000172 default: break;
173 case Instruction::And: {
174 // If either the LHS or the RHS are Zero, the result is zero.
175 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
176 APInt Mask2(Mask & ~KnownZero);
177 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
178 Depth+1);
179 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
180 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
181
182 // Output known-1 bits are only known if set in both the LHS & RHS.
183 KnownOne &= KnownOne2;
184 // Output known-0 are known to be clear if zero in either the LHS | RHS.
185 KnownZero |= KnownZero2;
186 return;
187 }
188 case Instruction::Or: {
189 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
190 APInt Mask2(Mask & ~KnownOne);
191 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
192 Depth+1);
193 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
194 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
195
196 // Output known-0 bits are only known if clear in both the LHS & RHS.
197 KnownZero &= KnownZero2;
198 // Output known-1 are known to be set if set in either the LHS | RHS.
199 KnownOne |= KnownOne2;
200 return;
201 }
202 case Instruction::Xor: {
203 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
204 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
205 Depth+1);
206 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 // Output known-0 bits are known if clear or set in both the LHS & RHS.
210 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
211 // Output known-1 are known to be set if set in only one of the LHS, RHS.
212 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
213 KnownZero = KnownZeroOut;
214 return;
215 }
216 case Instruction::Mul: {
217 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
218 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
219 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
220 Depth+1);
Duncan Sands32a43cc2011-10-27 19:16:21 +0000221 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
222 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
223
224 bool isKnownNegative = false;
225 bool isKnownNonNegative = false;
226 // If the multiplication is known not to overflow, compute the sign bit.
227 if (Mask.isNegative() &&
228 cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) {
229 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
230 if (Op1 == Op2) {
231 // The product of a number with itself is non-negative.
232 isKnownNonNegative = true;
233 } else {
234 bool isKnownNonNegative1 = KnownZero.isNegative();
235 bool isKnownNonNegative2 = KnownZero2.isNegative();
236 bool isKnownNegative1 = KnownOne.isNegative();
237 bool isKnownNegative2 = KnownOne2.isNegative();
238 // The product of two numbers with the same sign is non-negative.
239 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
240 (isKnownNonNegative1 && isKnownNonNegative2);
241 // The product of a negative number and a non-negative number is either
242 // negative or zero.
243 if (!isKnownNonNegative)
244 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
245 isKnownNonZero(Op2, TD, Depth)) ||
246 (isKnownNegative2 && isKnownNonNegative1 &&
247 isKnownNonZero(Op1, TD, Depth));
248 }
249 }
250
Chris Lattner173234a2008-06-02 01:18:21 +0000251 // If low bits are zero in either operand, output low known-0 bits.
252 // Also compute a conserative estimate for high known-0 bits.
253 // More trickiness is possible, but this is sufficient for the
254 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000255 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000256 unsigned TrailZ = KnownZero.countTrailingOnes() +
257 KnownZero2.countTrailingOnes();
258 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
259 KnownZero2.countLeadingOnes(),
260 BitWidth) - BitWidth;
261
262 TrailZ = std::min(TrailZ, BitWidth);
263 LeadZ = std::min(LeadZ, BitWidth);
264 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
265 APInt::getHighBitsSet(BitWidth, LeadZ);
266 KnownZero &= Mask;
Duncan Sands32a43cc2011-10-27 19:16:21 +0000267
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000268 // Only make use of no-wrap flags if we failed to compute the sign bit
269 // directly. This matters if the multiplication always overflows, in
270 // which case we prefer to follow the result of the direct computation,
271 // though as the program is invoking undefined behaviour we can choose
272 // whatever we like here.
273 if (isKnownNonNegative && !KnownOne.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000274 KnownZero.setBit(BitWidth - 1);
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000275 else if (isKnownNegative && !KnownZero.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000276 KnownOne.setBit(BitWidth - 1);
277
Chris Lattner173234a2008-06-02 01:18:21 +0000278 return;
279 }
280 case Instruction::UDiv: {
281 // For the purposes of computing leading zeros we can conservatively
282 // treat a udiv as a logical right shift by the power of 2 known to
283 // be less than the denominator.
284 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
285 ComputeMaskedBits(I->getOperand(0),
286 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
287 unsigned LeadZ = KnownZero2.countLeadingOnes();
288
Jay Foad7a874dd2010-12-01 08:53:58 +0000289 KnownOne2.clearAllBits();
290 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000291 ComputeMaskedBits(I->getOperand(1),
292 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
293 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
294 if (RHSUnknownLeadingOnes != BitWidth)
295 LeadZ = std::min(BitWidth,
296 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
297
298 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
299 return;
300 }
301 case Instruction::Select:
302 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
303 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
304 Depth+1);
305 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
306 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
307
308 // Only known if known in both the LHS and RHS.
309 KnownOne &= KnownOne2;
310 KnownZero &= KnownZero2;
311 return;
312 case Instruction::FPTrunc:
313 case Instruction::FPExt:
314 case Instruction::FPToUI:
315 case Instruction::FPToSI:
316 case Instruction::SIToFP:
317 case Instruction::UIToFP:
318 return; // Can't work with floating point.
319 case Instruction::PtrToInt:
320 case Instruction::IntToPtr:
321 // We can't handle these if we don't know the pointer size.
322 if (!TD) return;
323 // FALL THROUGH and handle them the same as zext/trunc.
324 case Instruction::ZExt:
325 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000326 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000327
328 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000329 // Note that we handle pointer operands here because of inttoptr/ptrtoint
330 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000331 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000332 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
333 else
334 SrcBitWidth = SrcTy->getScalarSizeInBits();
335
Jay Foad40f8f622010-12-07 08:25:19 +0000336 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
337 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
338 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000339 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
340 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000341 KnownZero = KnownZero.zextOrTrunc(BitWidth);
342 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000343 // Any top bits are known to be zero.
344 if (BitWidth > SrcBitWidth)
345 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
346 return;
347 }
348 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000349 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000350 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000351 // TODO: For now, not handling conversions like:
352 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000353 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000354 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
355 Depth+1);
356 return;
357 }
358 break;
359 }
360 case Instruction::SExt: {
361 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000362 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000363
Jay Foad40f8f622010-12-07 08:25:19 +0000364 APInt MaskIn = Mask.trunc(SrcBitWidth);
365 KnownZero = KnownZero.trunc(SrcBitWidth);
366 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000367 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
368 Depth+1);
369 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000370 KnownZero = KnownZero.zext(BitWidth);
371 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000372
373 // If the sign bit of the input is known set or clear, then we know the
374 // top bits of the result.
375 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
376 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
377 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
378 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
379 return;
380 }
381 case Instruction::Shl:
382 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
383 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
384 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
385 APInt Mask2(Mask.lshr(ShiftAmt));
386 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
387 Depth+1);
388 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
389 KnownZero <<= ShiftAmt;
390 KnownOne <<= ShiftAmt;
391 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
392 return;
393 }
394 break;
395 case Instruction::LShr:
396 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
398 // Compute the new bits that are at the top now.
399 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
400
401 // Unsigned shift right.
402 APInt Mask2(Mask.shl(ShiftAmt));
403 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
404 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000405 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000406 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
407 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
408 // high bits known zero.
409 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
410 return;
411 }
412 break;
413 case Instruction::AShr:
414 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
415 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
416 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000417 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000418
419 // Signed shift right.
420 APInt Mask2(Mask.shl(ShiftAmt));
421 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
422 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000423 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000424 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
425 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
426
427 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
428 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
429 KnownZero |= HighBits;
430 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
431 KnownOne |= HighBits;
432 return;
433 }
434 break;
435 case Instruction::Sub: {
436 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
437 // We know that the top bits of C-X are clear if X contains less bits
438 // than C (i.e. no wrap-around can happen). For example, 20-X is
439 // positive if we can prove that X is >= 0 and < 16.
440 if (!CLHS->getValue().isNegative()) {
441 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
442 // NLZ can't be BitWidth with no sign bit
443 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
444 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
445 TD, Depth+1);
446
447 // If all of the MaskV bits are known to be zero, then we know the
448 // output top bits are zero, because we now know that the output is
449 // from [0-C].
450 if ((KnownZero2 & MaskV) == MaskV) {
451 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
452 // Top bits known zero.
453 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
454 }
455 }
456 }
457 }
458 // fall through
459 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000460 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000461 // other operand has in those bit positions will be preserved in the
462 // result. For an add, this works with either operand. For a subtract,
463 // this only works if the known zeros are in the right operand.
464 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
465 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
466 BitWidth - Mask.countLeadingZeros());
467 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000468 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000469 assert((LHSKnownZero & LHSKnownOne) == 0 &&
470 "Bits known to be one AND zero?");
471 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000472
473 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
474 Depth+1);
475 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000476 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000477
Dan Gohman39250432009-05-24 18:02:35 +0000478 // Determine which operand has more trailing zeros, and use that
479 // many bits from the other operand.
480 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000481 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000482 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
483 KnownZero |= KnownZero2 & Mask;
484 KnownOne |= KnownOne2 & Mask;
485 } else {
486 // If the known zeros are in the left operand for a subtract,
487 // fall back to the minimum known zeros in both operands.
488 KnownZero |= APInt::getLowBitsSet(BitWidth,
489 std::min(LHSKnownZeroOut,
490 RHSKnownZeroOut));
491 }
492 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
493 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
494 KnownZero |= LHSKnownZero & Mask;
495 KnownOne |= LHSKnownOne & Mask;
496 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000497
498 // Are we still trying to solve for the sign bit?
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000499 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000500 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
501 if (OBO->hasNoSignedWrap()) {
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000502 if (I->getOpcode() == Instruction::Add) {
503 // Adding two positive numbers can't wrap into negative
504 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
505 KnownZero |= APInt::getSignBit(BitWidth);
506 // and adding two negative numbers can't wrap into positive.
507 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
508 KnownOne |= APInt::getSignBit(BitWidth);
509 } else {
510 // Subtracting a negative number from a positive one can't wrap
511 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
512 KnownZero |= APInt::getSignBit(BitWidth);
513 // neither can subtracting a positive number from a negative one.
514 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
515 KnownOne |= APInt::getSignBit(BitWidth);
516 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000517 }
518 }
519
Chris Lattner173234a2008-06-02 01:18:21 +0000520 return;
521 }
522 case Instruction::SRem:
523 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000524 APInt RA = Rem->getValue().abs();
525 if (RA.isPowerOf2()) {
526 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000527 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
528 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
529 Depth+1);
530
Duncan Sandscfd54182010-01-29 06:18:37 +0000531 // The low bits of the first operand are unchanged by the srem.
532 KnownZero = KnownZero2 & LowBits;
533 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000534
Duncan Sandscfd54182010-01-29 06:18:37 +0000535 // If the first operand is non-negative or has all low bits zero, then
536 // the upper bits are all zero.
537 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
538 KnownZero |= ~LowBits;
539
540 // If the first operand is negative and not all low bits are zero, then
541 // the upper bits are all one.
542 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
543 KnownOne |= ~LowBits;
544
545 KnownZero &= Mask;
546 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000547
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000548 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000549 }
550 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000551
552 // The sign bit is the LHS's sign bit, except when the result of the
553 // remainder is zero.
554 if (Mask.isNegative() && KnownZero.isNonNegative()) {
555 APInt Mask2 = APInt::getSignBit(BitWidth);
556 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
557 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
558 Depth+1);
559 // If it's known zero, our sign bit is also zero.
560 if (LHSKnownZero.isNegative())
561 KnownZero |= LHSKnownZero;
562 }
563
Chris Lattner173234a2008-06-02 01:18:21 +0000564 break;
565 case Instruction::URem: {
566 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
567 APInt RA = Rem->getValue();
568 if (RA.isPowerOf2()) {
569 APInt LowBits = (RA - 1);
570 APInt Mask2 = LowBits & Mask;
571 KnownZero |= ~LowBits & Mask;
572 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
573 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000574 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000575 break;
576 }
577 }
578
579 // Since the result is less than or equal to either operand, any leading
580 // zero bits in either operand must also exist in the result.
581 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
582 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
583 TD, Depth+1);
584 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
585 TD, Depth+1);
586
Chris Lattner79abedb2009-01-20 18:22:57 +0000587 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000588 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000589 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000590 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
591 break;
592 }
593
Victor Hernandeza276c602009-10-17 01:18:07 +0000594 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000595 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000596 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000597 if (Align == 0 && TD)
598 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000599
600 if (Align > 0)
601 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
602 CountTrailingZeros_32(Align));
603 break;
604 }
605 case Instruction::GetElementPtr: {
606 // Analyze all of the subscripts of this getelementptr instruction
607 // to determine if we can prove known low zero bits.
608 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
609 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
610 ComputeMaskedBits(I->getOperand(0), LocalMask,
611 LocalKnownZero, LocalKnownOne, TD, Depth+1);
612 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
613
614 gep_type_iterator GTI = gep_type_begin(I);
615 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
616 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000617 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000618 // Handle struct member offset arithmetic.
619 if (!TD) return;
620 const StructLayout *SL = TD->getStructLayout(STy);
621 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
622 uint64_t Offset = SL->getElementOffset(Idx);
623 TrailZ = std::min(TrailZ,
624 CountTrailingZeros_64(Offset));
625 } else {
626 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000627 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000628 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000629 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000630 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000631 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
632 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
633 ComputeMaskedBits(Index, LocalMask,
634 LocalKnownZero, LocalKnownOne, TD, Depth+1);
635 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000636 unsigned(CountTrailingZeros_64(TypeSize) +
637 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000638 }
639 }
640
641 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
642 break;
643 }
644 case Instruction::PHI: {
645 PHINode *P = cast<PHINode>(I);
646 // Handle the case of a simple two-predecessor recurrence PHI.
647 // There's a lot more that could theoretically be done here, but
648 // this is sufficient to catch some interesting cases.
649 if (P->getNumIncomingValues() == 2) {
650 for (unsigned i = 0; i != 2; ++i) {
651 Value *L = P->getIncomingValue(i);
652 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000653 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000654 if (!LU)
655 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000656 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000657 // Check for operations that have the property that if
658 // both their operands have low zero bits, the result
659 // will have low zero bits.
660 if (Opcode == Instruction::Add ||
661 Opcode == Instruction::Sub ||
662 Opcode == Instruction::And ||
663 Opcode == Instruction::Or ||
664 Opcode == Instruction::Mul) {
665 Value *LL = LU->getOperand(0);
666 Value *LR = LU->getOperand(1);
667 // Find a recurrence.
668 if (LL == I)
669 L = LR;
670 else if (LR == I)
671 L = LL;
672 else
673 break;
674 // Ok, we have a PHI of the form L op= R. Check for low
675 // zero bits.
676 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
677 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
678 Mask2 = APInt::getLowBitsSet(BitWidth,
679 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000680
681 // We need to take the minimum number of known bits
682 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
683 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
684
Chris Lattner173234a2008-06-02 01:18:21 +0000685 KnownZero = Mask &
686 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000687 std::min(KnownZero2.countTrailingOnes(),
688 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000689 break;
690 }
691 }
692 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000693
Nick Lewycky3b739d22011-02-10 23:54:10 +0000694 // Unreachable blocks may have zero-operand PHI nodes.
695 if (P->getNumIncomingValues() == 0)
696 return;
697
Dan Gohman9004c8a2009-05-21 02:28:33 +0000698 // Otherwise take the unions of the known bit sets of the operands,
699 // taking conservative care to avoid excessive recursion.
700 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000701 // Skip if every incoming value references to ourself.
702 if (P->hasConstantValue() == P)
703 break;
704
Dan Gohman9004c8a2009-05-21 02:28:33 +0000705 KnownZero = APInt::getAllOnesValue(BitWidth);
706 KnownOne = APInt::getAllOnesValue(BitWidth);
707 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
708 // Skip direct self references.
709 if (P->getIncomingValue(i) == P) continue;
710
711 KnownZero2 = APInt(BitWidth, 0);
712 KnownOne2 = APInt(BitWidth, 0);
713 // Recurse, but cap the recursion to one level, because we don't
714 // want to waste time spinning around in loops.
715 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
716 KnownZero2, KnownOne2, TD, MaxDepth-1);
717 KnownZero &= KnownZero2;
718 KnownOne &= KnownOne2;
719 // If all bits have been ruled out, there's no need to check
720 // more operands.
721 if (!KnownZero && !KnownOne)
722 break;
723 }
724 }
Chris Lattner173234a2008-06-02 01:18:21 +0000725 break;
726 }
727 case Instruction::Call:
728 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
729 switch (II->getIntrinsicID()) {
730 default: break;
Chris Lattner173234a2008-06-02 01:18:21 +0000731 case Intrinsic::ctlz:
732 case Intrinsic::cttz: {
733 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer009da052011-12-24 17:31:46 +0000734 // If this call is undefined for 0, the result will be less than 2^n.
735 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
736 LowBits -= 1;
737 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
738 break;
739 }
740 case Intrinsic::ctpop: {
741 unsigned LowBits = Log2_32(BitWidth)+1;
Chris Lattner173234a2008-06-02 01:18:21 +0000742 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
743 break;
744 }
Chad Rosier62660312011-05-26 23:13:19 +0000745 case Intrinsic::x86_sse42_crc32_64_8:
746 case Intrinsic::x86_sse42_crc32_64_64:
Evan Chengcb559c12011-05-22 18:25:30 +0000747 KnownZero = APInt::getHighBitsSet(64, 32);
748 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000749 }
750 }
751 break;
752 }
753}
754
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000755/// ComputeSignBit - Determine whether the sign bit is known to be zero or
756/// one. Convenience wrapper around ComputeMaskedBits.
757void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
758 const TargetData *TD, unsigned Depth) {
759 unsigned BitWidth = getBitWidth(V->getType(), TD);
760 if (!BitWidth) {
761 KnownZero = false;
762 KnownOne = false;
763 return;
764 }
765 APInt ZeroBits(BitWidth, 0);
766 APInt OneBits(BitWidth, 0);
767 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
768 Depth);
769 KnownOne = OneBits[BitWidth - 1];
770 KnownZero = ZeroBits[BitWidth - 1];
771}
772
773/// isPowerOfTwo - Return true if the given value is known to have exactly one
774/// bit set when defined. For vectors return true if every element is known to
775/// be a power of two when defined. Supports values with integer or pointer
776/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000777bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
778 unsigned Depth) {
779 if (Constant *C = dyn_cast<Constant>(V)) {
780 if (C->isNullValue())
781 return OrZero;
782 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
783 return CI->getValue().isPowerOf2();
784 // TODO: Handle vector constants.
785 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000786
787 // 1 << X is clearly a power of two if the one is not shifted off the end. If
788 // it is shifted off the end then the result is undefined.
789 if (match(V, m_Shl(m_One(), m_Value())))
790 return true;
791
792 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
793 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000794 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000795 return true;
796
797 // The remaining tests are all recursive, so bail out if we hit the limit.
798 if (Depth++ == MaxDepth)
799 return false;
800
Duncan Sands4604fc72011-10-28 18:30:05 +0000801 Value *X = 0, *Y = 0;
802 // A shift of a power of two is a power of two or zero.
803 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
804 match(V, m_Shr(m_Value(X), m_Value()))))
805 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
806
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000807 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000808 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000809
810 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000811 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
812 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
813
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000814 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
815 // A power of two and'd with anything is a power of two or zero.
816 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
817 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
818 return true;
819 // X & (-X) is always a power of two or zero.
820 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
821 return true;
822 return false;
823 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000824
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000825 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000826 // is a power of two only if the first operand is a power of two and not
827 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000828 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
829 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
830 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000831 }
832
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000833 return false;
834}
835
836/// isKnownNonZero - Return true if the given value is known to be non-zero
837/// when defined. For vectors return true if every element is known to be
838/// non-zero when defined. Supports values with integer or pointer type and
839/// vectors of integers.
840bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
841 if (Constant *C = dyn_cast<Constant>(V)) {
842 if (C->isNullValue())
843 return false;
844 if (isa<ConstantInt>(C))
845 // Must be non-zero due to null test above.
846 return true;
847 // TODO: Handle vectors
848 return false;
849 }
850
851 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000852 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000853 return false;
854
855 unsigned BitWidth = getBitWidth(V->getType(), TD);
856
857 // X | Y != 0 if X != 0 or Y != 0.
858 Value *X = 0, *Y = 0;
859 if (match(V, m_Or(m_Value(X), m_Value(Y))))
860 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
861
862 // ext X != 0 if X != 0.
863 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
864 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
865
Duncan Sands91367822011-01-29 13:27:00 +0000866 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000867 // if the lowest bit is shifted off the end.
868 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000869 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000870 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000871 if (BO->hasNoUnsignedWrap())
872 return isKnownNonZero(X, TD, Depth);
873
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000874 APInt KnownZero(BitWidth, 0);
875 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000876 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000877 if (KnownOne[0])
878 return true;
879 }
Duncan Sands91367822011-01-29 13:27:00 +0000880 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000881 // defined if the sign bit is shifted off the end.
882 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000883 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000884 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000885 if (BO->isExact())
886 return isKnownNonZero(X, TD, Depth);
887
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000888 bool XKnownNonNegative, XKnownNegative;
889 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
890 if (XKnownNegative)
891 return true;
892 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000893 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000894 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
895 return isKnownNonZero(X, TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000896 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000897 // X + Y.
898 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
899 bool XKnownNonNegative, XKnownNegative;
900 bool YKnownNonNegative, YKnownNegative;
901 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
902 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
903
904 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000905 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000906 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000907 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
908 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000909
910 // If X and Y are both negative (as signed values) then their sum is not
911 // zero unless both X and Y equal INT_MIN.
912 if (BitWidth && XKnownNegative && YKnownNegative) {
913 APInt KnownZero(BitWidth, 0);
914 APInt KnownOne(BitWidth, 0);
915 APInt Mask = APInt::getSignedMaxValue(BitWidth);
916 // The sign bit of X is set. If some other bit is set then X is not equal
917 // to INT_MIN.
918 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
919 if ((KnownOne & Mask) != 0)
920 return true;
921 // The sign bit of Y is set. If some other bit is set then Y is not equal
922 // to INT_MIN.
923 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
924 if ((KnownOne & Mask) != 0)
925 return true;
926 }
927
928 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000929 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000930 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000931 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000932 return true;
933 }
Duncan Sands32a43cc2011-10-27 19:16:21 +0000934 // X * Y.
935 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
936 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
937 // If X and Y are non-zero then so is X * Y as long as the multiplication
938 // does not overflow.
939 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
940 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
941 return true;
942 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000943 // (C ? X : Y) != 0 if X != 0 and Y != 0.
944 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
945 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
946 isKnownNonZero(SI->getFalseValue(), TD, Depth))
947 return true;
948 }
949
950 if (!BitWidth) return false;
951 APInt KnownZero(BitWidth, 0);
952 APInt KnownOne(BitWidth, 0);
953 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
954 TD, Depth);
955 return KnownOne != 0;
956}
957
Chris Lattner173234a2008-06-02 01:18:21 +0000958/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
959/// this predicate to simplify operations downstream. Mask is known to be zero
960/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000961///
962/// This function is defined on values with integer type, values with pointer
963/// type (but only if TD is non-null), and vectors of integers. In the case
964/// where V is a vector, the mask, known zero, and known one values are the
965/// same width as the vector element, and the bit is set only if it is true
966/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000967bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000968 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000969 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
970 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
971 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
972 return (KnownZero & Mask) == Mask;
973}
974
975
976
977/// ComputeNumSignBits - Return the number of times the sign bit of the
978/// register is replicated into the other bits. We know that at least 1 bit
979/// is always equal to the sign bit (itself), but other cases can give us
980/// information. For example, immediately after an "ashr X, 2", we know that
981/// the top 3 bits are all equal to each other, so we return 3.
982///
983/// 'Op' must have a scalar integer type.
984///
Dan Gohman846a2f22009-08-27 17:51:25 +0000985unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
986 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000987 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000988 "ComputeNumSignBits requires a TargetData object to operate "
989 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000990 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000991 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
992 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000993 unsigned Tmp, Tmp2;
994 unsigned FirstAnswer = 1;
995
Chris Lattnerd82e5112008-06-02 18:39:07 +0000996 // Note that ConstantInt is handled by the general ComputeMaskedBits case
997 // below.
998
Chris Lattner173234a2008-06-02 01:18:21 +0000999 if (Depth == 6)
1000 return 1; // Limit search depth.
1001
Dan Gohmanca178902009-07-17 20:47:02 +00001002 Operator *U = dyn_cast<Operator>(V);
1003 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +00001004 default: break;
1005 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +00001006 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001007 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1008
Chris Lattner6b0dc922012-01-26 21:37:55 +00001009 case Instruction::AShr: {
Chris Lattner173234a2008-06-02 01:18:21 +00001010 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001011 // ashr X, C -> adds C sign bits. Vectors too.
1012 const APInt *ShAmt;
1013 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1014 Tmp += ShAmt->getZExtValue();
Chris Lattner173234a2008-06-02 01:18:21 +00001015 if (Tmp > TyBits) Tmp = TyBits;
1016 }
1017 return Tmp;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001018 }
1019 case Instruction::Shl: {
1020 const APInt *ShAmt;
1021 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner173234a2008-06-02 01:18:21 +00001022 // shl destroys sign bits.
1023 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001024 Tmp2 = ShAmt->getZExtValue();
1025 if (Tmp2 >= TyBits || // Bad shift.
1026 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1027 return Tmp - Tmp2;
Chris Lattner173234a2008-06-02 01:18:21 +00001028 }
1029 break;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001030 }
Chris Lattner173234a2008-06-02 01:18:21 +00001031 case Instruction::And:
1032 case Instruction::Or:
1033 case Instruction::Xor: // NOT is handled here.
1034 // Logical binary ops preserve the number of sign bits at the worst.
1035 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1036 if (Tmp != 1) {
1037 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1038 FirstAnswer = std::min(Tmp, Tmp2);
1039 // We computed what we know about the sign bits as our first
1040 // answer. Now proceed to the generic code that uses
1041 // ComputeMaskedBits, and pick whichever answer is better.
1042 }
1043 break;
1044
1045 case Instruction::Select:
1046 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1047 if (Tmp == 1) return 1; // Early out.
1048 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1049 return std::min(Tmp, Tmp2);
1050
1051 case Instruction::Add:
1052 // Add can have at most one carry bit. Thus we know that the output
1053 // is, at worst, one more bit than the inputs.
1054 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1055 if (Tmp == 1) return 1; // Early out.
1056
1057 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001058 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001059 if (CRHS->isAllOnesValue()) {
1060 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1061 APInt Mask = APInt::getAllOnesValue(TyBits);
1062 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1063 Depth+1);
1064
1065 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1066 // sign bits set.
1067 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1068 return TyBits;
1069
1070 // If we are subtracting one from a positive number, there is no carry
1071 // out of the result.
1072 if (KnownZero.isNegative())
1073 return Tmp;
1074 }
1075
1076 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1077 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001078 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001079
1080 case Instruction::Sub:
1081 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1082 if (Tmp2 == 1) return 1;
1083
1084 // Handle NEG.
1085 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1086 if (CLHS->isNullValue()) {
1087 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1088 APInt Mask = APInt::getAllOnesValue(TyBits);
1089 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1090 TD, Depth+1);
1091 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1092 // sign bits set.
1093 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1094 return TyBits;
1095
1096 // If the input is known to be positive (the sign bit is known clear),
1097 // the output of the NEG has the same number of sign bits as the input.
1098 if (KnownZero.isNegative())
1099 return Tmp2;
1100
1101 // Otherwise, we treat this like a SUB.
1102 }
1103
1104 // Sub can have at most one carry bit. Thus we know that the output
1105 // is, at worst, one more bit than the inputs.
1106 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1107 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001108 return std::min(Tmp, Tmp2)-1;
1109
1110 case Instruction::PHI: {
1111 PHINode *PN = cast<PHINode>(U);
1112 // Don't analyze large in-degree PHIs.
1113 if (PN->getNumIncomingValues() > 4) break;
1114
1115 // Take the minimum of all incoming values. This can't infinitely loop
1116 // because of our depth threshold.
1117 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1118 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1119 if (Tmp == 1) return Tmp;
1120 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001121 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001122 }
1123 return Tmp;
1124 }
1125
Chris Lattner173234a2008-06-02 01:18:21 +00001126 case Instruction::Trunc:
1127 // FIXME: it's tricky to do anything useful for this, but it is an important
1128 // case for targets like X86.
1129 break;
1130 }
1131
1132 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1133 // use this information.
1134 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1135 APInt Mask = APInt::getAllOnesValue(TyBits);
1136 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1137
1138 if (KnownZero.isNegative()) { // sign bit is 0
1139 Mask = KnownZero;
1140 } else if (KnownOne.isNegative()) { // sign bit is 1;
1141 Mask = KnownOne;
1142 } else {
1143 // Nothing known.
1144 return FirstAnswer;
1145 }
1146
1147 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1148 // the number of identical bits in the top of the input value.
1149 Mask = ~Mask;
1150 Mask <<= Mask.getBitWidth()-TyBits;
1151 // Return # leading zeros. We use 'min' here in case Val was zero before
1152 // shifting. We don't want to return '64' as for an i32 "0".
1153 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1154}
Chris Lattner833f25d2008-06-02 01:29:46 +00001155
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001156/// ComputeMultiple - This function computes the integer multiple of Base that
1157/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001158/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001159/// through SExt instructions only if LookThroughSExt is true.
1160bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001161 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001162 const unsigned MaxDepth = 6;
1163
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001164 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001165 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001166 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001167
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001168 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001169
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001170 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001171
1172 if (Base == 0)
1173 return false;
1174
1175 if (Base == 1) {
1176 Multiple = V;
1177 return true;
1178 }
1179
1180 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1181 Constant *BaseVal = ConstantInt::get(T, Base);
1182 if (CO && CO == BaseVal) {
1183 // Multiple is 1.
1184 Multiple = ConstantInt::get(T, 1);
1185 return true;
1186 }
1187
1188 if (CI && CI->getZExtValue() % Base == 0) {
1189 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1190 return true;
1191 }
1192
1193 if (Depth == MaxDepth) return false; // Limit search depth.
1194
1195 Operator *I = dyn_cast<Operator>(V);
1196 if (!I) return false;
1197
1198 switch (I->getOpcode()) {
1199 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001200 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001201 if (!LookThroughSExt) return false;
1202 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001203 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001204 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1205 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001206 case Instruction::Shl:
1207 case Instruction::Mul: {
1208 Value *Op0 = I->getOperand(0);
1209 Value *Op1 = I->getOperand(1);
1210
1211 if (I->getOpcode() == Instruction::Shl) {
1212 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1213 if (!Op1CI) return false;
1214 // Turn Op0 << Op1 into Op0 * 2^Op1
1215 APInt Op1Int = Op1CI->getValue();
1216 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001217 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001218 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001219 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001220 }
1221
1222 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001223 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1224 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1225 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1226 if (Op1C->getType()->getPrimitiveSizeInBits() <
1227 MulC->getType()->getPrimitiveSizeInBits())
1228 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1229 if (Op1C->getType()->getPrimitiveSizeInBits() >
1230 MulC->getType()->getPrimitiveSizeInBits())
1231 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1232
1233 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1234 Multiple = ConstantExpr::getMul(MulC, Op1C);
1235 return true;
1236 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001237
1238 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1239 if (Mul0CI->getValue() == 1) {
1240 // V == Base * Op1, so return Op1
1241 Multiple = Op1;
1242 return true;
1243 }
1244 }
1245
Chris Lattnere9711312010-09-05 17:20:46 +00001246 Value *Mul1 = NULL;
1247 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1248 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1249 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1250 if (Op0C->getType()->getPrimitiveSizeInBits() <
1251 MulC->getType()->getPrimitiveSizeInBits())
1252 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1253 if (Op0C->getType()->getPrimitiveSizeInBits() >
1254 MulC->getType()->getPrimitiveSizeInBits())
1255 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1256
1257 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1258 Multiple = ConstantExpr::getMul(MulC, Op0C);
1259 return true;
1260 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001261
1262 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1263 if (Mul1CI->getValue() == 1) {
1264 // V == Base * Op0, so return Op0
1265 Multiple = Op0;
1266 return true;
1267 }
1268 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001269 }
1270 }
1271
1272 // We could not determine if V is a multiple of Base.
1273 return false;
1274}
1275
Chris Lattner833f25d2008-06-02 01:29:46 +00001276/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1277/// value is never equal to -0.0.
1278///
1279/// NOTE: this function will need to be revisited when we support non-default
1280/// rounding modes!
1281///
1282bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1283 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1284 return !CFP->getValueAPF().isNegZero();
1285
1286 if (Depth == 6)
1287 return 1; // Limit search depth.
1288
Dan Gohmanca178902009-07-17 20:47:02 +00001289 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001290 if (I == 0) return false;
1291
1292 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001293 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001294 isa<ConstantFP>(I->getOperand(1)) &&
1295 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1296 return true;
1297
1298 // sitofp and uitofp turn into +0.0 for zero.
1299 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1300 return true;
1301
1302 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1303 // sqrt(-0.0) = -0.0, no other negative results are possible.
1304 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001305 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001306
1307 if (const CallInst *CI = dyn_cast<CallInst>(I))
1308 if (const Function *F = CI->getCalledFunction()) {
1309 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001310 // abs(x) != -0.0
1311 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001312 // fabs[lf](x) != -0.0
1313 if (F->getName() == "fabs") return true;
1314 if (F->getName() == "fabsf") return true;
1315 if (F->getName() == "fabsl") return true;
1316 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1317 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001318 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001319 }
1320 }
1321
1322 return false;
1323}
1324
Chris Lattnerbb897102010-12-26 20:15:01 +00001325/// isBytewiseValue - If the specified value can be set by repeating the same
1326/// byte in memory, return the i8 value that it is represented with. This is
1327/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1328/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1329/// byte store (e.g. i16 0x1234), return null.
1330Value *llvm::isBytewiseValue(Value *V) {
1331 // All byte-wide stores are splatable, even of arbitrary variables.
1332 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001333
1334 // Handle 'null' ConstantArrayZero etc.
1335 if (Constant *C = dyn_cast<Constant>(V))
1336 if (C->isNullValue())
1337 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001338
1339 // Constant float and double values can be handled as integer values if the
1340 // corresponding integer value is "byteable". An important case is 0.0.
1341 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1342 if (CFP->getType()->isFloatTy())
1343 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1344 if (CFP->getType()->isDoubleTy())
1345 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1346 // Don't handle long double formats, which have strange constraints.
1347 }
1348
1349 // We can handle constant integers that are power of two in size and a
1350 // multiple of 8 bits.
1351 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1352 unsigned Width = CI->getBitWidth();
1353 if (isPowerOf2_32(Width) && Width > 8) {
1354 // We can handle this value if the recursive binary decomposition is the
1355 // same at all levels.
1356 APInt Val = CI->getValue();
1357 APInt Val2;
1358 while (Val.getBitWidth() != 8) {
1359 unsigned NextWidth = Val.getBitWidth()/2;
1360 Val2 = Val.lshr(NextWidth);
1361 Val2 = Val2.trunc(Val.getBitWidth()/2);
1362 Val = Val.trunc(Val.getBitWidth()/2);
1363
1364 // If the top/bottom halves aren't the same, reject it.
1365 if (Val != Val2)
1366 return 0;
1367 }
1368 return ConstantInt::get(V->getContext(), Val);
1369 }
1370 }
1371
Chris Lattner18c7f802012-02-05 02:29:43 +00001372 // A ConstantDataArray/Vector is splatable if all its members are equal and
1373 // also splatable.
1374 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1375 Value *Elt = CA->getElementAsConstant(0);
1376 Value *Val = isBytewiseValue(Elt);
Chris Lattnerbb897102010-12-26 20:15:01 +00001377 if (!Val)
1378 return 0;
1379
Chris Lattner18c7f802012-02-05 02:29:43 +00001380 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1381 if (CA->getElementAsConstant(I) != Elt)
Chris Lattnerbb897102010-12-26 20:15:01 +00001382 return 0;
1383
1384 return Val;
1385 }
Chad Rosierdce42b72011-12-06 00:19:08 +00001386
Chris Lattnerbb897102010-12-26 20:15:01 +00001387 // Conceptually, we could handle things like:
1388 // %a = zext i8 %X to i16
1389 // %b = shl i16 %a, 8
1390 // %c = or i16 %a, %b
1391 // but until there is an example that actually needs this, it doesn't seem
1392 // worth worrying about.
1393 return 0;
1394}
1395
1396
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001397// This is the recursive version of BuildSubAggregate. It takes a few different
1398// arguments. Idxs is the index within the nested struct From that we are
1399// looking at now (which is of type IndexedType). IdxSkip is the number of
1400// indices from Idxs that should be left out when inserting into the resulting
1401// struct. To is the result struct built so far, new insertvalue instructions
1402// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001403static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001404 SmallVector<unsigned, 10> &Idxs,
1405 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001406 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001407 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001408 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001409 // Save the original To argument so we can modify it
1410 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001411 // General case, the type indexed by Idxs is a struct
1412 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1413 // Process each struct element recursively
1414 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001415 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001416 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001417 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001418 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001419 if (!To) {
1420 // Couldn't find any inserted value for this index? Cleanup
1421 while (PrevTo != OrigTo) {
1422 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1423 PrevTo = Del->getAggregateOperand();
1424 Del->eraseFromParent();
1425 }
1426 // Stop processing elements
1427 break;
1428 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001429 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001430 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001431 if (To)
1432 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001433 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001434 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1435 // the struct's elements had a value that was inserted directly. In the latter
1436 // case, perhaps we can't determine each of the subelements individually, but
1437 // we might be able to find the complete struct somewhere.
1438
1439 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001440 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001441
1442 if (!V)
1443 return NULL;
1444
1445 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001446 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001447 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001448}
1449
1450// This helper takes a nested struct and extracts a part of it (which is again a
1451// struct) into a new value. For example, given the struct:
1452// { a, { b, { c, d }, e } }
1453// and the indices "1, 1" this returns
1454// { c, d }.
1455//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001456// It does this by inserting an insertvalue for each element in the resulting
1457// struct, as opposed to just inserting a single struct. This will only work if
1458// each of the elements of the substruct are known (ie, inserted into From by an
1459// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001460//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001461// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001462static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001463 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001464 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001465 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001466 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001467 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001468 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001469 unsigned IdxSkip = Idxs.size();
1470
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001471 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001472}
1473
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001474/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1475/// the scalar value indexed is already around as a register, for example if it
1476/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001477///
1478/// If InsertBefore is not null, this function will duplicate (modified)
1479/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001480Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1481 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001482 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerdf390282012-01-24 07:54:10 +00001483 // recursion).
Jay Foadfc6d3a42011-07-13 10:26:04 +00001484 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001485 return V;
Chris Lattnerdf390282012-01-24 07:54:10 +00001486 // We have indices, so V should have an indexable type.
1487 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1488 "Not looking at a struct or array?");
1489 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1490 "Invalid indices for type?");
Owen Anderson76f600b2009-07-06 22:37:39 +00001491
Chris Lattnera1f00f42012-01-25 06:48:06 +00001492 if (Constant *C = dyn_cast<Constant>(V)) {
1493 C = C->getAggregateElement(idx_range[0]);
1494 if (C == 0) return 0;
1495 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1496 }
Chris Lattnerdf390282012-01-24 07:54:10 +00001497
1498 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001499 // Loop the indices for the insertvalue instruction in parallel with the
1500 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001501 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001502 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1503 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001504 if (req_idx == idx_range.end()) {
Chris Lattnerdf390282012-01-24 07:54:10 +00001505 // We can't handle this without inserting insertvalues
1506 if (!InsertBefore)
Matthijs Kooijman97728912008-06-16 13:28:31 +00001507 return 0;
Chris Lattnerdf390282012-01-24 07:54:10 +00001508
1509 // The requested index identifies a part of a nested aggregate. Handle
1510 // this specially. For example,
1511 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1512 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1513 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1514 // This can be changed into
1515 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1516 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1517 // which allows the unused 0,0 element from the nested struct to be
1518 // removed.
1519 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1520 InsertBefore);
Duncan Sands9954c762008-06-19 08:47:31 +00001521 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001522
1523 // This insert value inserts something else than what we are looking for.
1524 // See if the (aggregrate) value inserted into has the value we are
1525 // looking for, then.
1526 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001527 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001528 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001529 }
1530 // If we end up here, the indices of the insertvalue match with those
1531 // requested (though possibly only partially). Now we recursively look at
1532 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001533 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001534 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001535 InsertBefore);
Chris Lattnerdf390282012-01-24 07:54:10 +00001536 }
1537
1538 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001539 // If we're extracting a value from an aggregrate that was extracted from
1540 // something else, we can extract from that something else directly instead.
1541 // However, we will need to chain I's indices with the requested indices.
1542
1543 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001544 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001545 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001546 SmallVector<unsigned, 5> Idxs;
1547 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001548 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001549 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001550
1551 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001552 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001553
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001554 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001555 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001556
Jay Foadfc6d3a42011-07-13 10:26:04 +00001557 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001558 }
1559 // Otherwise, we don't know (such as, extracting from a function return value
1560 // or load instruction)
1561 return 0;
1562}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001563
Chris Lattnered58a6f2010-11-30 22:25:26 +00001564/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1565/// it can be expressed as a base pointer plus a constant offset. Return the
1566/// base and offset to the caller.
1567Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1568 const TargetData &TD) {
1569 Operator *PtrOp = dyn_cast<Operator>(Ptr);
Nadav Rotem16087692011-12-05 06:29:09 +00001570 if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1571 return Ptr;
Chris Lattnered58a6f2010-11-30 22:25:26 +00001572
1573 // Just look through bitcasts.
1574 if (PtrOp->getOpcode() == Instruction::BitCast)
1575 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1576
1577 // If this is a GEP with constant indices, we can look through it.
1578 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1579 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1580
1581 gep_type_iterator GTI = gep_type_begin(GEP);
1582 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1583 ++I, ++GTI) {
1584 ConstantInt *OpC = cast<ConstantInt>(*I);
1585 if (OpC->isZero()) continue;
1586
1587 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001588 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001589 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1590 } else {
1591 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1592 Offset += OpC->getSExtValue()*Size;
1593 }
1594 }
1595
1596 // Re-sign extend from the pointer size if needed to get overflow edge cases
1597 // right.
1598 unsigned PtrSize = TD.getPointerSizeInBits();
1599 if (PtrSize < 64)
1600 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1601
1602 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1603}
1604
1605
Chris Lattner18c7f802012-02-05 02:29:43 +00001606/// getConstantStringInfo - This function computes the length of a
Evan Cheng0ff39b32008-06-30 07:31:25 +00001607/// null-terminated C string pointed to by V. If successful, it returns true
1608/// and returns the string in Str. If unsuccessful, it returns false.
Chris Lattner18c7f802012-02-05 02:29:43 +00001609bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1610 uint64_t Offset, bool TrimAtNul) {
1611 assert(V);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001612
Chris Lattner18c7f802012-02-05 02:29:43 +00001613 // Look through bitcast instructions and geps.
1614 V = V->stripPointerCasts();
Bill Wendling0582ae92009-03-13 04:39:26 +00001615
Chris Lattner18c7f802012-02-05 02:29:43 +00001616 // If the value is a GEP instructionor constant expression, treat it as an
1617 // offset.
1618 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001619 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001620 if (GEP->getNumOperands() != 3)
1621 return false;
1622
Evan Cheng0ff39b32008-06-30 07:31:25 +00001623 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001624 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1625 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001626 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001627 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001628
1629 // Check to make sure that the first operand of the GEP is an integer and
1630 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001631 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001632 if (FirstIdx == 0 || !FirstIdx->isZero())
1633 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001634
1635 // If the second index isn't a ConstantInt, then this is a variable index
1636 // into the array. If this occurs, we can't say anything meaningful about
1637 // the string.
1638 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001639 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001640 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001641 else
1642 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001643 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001644 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001645
Evan Cheng0ff39b32008-06-30 07:31:25 +00001646 // The GEP instruction, constant or instruction, must reference a global
1647 // variable that is a constant and is initialized. The referenced constant
1648 // initializer is the array that we'll use for optimization.
Chris Lattner18c7f802012-02-05 02:29:43 +00001649 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001650 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001651 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001652
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001653 // Handle the all-zeros case
Chris Lattner18c7f802012-02-05 02:29:43 +00001654 if (GV->getInitializer()->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001655 // This is a degenerate case. The initializer is constant zero so the
1656 // length of the string must be zero.
Chris Lattner18c7f802012-02-05 02:29:43 +00001657 Str = "";
Bill Wendling0582ae92009-03-13 04:39:26 +00001658 return true;
1659 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001660
1661 // Must be a Constant Array
Chris Lattner18c7f802012-02-05 02:29:43 +00001662 const ConstantDataArray *Array =
1663 dyn_cast<ConstantDataArray>(GV->getInitializer());
1664 if (Array == 0 || !Array->isString())
Bill Wendling0582ae92009-03-13 04:39:26 +00001665 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001666
1667 // Get the number of elements in the array
Chris Lattner18c7f802012-02-05 02:29:43 +00001668 uint64_t NumElts = Array->getType()->getArrayNumElements();
1669
1670 // Start out with the entire array in the StringRef.
1671 Str = Array->getAsString();
1672
Bill Wendling0582ae92009-03-13 04:39:26 +00001673 if (Offset > NumElts)
1674 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001675
Chris Lattner18c7f802012-02-05 02:29:43 +00001676 // Skip over 'offset' bytes.
1677 Str = Str.substr(Offset);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001678
Chris Lattner18c7f802012-02-05 02:29:43 +00001679 if (TrimAtNul) {
1680 // Trim off the \0 and anything after it. If the array is not nul
1681 // terminated, we just return the whole end of string. The client may know
1682 // some other way that the string is length-bound.
1683 Str = Str.substr(0, Str.find('\0'));
1684 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001685 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001686}
Eric Christopher25ec4832010-03-05 06:58:57 +00001687
1688// These next two are very similar to the above, but also look through PHI
1689// nodes.
1690// TODO: See if we can integrate these two together.
1691
1692/// GetStringLengthH - If we can compute the length of the string pointed to by
1693/// the specified pointer, return 'len+1'. If we can't, return 0.
1694static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1695 // Look through noop bitcast instructions.
Chris Lattner18c7f802012-02-05 02:29:43 +00001696 V = V->stripPointerCasts();
Eric Christopher25ec4832010-03-05 06:58:57 +00001697
1698 // If this is a PHI node, there are two cases: either we have already seen it
1699 // or we haven't.
1700 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1701 if (!PHIs.insert(PN))
1702 return ~0ULL; // already in the set.
1703
1704 // If it was new, see if all the input strings are the same length.
1705 uint64_t LenSoFar = ~0ULL;
1706 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1707 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1708 if (Len == 0) return 0; // Unknown length -> unknown.
1709
1710 if (Len == ~0ULL) continue;
1711
1712 if (Len != LenSoFar && LenSoFar != ~0ULL)
1713 return 0; // Disagree -> unknown.
1714 LenSoFar = Len;
1715 }
1716
1717 // Success, all agree.
1718 return LenSoFar;
1719 }
1720
1721 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1722 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1723 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1724 if (Len1 == 0) return 0;
1725 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1726 if (Len2 == 0) return 0;
1727 if (Len1 == ~0ULL) return Len2;
1728 if (Len2 == ~0ULL) return Len1;
1729 if (Len1 != Len2) return 0;
1730 return Len1;
1731 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001732
1733 // Otherwise, see if we can read the string.
1734 StringRef StrData;
1735 if (!getConstantStringInfo(V, StrData))
Eric Christopher25ec4832010-03-05 06:58:57 +00001736 return 0;
1737
Chris Lattner18c7f802012-02-05 02:29:43 +00001738 return StrData.size()+1;
Eric Christopher25ec4832010-03-05 06:58:57 +00001739}
1740
1741/// GetStringLength - If we can compute the length of the string pointed to by
1742/// the specified pointer, return 'len+1'. If we can't, return 0.
1743uint64_t llvm::GetStringLength(Value *V) {
1744 if (!V->getType()->isPointerTy()) return 0;
1745
1746 SmallPtrSet<PHINode*, 32> PHIs;
1747 uint64_t Len = GetStringLengthH(V, PHIs);
1748 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1749 // an empty string as a length.
1750 return Len == ~0ULL ? 1 : Len;
1751}
Dan Gohman5034dd32010-12-15 20:02:24 +00001752
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001753Value *
1754llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001755 if (!V->getType()->isPointerTy())
1756 return V;
1757 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1758 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1759 V = GEP->getPointerOperand();
1760 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1761 V = cast<Operator>(V)->getOperand(0);
1762 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1763 if (GA->mayBeOverridden())
1764 return V;
1765 V = GA->getAliasee();
1766 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001767 // See if InstructionSimplify knows any relevant tricks.
1768 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001769 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001770 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001771 V = Simplified;
1772 continue;
1773 }
1774
Dan Gohman5034dd32010-12-15 20:02:24 +00001775 return V;
1776 }
1777 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1778 }
1779 return V;
1780}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001781
1782/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1783/// are lifetime markers.
1784///
1785bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1786 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1787 UI != UE; ++UI) {
1788 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1789 if (!II) return false;
1790
1791 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1792 II->getIntrinsicID() != Intrinsic::lifetime_end)
1793 return false;
1794 }
1795 return true;
1796}
Dan Gohmanf0426602011-12-14 23:49:11 +00001797
Dan Gohmanfebaf842012-01-04 23:01:09 +00001798bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Dan Gohmanf0426602011-12-14 23:49:11 +00001799 const TargetData *TD) {
Dan Gohmanfebaf842012-01-04 23:01:09 +00001800 const Operator *Inst = dyn_cast<Operator>(V);
1801 if (!Inst)
1802 return false;
1803
Dan Gohmanf0426602011-12-14 23:49:11 +00001804 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1805 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1806 if (C->canTrap())
1807 return false;
1808
1809 switch (Inst->getOpcode()) {
1810 default:
1811 return true;
1812 case Instruction::UDiv:
1813 case Instruction::URem:
1814 // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1815 return isKnownNonZero(Inst->getOperand(1), TD);
1816 case Instruction::SDiv:
1817 case Instruction::SRem: {
1818 Value *Op = Inst->getOperand(1);
1819 // x / y is undefined if y == 0
1820 if (!isKnownNonZero(Op, TD))
1821 return false;
1822 // x / y might be undefined if y == -1
1823 unsigned BitWidth = getBitWidth(Op->getType(), TD);
1824 if (BitWidth == 0)
1825 return false;
1826 APInt KnownZero(BitWidth, 0);
1827 APInt KnownOne(BitWidth, 0);
1828 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1829 KnownZero, KnownOne, TD);
1830 return !!KnownZero;
1831 }
1832 case Instruction::Load: {
1833 const LoadInst *LI = cast<LoadInst>(Inst);
1834 if (!LI->isUnordered())
1835 return false;
1836 return LI->getPointerOperand()->isDereferenceablePointer();
1837 }
Nick Lewycky83696872011-12-21 05:52:02 +00001838 case Instruction::Call: {
1839 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1840 switch (II->getIntrinsicID()) {
1841 case Intrinsic::bswap:
1842 case Intrinsic::ctlz:
1843 case Intrinsic::ctpop:
1844 case Intrinsic::cttz:
1845 case Intrinsic::objectsize:
1846 case Intrinsic::sadd_with_overflow:
1847 case Intrinsic::smul_with_overflow:
1848 case Intrinsic::ssub_with_overflow:
1849 case Intrinsic::uadd_with_overflow:
1850 case Intrinsic::umul_with_overflow:
1851 case Intrinsic::usub_with_overflow:
1852 return true;
1853 // TODO: some fp intrinsics are marked as having the same error handling
1854 // as libm. They're safe to speculate when they won't error.
1855 // TODO: are convert_{from,to}_fp16 safe?
1856 // TODO: can we list target-specific intrinsics here?
1857 default: break;
1858 }
1859 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001860 return false; // The called function could have undefined behavior or
Nick Lewycky83696872011-12-21 05:52:02 +00001861 // side-effects, even if marked readnone nounwind.
1862 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001863 case Instruction::VAArg:
1864 case Instruction::Alloca:
1865 case Instruction::Invoke:
1866 case Instruction::PHI:
1867 case Instruction::Store:
1868 case Instruction::Ret:
1869 case Instruction::Br:
1870 case Instruction::IndirectBr:
1871 case Instruction::Switch:
Dan Gohmanf0426602011-12-14 23:49:11 +00001872 case Instruction::Unreachable:
1873 case Instruction::Fence:
1874 case Instruction::LandingPad:
1875 case Instruction::AtomicRMW:
1876 case Instruction::AtomicCmpXchg:
1877 case Instruction::Resume:
1878 return false; // Misc instructions which have effects
1879 }
1880}