blob: 01e00caa3b24c6b50dec0f5f51d4aff2e106a79a [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
Nick Lewycky00cbccc2012-03-09 09:23:50 +000044static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
45 const APInt &Mask,
46 APInt &KnownZero, APInt &KnownOne,
47 APInt &KnownZero2, APInt &KnownOne2,
48 const TargetData *TD, unsigned Depth) {
49 if (!Add) {
50 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
51 // We know that the top bits of C-X are clear if X contains less bits
52 // than C (i.e. no wrap-around can happen). For example, 20-X is
53 // positive if we can prove that X is >= 0 and < 16.
54 if (!CLHS->getValue().isNegative()) {
55 unsigned BitWidth = Mask.getBitWidth();
56 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
57 // NLZ can't be BitWidth with no sign bit
58 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
59 llvm::ComputeMaskedBits(Op1, MaskV, KnownZero2, KnownOne2, TD, Depth+1);
60
61 // If all of the MaskV bits are known to be zero, then we know the
62 // output top bits are zero, because we now know that the output is
63 // from [0-C].
64 if ((KnownZero2 & MaskV) == MaskV) {
65 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
66 // Top bits known zero.
67 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
68 }
69 }
70 }
71 }
72
73 unsigned BitWidth = Mask.getBitWidth();
74
75 // If one of the operands has trailing zeros, then the bits that the
76 // other operand has in those bit positions will be preserved in the
77 // result. For an add, this works with either operand. For a subtract,
78 // this only works if the known zeros are in the right operand.
79 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
80 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
81 BitWidth - Mask.countLeadingZeros());
82 llvm::ComputeMaskedBits(Op0, Mask2, LHSKnownZero, LHSKnownOne, TD, Depth+1);
83 assert((LHSKnownZero & LHSKnownOne) == 0 &&
84 "Bits known to be one AND zero?");
85 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
86
87 llvm::ComputeMaskedBits(Op1, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
88 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
89 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
90
91 // Determine which operand has more trailing zeros, and use that
92 // many bits from the other operand.
93 if (LHSKnownZeroOut > RHSKnownZeroOut) {
94 if (Add) {
95 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
96 KnownZero |= KnownZero2 & Mask;
97 KnownOne |= KnownOne2 & Mask;
98 } else {
99 // If the known zeros are in the left operand for a subtract,
100 // fall back to the minimum known zeros in both operands.
101 KnownZero |= APInt::getLowBitsSet(BitWidth,
102 std::min(LHSKnownZeroOut,
103 RHSKnownZeroOut));
104 }
105 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
106 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
107 KnownZero |= LHSKnownZero & Mask;
108 KnownOne |= LHSKnownOne & Mask;
109 }
110
111 // Are we still trying to solve for the sign bit?
112 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()) {
113 if (NSW) {
114 if (Add) {
115 // Adding two positive numbers can't wrap into negative
116 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
117 KnownZero |= APInt::getSignBit(BitWidth);
118 // and adding two negative numbers can't wrap into positive.
119 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
120 KnownOne |= APInt::getSignBit(BitWidth);
121 } else {
122 // Subtracting a negative number from a positive one can't wrap
123 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
124 KnownZero |= APInt::getSignBit(BitWidth);
125 // neither can subtracting a positive number from a negative one.
126 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
127 KnownOne |= APInt::getSignBit(BitWidth);
128 }
129 }
130 }
131}
132
Nick Lewyckyf201a062012-03-18 23:28:48 +0000133static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
134 const APInt &Mask,
135 APInt &KnownZero, APInt &KnownOne,
136 APInt &KnownZero2, APInt &KnownOne2,
137 const TargetData *TD, unsigned Depth) {
138 unsigned BitWidth = Mask.getBitWidth();
139 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
140 ComputeMaskedBits(Op1, Mask2, KnownZero, KnownOne, TD, Depth+1);
141 ComputeMaskedBits(Op0, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
142 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
143 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
144
145 bool isKnownNegative = false;
146 bool isKnownNonNegative = false;
147 // If the multiplication is known not to overflow, compute the sign bit.
148 if (Mask.isNegative() && NSW) {
149 if (Op0 == Op1) {
150 // The product of a number with itself is non-negative.
151 isKnownNonNegative = true;
152 } else {
153 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
154 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
155 bool isKnownNegativeOp1 = KnownOne.isNegative();
156 bool isKnownNegativeOp0 = KnownOne2.isNegative();
157 // The product of two numbers with the same sign is non-negative.
158 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
159 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
160 // The product of a negative number and a non-negative number is either
161 // negative or zero.
162 if (!isKnownNonNegative)
163 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
164 isKnownNonZero(Op0, TD, Depth)) ||
165 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
166 isKnownNonZero(Op1, TD, Depth));
167 }
168 }
169
170 // If low bits are zero in either operand, output low known-0 bits.
171 // Also compute a conserative estimate for high known-0 bits.
172 // More trickiness is possible, but this is sufficient for the
173 // interesting case of alignment computation.
174 KnownOne.clearAllBits();
175 unsigned TrailZ = KnownZero.countTrailingOnes() +
176 KnownZero2.countTrailingOnes();
177 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
178 KnownZero2.countLeadingOnes(),
179 BitWidth) - BitWidth;
180
181 TrailZ = std::min(TrailZ, BitWidth);
182 LeadZ = std::min(LeadZ, BitWidth);
183 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
184 APInt::getHighBitsSet(BitWidth, LeadZ);
185 KnownZero &= Mask;
186
187 // Only make use of no-wrap flags if we failed to compute the sign bit
188 // directly. This matters if the multiplication always overflows, in
189 // which case we prefer to follow the result of the direct computation,
190 // though as the program is invoking undefined behaviour we can choose
191 // whatever we like here.
192 if (isKnownNonNegative && !KnownOne.isNegative())
193 KnownZero.setBit(BitWidth - 1);
194 else if (isKnownNegative && !KnownZero.isNegative())
195 KnownOne.setBit(BitWidth - 1);
196}
197
Chris Lattner173234a2008-06-02 01:18:21 +0000198/// ComputeMaskedBits - Determine which of the bits specified in Mask are
199/// known to be either zero or one and return them in the KnownZero/KnownOne
200/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
201/// processing.
202/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
203/// we cannot optimize based on the assumption that it is zero without changing
204/// it to be an explicit zero. If we don't change it to zero, other code could
205/// optimized based on the contradictory assumption that it is non-zero.
206/// Because instcombine aggressively folds operations with undef args anyway,
207/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000208///
209/// This function is defined on values with integer type, values with pointer
210/// type (but only if TD is non-null), and vectors of integers. In the case
211/// where V is a vector, the mask, known zero, and known one values are the
212/// same width as the vector element, and the bit is set only if it is true
213/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000214void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
215 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +0000216 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000217 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +0000218 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +0000219 unsigned BitWidth = Mask.getBitWidth();
Nadav Rotem16087692011-12-05 06:29:09 +0000220 assert((V->getType()->isIntOrIntVectorTy() ||
221 V->getType()->getScalarType()->isPointerTy()) &&
222 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000223 assert((!TD ||
224 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000225 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +0000226 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem16087692011-12-05 06:29:09 +0000227 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner173234a2008-06-02 01:18:21 +0000228 KnownOne.getBitWidth() == BitWidth &&
229 "V, Mask, KnownOne and KnownZero should have same BitWidth");
230
231 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
232 // We know all of the bits for a constant!
233 KnownOne = CI->getValue() & Mask;
234 KnownZero = ~KnownOne & Mask;
235 return;
236 }
Dan Gohman6de29f82009-06-15 22:12:54 +0000237 // Null and aggregate-zero are all-zeros.
238 if (isa<ConstantPointerNull>(V) ||
239 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000240 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000241 KnownZero = Mask;
242 return;
243 }
Dan Gohman6de29f82009-06-15 22:12:54 +0000244 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner7302d802012-02-06 21:56:39 +0000245 // each element. There is no real need to handle ConstantVector here, because
246 // we don't handle undef in any particularly useful way.
Chris Lattnerdf390282012-01-24 07:54:10 +0000247 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
248 // We know that CDS must be a vector of integers. Take the intersection of
249 // each element.
250 KnownZero.setAllBits(); KnownOne.setAllBits();
251 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner0f193b82012-01-25 01:27:20 +0000252 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerdf390282012-01-24 07:54:10 +0000253 Elt = CDS->getElementAsInteger(i);
254 KnownZero &= ~Elt;
255 KnownOne &= Elt;
256 }
257 return;
258 }
259
Chris Lattner173234a2008-06-02 01:18:21 +0000260 // The address of an aligned GlobalValue has trailing zeros.
261 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
262 unsigned Align = GV->getAlignment();
Nick Lewycky891495e2012-03-07 02:27:53 +0000263 if (Align == 0 && TD) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000264 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
265 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky891495e2012-03-07 02:27:53 +0000266 if (ObjectType->isSized()) {
267 // If the object is defined in the current Module, we'll be giving
268 // it the preferred alignment. Otherwise, we have to assume that it
269 // may only have the minimum ABI alignment.
270 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
271 Align = TD->getPreferredAlignment(GVar);
272 else
273 Align = TD->getABITypeAlignment(ObjectType);
274 }
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000275 }
Dan Gohman00407252009-08-11 15:50:03 +0000276 }
Chris Lattner173234a2008-06-02 01:18:21 +0000277 if (Align > 0)
278 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
279 CountTrailingZeros_32(Align));
280 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000281 KnownZero.clearAllBits();
282 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000283 return;
284 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000285 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
286 // the bits of its aliasee.
287 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
288 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000289 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000290 } else {
291 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
292 TD, Depth+1);
293 }
294 return;
295 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000296
297 if (Argument *A = dyn_cast<Argument>(V)) {
298 // Get alignment information off byval arguments if specified in the IR.
299 if (A->hasByValAttr())
300 if (unsigned Align = A->getParamAlignment())
301 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
302 CountTrailingZeros_32(Align));
303 return;
304 }
Chris Lattner173234a2008-06-02 01:18:21 +0000305
Chris Lattnerb3f06732011-05-23 00:03:39 +0000306 // Start out not knowing anything.
307 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000308
Dan Gohman9004c8a2009-05-21 02:28:33 +0000309 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000310 return; // Limit search depth.
311
Dan Gohmanca178902009-07-17 20:47:02 +0000312 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000313 if (!I) return;
314
315 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000316 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000317 default: break;
318 case Instruction::And: {
319 // If either the LHS or the RHS are Zero, the result is zero.
320 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
321 APInt Mask2(Mask & ~KnownZero);
322 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
323 Depth+1);
324 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
325 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
326
327 // Output known-1 bits are only known if set in both the LHS & RHS.
328 KnownOne &= KnownOne2;
329 // Output known-0 are known to be clear if zero in either the LHS | RHS.
330 KnownZero |= KnownZero2;
331 return;
332 }
333 case Instruction::Or: {
334 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
335 APInt Mask2(Mask & ~KnownOne);
336 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
337 Depth+1);
338 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
339 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
340
341 // Output known-0 bits are only known if clear in both the LHS & RHS.
342 KnownZero &= KnownZero2;
343 // Output known-1 are known to be set if set in either the LHS | RHS.
344 KnownOne |= KnownOne2;
345 return;
346 }
347 case Instruction::Xor: {
348 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
349 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
350 Depth+1);
351 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
352 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
353
354 // Output known-0 bits are known if clear or set in both the LHS & RHS.
355 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
356 // Output known-1 are known to be set if set in only one of the LHS, RHS.
357 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
358 KnownZero = KnownZeroOut;
359 return;
360 }
361 case Instruction::Mul: {
Nick Lewyckyf201a062012-03-18 23:28:48 +0000362 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
363 ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
364 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
365 TD, Depth);
366 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000367 }
368 case Instruction::UDiv: {
369 // For the purposes of computing leading zeros we can conservatively
370 // treat a udiv as a logical right shift by the power of 2 known to
371 // be less than the denominator.
372 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
373 ComputeMaskedBits(I->getOperand(0),
374 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
375 unsigned LeadZ = KnownZero2.countLeadingOnes();
376
Jay Foad7a874dd2010-12-01 08:53:58 +0000377 KnownOne2.clearAllBits();
378 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000379 ComputeMaskedBits(I->getOperand(1),
380 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
381 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
382 if (RHSUnknownLeadingOnes != BitWidth)
383 LeadZ = std::min(BitWidth,
384 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
385
386 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
387 return;
388 }
389 case Instruction::Select:
390 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
391 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
392 Depth+1);
393 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
394 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
395
396 // Only known if known in both the LHS and RHS.
397 KnownOne &= KnownOne2;
398 KnownZero &= KnownZero2;
399 return;
400 case Instruction::FPTrunc:
401 case Instruction::FPExt:
402 case Instruction::FPToUI:
403 case Instruction::FPToSI:
404 case Instruction::SIToFP:
405 case Instruction::UIToFP:
406 return; // Can't work with floating point.
407 case Instruction::PtrToInt:
408 case Instruction::IntToPtr:
409 // We can't handle these if we don't know the pointer size.
410 if (!TD) return;
411 // FALL THROUGH and handle them the same as zext/trunc.
412 case Instruction::ZExt:
413 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000414 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000415
416 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000417 // Note that we handle pointer operands here because of inttoptr/ptrtoint
418 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000419 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000420 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
421 else
422 SrcBitWidth = SrcTy->getScalarSizeInBits();
423
Jay Foad40f8f622010-12-07 08:25:19 +0000424 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
425 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
426 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000427 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
428 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000429 KnownZero = KnownZero.zextOrTrunc(BitWidth);
430 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000431 // Any top bits are known to be zero.
432 if (BitWidth > SrcBitWidth)
433 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
434 return;
435 }
436 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000437 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000438 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000439 // TODO: For now, not handling conversions like:
440 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000441 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000442 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
443 Depth+1);
444 return;
445 }
446 break;
447 }
448 case Instruction::SExt: {
449 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000450 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000451
Jay Foad40f8f622010-12-07 08:25:19 +0000452 APInt MaskIn = Mask.trunc(SrcBitWidth);
453 KnownZero = KnownZero.trunc(SrcBitWidth);
454 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000455 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
456 Depth+1);
457 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000458 KnownZero = KnownZero.zext(BitWidth);
459 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000460
461 // If the sign bit of the input is known set or clear, then we know the
462 // top bits of the result.
463 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
464 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
465 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
466 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
467 return;
468 }
469 case Instruction::Shl:
470 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
471 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
472 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
473 APInt Mask2(Mask.lshr(ShiftAmt));
474 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
475 Depth+1);
476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
477 KnownZero <<= ShiftAmt;
478 KnownOne <<= ShiftAmt;
479 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
480 return;
481 }
482 break;
483 case Instruction::LShr:
484 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
485 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
486 // Compute the new bits that are at the top now.
487 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
488
489 // Unsigned shift right.
490 APInt Mask2(Mask.shl(ShiftAmt));
491 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
492 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000493 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000494 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
495 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
496 // high bits known zero.
497 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
498 return;
499 }
500 break;
501 case Instruction::AShr:
502 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
503 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
504 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000505 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000506
507 // Signed shift right.
508 APInt Mask2(Mask.shl(ShiftAmt));
509 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
510 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000511 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000512 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
513 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
514
515 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
516 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
517 KnownZero |= HighBits;
518 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
519 KnownOne |= HighBits;
520 return;
521 }
522 break;
523 case Instruction::Sub: {
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000524 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
525 ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
526 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
527 TD, Depth);
528 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000529 }
Chris Lattner173234a2008-06-02 01:18:21 +0000530 case Instruction::Add: {
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000531 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
532 ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
533 Mask, KnownZero, KnownOne, KnownZero2, KnownOne2,
534 TD, Depth);
535 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000536 }
537 case Instruction::SRem:
538 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000539 APInt RA = Rem->getValue().abs();
540 if (RA.isPowerOf2()) {
541 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000542 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
543 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
544 Depth+1);
545
Duncan Sandscfd54182010-01-29 06:18:37 +0000546 // The low bits of the first operand are unchanged by the srem.
547 KnownZero = KnownZero2 & LowBits;
548 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000549
Duncan Sandscfd54182010-01-29 06:18:37 +0000550 // If the first operand is non-negative or has all low bits zero, then
551 // the upper bits are all zero.
552 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
553 KnownZero |= ~LowBits;
554
555 // If the first operand is negative and not all low bits are zero, then
556 // the upper bits are all one.
557 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
558 KnownOne |= ~LowBits;
559
560 KnownZero &= Mask;
561 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000562
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000563 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000564 }
565 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000566
567 // The sign bit is the LHS's sign bit, except when the result of the
568 // remainder is zero.
569 if (Mask.isNegative() && KnownZero.isNonNegative()) {
570 APInt Mask2 = APInt::getSignBit(BitWidth);
571 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
572 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
573 Depth+1);
574 // If it's known zero, our sign bit is also zero.
575 if (LHSKnownZero.isNegative())
576 KnownZero |= LHSKnownZero;
577 }
578
Chris Lattner173234a2008-06-02 01:18:21 +0000579 break;
580 case Instruction::URem: {
581 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
582 APInt RA = Rem->getValue();
583 if (RA.isPowerOf2()) {
584 APInt LowBits = (RA - 1);
585 APInt Mask2 = LowBits & Mask;
586 KnownZero |= ~LowBits & Mask;
587 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
588 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000589 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000590 break;
591 }
592 }
593
594 // Since the result is less than or equal to either operand, any leading
595 // zero bits in either operand must also exist in the result.
596 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
597 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
598 TD, Depth+1);
599 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
600 TD, Depth+1);
601
Chris Lattner79abedb2009-01-20 18:22:57 +0000602 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000603 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000604 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000605 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
606 break;
607 }
608
Victor Hernandeza276c602009-10-17 01:18:07 +0000609 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000610 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000611 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000612 if (Align == 0 && TD)
613 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000614
615 if (Align > 0)
616 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
617 CountTrailingZeros_32(Align));
618 break;
619 }
620 case Instruction::GetElementPtr: {
621 // Analyze all of the subscripts of this getelementptr instruction
622 // to determine if we can prove known low zero bits.
623 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
624 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
625 ComputeMaskedBits(I->getOperand(0), LocalMask,
626 LocalKnownZero, LocalKnownOne, TD, Depth+1);
627 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
628
629 gep_type_iterator GTI = gep_type_begin(I);
630 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
631 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000632 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000633 // Handle struct member offset arithmetic.
634 if (!TD) return;
635 const StructLayout *SL = TD->getStructLayout(STy);
636 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
637 uint64_t Offset = SL->getElementOffset(Idx);
638 TrailZ = std::min(TrailZ,
639 CountTrailingZeros_64(Offset));
640 } else {
641 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000642 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000643 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000644 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000645 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000646 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
647 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
648 ComputeMaskedBits(Index, LocalMask,
649 LocalKnownZero, LocalKnownOne, TD, Depth+1);
650 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000651 unsigned(CountTrailingZeros_64(TypeSize) +
652 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000653 }
654 }
655
656 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
657 break;
658 }
659 case Instruction::PHI: {
660 PHINode *P = cast<PHINode>(I);
661 // Handle the case of a simple two-predecessor recurrence PHI.
662 // There's a lot more that could theoretically be done here, but
663 // this is sufficient to catch some interesting cases.
664 if (P->getNumIncomingValues() == 2) {
665 for (unsigned i = 0; i != 2; ++i) {
666 Value *L = P->getIncomingValue(i);
667 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000668 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000669 if (!LU)
670 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000671 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000672 // Check for operations that have the property that if
673 // both their operands have low zero bits, the result
674 // will have low zero bits.
675 if (Opcode == Instruction::Add ||
676 Opcode == Instruction::Sub ||
677 Opcode == Instruction::And ||
678 Opcode == Instruction::Or ||
679 Opcode == Instruction::Mul) {
680 Value *LL = LU->getOperand(0);
681 Value *LR = LU->getOperand(1);
682 // Find a recurrence.
683 if (LL == I)
684 L = LR;
685 else if (LR == I)
686 L = LL;
687 else
688 break;
689 // Ok, we have a PHI of the form L op= R. Check for low
690 // zero bits.
691 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
692 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
693 Mask2 = APInt::getLowBitsSet(BitWidth,
694 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000695
696 // We need to take the minimum number of known bits
697 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
698 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
699
Chris Lattner173234a2008-06-02 01:18:21 +0000700 KnownZero = Mask &
701 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000702 std::min(KnownZero2.countTrailingOnes(),
703 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000704 break;
705 }
706 }
707 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000708
Nick Lewycky3b739d22011-02-10 23:54:10 +0000709 // Unreachable blocks may have zero-operand PHI nodes.
710 if (P->getNumIncomingValues() == 0)
711 return;
712
Dan Gohman9004c8a2009-05-21 02:28:33 +0000713 // Otherwise take the unions of the known bit sets of the operands,
714 // taking conservative care to avoid excessive recursion.
715 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000716 // Skip if every incoming value references to ourself.
717 if (P->hasConstantValue() == P)
718 break;
719
Eli Friedman049d08f2012-03-05 23:09:40 +0000720 KnownZero = Mask;
721 KnownOne = Mask;
Dan Gohman9004c8a2009-05-21 02:28:33 +0000722 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
723 // Skip direct self references.
724 if (P->getIncomingValue(i) == P) continue;
725
726 KnownZero2 = APInt(BitWidth, 0);
727 KnownOne2 = APInt(BitWidth, 0);
728 // Recurse, but cap the recursion to one level, because we don't
729 // want to waste time spinning around in loops.
730 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
731 KnownZero2, KnownOne2, TD, MaxDepth-1);
732 KnownZero &= KnownZero2;
733 KnownOne &= KnownOne2;
734 // If all bits have been ruled out, there's no need to check
735 // more operands.
736 if (!KnownZero && !KnownOne)
737 break;
738 }
739 }
Chris Lattner173234a2008-06-02 01:18:21 +0000740 break;
741 }
742 case Instruction::Call:
743 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
744 switch (II->getIntrinsicID()) {
745 default: break;
Chris Lattner173234a2008-06-02 01:18:21 +0000746 case Intrinsic::ctlz:
747 case Intrinsic::cttz: {
748 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer009da052011-12-24 17:31:46 +0000749 // If this call is undefined for 0, the result will be less than 2^n.
750 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
751 LowBits -= 1;
Eli Friedman923bb412012-03-05 23:22:40 +0000752 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer009da052011-12-24 17:31:46 +0000753 break;
754 }
755 case Intrinsic::ctpop: {
756 unsigned LowBits = Log2_32(BitWidth)+1;
Eli Friedman923bb412012-03-05 23:22:40 +0000757 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner173234a2008-06-02 01:18:21 +0000758 break;
759 }
Chad Rosier62660312011-05-26 23:13:19 +0000760 case Intrinsic::x86_sse42_crc32_64_8:
761 case Intrinsic::x86_sse42_crc32_64_64:
Eli Friedman923bb412012-03-05 23:22:40 +0000762 KnownZero = Mask & APInt::getHighBitsSet(64, 32);
Evan Chengcb559c12011-05-22 18:25:30 +0000763 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000764 }
765 }
766 break;
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000767 case Instruction::ExtractValue:
768 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
769 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
770 if (EVI->getNumIndices() != 1) break;
771 if (EVI->getIndices()[0] == 0) {
772 switch (II->getIntrinsicID()) {
773 default: break;
774 case Intrinsic::uadd_with_overflow:
775 case Intrinsic::sadd_with_overflow:
776 ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
777 II->getArgOperand(1), false, Mask,
778 KnownZero, KnownOne, KnownZero2, KnownOne2,
779 TD, Depth);
780 break;
781 case Intrinsic::usub_with_overflow:
782 case Intrinsic::ssub_with_overflow:
783 ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
784 II->getArgOperand(1), false, Mask,
785 KnownZero, KnownOne, KnownZero2, KnownOne2,
786 TD, Depth);
787 break;
Nick Lewyckyf201a062012-03-18 23:28:48 +0000788 case Intrinsic::umul_with_overflow:
789 case Intrinsic::smul_with_overflow:
790 ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
791 false, Mask, KnownZero, KnownOne,
792 KnownZero2, KnownOne2, TD, Depth);
793 break;
Nick Lewycky00cbccc2012-03-09 09:23:50 +0000794 }
795 }
796 }
Chris Lattner173234a2008-06-02 01:18:21 +0000797 }
798}
799
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000800/// ComputeSignBit - Determine whether the sign bit is known to be zero or
801/// one. Convenience wrapper around ComputeMaskedBits.
802void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
803 const TargetData *TD, unsigned Depth) {
804 unsigned BitWidth = getBitWidth(V->getType(), TD);
805 if (!BitWidth) {
806 KnownZero = false;
807 KnownOne = false;
808 return;
809 }
810 APInt ZeroBits(BitWidth, 0);
811 APInt OneBits(BitWidth, 0);
812 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
813 Depth);
814 KnownOne = OneBits[BitWidth - 1];
815 KnownZero = ZeroBits[BitWidth - 1];
816}
817
818/// isPowerOfTwo - Return true if the given value is known to have exactly one
819/// bit set when defined. For vectors return true if every element is known to
820/// be a power of two when defined. Supports values with integer or pointer
821/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000822bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
823 unsigned Depth) {
824 if (Constant *C = dyn_cast<Constant>(V)) {
825 if (C->isNullValue())
826 return OrZero;
827 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
828 return CI->getValue().isPowerOf2();
829 // TODO: Handle vector constants.
830 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000831
832 // 1 << X is clearly a power of two if the one is not shifted off the end. If
833 // it is shifted off the end then the result is undefined.
834 if (match(V, m_Shl(m_One(), m_Value())))
835 return true;
836
837 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
838 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000839 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000840 return true;
841
842 // The remaining tests are all recursive, so bail out if we hit the limit.
843 if (Depth++ == MaxDepth)
844 return false;
845
Duncan Sands4604fc72011-10-28 18:30:05 +0000846 Value *X = 0, *Y = 0;
847 // A shift of a power of two is a power of two or zero.
848 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
849 match(V, m_Shr(m_Value(X), m_Value()))))
850 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
851
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000852 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000853 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000854
855 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000856 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
857 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
858
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000859 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
860 // A power of two and'd with anything is a power of two or zero.
861 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
862 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
863 return true;
864 // X & (-X) is always a power of two or zero.
865 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
866 return true;
867 return false;
868 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000869
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000870 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000871 // is a power of two only if the first operand is a power of two and not
872 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000873 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
874 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
875 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000876 }
877
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000878 return false;
879}
880
881/// isKnownNonZero - Return true if the given value is known to be non-zero
882/// when defined. For vectors return true if every element is known to be
883/// non-zero when defined. Supports values with integer or pointer type and
884/// vectors of integers.
885bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
886 if (Constant *C = dyn_cast<Constant>(V)) {
887 if (C->isNullValue())
888 return false;
889 if (isa<ConstantInt>(C))
890 // Must be non-zero due to null test above.
891 return true;
892 // TODO: Handle vectors
893 return false;
894 }
895
896 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000897 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000898 return false;
899
900 unsigned BitWidth = getBitWidth(V->getType(), TD);
901
902 // X | Y != 0 if X != 0 or Y != 0.
903 Value *X = 0, *Y = 0;
904 if (match(V, m_Or(m_Value(X), m_Value(Y))))
905 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
906
907 // ext X != 0 if X != 0.
908 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
909 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
910
Duncan Sands91367822011-01-29 13:27:00 +0000911 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000912 // if the lowest bit is shifted off the end.
913 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000914 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000915 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000916 if (BO->hasNoUnsignedWrap())
917 return isKnownNonZero(X, TD, Depth);
918
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000919 APInt KnownZero(BitWidth, 0);
920 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000921 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000922 if (KnownOne[0])
923 return true;
924 }
Duncan Sands91367822011-01-29 13:27:00 +0000925 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000926 // defined if the sign bit is shifted off the end.
927 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000928 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000929 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000930 if (BO->isExact())
931 return isKnownNonZero(X, TD, Depth);
932
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000933 bool XKnownNonNegative, XKnownNegative;
934 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
935 if (XKnownNegative)
936 return true;
937 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000938 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000939 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
940 return isKnownNonZero(X, TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000941 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000942 // X + Y.
943 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
944 bool XKnownNonNegative, XKnownNegative;
945 bool YKnownNonNegative, YKnownNegative;
946 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
947 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
948
949 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000950 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000951 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000952 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
953 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000954
955 // If X and Y are both negative (as signed values) then their sum is not
956 // zero unless both X and Y equal INT_MIN.
957 if (BitWidth && XKnownNegative && YKnownNegative) {
958 APInt KnownZero(BitWidth, 0);
959 APInt KnownOne(BitWidth, 0);
960 APInt Mask = APInt::getSignedMaxValue(BitWidth);
961 // The sign bit of X is set. If some other bit is set then X is not equal
962 // to INT_MIN.
963 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
964 if ((KnownOne & Mask) != 0)
965 return true;
966 // The sign bit of Y is set. If some other bit is set then Y is not equal
967 // to INT_MIN.
968 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
969 if ((KnownOne & Mask) != 0)
970 return true;
971 }
972
973 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000974 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000975 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000976 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000977 return true;
978 }
Duncan Sands32a43cc2011-10-27 19:16:21 +0000979 // X * Y.
980 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
981 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
982 // If X and Y are non-zero then so is X * Y as long as the multiplication
983 // does not overflow.
984 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
985 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
986 return true;
987 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000988 // (C ? X : Y) != 0 if X != 0 and Y != 0.
989 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
990 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
991 isKnownNonZero(SI->getFalseValue(), TD, Depth))
992 return true;
993 }
994
995 if (!BitWidth) return false;
996 APInt KnownZero(BitWidth, 0);
997 APInt KnownOne(BitWidth, 0);
998 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
999 TD, Depth);
1000 return KnownOne != 0;
1001}
1002
Chris Lattner173234a2008-06-02 01:18:21 +00001003/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1004/// this predicate to simplify operations downstream. Mask is known to be zero
1005/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +00001006///
1007/// This function is defined on values with integer type, values with pointer
1008/// type (but only if TD is non-null), and vectors of integers. In the case
1009/// where V is a vector, the mask, known zero, and known one values are the
1010/// same width as the vector element, and the bit is set only if it is true
1011/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +00001012bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +00001013 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +00001014 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1015 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1016 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1017 return (KnownZero & Mask) == Mask;
1018}
1019
1020
1021
1022/// ComputeNumSignBits - Return the number of times the sign bit of the
1023/// register is replicated into the other bits. We know that at least 1 bit
1024/// is always equal to the sign bit (itself), but other cases can give us
1025/// information. For example, immediately after an "ashr X, 2", we know that
1026/// the top 3 bits are all equal to each other, so we return 3.
1027///
1028/// 'Op' must have a scalar integer type.
1029///
Dan Gohman846a2f22009-08-27 17:51:25 +00001030unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
1031 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001032 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +00001033 "ComputeNumSignBits requires a TargetData object to operate "
1034 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001035 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +00001036 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1037 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001038 unsigned Tmp, Tmp2;
1039 unsigned FirstAnswer = 1;
1040
Chris Lattnerd82e5112008-06-02 18:39:07 +00001041 // Note that ConstantInt is handled by the general ComputeMaskedBits case
1042 // below.
1043
Chris Lattner173234a2008-06-02 01:18:21 +00001044 if (Depth == 6)
1045 return 1; // Limit search depth.
1046
Dan Gohmanca178902009-07-17 20:47:02 +00001047 Operator *U = dyn_cast<Operator>(V);
1048 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +00001049 default: break;
1050 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +00001051 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001052 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1053
Chris Lattner6b0dc922012-01-26 21:37:55 +00001054 case Instruction::AShr: {
Chris Lattner173234a2008-06-02 01:18:21 +00001055 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001056 // ashr X, C -> adds C sign bits. Vectors too.
1057 const APInt *ShAmt;
1058 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1059 Tmp += ShAmt->getZExtValue();
Chris Lattner173234a2008-06-02 01:18:21 +00001060 if (Tmp > TyBits) Tmp = TyBits;
1061 }
1062 return Tmp;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001063 }
1064 case Instruction::Shl: {
1065 const APInt *ShAmt;
1066 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner173234a2008-06-02 01:18:21 +00001067 // shl destroys sign bits.
1068 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001069 Tmp2 = ShAmt->getZExtValue();
1070 if (Tmp2 >= TyBits || // Bad shift.
1071 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1072 return Tmp - Tmp2;
Chris Lattner173234a2008-06-02 01:18:21 +00001073 }
1074 break;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001075 }
Chris Lattner173234a2008-06-02 01:18:21 +00001076 case Instruction::And:
1077 case Instruction::Or:
1078 case Instruction::Xor: // NOT is handled here.
1079 // Logical binary ops preserve the number of sign bits at the worst.
1080 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1081 if (Tmp != 1) {
1082 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1083 FirstAnswer = std::min(Tmp, Tmp2);
1084 // We computed what we know about the sign bits as our first
1085 // answer. Now proceed to the generic code that uses
1086 // ComputeMaskedBits, and pick whichever answer is better.
1087 }
1088 break;
1089
1090 case Instruction::Select:
1091 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1092 if (Tmp == 1) return 1; // Early out.
1093 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1094 return std::min(Tmp, Tmp2);
1095
1096 case Instruction::Add:
1097 // Add can have at most one carry bit. Thus we know that the output
1098 // is, at worst, one more bit than the inputs.
1099 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1100 if (Tmp == 1) return 1; // Early out.
1101
1102 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001103 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001104 if (CRHS->isAllOnesValue()) {
1105 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1106 APInt Mask = APInt::getAllOnesValue(TyBits);
1107 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1108 Depth+1);
1109
1110 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1111 // sign bits set.
1112 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1113 return TyBits;
1114
1115 // If we are subtracting one from a positive number, there is no carry
1116 // out of the result.
1117 if (KnownZero.isNegative())
1118 return Tmp;
1119 }
1120
1121 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1122 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001123 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001124
1125 case Instruction::Sub:
1126 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1127 if (Tmp2 == 1) return 1;
1128
1129 // Handle NEG.
1130 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1131 if (CLHS->isNullValue()) {
1132 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1133 APInt Mask = APInt::getAllOnesValue(TyBits);
1134 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1135 TD, Depth+1);
1136 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1137 // sign bits set.
1138 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1139 return TyBits;
1140
1141 // If the input is known to be positive (the sign bit is known clear),
1142 // the output of the NEG has the same number of sign bits as the input.
1143 if (KnownZero.isNegative())
1144 return Tmp2;
1145
1146 // Otherwise, we treat this like a SUB.
1147 }
1148
1149 // Sub can have at most one carry bit. Thus we know that the output
1150 // is, at worst, one more bit than the inputs.
1151 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1152 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001153 return std::min(Tmp, Tmp2)-1;
1154
1155 case Instruction::PHI: {
1156 PHINode *PN = cast<PHINode>(U);
1157 // Don't analyze large in-degree PHIs.
1158 if (PN->getNumIncomingValues() > 4) break;
1159
1160 // Take the minimum of all incoming values. This can't infinitely loop
1161 // because of our depth threshold.
1162 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1163 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1164 if (Tmp == 1) return Tmp;
1165 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001166 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001167 }
1168 return Tmp;
1169 }
1170
Chris Lattner173234a2008-06-02 01:18:21 +00001171 case Instruction::Trunc:
1172 // FIXME: it's tricky to do anything useful for this, but it is an important
1173 // case for targets like X86.
1174 break;
1175 }
1176
1177 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1178 // use this information.
1179 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1180 APInt Mask = APInt::getAllOnesValue(TyBits);
1181 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1182
1183 if (KnownZero.isNegative()) { // sign bit is 0
1184 Mask = KnownZero;
1185 } else if (KnownOne.isNegative()) { // sign bit is 1;
1186 Mask = KnownOne;
1187 } else {
1188 // Nothing known.
1189 return FirstAnswer;
1190 }
1191
1192 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1193 // the number of identical bits in the top of the input value.
1194 Mask = ~Mask;
1195 Mask <<= Mask.getBitWidth()-TyBits;
1196 // Return # leading zeros. We use 'min' here in case Val was zero before
1197 // shifting. We don't want to return '64' as for an i32 "0".
1198 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1199}
Chris Lattner833f25d2008-06-02 01:29:46 +00001200
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001201/// ComputeMultiple - This function computes the integer multiple of Base that
1202/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001203/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001204/// through SExt instructions only if LookThroughSExt is true.
1205bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001206 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001207 const unsigned MaxDepth = 6;
1208
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001209 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001210 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001211 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001212
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001213 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001214
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001215 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001216
1217 if (Base == 0)
1218 return false;
1219
1220 if (Base == 1) {
1221 Multiple = V;
1222 return true;
1223 }
1224
1225 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1226 Constant *BaseVal = ConstantInt::get(T, Base);
1227 if (CO && CO == BaseVal) {
1228 // Multiple is 1.
1229 Multiple = ConstantInt::get(T, 1);
1230 return true;
1231 }
1232
1233 if (CI && CI->getZExtValue() % Base == 0) {
1234 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1235 return true;
1236 }
1237
1238 if (Depth == MaxDepth) return false; // Limit search depth.
1239
1240 Operator *I = dyn_cast<Operator>(V);
1241 if (!I) return false;
1242
1243 switch (I->getOpcode()) {
1244 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001245 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001246 if (!LookThroughSExt) return false;
1247 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001248 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001249 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1250 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001251 case Instruction::Shl:
1252 case Instruction::Mul: {
1253 Value *Op0 = I->getOperand(0);
1254 Value *Op1 = I->getOperand(1);
1255
1256 if (I->getOpcode() == Instruction::Shl) {
1257 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1258 if (!Op1CI) return false;
1259 // Turn Op0 << Op1 into Op0 * 2^Op1
1260 APInt Op1Int = Op1CI->getValue();
1261 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001262 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001263 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001264 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001265 }
1266
1267 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001268 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1269 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1270 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1271 if (Op1C->getType()->getPrimitiveSizeInBits() <
1272 MulC->getType()->getPrimitiveSizeInBits())
1273 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1274 if (Op1C->getType()->getPrimitiveSizeInBits() >
1275 MulC->getType()->getPrimitiveSizeInBits())
1276 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1277
1278 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1279 Multiple = ConstantExpr::getMul(MulC, Op1C);
1280 return true;
1281 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001282
1283 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1284 if (Mul0CI->getValue() == 1) {
1285 // V == Base * Op1, so return Op1
1286 Multiple = Op1;
1287 return true;
1288 }
1289 }
1290
Chris Lattnere9711312010-09-05 17:20:46 +00001291 Value *Mul1 = NULL;
1292 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1293 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1294 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1295 if (Op0C->getType()->getPrimitiveSizeInBits() <
1296 MulC->getType()->getPrimitiveSizeInBits())
1297 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1298 if (Op0C->getType()->getPrimitiveSizeInBits() >
1299 MulC->getType()->getPrimitiveSizeInBits())
1300 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1301
1302 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1303 Multiple = ConstantExpr::getMul(MulC, Op0C);
1304 return true;
1305 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001306
1307 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1308 if (Mul1CI->getValue() == 1) {
1309 // V == Base * Op0, so return Op0
1310 Multiple = Op0;
1311 return true;
1312 }
1313 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001314 }
1315 }
1316
1317 // We could not determine if V is a multiple of Base.
1318 return false;
1319}
1320
Chris Lattner833f25d2008-06-02 01:29:46 +00001321/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1322/// value is never equal to -0.0.
1323///
1324/// NOTE: this function will need to be revisited when we support non-default
1325/// rounding modes!
1326///
1327bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1328 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1329 return !CFP->getValueAPF().isNegZero();
1330
1331 if (Depth == 6)
1332 return 1; // Limit search depth.
1333
Dan Gohmanca178902009-07-17 20:47:02 +00001334 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001335 if (I == 0) return false;
1336
1337 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001338 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001339 isa<ConstantFP>(I->getOperand(1)) &&
1340 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1341 return true;
1342
1343 // sitofp and uitofp turn into +0.0 for zero.
1344 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1345 return true;
1346
1347 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1348 // sqrt(-0.0) = -0.0, no other negative results are possible.
1349 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001350 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001351
1352 if (const CallInst *CI = dyn_cast<CallInst>(I))
1353 if (const Function *F = CI->getCalledFunction()) {
1354 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001355 // abs(x) != -0.0
1356 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001357 // fabs[lf](x) != -0.0
1358 if (F->getName() == "fabs") return true;
1359 if (F->getName() == "fabsf") return true;
1360 if (F->getName() == "fabsl") return true;
1361 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1362 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001363 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001364 }
1365 }
1366
1367 return false;
1368}
1369
Chris Lattnerbb897102010-12-26 20:15:01 +00001370/// isBytewiseValue - If the specified value can be set by repeating the same
1371/// byte in memory, return the i8 value that it is represented with. This is
1372/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1373/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1374/// byte store (e.g. i16 0x1234), return null.
1375Value *llvm::isBytewiseValue(Value *V) {
1376 // All byte-wide stores are splatable, even of arbitrary variables.
1377 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001378
1379 // Handle 'null' ConstantArrayZero etc.
1380 if (Constant *C = dyn_cast<Constant>(V))
1381 if (C->isNullValue())
1382 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001383
1384 // Constant float and double values can be handled as integer values if the
1385 // corresponding integer value is "byteable". An important case is 0.0.
1386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1387 if (CFP->getType()->isFloatTy())
1388 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1389 if (CFP->getType()->isDoubleTy())
1390 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1391 // Don't handle long double formats, which have strange constraints.
1392 }
1393
1394 // We can handle constant integers that are power of two in size and a
1395 // multiple of 8 bits.
1396 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1397 unsigned Width = CI->getBitWidth();
1398 if (isPowerOf2_32(Width) && Width > 8) {
1399 // We can handle this value if the recursive binary decomposition is the
1400 // same at all levels.
1401 APInt Val = CI->getValue();
1402 APInt Val2;
1403 while (Val.getBitWidth() != 8) {
1404 unsigned NextWidth = Val.getBitWidth()/2;
1405 Val2 = Val.lshr(NextWidth);
1406 Val2 = Val2.trunc(Val.getBitWidth()/2);
1407 Val = Val.trunc(Val.getBitWidth()/2);
1408
1409 // If the top/bottom halves aren't the same, reject it.
1410 if (Val != Val2)
1411 return 0;
1412 }
1413 return ConstantInt::get(V->getContext(), Val);
1414 }
1415 }
1416
Chris Lattner18c7f802012-02-05 02:29:43 +00001417 // A ConstantDataArray/Vector is splatable if all its members are equal and
1418 // also splatable.
1419 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1420 Value *Elt = CA->getElementAsConstant(0);
1421 Value *Val = isBytewiseValue(Elt);
Chris Lattnerbb897102010-12-26 20:15:01 +00001422 if (!Val)
1423 return 0;
1424
Chris Lattner18c7f802012-02-05 02:29:43 +00001425 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1426 if (CA->getElementAsConstant(I) != Elt)
Chris Lattnerbb897102010-12-26 20:15:01 +00001427 return 0;
1428
1429 return Val;
1430 }
Chad Rosierdce42b72011-12-06 00:19:08 +00001431
Chris Lattnerbb897102010-12-26 20:15:01 +00001432 // Conceptually, we could handle things like:
1433 // %a = zext i8 %X to i16
1434 // %b = shl i16 %a, 8
1435 // %c = or i16 %a, %b
1436 // but until there is an example that actually needs this, it doesn't seem
1437 // worth worrying about.
1438 return 0;
1439}
1440
1441
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001442// This is the recursive version of BuildSubAggregate. It takes a few different
1443// arguments. Idxs is the index within the nested struct From that we are
1444// looking at now (which is of type IndexedType). IdxSkip is the number of
1445// indices from Idxs that should be left out when inserting into the resulting
1446// struct. To is the result struct built so far, new insertvalue instructions
1447// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001448static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001449 SmallVector<unsigned, 10> &Idxs,
1450 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001451 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001452 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001453 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001454 // Save the original To argument so we can modify it
1455 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001456 // General case, the type indexed by Idxs is a struct
1457 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1458 // Process each struct element recursively
1459 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001460 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001461 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001462 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001463 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001464 if (!To) {
1465 // Couldn't find any inserted value for this index? Cleanup
1466 while (PrevTo != OrigTo) {
1467 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1468 PrevTo = Del->getAggregateOperand();
1469 Del->eraseFromParent();
1470 }
1471 // Stop processing elements
1472 break;
1473 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001474 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001475 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001476 if (To)
1477 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001478 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001479 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1480 // the struct's elements had a value that was inserted directly. In the latter
1481 // case, perhaps we can't determine each of the subelements individually, but
1482 // we might be able to find the complete struct somewhere.
1483
1484 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001485 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001486
1487 if (!V)
1488 return NULL;
1489
1490 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001491 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001492 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001493}
1494
1495// This helper takes a nested struct and extracts a part of it (which is again a
1496// struct) into a new value. For example, given the struct:
1497// { a, { b, { c, d }, e } }
1498// and the indices "1, 1" this returns
1499// { c, d }.
1500//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001501// It does this by inserting an insertvalue for each element in the resulting
1502// struct, as opposed to just inserting a single struct. This will only work if
1503// each of the elements of the substruct are known (ie, inserted into From by an
1504// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001505//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001506// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001507static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001508 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001509 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001510 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001511 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001512 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001513 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001514 unsigned IdxSkip = Idxs.size();
1515
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001516 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001517}
1518
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001519/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1520/// the scalar value indexed is already around as a register, for example if it
1521/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001522///
1523/// If InsertBefore is not null, this function will duplicate (modified)
1524/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001525Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1526 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001527 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerdf390282012-01-24 07:54:10 +00001528 // recursion).
Jay Foadfc6d3a42011-07-13 10:26:04 +00001529 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001530 return V;
Chris Lattnerdf390282012-01-24 07:54:10 +00001531 // We have indices, so V should have an indexable type.
1532 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1533 "Not looking at a struct or array?");
1534 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1535 "Invalid indices for type?");
Owen Anderson76f600b2009-07-06 22:37:39 +00001536
Chris Lattnera1f00f42012-01-25 06:48:06 +00001537 if (Constant *C = dyn_cast<Constant>(V)) {
1538 C = C->getAggregateElement(idx_range[0]);
1539 if (C == 0) return 0;
1540 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1541 }
Chris Lattnerdf390282012-01-24 07:54:10 +00001542
1543 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001544 // Loop the indices for the insertvalue instruction in parallel with the
1545 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001546 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001547 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1548 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001549 if (req_idx == idx_range.end()) {
Chris Lattnerdf390282012-01-24 07:54:10 +00001550 // We can't handle this without inserting insertvalues
1551 if (!InsertBefore)
Matthijs Kooijman97728912008-06-16 13:28:31 +00001552 return 0;
Chris Lattnerdf390282012-01-24 07:54:10 +00001553
1554 // The requested index identifies a part of a nested aggregate. Handle
1555 // this specially. For example,
1556 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1557 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1558 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1559 // This can be changed into
1560 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1561 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1562 // which allows the unused 0,0 element from the nested struct to be
1563 // removed.
1564 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1565 InsertBefore);
Duncan Sands9954c762008-06-19 08:47:31 +00001566 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001567
1568 // This insert value inserts something else than what we are looking for.
1569 // See if the (aggregrate) value inserted into has the value we are
1570 // looking for, then.
1571 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001572 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001573 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001574 }
1575 // If we end up here, the indices of the insertvalue match with those
1576 // requested (though possibly only partially). Now we recursively look at
1577 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001578 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001579 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001580 InsertBefore);
Chris Lattnerdf390282012-01-24 07:54:10 +00001581 }
1582
1583 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001584 // If we're extracting a value from an aggregrate that was extracted from
1585 // something else, we can extract from that something else directly instead.
1586 // However, we will need to chain I's indices with the requested indices.
1587
1588 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001589 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001590 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001591 SmallVector<unsigned, 5> Idxs;
1592 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001593 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001594 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001595
1596 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001597 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001598
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001599 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001600 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001601
Jay Foadfc6d3a42011-07-13 10:26:04 +00001602 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001603 }
1604 // Otherwise, we don't know (such as, extracting from a function return value
1605 // or load instruction)
1606 return 0;
1607}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001608
Chris Lattnered58a6f2010-11-30 22:25:26 +00001609/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1610/// it can be expressed as a base pointer plus a constant offset. Return the
1611/// base and offset to the caller.
1612Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1613 const TargetData &TD) {
1614 Operator *PtrOp = dyn_cast<Operator>(Ptr);
Nadav Rotem16087692011-12-05 06:29:09 +00001615 if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1616 return Ptr;
Chris Lattnered58a6f2010-11-30 22:25:26 +00001617
1618 // Just look through bitcasts.
1619 if (PtrOp->getOpcode() == Instruction::BitCast)
1620 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1621
1622 // If this is a GEP with constant indices, we can look through it.
1623 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1624 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1625
1626 gep_type_iterator GTI = gep_type_begin(GEP);
1627 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1628 ++I, ++GTI) {
1629 ConstantInt *OpC = cast<ConstantInt>(*I);
1630 if (OpC->isZero()) continue;
1631
1632 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001633 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001634 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1635 } else {
1636 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1637 Offset += OpC->getSExtValue()*Size;
1638 }
1639 }
1640
1641 // Re-sign extend from the pointer size if needed to get overflow edge cases
1642 // right.
1643 unsigned PtrSize = TD.getPointerSizeInBits();
1644 if (PtrSize < 64)
1645 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1646
1647 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1648}
1649
1650
Chris Lattner18c7f802012-02-05 02:29:43 +00001651/// getConstantStringInfo - This function computes the length of a
Evan Cheng0ff39b32008-06-30 07:31:25 +00001652/// null-terminated C string pointed to by V. If successful, it returns true
1653/// and returns the string in Str. If unsuccessful, it returns false.
Chris Lattner18c7f802012-02-05 02:29:43 +00001654bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1655 uint64_t Offset, bool TrimAtNul) {
1656 assert(V);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001657
Chris Lattner18c7f802012-02-05 02:29:43 +00001658 // Look through bitcast instructions and geps.
1659 V = V->stripPointerCasts();
Bill Wendling0582ae92009-03-13 04:39:26 +00001660
Chris Lattner18c7f802012-02-05 02:29:43 +00001661 // If the value is a GEP instructionor constant expression, treat it as an
1662 // offset.
1663 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001664 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001665 if (GEP->getNumOperands() != 3)
1666 return false;
1667
Evan Cheng0ff39b32008-06-30 07:31:25 +00001668 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001669 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1670 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001671 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001672 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001673
1674 // Check to make sure that the first operand of the GEP is an integer and
1675 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001676 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001677 if (FirstIdx == 0 || !FirstIdx->isZero())
1678 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001679
1680 // If the second index isn't a ConstantInt, then this is a variable index
1681 // into the array. If this occurs, we can't say anything meaningful about
1682 // the string.
1683 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001684 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001685 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001686 else
1687 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001688 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001689 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001690
Evan Cheng0ff39b32008-06-30 07:31:25 +00001691 // The GEP instruction, constant or instruction, must reference a global
1692 // variable that is a constant and is initialized. The referenced constant
1693 // initializer is the array that we'll use for optimization.
Chris Lattner18c7f802012-02-05 02:29:43 +00001694 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001695 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001696 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001697
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001698 // Handle the all-zeros case
Chris Lattner18c7f802012-02-05 02:29:43 +00001699 if (GV->getInitializer()->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001700 // This is a degenerate case. The initializer is constant zero so the
1701 // length of the string must be zero.
Chris Lattner18c7f802012-02-05 02:29:43 +00001702 Str = "";
Bill Wendling0582ae92009-03-13 04:39:26 +00001703 return true;
1704 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001705
1706 // Must be a Constant Array
Chris Lattner18c7f802012-02-05 02:29:43 +00001707 const ConstantDataArray *Array =
1708 dyn_cast<ConstantDataArray>(GV->getInitializer());
1709 if (Array == 0 || !Array->isString())
Bill Wendling0582ae92009-03-13 04:39:26 +00001710 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001711
1712 // Get the number of elements in the array
Chris Lattner18c7f802012-02-05 02:29:43 +00001713 uint64_t NumElts = Array->getType()->getArrayNumElements();
1714
1715 // Start out with the entire array in the StringRef.
1716 Str = Array->getAsString();
1717
Bill Wendling0582ae92009-03-13 04:39:26 +00001718 if (Offset > NumElts)
1719 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001720
Chris Lattner18c7f802012-02-05 02:29:43 +00001721 // Skip over 'offset' bytes.
1722 Str = Str.substr(Offset);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001723
Chris Lattner18c7f802012-02-05 02:29:43 +00001724 if (TrimAtNul) {
1725 // Trim off the \0 and anything after it. If the array is not nul
1726 // terminated, we just return the whole end of string. The client may know
1727 // some other way that the string is length-bound.
1728 Str = Str.substr(0, Str.find('\0'));
1729 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001730 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001731}
Eric Christopher25ec4832010-03-05 06:58:57 +00001732
1733// These next two are very similar to the above, but also look through PHI
1734// nodes.
1735// TODO: See if we can integrate these two together.
1736
1737/// GetStringLengthH - If we can compute the length of the string pointed to by
1738/// the specified pointer, return 'len+1'. If we can't, return 0.
1739static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1740 // Look through noop bitcast instructions.
Chris Lattner18c7f802012-02-05 02:29:43 +00001741 V = V->stripPointerCasts();
Eric Christopher25ec4832010-03-05 06:58:57 +00001742
1743 // If this is a PHI node, there are two cases: either we have already seen it
1744 // or we haven't.
1745 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1746 if (!PHIs.insert(PN))
1747 return ~0ULL; // already in the set.
1748
1749 // If it was new, see if all the input strings are the same length.
1750 uint64_t LenSoFar = ~0ULL;
1751 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1752 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1753 if (Len == 0) return 0; // Unknown length -> unknown.
1754
1755 if (Len == ~0ULL) continue;
1756
1757 if (Len != LenSoFar && LenSoFar != ~0ULL)
1758 return 0; // Disagree -> unknown.
1759 LenSoFar = Len;
1760 }
1761
1762 // Success, all agree.
1763 return LenSoFar;
1764 }
1765
1766 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1767 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1768 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1769 if (Len1 == 0) return 0;
1770 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1771 if (Len2 == 0) return 0;
1772 if (Len1 == ~0ULL) return Len2;
1773 if (Len2 == ~0ULL) return Len1;
1774 if (Len1 != Len2) return 0;
1775 return Len1;
1776 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001777
1778 // Otherwise, see if we can read the string.
1779 StringRef StrData;
1780 if (!getConstantStringInfo(V, StrData))
Eric Christopher25ec4832010-03-05 06:58:57 +00001781 return 0;
1782
Chris Lattner18c7f802012-02-05 02:29:43 +00001783 return StrData.size()+1;
Eric Christopher25ec4832010-03-05 06:58:57 +00001784}
1785
1786/// GetStringLength - If we can compute the length of the string pointed to by
1787/// the specified pointer, return 'len+1'. If we can't, return 0.
1788uint64_t llvm::GetStringLength(Value *V) {
1789 if (!V->getType()->isPointerTy()) return 0;
1790
1791 SmallPtrSet<PHINode*, 32> PHIs;
1792 uint64_t Len = GetStringLengthH(V, PHIs);
1793 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1794 // an empty string as a length.
1795 return Len == ~0ULL ? 1 : Len;
1796}
Dan Gohman5034dd32010-12-15 20:02:24 +00001797
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001798Value *
1799llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001800 if (!V->getType()->isPointerTy())
1801 return V;
1802 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1803 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1804 V = GEP->getPointerOperand();
1805 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1806 V = cast<Operator>(V)->getOperand(0);
1807 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1808 if (GA->mayBeOverridden())
1809 return V;
1810 V = GA->getAliasee();
1811 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001812 // See if InstructionSimplify knows any relevant tricks.
1813 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001814 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001815 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001816 V = Simplified;
1817 continue;
1818 }
1819
Dan Gohman5034dd32010-12-15 20:02:24 +00001820 return V;
1821 }
1822 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1823 }
1824 return V;
1825}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001826
1827/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1828/// are lifetime markers.
1829///
1830bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1831 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1832 UI != UE; ++UI) {
1833 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1834 if (!II) return false;
1835
1836 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1837 II->getIntrinsicID() != Intrinsic::lifetime_end)
1838 return false;
1839 }
1840 return true;
1841}
Dan Gohmanf0426602011-12-14 23:49:11 +00001842
Dan Gohmanfebaf842012-01-04 23:01:09 +00001843bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Dan Gohmanf0426602011-12-14 23:49:11 +00001844 const TargetData *TD) {
Dan Gohmanfebaf842012-01-04 23:01:09 +00001845 const Operator *Inst = dyn_cast<Operator>(V);
1846 if (!Inst)
1847 return false;
1848
Dan Gohmanf0426602011-12-14 23:49:11 +00001849 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1850 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1851 if (C->canTrap())
1852 return false;
1853
1854 switch (Inst->getOpcode()) {
1855 default:
1856 return true;
1857 case Instruction::UDiv:
1858 case Instruction::URem:
1859 // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1860 return isKnownNonZero(Inst->getOperand(1), TD);
1861 case Instruction::SDiv:
1862 case Instruction::SRem: {
1863 Value *Op = Inst->getOperand(1);
1864 // x / y is undefined if y == 0
1865 if (!isKnownNonZero(Op, TD))
1866 return false;
1867 // x / y might be undefined if y == -1
1868 unsigned BitWidth = getBitWidth(Op->getType(), TD);
1869 if (BitWidth == 0)
1870 return false;
1871 APInt KnownZero(BitWidth, 0);
1872 APInt KnownOne(BitWidth, 0);
1873 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1874 KnownZero, KnownOne, TD);
1875 return !!KnownZero;
1876 }
1877 case Instruction::Load: {
1878 const LoadInst *LI = cast<LoadInst>(Inst);
1879 if (!LI->isUnordered())
1880 return false;
1881 return LI->getPointerOperand()->isDereferenceablePointer();
1882 }
Nick Lewycky83696872011-12-21 05:52:02 +00001883 case Instruction::Call: {
1884 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1885 switch (II->getIntrinsicID()) {
1886 case Intrinsic::bswap:
1887 case Intrinsic::ctlz:
1888 case Intrinsic::ctpop:
1889 case Intrinsic::cttz:
1890 case Intrinsic::objectsize:
1891 case Intrinsic::sadd_with_overflow:
1892 case Intrinsic::smul_with_overflow:
1893 case Intrinsic::ssub_with_overflow:
1894 case Intrinsic::uadd_with_overflow:
1895 case Intrinsic::umul_with_overflow:
1896 case Intrinsic::usub_with_overflow:
1897 return true;
1898 // TODO: some fp intrinsics are marked as having the same error handling
1899 // as libm. They're safe to speculate when they won't error.
1900 // TODO: are convert_{from,to}_fp16 safe?
1901 // TODO: can we list target-specific intrinsics here?
1902 default: break;
1903 }
1904 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001905 return false; // The called function could have undefined behavior or
Nick Lewycky83696872011-12-21 05:52:02 +00001906 // side-effects, even if marked readnone nounwind.
1907 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001908 case Instruction::VAArg:
1909 case Instruction::Alloca:
1910 case Instruction::Invoke:
1911 case Instruction::PHI:
1912 case Instruction::Store:
1913 case Instruction::Ret:
1914 case Instruction::Br:
1915 case Instruction::IndirectBr:
1916 case Instruction::Switch:
Dan Gohmanf0426602011-12-14 23:49:11 +00001917 case Instruction::Unreachable:
1918 case Instruction::Fence:
1919 case Instruction::LandingPad:
1920 case Instruction::AtomicRMW:
1921 case Instruction::AtomicCmpXchg:
1922 case Instruction::Resume:
1923 return false; // Misc instructions which have effects
1924 }
1925}