blob: 21008a14678f62b0c9791e36629b93fda3f9d31a [file] [log] [blame]
Chris Lattner173234a2008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
Dan Gohman24371272010-12-15 20:10:26 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner173234a2008-06-02 01:18:21 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000019#include "llvm/GlobalVariable.h"
Dan Gohman307a7c42009-09-15 16:14:44 +000020#include "llvm/GlobalAlias.h"
Chris Lattner173234a2008-06-02 01:18:21 +000021#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000022#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000023#include "llvm/Operator.h"
Bill Wendling0582ae92009-03-13 04:39:26 +000024#include "llvm/Target/TargetData.h"
Chris Lattner173234a2008-06-02 01:18:21 +000025#include "llvm/Support/GetElementPtrTypeIterator.h"
26#include "llvm/Support/MathExtras.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000027#include "llvm/Support/PatternMatch.h"
Eric Christopher25ec4832010-03-05 06:58:57 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner32a9e7a2008-06-04 04:46:14 +000029#include <cstring>
Chris Lattner173234a2008-06-02 01:18:21 +000030using namespace llvm;
Duncan Sandsd70d1a52011-01-25 09:38:29 +000031using namespace llvm::PatternMatch;
32
33const unsigned MaxDepth = 6;
34
35/// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
36/// unknown returns 0). For vector types, returns the element type's bitwidth.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000037static unsigned getBitWidth(Type *Ty, const TargetData *TD) {
Duncan Sandsd70d1a52011-01-25 09:38:29 +000038 if (unsigned BitWidth = Ty->getScalarSizeInBits())
39 return BitWidth;
40 assert(isa<PointerType>(Ty) && "Expected a pointer type!");
41 return TD ? TD->getPointerSizeInBits() : 0;
42}
Chris Lattner173234a2008-06-02 01:18:21 +000043
Chris Lattner173234a2008-06-02 01:18:21 +000044/// ComputeMaskedBits - Determine which of the bits specified in Mask are
45/// known to be either zero or one and return them in the KnownZero/KnownOne
46/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
47/// processing.
48/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
49/// we cannot optimize based on the assumption that it is zero without changing
50/// it to be an explicit zero. If we don't change it to zero, other code could
51/// optimized based on the contradictory assumption that it is non-zero.
52/// Because instcombine aggressively folds operations with undef args anyway,
53/// this won't lose us code quality.
Chris Lattnercf5128e2009-09-08 00:06:16 +000054///
55/// This function is defined on values with integer type, values with pointer
56/// type (but only if TD is non-null), and vectors of integers. In the case
57/// where V is a vector, the mask, known zero, and known one values are the
58/// same width as the vector element, and the bit is set only if it is true
59/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +000060void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
61 APInt &KnownZero, APInt &KnownOne,
Dan Gohman846a2f22009-08-27 17:51:25 +000062 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +000063 assert(V && "No Value?");
Dan Gohman9004c8a2009-05-21 02:28:33 +000064 assert(Depth <= MaxDepth && "Limit Search Depth");
Chris Lattner79abedb2009-01-20 18:22:57 +000065 unsigned BitWidth = Mask.getBitWidth();
Nadav Rotem16087692011-12-05 06:29:09 +000066 assert((V->getType()->isIntOrIntVectorTy() ||
67 V->getType()->getScalarType()->isPointerTy()) &&
68 "Not integer or pointer type!");
Dan Gohman6de29f82009-06-15 22:12:54 +000069 assert((!TD ||
70 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000071 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman6de29f82009-06-15 22:12:54 +000072 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem16087692011-12-05 06:29:09 +000073 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner173234a2008-06-02 01:18:21 +000074 KnownOne.getBitWidth() == BitWidth &&
75 "V, Mask, KnownOne and KnownZero should have same BitWidth");
76
77 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
78 // We know all of the bits for a constant!
79 KnownOne = CI->getValue() & Mask;
80 KnownZero = ~KnownOne & Mask;
81 return;
82 }
Dan Gohman6de29f82009-06-15 22:12:54 +000083 // Null and aggregate-zero are all-zeros.
84 if (isa<ConstantPointerNull>(V) ||
85 isa<ConstantAggregateZero>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000086 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +000087 KnownZero = Mask;
88 return;
89 }
Dan Gohman6de29f82009-06-15 22:12:54 +000090 // Handle a constant vector by taking the intersection of the known bits of
91 // each element.
92 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
Jay Foad7a874dd2010-12-01 08:53:58 +000093 KnownZero.setAllBits(); KnownOne.setAllBits();
Dan Gohman6de29f82009-06-15 22:12:54 +000094 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
95 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
96 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
97 TD, Depth);
98 KnownZero &= KnownZero2;
99 KnownOne &= KnownOne2;
100 }
101 return;
102 }
Chris Lattnerdf390282012-01-24 07:54:10 +0000103 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
104 // We know that CDS must be a vector of integers. Take the intersection of
105 // each element.
106 KnownZero.setAllBits(); KnownOne.setAllBits();
107 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner0f193b82012-01-25 01:27:20 +0000108 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerdf390282012-01-24 07:54:10 +0000109 Elt = CDS->getElementAsInteger(i);
110 KnownZero &= ~Elt;
111 KnownOne &= Elt;
112 }
113 return;
114 }
115
Chris Lattner173234a2008-06-02 01:18:21 +0000116 // The address of an aligned GlobalValue has trailing zeros.
117 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
118 unsigned Align = GV->getAlignment();
Dan Gohman00407252009-08-11 15:50:03 +0000119 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000120 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
121 Type *ObjectType = GVar->getType()->getElementType();
122 // If the object is defined in the current Module, we'll be giving
123 // it the preferred alignment. Otherwise, we have to assume that it
124 // may only have the minimum ABI alignment.
Duncan Sandsd3a38cc2011-11-29 18:26:38 +0000125 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000126 Align = TD->getPreferredAlignment(GVar);
127 else
128 Align = TD->getABITypeAlignment(ObjectType);
129 }
Dan Gohman00407252009-08-11 15:50:03 +0000130 }
Chris Lattner173234a2008-06-02 01:18:21 +0000131 if (Align > 0)
132 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
133 CountTrailingZeros_32(Align));
134 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000135 KnownZero.clearAllBits();
136 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000137 return;
138 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000139 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
140 // the bits of its aliasee.
141 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
142 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000143 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000144 } else {
145 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
146 TD, Depth+1);
147 }
148 return;
149 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000150
151 if (Argument *A = dyn_cast<Argument>(V)) {
152 // Get alignment information off byval arguments if specified in the IR.
153 if (A->hasByValAttr())
154 if (unsigned Align = A->getParamAlignment())
155 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
156 CountTrailingZeros_32(Align));
157 return;
158 }
Chris Lattner173234a2008-06-02 01:18:21 +0000159
Chris Lattnerb3f06732011-05-23 00:03:39 +0000160 // Start out not knowing anything.
161 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000162
Dan Gohman9004c8a2009-05-21 02:28:33 +0000163 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000164 return; // Limit search depth.
165
Dan Gohmanca178902009-07-17 20:47:02 +0000166 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000167 if (!I) return;
168
169 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000170 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000171 default: break;
172 case Instruction::And: {
173 // If either the LHS or the RHS are Zero, the result is zero.
174 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
175 APInt Mask2(Mask & ~KnownZero);
176 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
177 Depth+1);
178 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
179 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
180
181 // Output known-1 bits are only known if set in both the LHS & RHS.
182 KnownOne &= KnownOne2;
183 // Output known-0 are known to be clear if zero in either the LHS | RHS.
184 KnownZero |= KnownZero2;
185 return;
186 }
187 case Instruction::Or: {
188 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
189 APInt Mask2(Mask & ~KnownOne);
190 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
191 Depth+1);
192 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
193 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
194
195 // Output known-0 bits are only known if clear in both the LHS & RHS.
196 KnownZero &= KnownZero2;
197 // Output known-1 are known to be set if set in either the LHS | RHS.
198 KnownOne |= KnownOne2;
199 return;
200 }
201 case Instruction::Xor: {
202 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
203 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
204 Depth+1);
205 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
206 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
207
208 // Output known-0 bits are known if clear or set in both the LHS & RHS.
209 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
210 // Output known-1 are known to be set if set in only one of the LHS, RHS.
211 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
212 KnownZero = KnownZeroOut;
213 return;
214 }
215 case Instruction::Mul: {
216 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
217 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
218 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
219 Depth+1);
Duncan Sands32a43cc2011-10-27 19:16:21 +0000220 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
221 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
222
223 bool isKnownNegative = false;
224 bool isKnownNonNegative = false;
225 // If the multiplication is known not to overflow, compute the sign bit.
226 if (Mask.isNegative() &&
227 cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) {
228 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
229 if (Op1 == Op2) {
230 // The product of a number with itself is non-negative.
231 isKnownNonNegative = true;
232 } else {
233 bool isKnownNonNegative1 = KnownZero.isNegative();
234 bool isKnownNonNegative2 = KnownZero2.isNegative();
235 bool isKnownNegative1 = KnownOne.isNegative();
236 bool isKnownNegative2 = KnownOne2.isNegative();
237 // The product of two numbers with the same sign is non-negative.
238 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
239 (isKnownNonNegative1 && isKnownNonNegative2);
240 // The product of a negative number and a non-negative number is either
241 // negative or zero.
242 if (!isKnownNonNegative)
243 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
244 isKnownNonZero(Op2, TD, Depth)) ||
245 (isKnownNegative2 && isKnownNonNegative1 &&
246 isKnownNonZero(Op1, TD, Depth));
247 }
248 }
249
Chris Lattner173234a2008-06-02 01:18:21 +0000250 // If low bits are zero in either operand, output low known-0 bits.
251 // Also compute a conserative estimate for high known-0 bits.
252 // More trickiness is possible, but this is sufficient for the
253 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000254 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000255 unsigned TrailZ = KnownZero.countTrailingOnes() +
256 KnownZero2.countTrailingOnes();
257 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
258 KnownZero2.countLeadingOnes(),
259 BitWidth) - BitWidth;
260
261 TrailZ = std::min(TrailZ, BitWidth);
262 LeadZ = std::min(LeadZ, BitWidth);
263 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
264 APInt::getHighBitsSet(BitWidth, LeadZ);
265 KnownZero &= Mask;
Duncan Sands32a43cc2011-10-27 19:16:21 +0000266
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000267 // Only make use of no-wrap flags if we failed to compute the sign bit
268 // directly. This matters if the multiplication always overflows, in
269 // which case we prefer to follow the result of the direct computation,
270 // though as the program is invoking undefined behaviour we can choose
271 // whatever we like here.
272 if (isKnownNonNegative && !KnownOne.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000273 KnownZero.setBit(BitWidth - 1);
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000274 else if (isKnownNegative && !KnownZero.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000275 KnownOne.setBit(BitWidth - 1);
276
Chris Lattner173234a2008-06-02 01:18:21 +0000277 return;
278 }
279 case Instruction::UDiv: {
280 // For the purposes of computing leading zeros we can conservatively
281 // treat a udiv as a logical right shift by the power of 2 known to
282 // be less than the denominator.
283 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
284 ComputeMaskedBits(I->getOperand(0),
285 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
286 unsigned LeadZ = KnownZero2.countLeadingOnes();
287
Jay Foad7a874dd2010-12-01 08:53:58 +0000288 KnownOne2.clearAllBits();
289 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000290 ComputeMaskedBits(I->getOperand(1),
291 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
292 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
293 if (RHSUnknownLeadingOnes != BitWidth)
294 LeadZ = std::min(BitWidth,
295 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
296
297 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
298 return;
299 }
300 case Instruction::Select:
301 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
302 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
303 Depth+1);
304 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
305 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
306
307 // Only known if known in both the LHS and RHS.
308 KnownOne &= KnownOne2;
309 KnownZero &= KnownZero2;
310 return;
311 case Instruction::FPTrunc:
312 case Instruction::FPExt:
313 case Instruction::FPToUI:
314 case Instruction::FPToSI:
315 case Instruction::SIToFP:
316 case Instruction::UIToFP:
317 return; // Can't work with floating point.
318 case Instruction::PtrToInt:
319 case Instruction::IntToPtr:
320 // We can't handle these if we don't know the pointer size.
321 if (!TD) return;
322 // FALL THROUGH and handle them the same as zext/trunc.
323 case Instruction::ZExt:
324 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000325 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000326
327 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000328 // Note that we handle pointer operands here because of inttoptr/ptrtoint
329 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000330 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000331 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
332 else
333 SrcBitWidth = SrcTy->getScalarSizeInBits();
334
Jay Foad40f8f622010-12-07 08:25:19 +0000335 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
336 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
337 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000338 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
339 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000340 KnownZero = KnownZero.zextOrTrunc(BitWidth);
341 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000342 // Any top bits are known to be zero.
343 if (BitWidth > SrcBitWidth)
344 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
345 return;
346 }
347 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000348 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000349 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000350 // TODO: For now, not handling conversions like:
351 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000352 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000353 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
354 Depth+1);
355 return;
356 }
357 break;
358 }
359 case Instruction::SExt: {
360 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000361 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000362
Jay Foad40f8f622010-12-07 08:25:19 +0000363 APInt MaskIn = Mask.trunc(SrcBitWidth);
364 KnownZero = KnownZero.trunc(SrcBitWidth);
365 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000366 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
367 Depth+1);
368 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000369 KnownZero = KnownZero.zext(BitWidth);
370 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000371
372 // If the sign bit of the input is known set or clear, then we know the
373 // top bits of the result.
374 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
375 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
376 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
377 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
378 return;
379 }
380 case Instruction::Shl:
381 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
382 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
383 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
384 APInt Mask2(Mask.lshr(ShiftAmt));
385 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
386 Depth+1);
387 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
388 KnownZero <<= ShiftAmt;
389 KnownOne <<= ShiftAmt;
390 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
391 return;
392 }
393 break;
394 case Instruction::LShr:
395 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
396 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
397 // Compute the new bits that are at the top now.
398 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
399
400 // Unsigned shift right.
401 APInt Mask2(Mask.shl(ShiftAmt));
402 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
403 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000404 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000405 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
406 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
407 // high bits known zero.
408 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
409 return;
410 }
411 break;
412 case Instruction::AShr:
413 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
414 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
415 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000416 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000417
418 // Signed shift right.
419 APInt Mask2(Mask.shl(ShiftAmt));
420 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
421 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000422 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000423 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
424 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
425
426 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
427 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
428 KnownZero |= HighBits;
429 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
430 KnownOne |= HighBits;
431 return;
432 }
433 break;
434 case Instruction::Sub: {
435 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
436 // We know that the top bits of C-X are clear if X contains less bits
437 // than C (i.e. no wrap-around can happen). For example, 20-X is
438 // positive if we can prove that X is >= 0 and < 16.
439 if (!CLHS->getValue().isNegative()) {
440 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
441 // NLZ can't be BitWidth with no sign bit
442 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
443 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
444 TD, Depth+1);
445
446 // If all of the MaskV bits are known to be zero, then we know the
447 // output top bits are zero, because we now know that the output is
448 // from [0-C].
449 if ((KnownZero2 & MaskV) == MaskV) {
450 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
451 // Top bits known zero.
452 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
453 }
454 }
455 }
456 }
457 // fall through
458 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000459 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000460 // other operand has in those bit positions will be preserved in the
461 // result. For an add, this works with either operand. For a subtract,
462 // this only works if the known zeros are in the right operand.
463 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
464 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
465 BitWidth - Mask.countLeadingZeros());
466 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000467 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000468 assert((LHSKnownZero & LHSKnownOne) == 0 &&
469 "Bits known to be one AND zero?");
470 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000471
472 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
473 Depth+1);
474 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000475 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000476
Dan Gohman39250432009-05-24 18:02:35 +0000477 // Determine which operand has more trailing zeros, and use that
478 // many bits from the other operand.
479 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000480 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000481 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
482 KnownZero |= KnownZero2 & Mask;
483 KnownOne |= KnownOne2 & Mask;
484 } else {
485 // If the known zeros are in the left operand for a subtract,
486 // fall back to the minimum known zeros in both operands.
487 KnownZero |= APInt::getLowBitsSet(BitWidth,
488 std::min(LHSKnownZeroOut,
489 RHSKnownZeroOut));
490 }
491 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
492 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
493 KnownZero |= LHSKnownZero & Mask;
494 KnownOne |= LHSKnownOne & Mask;
495 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000496
497 // Are we still trying to solve for the sign bit?
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000498 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000499 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
500 if (OBO->hasNoSignedWrap()) {
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000501 if (I->getOpcode() == Instruction::Add) {
502 // Adding two positive numbers can't wrap into negative
503 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
504 KnownZero |= APInt::getSignBit(BitWidth);
505 // and adding two negative numbers can't wrap into positive.
506 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
507 KnownOne |= APInt::getSignBit(BitWidth);
508 } else {
509 // Subtracting a negative number from a positive one can't wrap
510 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
511 KnownZero |= APInt::getSignBit(BitWidth);
512 // neither can subtracting a positive number from a negative one.
513 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
514 KnownOne |= APInt::getSignBit(BitWidth);
515 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000516 }
517 }
518
Chris Lattner173234a2008-06-02 01:18:21 +0000519 return;
520 }
521 case Instruction::SRem:
522 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000523 APInt RA = Rem->getValue().abs();
524 if (RA.isPowerOf2()) {
525 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000526 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
527 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
528 Depth+1);
529
Duncan Sandscfd54182010-01-29 06:18:37 +0000530 // The low bits of the first operand are unchanged by the srem.
531 KnownZero = KnownZero2 & LowBits;
532 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000533
Duncan Sandscfd54182010-01-29 06:18:37 +0000534 // If the first operand is non-negative or has all low bits zero, then
535 // the upper bits are all zero.
536 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
537 KnownZero |= ~LowBits;
538
539 // If the first operand is negative and not all low bits are zero, then
540 // the upper bits are all one.
541 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
542 KnownOne |= ~LowBits;
543
544 KnownZero &= Mask;
545 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000546
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000547 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000548 }
549 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000550
551 // The sign bit is the LHS's sign bit, except when the result of the
552 // remainder is zero.
553 if (Mask.isNegative() && KnownZero.isNonNegative()) {
554 APInt Mask2 = APInt::getSignBit(BitWidth);
555 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
556 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
557 Depth+1);
558 // If it's known zero, our sign bit is also zero.
559 if (LHSKnownZero.isNegative())
560 KnownZero |= LHSKnownZero;
561 }
562
Chris Lattner173234a2008-06-02 01:18:21 +0000563 break;
564 case Instruction::URem: {
565 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
566 APInt RA = Rem->getValue();
567 if (RA.isPowerOf2()) {
568 APInt LowBits = (RA - 1);
569 APInt Mask2 = LowBits & Mask;
570 KnownZero |= ~LowBits & Mask;
571 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
572 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000573 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000574 break;
575 }
576 }
577
578 // Since the result is less than or equal to either operand, any leading
579 // zero bits in either operand must also exist in the result.
580 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
581 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
582 TD, Depth+1);
583 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
584 TD, Depth+1);
585
Chris Lattner79abedb2009-01-20 18:22:57 +0000586 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000587 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000588 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000589 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
590 break;
591 }
592
Victor Hernandeza276c602009-10-17 01:18:07 +0000593 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000594 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000595 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000596 if (Align == 0 && TD)
597 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000598
599 if (Align > 0)
600 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
601 CountTrailingZeros_32(Align));
602 break;
603 }
604 case Instruction::GetElementPtr: {
605 // Analyze all of the subscripts of this getelementptr instruction
606 // to determine if we can prove known low zero bits.
607 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
608 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
609 ComputeMaskedBits(I->getOperand(0), LocalMask,
610 LocalKnownZero, LocalKnownOne, TD, Depth+1);
611 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
612
613 gep_type_iterator GTI = gep_type_begin(I);
614 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
615 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000616 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000617 // Handle struct member offset arithmetic.
618 if (!TD) return;
619 const StructLayout *SL = TD->getStructLayout(STy);
620 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
621 uint64_t Offset = SL->getElementOffset(Idx);
622 TrailZ = std::min(TrailZ,
623 CountTrailingZeros_64(Offset));
624 } else {
625 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000626 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000627 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000628 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000629 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000630 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
631 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
632 ComputeMaskedBits(Index, LocalMask,
633 LocalKnownZero, LocalKnownOne, TD, Depth+1);
634 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000635 unsigned(CountTrailingZeros_64(TypeSize) +
636 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000637 }
638 }
639
640 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
641 break;
642 }
643 case Instruction::PHI: {
644 PHINode *P = cast<PHINode>(I);
645 // Handle the case of a simple two-predecessor recurrence PHI.
646 // There's a lot more that could theoretically be done here, but
647 // this is sufficient to catch some interesting cases.
648 if (P->getNumIncomingValues() == 2) {
649 for (unsigned i = 0; i != 2; ++i) {
650 Value *L = P->getIncomingValue(i);
651 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000652 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000653 if (!LU)
654 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000655 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000656 // Check for operations that have the property that if
657 // both their operands have low zero bits, the result
658 // will have low zero bits.
659 if (Opcode == Instruction::Add ||
660 Opcode == Instruction::Sub ||
661 Opcode == Instruction::And ||
662 Opcode == Instruction::Or ||
663 Opcode == Instruction::Mul) {
664 Value *LL = LU->getOperand(0);
665 Value *LR = LU->getOperand(1);
666 // Find a recurrence.
667 if (LL == I)
668 L = LR;
669 else if (LR == I)
670 L = LL;
671 else
672 break;
673 // Ok, we have a PHI of the form L op= R. Check for low
674 // zero bits.
675 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
676 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
677 Mask2 = APInt::getLowBitsSet(BitWidth,
678 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000679
680 // We need to take the minimum number of known bits
681 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
682 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
683
Chris Lattner173234a2008-06-02 01:18:21 +0000684 KnownZero = Mask &
685 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000686 std::min(KnownZero2.countTrailingOnes(),
687 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000688 break;
689 }
690 }
691 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000692
Nick Lewycky3b739d22011-02-10 23:54:10 +0000693 // Unreachable blocks may have zero-operand PHI nodes.
694 if (P->getNumIncomingValues() == 0)
695 return;
696
Dan Gohman9004c8a2009-05-21 02:28:33 +0000697 // Otherwise take the unions of the known bit sets of the operands,
698 // taking conservative care to avoid excessive recursion.
699 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000700 // Skip if every incoming value references to ourself.
701 if (P->hasConstantValue() == P)
702 break;
703
Dan Gohman9004c8a2009-05-21 02:28:33 +0000704 KnownZero = APInt::getAllOnesValue(BitWidth);
705 KnownOne = APInt::getAllOnesValue(BitWidth);
706 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
707 // Skip direct self references.
708 if (P->getIncomingValue(i) == P) continue;
709
710 KnownZero2 = APInt(BitWidth, 0);
711 KnownOne2 = APInt(BitWidth, 0);
712 // Recurse, but cap the recursion to one level, because we don't
713 // want to waste time spinning around in loops.
714 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
715 KnownZero2, KnownOne2, TD, MaxDepth-1);
716 KnownZero &= KnownZero2;
717 KnownOne &= KnownOne2;
718 // If all bits have been ruled out, there's no need to check
719 // more operands.
720 if (!KnownZero && !KnownOne)
721 break;
722 }
723 }
Chris Lattner173234a2008-06-02 01:18:21 +0000724 break;
725 }
726 case Instruction::Call:
727 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
728 switch (II->getIntrinsicID()) {
729 default: break;
Chris Lattner173234a2008-06-02 01:18:21 +0000730 case Intrinsic::ctlz:
731 case Intrinsic::cttz: {
732 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer009da052011-12-24 17:31:46 +0000733 // If this call is undefined for 0, the result will be less than 2^n.
734 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
735 LowBits -= 1;
736 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
737 break;
738 }
739 case Intrinsic::ctpop: {
740 unsigned LowBits = Log2_32(BitWidth)+1;
Chris Lattner173234a2008-06-02 01:18:21 +0000741 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
742 break;
743 }
Chad Rosier62660312011-05-26 23:13:19 +0000744 case Intrinsic::x86_sse42_crc32_64_8:
745 case Intrinsic::x86_sse42_crc32_64_64:
Evan Chengcb559c12011-05-22 18:25:30 +0000746 KnownZero = APInt::getHighBitsSet(64, 32);
747 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000748 }
749 }
750 break;
751 }
752}
753
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000754/// ComputeSignBit - Determine whether the sign bit is known to be zero or
755/// one. Convenience wrapper around ComputeMaskedBits.
756void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
757 const TargetData *TD, unsigned Depth) {
758 unsigned BitWidth = getBitWidth(V->getType(), TD);
759 if (!BitWidth) {
760 KnownZero = false;
761 KnownOne = false;
762 return;
763 }
764 APInt ZeroBits(BitWidth, 0);
765 APInt OneBits(BitWidth, 0);
766 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
767 Depth);
768 KnownOne = OneBits[BitWidth - 1];
769 KnownZero = ZeroBits[BitWidth - 1];
770}
771
772/// isPowerOfTwo - Return true if the given value is known to have exactly one
773/// bit set when defined. For vectors return true if every element is known to
774/// be a power of two when defined. Supports values with integer or pointer
775/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000776bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
777 unsigned Depth) {
778 if (Constant *C = dyn_cast<Constant>(V)) {
779 if (C->isNullValue())
780 return OrZero;
781 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
782 return CI->getValue().isPowerOf2();
783 // TODO: Handle vector constants.
784 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000785
786 // 1 << X is clearly a power of two if the one is not shifted off the end. If
787 // it is shifted off the end then the result is undefined.
788 if (match(V, m_Shl(m_One(), m_Value())))
789 return true;
790
791 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
792 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000793 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000794 return true;
795
796 // The remaining tests are all recursive, so bail out if we hit the limit.
797 if (Depth++ == MaxDepth)
798 return false;
799
Duncan Sands4604fc72011-10-28 18:30:05 +0000800 Value *X = 0, *Y = 0;
801 // A shift of a power of two is a power of two or zero.
802 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
803 match(V, m_Shr(m_Value(X), m_Value()))))
804 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
805
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000806 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000807 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000808
809 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000810 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
811 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
812
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000813 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
814 // A power of two and'd with anything is a power of two or zero.
815 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
816 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
817 return true;
818 // X & (-X) is always a power of two or zero.
819 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
820 return true;
821 return false;
822 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000823
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000824 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000825 // is a power of two only if the first operand is a power of two and not
826 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000827 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
828 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
829 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000830 }
831
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000832 return false;
833}
834
835/// isKnownNonZero - Return true if the given value is known to be non-zero
836/// when defined. For vectors return true if every element is known to be
837/// non-zero when defined. Supports values with integer or pointer type and
838/// vectors of integers.
839bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
840 if (Constant *C = dyn_cast<Constant>(V)) {
841 if (C->isNullValue())
842 return false;
843 if (isa<ConstantInt>(C))
844 // Must be non-zero due to null test above.
845 return true;
846 // TODO: Handle vectors
847 return false;
848 }
849
850 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000851 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000852 return false;
853
854 unsigned BitWidth = getBitWidth(V->getType(), TD);
855
856 // X | Y != 0 if X != 0 or Y != 0.
857 Value *X = 0, *Y = 0;
858 if (match(V, m_Or(m_Value(X), m_Value(Y))))
859 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
860
861 // ext X != 0 if X != 0.
862 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
863 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
864
Duncan Sands91367822011-01-29 13:27:00 +0000865 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000866 // if the lowest bit is shifted off the end.
867 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000868 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000869 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000870 if (BO->hasNoUnsignedWrap())
871 return isKnownNonZero(X, TD, Depth);
872
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000873 APInt KnownZero(BitWidth, 0);
874 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000875 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000876 if (KnownOne[0])
877 return true;
878 }
Duncan Sands91367822011-01-29 13:27:00 +0000879 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000880 // defined if the sign bit is shifted off the end.
881 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000882 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000883 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000884 if (BO->isExact())
885 return isKnownNonZero(X, TD, Depth);
886
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000887 bool XKnownNonNegative, XKnownNegative;
888 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
889 if (XKnownNegative)
890 return true;
891 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000892 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000893 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
894 return isKnownNonZero(X, TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000895 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000896 // X + Y.
897 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
898 bool XKnownNonNegative, XKnownNegative;
899 bool YKnownNonNegative, YKnownNegative;
900 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
901 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
902
903 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000904 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000905 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000906 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
907 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000908
909 // If X and Y are both negative (as signed values) then their sum is not
910 // zero unless both X and Y equal INT_MIN.
911 if (BitWidth && XKnownNegative && YKnownNegative) {
912 APInt KnownZero(BitWidth, 0);
913 APInt KnownOne(BitWidth, 0);
914 APInt Mask = APInt::getSignedMaxValue(BitWidth);
915 // The sign bit of X is set. If some other bit is set then X is not equal
916 // to INT_MIN.
917 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
918 if ((KnownOne & Mask) != 0)
919 return true;
920 // The sign bit of Y is set. If some other bit is set then Y is not equal
921 // to INT_MIN.
922 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
923 if ((KnownOne & Mask) != 0)
924 return true;
925 }
926
927 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000928 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000929 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000930 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000931 return true;
932 }
Duncan Sands32a43cc2011-10-27 19:16:21 +0000933 // X * Y.
934 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
935 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
936 // If X and Y are non-zero then so is X * Y as long as the multiplication
937 // does not overflow.
938 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
939 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
940 return true;
941 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000942 // (C ? X : Y) != 0 if X != 0 and Y != 0.
943 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
944 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
945 isKnownNonZero(SI->getFalseValue(), TD, Depth))
946 return true;
947 }
948
949 if (!BitWidth) return false;
950 APInt KnownZero(BitWidth, 0);
951 APInt KnownOne(BitWidth, 0);
952 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
953 TD, Depth);
954 return KnownOne != 0;
955}
956
Chris Lattner173234a2008-06-02 01:18:21 +0000957/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
958/// this predicate to simplify operations downstream. Mask is known to be zero
959/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000960///
961/// This function is defined on values with integer type, values with pointer
962/// type (but only if TD is non-null), and vectors of integers. In the case
963/// where V is a vector, the mask, known zero, and known one values are the
964/// same width as the vector element, and the bit is set only if it is true
965/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000966bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000967 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000968 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
969 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
970 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
971 return (KnownZero & Mask) == Mask;
972}
973
974
975
976/// ComputeNumSignBits - Return the number of times the sign bit of the
977/// register is replicated into the other bits. We know that at least 1 bit
978/// is always equal to the sign bit (itself), but other cases can give us
979/// information. For example, immediately after an "ashr X, 2", we know that
980/// the top 3 bits are all equal to each other, so we return 3.
981///
982/// 'Op' must have a scalar integer type.
983///
Dan Gohman846a2f22009-08-27 17:51:25 +0000984unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
985 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000986 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000987 "ComputeNumSignBits requires a TargetData object to operate "
988 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000989 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000990 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
991 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000992 unsigned Tmp, Tmp2;
993 unsigned FirstAnswer = 1;
994
Chris Lattnerd82e5112008-06-02 18:39:07 +0000995 // Note that ConstantInt is handled by the general ComputeMaskedBits case
996 // below.
997
Chris Lattner173234a2008-06-02 01:18:21 +0000998 if (Depth == 6)
999 return 1; // Limit search depth.
1000
Dan Gohmanca178902009-07-17 20:47:02 +00001001 Operator *U = dyn_cast<Operator>(V);
1002 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +00001003 default: break;
1004 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +00001005 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +00001006 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
1007
1008 case Instruction::AShr:
1009 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1010 // ashr X, C -> adds C sign bits.
1011 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
1012 Tmp += C->getZExtValue();
1013 if (Tmp > TyBits) Tmp = TyBits;
1014 }
Nate Begeman9a3dc552010-12-17 23:12:19 +00001015 // vector ashr X, <C, C, C, C> -> adds C sign bits
1016 if (ConstantVector *C = dyn_cast<ConstantVector>(U->getOperand(1))) {
1017 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
1018 Tmp += CI->getZExtValue();
1019 if (Tmp > TyBits) Tmp = TyBits;
1020 }
1021 }
Chris Lattner173234a2008-06-02 01:18:21 +00001022 return Tmp;
1023 case Instruction::Shl:
1024 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
1025 // shl destroys sign bits.
1026 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1027 if (C->getZExtValue() >= TyBits || // Bad shift.
1028 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1029 return Tmp - C->getZExtValue();
1030 }
1031 break;
1032 case Instruction::And:
1033 case Instruction::Or:
1034 case Instruction::Xor: // NOT is handled here.
1035 // Logical binary ops preserve the number of sign bits at the worst.
1036 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1037 if (Tmp != 1) {
1038 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1039 FirstAnswer = std::min(Tmp, Tmp2);
1040 // We computed what we know about the sign bits as our first
1041 // answer. Now proceed to the generic code that uses
1042 // ComputeMaskedBits, and pick whichever answer is better.
1043 }
1044 break;
1045
1046 case Instruction::Select:
1047 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1048 if (Tmp == 1) return 1; // Early out.
1049 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1050 return std::min(Tmp, Tmp2);
1051
1052 case Instruction::Add:
1053 // Add can have at most one carry bit. Thus we know that the output
1054 // is, at worst, one more bit than the inputs.
1055 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1056 if (Tmp == 1) return 1; // Early out.
1057
1058 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001059 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001060 if (CRHS->isAllOnesValue()) {
1061 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1062 APInt Mask = APInt::getAllOnesValue(TyBits);
1063 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1064 Depth+1);
1065
1066 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1067 // sign bits set.
1068 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1069 return TyBits;
1070
1071 // If we are subtracting one from a positive number, there is no carry
1072 // out of the result.
1073 if (KnownZero.isNegative())
1074 return Tmp;
1075 }
1076
1077 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1078 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001079 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001080
1081 case Instruction::Sub:
1082 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1083 if (Tmp2 == 1) return 1;
1084
1085 // Handle NEG.
1086 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1087 if (CLHS->isNullValue()) {
1088 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1089 APInt Mask = APInt::getAllOnesValue(TyBits);
1090 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1091 TD, Depth+1);
1092 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1093 // sign bits set.
1094 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1095 return TyBits;
1096
1097 // If the input is known to be positive (the sign bit is known clear),
1098 // the output of the NEG has the same number of sign bits as the input.
1099 if (KnownZero.isNegative())
1100 return Tmp2;
1101
1102 // Otherwise, we treat this like a SUB.
1103 }
1104
1105 // Sub can have at most one carry bit. Thus we know that the output
1106 // is, at worst, one more bit than the inputs.
1107 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1108 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001109 return std::min(Tmp, Tmp2)-1;
1110
1111 case Instruction::PHI: {
1112 PHINode *PN = cast<PHINode>(U);
1113 // Don't analyze large in-degree PHIs.
1114 if (PN->getNumIncomingValues() > 4) break;
1115
1116 // Take the minimum of all incoming values. This can't infinitely loop
1117 // because of our depth threshold.
1118 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1119 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1120 if (Tmp == 1) return Tmp;
1121 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001122 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001123 }
1124 return Tmp;
1125 }
1126
Chris Lattner173234a2008-06-02 01:18:21 +00001127 case Instruction::Trunc:
1128 // FIXME: it's tricky to do anything useful for this, but it is an important
1129 // case for targets like X86.
1130 break;
1131 }
1132
1133 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1134 // use this information.
1135 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1136 APInt Mask = APInt::getAllOnesValue(TyBits);
1137 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1138
1139 if (KnownZero.isNegative()) { // sign bit is 0
1140 Mask = KnownZero;
1141 } else if (KnownOne.isNegative()) { // sign bit is 1;
1142 Mask = KnownOne;
1143 } else {
1144 // Nothing known.
1145 return FirstAnswer;
1146 }
1147
1148 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1149 // the number of identical bits in the top of the input value.
1150 Mask = ~Mask;
1151 Mask <<= Mask.getBitWidth()-TyBits;
1152 // Return # leading zeros. We use 'min' here in case Val was zero before
1153 // shifting. We don't want to return '64' as for an i32 "0".
1154 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1155}
Chris Lattner833f25d2008-06-02 01:29:46 +00001156
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001157/// ComputeMultiple - This function computes the integer multiple of Base that
1158/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001159/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001160/// through SExt instructions only if LookThroughSExt is true.
1161bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001162 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001163 const unsigned MaxDepth = 6;
1164
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001165 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001166 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001167 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001168
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001169 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001170
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001171 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001172
1173 if (Base == 0)
1174 return false;
1175
1176 if (Base == 1) {
1177 Multiple = V;
1178 return true;
1179 }
1180
1181 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1182 Constant *BaseVal = ConstantInt::get(T, Base);
1183 if (CO && CO == BaseVal) {
1184 // Multiple is 1.
1185 Multiple = ConstantInt::get(T, 1);
1186 return true;
1187 }
1188
1189 if (CI && CI->getZExtValue() % Base == 0) {
1190 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1191 return true;
1192 }
1193
1194 if (Depth == MaxDepth) return false; // Limit search depth.
1195
1196 Operator *I = dyn_cast<Operator>(V);
1197 if (!I) return false;
1198
1199 switch (I->getOpcode()) {
1200 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001201 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001202 if (!LookThroughSExt) return false;
1203 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001204 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001205 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1206 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001207 case Instruction::Shl:
1208 case Instruction::Mul: {
1209 Value *Op0 = I->getOperand(0);
1210 Value *Op1 = I->getOperand(1);
1211
1212 if (I->getOpcode() == Instruction::Shl) {
1213 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1214 if (!Op1CI) return false;
1215 // Turn Op0 << Op1 into Op0 * 2^Op1
1216 APInt Op1Int = Op1CI->getValue();
1217 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001218 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001219 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001220 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001221 }
1222
1223 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001224 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1225 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1226 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1227 if (Op1C->getType()->getPrimitiveSizeInBits() <
1228 MulC->getType()->getPrimitiveSizeInBits())
1229 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1230 if (Op1C->getType()->getPrimitiveSizeInBits() >
1231 MulC->getType()->getPrimitiveSizeInBits())
1232 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1233
1234 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1235 Multiple = ConstantExpr::getMul(MulC, Op1C);
1236 return true;
1237 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001238
1239 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1240 if (Mul0CI->getValue() == 1) {
1241 // V == Base * Op1, so return Op1
1242 Multiple = Op1;
1243 return true;
1244 }
1245 }
1246
Chris Lattnere9711312010-09-05 17:20:46 +00001247 Value *Mul1 = NULL;
1248 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1249 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1250 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1251 if (Op0C->getType()->getPrimitiveSizeInBits() <
1252 MulC->getType()->getPrimitiveSizeInBits())
1253 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1254 if (Op0C->getType()->getPrimitiveSizeInBits() >
1255 MulC->getType()->getPrimitiveSizeInBits())
1256 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1257
1258 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1259 Multiple = ConstantExpr::getMul(MulC, Op0C);
1260 return true;
1261 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001262
1263 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1264 if (Mul1CI->getValue() == 1) {
1265 // V == Base * Op0, so return Op0
1266 Multiple = Op0;
1267 return true;
1268 }
1269 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001270 }
1271 }
1272
1273 // We could not determine if V is a multiple of Base.
1274 return false;
1275}
1276
Chris Lattner833f25d2008-06-02 01:29:46 +00001277/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1278/// value is never equal to -0.0.
1279///
1280/// NOTE: this function will need to be revisited when we support non-default
1281/// rounding modes!
1282///
1283bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1284 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1285 return !CFP->getValueAPF().isNegZero();
1286
1287 if (Depth == 6)
1288 return 1; // Limit search depth.
1289
Dan Gohmanca178902009-07-17 20:47:02 +00001290 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001291 if (I == 0) return false;
1292
1293 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001294 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001295 isa<ConstantFP>(I->getOperand(1)) &&
1296 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1297 return true;
1298
1299 // sitofp and uitofp turn into +0.0 for zero.
1300 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1301 return true;
1302
1303 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1304 // sqrt(-0.0) = -0.0, no other negative results are possible.
1305 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001306 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001307
1308 if (const CallInst *CI = dyn_cast<CallInst>(I))
1309 if (const Function *F = CI->getCalledFunction()) {
1310 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001311 // abs(x) != -0.0
1312 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001313 // fabs[lf](x) != -0.0
1314 if (F->getName() == "fabs") return true;
1315 if (F->getName() == "fabsf") return true;
1316 if (F->getName() == "fabsl") return true;
1317 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1318 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001319 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001320 }
1321 }
1322
1323 return false;
1324}
1325
Chris Lattnerbb897102010-12-26 20:15:01 +00001326/// isBytewiseValue - If the specified value can be set by repeating the same
1327/// byte in memory, return the i8 value that it is represented with. This is
1328/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1329/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1330/// byte store (e.g. i16 0x1234), return null.
1331Value *llvm::isBytewiseValue(Value *V) {
1332 // All byte-wide stores are splatable, even of arbitrary variables.
1333 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001334
1335 // Handle 'null' ConstantArrayZero etc.
1336 if (Constant *C = dyn_cast<Constant>(V))
1337 if (C->isNullValue())
1338 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001339
1340 // Constant float and double values can be handled as integer values if the
1341 // corresponding integer value is "byteable". An important case is 0.0.
1342 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1343 if (CFP->getType()->isFloatTy())
1344 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1345 if (CFP->getType()->isDoubleTy())
1346 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1347 // Don't handle long double formats, which have strange constraints.
1348 }
1349
1350 // We can handle constant integers that are power of two in size and a
1351 // multiple of 8 bits.
1352 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1353 unsigned Width = CI->getBitWidth();
1354 if (isPowerOf2_32(Width) && Width > 8) {
1355 // We can handle this value if the recursive binary decomposition is the
1356 // same at all levels.
1357 APInt Val = CI->getValue();
1358 APInt Val2;
1359 while (Val.getBitWidth() != 8) {
1360 unsigned NextWidth = Val.getBitWidth()/2;
1361 Val2 = Val.lshr(NextWidth);
1362 Val2 = Val2.trunc(Val.getBitWidth()/2);
1363 Val = Val.trunc(Val.getBitWidth()/2);
1364
1365 // If the top/bottom halves aren't the same, reject it.
1366 if (Val != Val2)
1367 return 0;
1368 }
1369 return ConstantInt::get(V->getContext(), Val);
1370 }
1371 }
1372
1373 // A ConstantArray is splatable if all its members are equal and also
1374 // splatable.
1375 if (ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
1376 if (CA->getNumOperands() == 0)
1377 return 0;
1378
1379 Value *Val = isBytewiseValue(CA->getOperand(0));
1380 if (!Val)
1381 return 0;
1382
1383 for (unsigned I = 1, E = CA->getNumOperands(); I != E; ++I)
1384 if (CA->getOperand(I-1) != CA->getOperand(I))
1385 return 0;
1386
1387 return Val;
1388 }
Chad Rosierdce42b72011-12-06 00:19:08 +00001389
1390 // FIXME: Vector types (e.g., <4 x i32> <i32 -1, i32 -1, i32 -1, i32 -1>).
Chris Lattnerbb897102010-12-26 20:15:01 +00001391
1392 // Conceptually, we could handle things like:
1393 // %a = zext i8 %X to i16
1394 // %b = shl i16 %a, 8
1395 // %c = or i16 %a, %b
1396 // but until there is an example that actually needs this, it doesn't seem
1397 // worth worrying about.
1398 return 0;
1399}
1400
1401
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001402// This is the recursive version of BuildSubAggregate. It takes a few different
1403// arguments. Idxs is the index within the nested struct From that we are
1404// looking at now (which is of type IndexedType). IdxSkip is the number of
1405// indices from Idxs that should be left out when inserting into the resulting
1406// struct. To is the result struct built so far, new insertvalue instructions
1407// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001408static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001409 SmallVector<unsigned, 10> &Idxs,
1410 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001411 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001412 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001413 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001414 // Save the original To argument so we can modify it
1415 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001416 // General case, the type indexed by Idxs is a struct
1417 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1418 // Process each struct element recursively
1419 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001420 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001421 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001422 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001423 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001424 if (!To) {
1425 // Couldn't find any inserted value for this index? Cleanup
1426 while (PrevTo != OrigTo) {
1427 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1428 PrevTo = Del->getAggregateOperand();
1429 Del->eraseFromParent();
1430 }
1431 // Stop processing elements
1432 break;
1433 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001434 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001435 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001436 if (To)
1437 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001438 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001439 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1440 // the struct's elements had a value that was inserted directly. In the latter
1441 // case, perhaps we can't determine each of the subelements individually, but
1442 // we might be able to find the complete struct somewhere.
1443
1444 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001445 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001446
1447 if (!V)
1448 return NULL;
1449
1450 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001451 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001452 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001453}
1454
1455// This helper takes a nested struct and extracts a part of it (which is again a
1456// struct) into a new value. For example, given the struct:
1457// { a, { b, { c, d }, e } }
1458// and the indices "1, 1" this returns
1459// { c, d }.
1460//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001461// It does this by inserting an insertvalue for each element in the resulting
1462// struct, as opposed to just inserting a single struct. This will only work if
1463// each of the elements of the substruct are known (ie, inserted into From by an
1464// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001465//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001466// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001467static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001468 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001469 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001470 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001471 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001472 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001473 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001474 unsigned IdxSkip = Idxs.size();
1475
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001476 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001477}
1478
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001479/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1480/// the scalar value indexed is already around as a register, for example if it
1481/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001482///
1483/// If InsertBefore is not null, this function will duplicate (modified)
1484/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001485Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1486 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001487 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerdf390282012-01-24 07:54:10 +00001488 // recursion).
Jay Foadfc6d3a42011-07-13 10:26:04 +00001489 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001490 return V;
Chris Lattnerdf390282012-01-24 07:54:10 +00001491 // We have indices, so V should have an indexable type.
1492 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1493 "Not looking at a struct or array?");
1494 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1495 "Invalid indices for type?");
Owen Anderson76f600b2009-07-06 22:37:39 +00001496
Chris Lattnera1f00f42012-01-25 06:48:06 +00001497 if (Constant *C = dyn_cast<Constant>(V)) {
1498 C = C->getAggregateElement(idx_range[0]);
1499 if (C == 0) return 0;
1500 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1501 }
Chris Lattnerdf390282012-01-24 07:54:10 +00001502
1503 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001504 // Loop the indices for the insertvalue instruction in parallel with the
1505 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001506 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001507 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1508 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001509 if (req_idx == idx_range.end()) {
Chris Lattnerdf390282012-01-24 07:54:10 +00001510 // We can't handle this without inserting insertvalues
1511 if (!InsertBefore)
Matthijs Kooijman97728912008-06-16 13:28:31 +00001512 return 0;
Chris Lattnerdf390282012-01-24 07:54:10 +00001513
1514 // The requested index identifies a part of a nested aggregate. Handle
1515 // this specially. For example,
1516 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1517 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1518 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1519 // This can be changed into
1520 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1521 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1522 // which allows the unused 0,0 element from the nested struct to be
1523 // removed.
1524 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1525 InsertBefore);
Duncan Sands9954c762008-06-19 08:47:31 +00001526 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001527
1528 // This insert value inserts something else than what we are looking for.
1529 // See if the (aggregrate) value inserted into has the value we are
1530 // looking for, then.
1531 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001532 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001533 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001534 }
1535 // If we end up here, the indices of the insertvalue match with those
1536 // requested (though possibly only partially). Now we recursively look at
1537 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001538 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001539 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001540 InsertBefore);
Chris Lattnerdf390282012-01-24 07:54:10 +00001541 }
1542
1543 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001544 // If we're extracting a value from an aggregrate that was extracted from
1545 // something else, we can extract from that something else directly instead.
1546 // However, we will need to chain I's indices with the requested indices.
1547
1548 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001549 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001550 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001551 SmallVector<unsigned, 5> Idxs;
1552 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001553 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001554 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001555
1556 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001557 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001558
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001559 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001560 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001561
Jay Foadfc6d3a42011-07-13 10:26:04 +00001562 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001563 }
1564 // Otherwise, we don't know (such as, extracting from a function return value
1565 // or load instruction)
1566 return 0;
1567}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001568
Chris Lattnered58a6f2010-11-30 22:25:26 +00001569/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1570/// it can be expressed as a base pointer plus a constant offset. Return the
1571/// base and offset to the caller.
1572Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1573 const TargetData &TD) {
1574 Operator *PtrOp = dyn_cast<Operator>(Ptr);
Nadav Rotem16087692011-12-05 06:29:09 +00001575 if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1576 return Ptr;
Chris Lattnered58a6f2010-11-30 22:25:26 +00001577
1578 // Just look through bitcasts.
1579 if (PtrOp->getOpcode() == Instruction::BitCast)
1580 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1581
1582 // If this is a GEP with constant indices, we can look through it.
1583 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1584 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1585
1586 gep_type_iterator GTI = gep_type_begin(GEP);
1587 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1588 ++I, ++GTI) {
1589 ConstantInt *OpC = cast<ConstantInt>(*I);
1590 if (OpC->isZero()) continue;
1591
1592 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001593 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001594 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1595 } else {
1596 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1597 Offset += OpC->getSExtValue()*Size;
1598 }
1599 }
1600
1601 // Re-sign extend from the pointer size if needed to get overflow edge cases
1602 // right.
1603 unsigned PtrSize = TD.getPointerSizeInBits();
1604 if (PtrSize < 64)
1605 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1606
1607 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1608}
1609
1610
Evan Cheng0ff39b32008-06-30 07:31:25 +00001611/// GetConstantStringInfo - This function computes the length of a
1612/// null-terminated C string pointed to by V. If successful, it returns true
1613/// and returns the string in Str. If unsuccessful, it returns false.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001614bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001615 uint64_t Offset, bool StopAtNul) {
Bill Wendling0582ae92009-03-13 04:39:26 +00001616 // If V is NULL then return false;
1617 if (V == NULL) return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001618
1619 // Look through bitcast instructions.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001620 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Bill Wendling0582ae92009-03-13 04:39:26 +00001621 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul);
1622
Evan Cheng0ff39b32008-06-30 07:31:25 +00001623 // If the value is not a GEP instruction nor a constant expression with a
1624 // GEP instruction, then return false because ConstantArray can't occur
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001625 // any other way.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001626 const User *GEP = 0;
1627 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001628 GEP = GEPI;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001629 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001630 if (CE->getOpcode() == Instruction::BitCast)
Bill Wendling0582ae92009-03-13 04:39:26 +00001631 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul);
1632 if (CE->getOpcode() != Instruction::GetElementPtr)
1633 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001634 GEP = CE;
1635 }
1636
1637 if (GEP) {
1638 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001639 if (GEP->getNumOperands() != 3)
1640 return false;
1641
Evan Cheng0ff39b32008-06-30 07:31:25 +00001642 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001643 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1644 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001645 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001646 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001647
1648 // Check to make sure that the first operand of the GEP is an integer and
1649 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001650 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001651 if (FirstIdx == 0 || !FirstIdx->isZero())
1652 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001653
1654 // If the second index isn't a ConstantInt, then this is a variable index
1655 // into the array. If this occurs, we can't say anything meaningful about
1656 // the string.
1657 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001658 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001659 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001660 else
1661 return false;
1662 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
Evan Cheng0ff39b32008-06-30 07:31:25 +00001663 StopAtNul);
1664 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001665
Evan Cheng0ff39b32008-06-30 07:31:25 +00001666 // The GEP instruction, constant or instruction, must reference a global
1667 // variable that is a constant and is initialized. The referenced constant
1668 // initializer is the array that we'll use for optimization.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001669 const GlobalVariable* GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001670 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001671 return false;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001672 const Constant *GlobalInit = GV->getInitializer();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001673
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001674 // Handle the all-zeros case
1675 if (GlobalInit->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001676 // This is a degenerate case. The initializer is constant zero so the
1677 // length of the string must be zero.
Bill Wendling0582ae92009-03-13 04:39:26 +00001678 Str.clear();
1679 return true;
1680 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001681
1682 // Must be a Constant Array
Dan Gohman0a60fa32010-04-14 22:20:45 +00001683 const ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001684 if (Array == 0 || !Array->getType()->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001685 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001686
1687 // Get the number of elements in the array
1688 uint64_t NumElts = Array->getType()->getNumElements();
1689
Bill Wendling0582ae92009-03-13 04:39:26 +00001690 if (Offset > NumElts)
1691 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001692
1693 // Traverse the constant array from 'Offset' which is the place the GEP refers
1694 // to in the array.
Bill Wendling0582ae92009-03-13 04:39:26 +00001695 Str.reserve(NumElts-Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001696 for (unsigned i = Offset; i != NumElts; ++i) {
Dan Gohman0a60fa32010-04-14 22:20:45 +00001697 const Constant *Elt = Array->getOperand(i);
1698 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
Bill Wendling0582ae92009-03-13 04:39:26 +00001699 if (!CI) // This array isn't suitable, non-int initializer.
1700 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001701 if (StopAtNul && CI->isZero())
Bill Wendling0582ae92009-03-13 04:39:26 +00001702 return true; // we found end of string, success!
1703 Str += (char)CI->getZExtValue();
Evan Cheng0ff39b32008-06-30 07:31:25 +00001704 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001705
Evan Cheng0ff39b32008-06-30 07:31:25 +00001706 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy.
Bill Wendling0582ae92009-03-13 04:39:26 +00001707 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001708}
Eric Christopher25ec4832010-03-05 06:58:57 +00001709
1710// These next two are very similar to the above, but also look through PHI
1711// nodes.
1712// TODO: See if we can integrate these two together.
1713
1714/// GetStringLengthH - If we can compute the length of the string pointed to by
1715/// the specified pointer, return 'len+1'. If we can't, return 0.
1716static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1717 // Look through noop bitcast instructions.
1718 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
1719 return GetStringLengthH(BCI->getOperand(0), PHIs);
1720
1721 // If this is a PHI node, there are two cases: either we have already seen it
1722 // or we haven't.
1723 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1724 if (!PHIs.insert(PN))
1725 return ~0ULL; // already in the set.
1726
1727 // If it was new, see if all the input strings are the same length.
1728 uint64_t LenSoFar = ~0ULL;
1729 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1730 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1731 if (Len == 0) return 0; // Unknown length -> unknown.
1732
1733 if (Len == ~0ULL) continue;
1734
1735 if (Len != LenSoFar && LenSoFar != ~0ULL)
1736 return 0; // Disagree -> unknown.
1737 LenSoFar = Len;
1738 }
1739
1740 // Success, all agree.
1741 return LenSoFar;
1742 }
1743
1744 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1745 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1746 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1747 if (Len1 == 0) return 0;
1748 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1749 if (Len2 == 0) return 0;
1750 if (Len1 == ~0ULL) return Len2;
1751 if (Len2 == ~0ULL) return Len1;
1752 if (Len1 != Len2) return 0;
1753 return Len1;
1754 }
1755
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001756 // As a special-case, "@string = constant i8 0" is also a string with zero
1757 // length, not wrapped in a bitcast or GEP.
1758 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
1759 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1760 if (GV->getInitializer()->isNullValue()) return 1;
1761 return 0;
1762 }
1763
Eric Christopher25ec4832010-03-05 06:58:57 +00001764 // If the value is not a GEP instruction nor a constant expression with a
1765 // GEP instruction, then return unknown.
1766 User *GEP = 0;
1767 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1768 GEP = GEPI;
1769 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1770 if (CE->getOpcode() != Instruction::GetElementPtr)
1771 return 0;
1772 GEP = CE;
1773 } else {
1774 return 0;
1775 }
1776
1777 // Make sure the GEP has exactly three arguments.
1778 if (GEP->getNumOperands() != 3)
1779 return 0;
1780
1781 // Check to make sure that the first operand of the GEP is an integer and
1782 // has value 0 so that we are sure we're indexing into the initializer.
1783 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1784 if (!Idx->isZero())
1785 return 0;
1786 } else
1787 return 0;
1788
1789 // If the second index isn't a ConstantInt, then this is a variable index
1790 // into the array. If this occurs, we can't say anything meaningful about
1791 // the string.
1792 uint64_t StartIdx = 0;
1793 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1794 StartIdx = CI->getZExtValue();
1795 else
1796 return 0;
1797
1798 // The GEP instruction, constant or instruction, must reference a global
1799 // variable that is a constant and is initialized. The referenced constant
1800 // initializer is the array that we'll use for optimization.
1801 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1802 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1803 GV->mayBeOverridden())
1804 return 0;
1805 Constant *GlobalInit = GV->getInitializer();
1806
1807 // Handle the ConstantAggregateZero case, which is a degenerate case. The
1808 // initializer is constant zero so the length of the string must be zero.
1809 if (isa<ConstantAggregateZero>(GlobalInit))
1810 return 1; // Len = 0 offset by 1.
1811
1812 // Must be a Constant Array
1813 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
1814 if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
1815 return false;
1816
1817 // Get the number of elements in the array
1818 uint64_t NumElts = Array->getType()->getNumElements();
1819
1820 // Traverse the constant array from StartIdx (derived above) which is
1821 // the place the GEP refers to in the array.
1822 for (unsigned i = StartIdx; i != NumElts; ++i) {
1823 Constant *Elt = Array->getOperand(i);
1824 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1825 if (!CI) // This array isn't suitable, non-int initializer.
1826 return 0;
1827 if (CI->isZero())
1828 return i-StartIdx+1; // We found end of string, success!
1829 }
1830
1831 return 0; // The array isn't null terminated, conservatively return 'unknown'.
1832}
1833
1834/// GetStringLength - If we can compute the length of the string pointed to by
1835/// the specified pointer, return 'len+1'. If we can't, return 0.
1836uint64_t llvm::GetStringLength(Value *V) {
1837 if (!V->getType()->isPointerTy()) return 0;
1838
1839 SmallPtrSet<PHINode*, 32> PHIs;
1840 uint64_t Len = GetStringLengthH(V, PHIs);
1841 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1842 // an empty string as a length.
1843 return Len == ~0ULL ? 1 : Len;
1844}
Dan Gohman5034dd32010-12-15 20:02:24 +00001845
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001846Value *
1847llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001848 if (!V->getType()->isPointerTy())
1849 return V;
1850 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1851 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1852 V = GEP->getPointerOperand();
1853 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1854 V = cast<Operator>(V)->getOperand(0);
1855 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1856 if (GA->mayBeOverridden())
1857 return V;
1858 V = GA->getAliasee();
1859 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001860 // See if InstructionSimplify knows any relevant tricks.
1861 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001862 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001863 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001864 V = Simplified;
1865 continue;
1866 }
1867
Dan Gohman5034dd32010-12-15 20:02:24 +00001868 return V;
1869 }
1870 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1871 }
1872 return V;
1873}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001874
1875/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1876/// are lifetime markers.
1877///
1878bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1879 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1880 UI != UE; ++UI) {
1881 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1882 if (!II) return false;
1883
1884 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1885 II->getIntrinsicID() != Intrinsic::lifetime_end)
1886 return false;
1887 }
1888 return true;
1889}
Dan Gohmanf0426602011-12-14 23:49:11 +00001890
Dan Gohmanfebaf842012-01-04 23:01:09 +00001891bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Dan Gohmanf0426602011-12-14 23:49:11 +00001892 const TargetData *TD) {
Dan Gohmanfebaf842012-01-04 23:01:09 +00001893 const Operator *Inst = dyn_cast<Operator>(V);
1894 if (!Inst)
1895 return false;
1896
Dan Gohmanf0426602011-12-14 23:49:11 +00001897 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1898 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1899 if (C->canTrap())
1900 return false;
1901
1902 switch (Inst->getOpcode()) {
1903 default:
1904 return true;
1905 case Instruction::UDiv:
1906 case Instruction::URem:
1907 // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1908 return isKnownNonZero(Inst->getOperand(1), TD);
1909 case Instruction::SDiv:
1910 case Instruction::SRem: {
1911 Value *Op = Inst->getOperand(1);
1912 // x / y is undefined if y == 0
1913 if (!isKnownNonZero(Op, TD))
1914 return false;
1915 // x / y might be undefined if y == -1
1916 unsigned BitWidth = getBitWidth(Op->getType(), TD);
1917 if (BitWidth == 0)
1918 return false;
1919 APInt KnownZero(BitWidth, 0);
1920 APInt KnownOne(BitWidth, 0);
1921 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1922 KnownZero, KnownOne, TD);
1923 return !!KnownZero;
1924 }
1925 case Instruction::Load: {
1926 const LoadInst *LI = cast<LoadInst>(Inst);
1927 if (!LI->isUnordered())
1928 return false;
1929 return LI->getPointerOperand()->isDereferenceablePointer();
1930 }
Nick Lewycky83696872011-12-21 05:52:02 +00001931 case Instruction::Call: {
1932 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1933 switch (II->getIntrinsicID()) {
1934 case Intrinsic::bswap:
1935 case Intrinsic::ctlz:
1936 case Intrinsic::ctpop:
1937 case Intrinsic::cttz:
1938 case Intrinsic::objectsize:
1939 case Intrinsic::sadd_with_overflow:
1940 case Intrinsic::smul_with_overflow:
1941 case Intrinsic::ssub_with_overflow:
1942 case Intrinsic::uadd_with_overflow:
1943 case Intrinsic::umul_with_overflow:
1944 case Intrinsic::usub_with_overflow:
1945 return true;
1946 // TODO: some fp intrinsics are marked as having the same error handling
1947 // as libm. They're safe to speculate when they won't error.
1948 // TODO: are convert_{from,to}_fp16 safe?
1949 // TODO: can we list target-specific intrinsics here?
1950 default: break;
1951 }
1952 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001953 return false; // The called function could have undefined behavior or
Nick Lewycky83696872011-12-21 05:52:02 +00001954 // side-effects, even if marked readnone nounwind.
1955 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001956 case Instruction::VAArg:
1957 case Instruction::Alloca:
1958 case Instruction::Invoke:
1959 case Instruction::PHI:
1960 case Instruction::Store:
1961 case Instruction::Ret:
1962 case Instruction::Br:
1963 case Instruction::IndirectBr:
1964 case Instruction::Switch:
1965 case Instruction::Unwind:
1966 case Instruction::Unreachable:
1967 case Instruction::Fence:
1968 case Instruction::LandingPad:
1969 case Instruction::AtomicRMW:
1970 case Instruction::AtomicCmpXchg:
1971 case Instruction::Resume:
1972 return false; // Misc instructions which have effects
1973 }
1974}