blob: ed4f243fb6cf698b4c2b6c0ae10fe3262095abd1 [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
Chris Lattner7302d802012-02-06 21:56:39 +000091 // each element. There is no real need to handle ConstantVector here, because
92 // we don't handle undef in any particularly useful way.
Chris Lattnerdf390282012-01-24 07:54:10 +000093 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
94 // We know that CDS must be a vector of integers. Take the intersection of
95 // each element.
96 KnownZero.setAllBits(); KnownOne.setAllBits();
97 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner0f193b82012-01-25 01:27:20 +000098 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerdf390282012-01-24 07:54:10 +000099 Elt = CDS->getElementAsInteger(i);
100 KnownZero &= ~Elt;
101 KnownOne &= Elt;
102 }
103 return;
104 }
105
Chris Lattner173234a2008-06-02 01:18:21 +0000106 // The address of an aligned GlobalValue has trailing zeros.
107 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
108 unsigned Align = GV->getAlignment();
Nick Lewycky891495e2012-03-07 02:27:53 +0000109 if (Align == 0 && TD) {
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000110 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
111 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky891495e2012-03-07 02:27:53 +0000112 if (ObjectType->isSized()) {
113 // If the object is defined in the current Module, we'll be giving
114 // it the preferred alignment. Otherwise, we have to assume that it
115 // may only have the minimum ABI alignment.
116 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
117 Align = TD->getPreferredAlignment(GVar);
118 else
119 Align = TD->getABITypeAlignment(ObjectType);
120 }
Eli Friedmanc4c2a022011-11-28 22:48:22 +0000121 }
Dan Gohman00407252009-08-11 15:50:03 +0000122 }
Chris Lattner173234a2008-06-02 01:18:21 +0000123 if (Align > 0)
124 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
125 CountTrailingZeros_32(Align));
126 else
Jay Foad7a874dd2010-12-01 08:53:58 +0000127 KnownZero.clearAllBits();
128 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000129 return;
130 }
Dan Gohman307a7c42009-09-15 16:14:44 +0000131 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
132 // the bits of its aliasee.
133 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
134 if (GA->mayBeOverridden()) {
Jay Foad7a874dd2010-12-01 08:53:58 +0000135 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman307a7c42009-09-15 16:14:44 +0000136 } else {
137 ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
138 TD, Depth+1);
139 }
140 return;
141 }
Chris Lattnerb3f06732011-05-23 00:03:39 +0000142
143 if (Argument *A = dyn_cast<Argument>(V)) {
144 // Get alignment information off byval arguments if specified in the IR.
145 if (A->hasByValAttr())
146 if (unsigned Align = A->getParamAlignment())
147 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
148 CountTrailingZeros_32(Align));
149 return;
150 }
Chris Lattner173234a2008-06-02 01:18:21 +0000151
Chris Lattnerb3f06732011-05-23 00:03:39 +0000152 // Start out not knowing anything.
153 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000154
Dan Gohman9004c8a2009-05-21 02:28:33 +0000155 if (Depth == MaxDepth || Mask == 0)
Chris Lattner173234a2008-06-02 01:18:21 +0000156 return; // Limit search depth.
157
Dan Gohmanca178902009-07-17 20:47:02 +0000158 Operator *I = dyn_cast<Operator>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000159 if (!I) return;
160
161 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmanca178902009-07-17 20:47:02 +0000162 switch (I->getOpcode()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000163 default: break;
164 case Instruction::And: {
165 // If either the LHS or the RHS are Zero, the result is zero.
166 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
167 APInt Mask2(Mask & ~KnownZero);
168 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
169 Depth+1);
170 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
171 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
172
173 // Output known-1 bits are only known if set in both the LHS & RHS.
174 KnownOne &= KnownOne2;
175 // Output known-0 are known to be clear if zero in either the LHS | RHS.
176 KnownZero |= KnownZero2;
177 return;
178 }
179 case Instruction::Or: {
180 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
181 APInt Mask2(Mask & ~KnownOne);
182 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
183 Depth+1);
184 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
185 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
186
187 // Output known-0 bits are only known if clear in both the LHS & RHS.
188 KnownZero &= KnownZero2;
189 // Output known-1 are known to be set if set in either the LHS | RHS.
190 KnownOne |= KnownOne2;
191 return;
192 }
193 case Instruction::Xor: {
194 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1);
195 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
196 Depth+1);
197 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
198 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
199
200 // Output known-0 bits are known if clear or set in both the LHS & RHS.
201 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
202 // Output known-1 are known to be set if set in only one of the LHS, RHS.
203 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
204 KnownZero = KnownZeroOut;
205 return;
206 }
207 case Instruction::Mul: {
208 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
209 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1);
210 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
211 Depth+1);
Duncan Sands32a43cc2011-10-27 19:16:21 +0000212 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
213 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
214
215 bool isKnownNegative = false;
216 bool isKnownNonNegative = false;
217 // If the multiplication is known not to overflow, compute the sign bit.
218 if (Mask.isNegative() &&
219 cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap()) {
220 Value *Op1 = I->getOperand(1), *Op2 = I->getOperand(0);
221 if (Op1 == Op2) {
222 // The product of a number with itself is non-negative.
223 isKnownNonNegative = true;
224 } else {
225 bool isKnownNonNegative1 = KnownZero.isNegative();
226 bool isKnownNonNegative2 = KnownZero2.isNegative();
227 bool isKnownNegative1 = KnownOne.isNegative();
228 bool isKnownNegative2 = KnownOne2.isNegative();
229 // The product of two numbers with the same sign is non-negative.
230 isKnownNonNegative = (isKnownNegative1 && isKnownNegative2) ||
231 (isKnownNonNegative1 && isKnownNonNegative2);
232 // The product of a negative number and a non-negative number is either
233 // negative or zero.
234 if (!isKnownNonNegative)
235 isKnownNegative = (isKnownNegative1 && isKnownNonNegative2 &&
236 isKnownNonZero(Op2, TD, Depth)) ||
237 (isKnownNegative2 && isKnownNonNegative1 &&
238 isKnownNonZero(Op1, TD, Depth));
239 }
240 }
241
Chris Lattner173234a2008-06-02 01:18:21 +0000242 // If low bits are zero in either operand, output low known-0 bits.
243 // Also compute a conserative estimate for high known-0 bits.
244 // More trickiness is possible, but this is sufficient for the
245 // interesting case of alignment computation.
Jay Foad7a874dd2010-12-01 08:53:58 +0000246 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000247 unsigned TrailZ = KnownZero.countTrailingOnes() +
248 KnownZero2.countTrailingOnes();
249 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
250 KnownZero2.countLeadingOnes(),
251 BitWidth) - BitWidth;
252
253 TrailZ = std::min(TrailZ, BitWidth);
254 LeadZ = std::min(LeadZ, BitWidth);
255 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
256 APInt::getHighBitsSet(BitWidth, LeadZ);
257 KnownZero &= Mask;
Duncan Sands32a43cc2011-10-27 19:16:21 +0000258
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000259 // Only make use of no-wrap flags if we failed to compute the sign bit
260 // directly. This matters if the multiplication always overflows, in
261 // which case we prefer to follow the result of the direct computation,
262 // though as the program is invoking undefined behaviour we can choose
263 // whatever we like here.
264 if (isKnownNonNegative && !KnownOne.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000265 KnownZero.setBit(BitWidth - 1);
Duncan Sandsa8f5cd32011-11-23 16:26:47 +0000266 else if (isKnownNegative && !KnownZero.isNegative())
Duncan Sands32a43cc2011-10-27 19:16:21 +0000267 KnownOne.setBit(BitWidth - 1);
268
Chris Lattner173234a2008-06-02 01:18:21 +0000269 return;
270 }
271 case Instruction::UDiv: {
272 // For the purposes of computing leading zeros we can conservatively
273 // treat a udiv as a logical right shift by the power of 2 known to
274 // be less than the denominator.
275 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
276 ComputeMaskedBits(I->getOperand(0),
277 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
278 unsigned LeadZ = KnownZero2.countLeadingOnes();
279
Jay Foad7a874dd2010-12-01 08:53:58 +0000280 KnownOne2.clearAllBits();
281 KnownZero2.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000282 ComputeMaskedBits(I->getOperand(1),
283 AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
284 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
285 if (RHSUnknownLeadingOnes != BitWidth)
286 LeadZ = std::min(BitWidth,
287 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
288
289 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
290 return;
291 }
292 case Instruction::Select:
293 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1);
294 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
295 Depth+1);
296 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
297 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
298
299 // Only known if known in both the LHS and RHS.
300 KnownOne &= KnownOne2;
301 KnownZero &= KnownZero2;
302 return;
303 case Instruction::FPTrunc:
304 case Instruction::FPExt:
305 case Instruction::FPToUI:
306 case Instruction::FPToSI:
307 case Instruction::SIToFP:
308 case Instruction::UIToFP:
309 return; // Can't work with floating point.
310 case Instruction::PtrToInt:
311 case Instruction::IntToPtr:
312 // We can't handle these if we don't know the pointer size.
313 if (!TD) return;
314 // FALL THROUGH and handle them the same as zext/trunc.
315 case Instruction::ZExt:
316 case Instruction::Trunc: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000317 Type *SrcTy = I->getOperand(0)->getType();
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000318
319 unsigned SrcBitWidth;
Chris Lattner173234a2008-06-02 01:18:21 +0000320 // Note that we handle pointer operands here because of inttoptr/ptrtoint
321 // which fall through here.
Duncan Sands1df98592010-02-16 11:11:14 +0000322 if (SrcTy->isPointerTy())
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000323 SrcBitWidth = TD->getTypeSizeInBits(SrcTy);
324 else
325 SrcBitWidth = SrcTy->getScalarSizeInBits();
326
Jay Foad40f8f622010-12-07 08:25:19 +0000327 APInt MaskIn = Mask.zextOrTrunc(SrcBitWidth);
328 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
329 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000330 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
331 Depth+1);
Jay Foad40f8f622010-12-07 08:25:19 +0000332 KnownZero = KnownZero.zextOrTrunc(BitWidth);
333 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000334 // Any top bits are known to be zero.
335 if (BitWidth > SrcBitWidth)
336 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
337 return;
338 }
339 case Instruction::BitCast: {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000340 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands1df98592010-02-16 11:11:14 +0000341 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattner0dabb0b2009-07-02 16:04:08 +0000342 // TODO: For now, not handling conversions like:
343 // (bitcast i64 %x to <2 x i32>)
Duncan Sands1df98592010-02-16 11:11:14 +0000344 !I->getType()->isVectorTy()) {
Chris Lattner173234a2008-06-02 01:18:21 +0000345 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
346 Depth+1);
347 return;
348 }
349 break;
350 }
351 case Instruction::SExt: {
352 // Compute the bits in the result that are not present in the input.
Chris Lattnerb9a4ddb2009-09-08 00:13:52 +0000353 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000354
Jay Foad40f8f622010-12-07 08:25:19 +0000355 APInt MaskIn = Mask.trunc(SrcBitWidth);
356 KnownZero = KnownZero.trunc(SrcBitWidth);
357 KnownOne = KnownOne.trunc(SrcBitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000358 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
359 Depth+1);
360 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Jay Foad40f8f622010-12-07 08:25:19 +0000361 KnownZero = KnownZero.zext(BitWidth);
362 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner173234a2008-06-02 01:18:21 +0000363
364 // If the sign bit of the input is known set or clear, then we know the
365 // top bits of the result.
366 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
367 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
368 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
369 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
370 return;
371 }
372 case Instruction::Shl:
373 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
374 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
375 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
376 APInt Mask2(Mask.lshr(ShiftAmt));
377 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
378 Depth+1);
379 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
380 KnownZero <<= ShiftAmt;
381 KnownOne <<= ShiftAmt;
382 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
383 return;
384 }
385 break;
386 case Instruction::LShr:
387 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
388 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
389 // Compute the new bits that are at the top now.
390 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
391
392 // Unsigned shift right.
393 APInt Mask2(Mask.shl(ShiftAmt));
394 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
395 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000396 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000397 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
398 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
399 // high bits known zero.
400 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
401 return;
402 }
403 break;
404 case Instruction::AShr:
405 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
406 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
407 // Compute the new bits that are at the top now.
Chris Lattner43b40a42011-01-04 18:19:15 +0000408 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Chris Lattner173234a2008-06-02 01:18:21 +0000409
410 // Signed shift right.
411 APInt Mask2(Mask.shl(ShiftAmt));
412 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
413 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000414 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000415 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
416 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
417
418 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
419 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
420 KnownZero |= HighBits;
421 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
422 KnownOne |= HighBits;
423 return;
424 }
425 break;
426 case Instruction::Sub: {
427 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
428 // We know that the top bits of C-X are clear if X contains less bits
429 // than C (i.e. no wrap-around can happen). For example, 20-X is
430 // positive if we can prove that X is >= 0 and < 16.
431 if (!CLHS->getValue().isNegative()) {
432 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
433 // NLZ can't be BitWidth with no sign bit
434 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
435 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
436 TD, Depth+1);
437
438 // If all of the MaskV bits are known to be zero, then we know the
439 // output top bits are zero, because we now know that the output is
440 // from [0-C].
441 if ((KnownZero2 & MaskV) == MaskV) {
442 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
443 // Top bits known zero.
444 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
445 }
446 }
447 }
448 }
449 // fall through
450 case Instruction::Add: {
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000451 // If one of the operands has trailing zeros, then the bits that the
Dan Gohman39250432009-05-24 18:02:35 +0000452 // other operand has in those bit positions will be preserved in the
453 // result. For an add, this works with either operand. For a subtract,
454 // this only works if the known zeros are in the right operand.
455 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
456 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
457 BitWidth - Mask.countLeadingZeros());
458 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
Chris Lattner173234a2008-06-02 01:18:21 +0000459 Depth+1);
Dan Gohman39250432009-05-24 18:02:35 +0000460 assert((LHSKnownZero & LHSKnownOne) == 0 &&
461 "Bits known to be one AND zero?");
462 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000463
464 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,
465 Depth+1);
466 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
Dan Gohman39250432009-05-24 18:02:35 +0000467 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
Chris Lattner173234a2008-06-02 01:18:21 +0000468
Dan Gohman39250432009-05-24 18:02:35 +0000469 // Determine which operand has more trailing zeros, and use that
470 // many bits from the other operand.
471 if (LHSKnownZeroOut > RHSKnownZeroOut) {
Dan Gohmanca178902009-07-17 20:47:02 +0000472 if (I->getOpcode() == Instruction::Add) {
Dan Gohman39250432009-05-24 18:02:35 +0000473 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
474 KnownZero |= KnownZero2 & Mask;
475 KnownOne |= KnownOne2 & Mask;
476 } else {
477 // If the known zeros are in the left operand for a subtract,
478 // fall back to the minimum known zeros in both operands.
479 KnownZero |= APInt::getLowBitsSet(BitWidth,
480 std::min(LHSKnownZeroOut,
481 RHSKnownZeroOut));
482 }
483 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
484 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
485 KnownZero |= LHSKnownZero & Mask;
486 KnownOne |= LHSKnownOne & Mask;
487 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000488
489 // Are we still trying to solve for the sign bit?
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000490 if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegative()){
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000491 OverflowingBinaryOperator *OBO = cast<OverflowingBinaryOperator>(I);
492 if (OBO->hasNoSignedWrap()) {
Benjamin Kramer14b2a592011-03-12 17:18:11 +0000493 if (I->getOpcode() == Instruction::Add) {
494 // Adding two positive numbers can't wrap into negative
495 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
496 KnownZero |= APInt::getSignBit(BitWidth);
497 // and adding two negative numbers can't wrap into positive.
498 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
499 KnownOne |= APInt::getSignBit(BitWidth);
500 } else {
501 // Subtracting a negative number from a positive one can't wrap
502 if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
503 KnownZero |= APInt::getSignBit(BitWidth);
504 // neither can subtracting a positive number from a negative one.
505 else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
506 KnownOne |= APInt::getSignBit(BitWidth);
507 }
Nick Lewyckyb69050a2011-03-11 09:00:19 +0000508 }
509 }
510
Chris Lattner173234a2008-06-02 01:18:21 +0000511 return;
512 }
513 case Instruction::SRem:
514 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sandscfd54182010-01-29 06:18:37 +0000515 APInt RA = Rem->getValue().abs();
516 if (RA.isPowerOf2()) {
517 APInt LowBits = RA - 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000518 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
519 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
520 Depth+1);
521
Duncan Sandscfd54182010-01-29 06:18:37 +0000522 // The low bits of the first operand are unchanged by the srem.
523 KnownZero = KnownZero2 & LowBits;
524 KnownOne = KnownOne2 & LowBits;
Chris Lattner173234a2008-06-02 01:18:21 +0000525
Duncan Sandscfd54182010-01-29 06:18:37 +0000526 // If the first operand is non-negative or has all low bits zero, then
527 // the upper bits are all zero.
528 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
529 KnownZero |= ~LowBits;
530
531 // If the first operand is negative and not all low bits are zero, then
532 // the upper bits are all one.
533 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
534 KnownOne |= ~LowBits;
535
536 KnownZero &= Mask;
537 KnownOne &= Mask;
Chris Lattner173234a2008-06-02 01:18:21 +0000538
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000539 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000540 }
541 }
Nick Lewyckyc14bc772011-03-07 01:50:10 +0000542
543 // The sign bit is the LHS's sign bit, except when the result of the
544 // remainder is zero.
545 if (Mask.isNegative() && KnownZero.isNonNegative()) {
546 APInt Mask2 = APInt::getSignBit(BitWidth);
547 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
548 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD,
549 Depth+1);
550 // If it's known zero, our sign bit is also zero.
551 if (LHSKnownZero.isNegative())
552 KnownZero |= LHSKnownZero;
553 }
554
Chris Lattner173234a2008-06-02 01:18:21 +0000555 break;
556 case Instruction::URem: {
557 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
558 APInt RA = Rem->getValue();
559 if (RA.isPowerOf2()) {
560 APInt LowBits = (RA - 1);
561 APInt Mask2 = LowBits & Mask;
562 KnownZero |= ~LowBits & Mask;
563 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
564 Depth+1);
Nick Lewyckyae3d8022009-11-23 03:29:18 +0000565 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner173234a2008-06-02 01:18:21 +0000566 break;
567 }
568 }
569
570 // Since the result is less than or equal to either operand, any leading
571 // zero bits in either operand must also exist in the result.
572 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
573 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
574 TD, Depth+1);
575 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
576 TD, Depth+1);
577
Chris Lattner79abedb2009-01-20 18:22:57 +0000578 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner173234a2008-06-02 01:18:21 +0000579 KnownZero2.countLeadingOnes());
Jay Foad7a874dd2010-12-01 08:53:58 +0000580 KnownOne.clearAllBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000581 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
582 break;
583 }
584
Victor Hernandeza276c602009-10-17 01:18:07 +0000585 case Instruction::Alloca: {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000586 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner173234a2008-06-02 01:18:21 +0000587 unsigned Align = AI->getAlignment();
Victor Hernandeza276c602009-10-17 01:18:07 +0000588 if (Align == 0 && TD)
589 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner173234a2008-06-02 01:18:21 +0000590
591 if (Align > 0)
592 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
593 CountTrailingZeros_32(Align));
594 break;
595 }
596 case Instruction::GetElementPtr: {
597 // Analyze all of the subscripts of this getelementptr instruction
598 // to determine if we can prove known low zero bits.
599 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
600 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
601 ComputeMaskedBits(I->getOperand(0), LocalMask,
602 LocalKnownZero, LocalKnownOne, TD, Depth+1);
603 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
604
605 gep_type_iterator GTI = gep_type_begin(I);
606 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
607 Value *Index = I->getOperand(i);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000608 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000609 // Handle struct member offset arithmetic.
610 if (!TD) return;
611 const StructLayout *SL = TD->getStructLayout(STy);
612 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
613 uint64_t Offset = SL->getElementOffset(Idx);
614 TrailZ = std::min(TrailZ,
615 CountTrailingZeros_64(Offset));
616 } else {
617 // Handle array index arithmetic.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000618 Type *IndexedTy = GTI.getIndexedType();
Chris Lattner173234a2008-06-02 01:18:21 +0000619 if (!IndexedTy->isSized()) return;
Dan Gohman6de29f82009-06-15 22:12:54 +0000620 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sands777d2302009-05-09 07:06:46 +0000621 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner173234a2008-06-02 01:18:21 +0000622 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
623 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
624 ComputeMaskedBits(Index, LocalMask,
625 LocalKnownZero, LocalKnownOne, TD, Depth+1);
626 TrailZ = std::min(TrailZ,
Chris Lattner79abedb2009-01-20 18:22:57 +0000627 unsigned(CountTrailingZeros_64(TypeSize) +
628 LocalKnownZero.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000629 }
630 }
631
632 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
633 break;
634 }
635 case Instruction::PHI: {
636 PHINode *P = cast<PHINode>(I);
637 // Handle the case of a simple two-predecessor recurrence PHI.
638 // There's a lot more that could theoretically be done here, but
639 // this is sufficient to catch some interesting cases.
640 if (P->getNumIncomingValues() == 2) {
641 for (unsigned i = 0; i != 2; ++i) {
642 Value *L = P->getIncomingValue(i);
643 Value *R = P->getIncomingValue(!i);
Dan Gohmanca178902009-07-17 20:47:02 +0000644 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner173234a2008-06-02 01:18:21 +0000645 if (!LU)
646 continue;
Dan Gohmanca178902009-07-17 20:47:02 +0000647 unsigned Opcode = LU->getOpcode();
Chris Lattner173234a2008-06-02 01:18:21 +0000648 // Check for operations that have the property that if
649 // both their operands have low zero bits, the result
650 // will have low zero bits.
651 if (Opcode == Instruction::Add ||
652 Opcode == Instruction::Sub ||
653 Opcode == Instruction::And ||
654 Opcode == Instruction::Or ||
655 Opcode == Instruction::Mul) {
656 Value *LL = LU->getOperand(0);
657 Value *LR = LU->getOperand(1);
658 // Find a recurrence.
659 if (LL == I)
660 L = LR;
661 else if (LR == I)
662 L = LL;
663 else
664 break;
665 // Ok, we have a PHI of the form L op= R. Check for low
666 // zero bits.
667 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
668 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
669 Mask2 = APInt::getLowBitsSet(BitWidth,
670 KnownZero2.countTrailingOnes());
David Greenec714f132008-10-27 23:24:03 +0000671
672 // We need to take the minimum number of known bits
673 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
674 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
675
Chris Lattner173234a2008-06-02 01:18:21 +0000676 KnownZero = Mask &
677 APInt::getLowBitsSet(BitWidth,
David Greenec714f132008-10-27 23:24:03 +0000678 std::min(KnownZero2.countTrailingOnes(),
679 KnownZero3.countTrailingOnes()));
Chris Lattner173234a2008-06-02 01:18:21 +0000680 break;
681 }
682 }
683 }
Dan Gohman9004c8a2009-05-21 02:28:33 +0000684
Nick Lewycky3b739d22011-02-10 23:54:10 +0000685 // Unreachable blocks may have zero-operand PHI nodes.
686 if (P->getNumIncomingValues() == 0)
687 return;
688
Dan Gohman9004c8a2009-05-21 02:28:33 +0000689 // Otherwise take the unions of the known bit sets of the operands,
690 // taking conservative care to avoid excessive recursion.
691 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands606199f2011-03-08 12:39:03 +0000692 // Skip if every incoming value references to ourself.
693 if (P->hasConstantValue() == P)
694 break;
695
Eli Friedman049d08f2012-03-05 23:09:40 +0000696 KnownZero = Mask;
697 KnownOne = Mask;
Dan Gohman9004c8a2009-05-21 02:28:33 +0000698 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
699 // Skip direct self references.
700 if (P->getIncomingValue(i) == P) continue;
701
702 KnownZero2 = APInt(BitWidth, 0);
703 KnownOne2 = APInt(BitWidth, 0);
704 // Recurse, but cap the recursion to one level, because we don't
705 // want to waste time spinning around in loops.
706 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
707 KnownZero2, KnownOne2, TD, MaxDepth-1);
708 KnownZero &= KnownZero2;
709 KnownOne &= KnownOne2;
710 // If all bits have been ruled out, there's no need to check
711 // more operands.
712 if (!KnownZero && !KnownOne)
713 break;
714 }
715 }
Chris Lattner173234a2008-06-02 01:18:21 +0000716 break;
717 }
718 case Instruction::Call:
719 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
720 switch (II->getIntrinsicID()) {
721 default: break;
Chris Lattner173234a2008-06-02 01:18:21 +0000722 case Intrinsic::ctlz:
723 case Intrinsic::cttz: {
724 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer009da052011-12-24 17:31:46 +0000725 // If this call is undefined for 0, the result will be less than 2^n.
726 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
727 LowBits -= 1;
Eli Friedman923bb412012-03-05 23:22:40 +0000728 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer009da052011-12-24 17:31:46 +0000729 break;
730 }
731 case Intrinsic::ctpop: {
732 unsigned LowBits = Log2_32(BitWidth)+1;
Eli Friedman923bb412012-03-05 23:22:40 +0000733 KnownZero = Mask & APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner173234a2008-06-02 01:18:21 +0000734 break;
735 }
Chad Rosier62660312011-05-26 23:13:19 +0000736 case Intrinsic::x86_sse42_crc32_64_8:
737 case Intrinsic::x86_sse42_crc32_64_64:
Eli Friedman923bb412012-03-05 23:22:40 +0000738 KnownZero = Mask & APInt::getHighBitsSet(64, 32);
Evan Chengcb559c12011-05-22 18:25:30 +0000739 break;
Chris Lattner173234a2008-06-02 01:18:21 +0000740 }
741 }
742 break;
743 }
744}
745
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000746/// ComputeSignBit - Determine whether the sign bit is known to be zero or
747/// one. Convenience wrapper around ComputeMaskedBits.
748void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
749 const TargetData *TD, unsigned Depth) {
750 unsigned BitWidth = getBitWidth(V->getType(), TD);
751 if (!BitWidth) {
752 KnownZero = false;
753 KnownOne = false;
754 return;
755 }
756 APInt ZeroBits(BitWidth, 0);
757 APInt OneBits(BitWidth, 0);
758 ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
759 Depth);
760 KnownOne = OneBits[BitWidth - 1];
761 KnownZero = ZeroBits[BitWidth - 1];
762}
763
764/// isPowerOfTwo - Return true if the given value is known to have exactly one
765/// bit set when defined. For vectors return true if every element is known to
766/// be a power of two when defined. Supports values with integer or pointer
767/// types and vectors of integers.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000768bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
769 unsigned Depth) {
770 if (Constant *C = dyn_cast<Constant>(V)) {
771 if (C->isNullValue())
772 return OrZero;
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
774 return CI->getValue().isPowerOf2();
775 // TODO: Handle vector constants.
776 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000777
778 // 1 << X is clearly a power of two if the one is not shifted off the end. If
779 // it is shifted off the end then the result is undefined.
780 if (match(V, m_Shl(m_One(), m_Value())))
781 return true;
782
783 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
784 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands93c78022011-02-01 08:50:33 +0000785 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000786 return true;
787
788 // The remaining tests are all recursive, so bail out if we hit the limit.
789 if (Depth++ == MaxDepth)
790 return false;
791
Duncan Sands4604fc72011-10-28 18:30:05 +0000792 Value *X = 0, *Y = 0;
793 // A shift of a power of two is a power of two or zero.
794 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
795 match(V, m_Shr(m_Value(X), m_Value()))))
796 return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
797
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000798 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000799 return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000800
801 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000802 return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
803 isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
804
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000805 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
806 // A power of two and'd with anything is a power of two or zero.
807 if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
808 isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
809 return true;
810 // X & (-X) is always a power of two or zero.
811 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
812 return true;
813 return false;
814 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000815
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000816 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewycky1f7bc702011-03-21 21:40:32 +0000817 // is a power of two only if the first operand is a power of two and not
818 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000819 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
820 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
821 return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000822 }
823
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000824 return false;
825}
826
827/// isKnownNonZero - Return true if the given value is known to be non-zero
828/// when defined. For vectors return true if every element is known to be
829/// non-zero when defined. Supports values with integer or pointer type and
830/// vectors of integers.
831bool llvm::isKnownNonZero(Value *V, const TargetData *TD, unsigned Depth) {
832 if (Constant *C = dyn_cast<Constant>(V)) {
833 if (C->isNullValue())
834 return false;
835 if (isa<ConstantInt>(C))
836 // Must be non-zero due to null test above.
837 return true;
838 // TODO: Handle vectors
839 return false;
840 }
841
842 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000843 if (Depth++ >= MaxDepth)
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000844 return false;
845
846 unsigned BitWidth = getBitWidth(V->getType(), TD);
847
848 // X | Y != 0 if X != 0 or Y != 0.
849 Value *X = 0, *Y = 0;
850 if (match(V, m_Or(m_Value(X), m_Value(Y))))
851 return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
852
853 // ext X != 0 if X != 0.
854 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
855 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
856
Duncan Sands91367822011-01-29 13:27:00 +0000857 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000858 // if the lowest bit is shifted off the end.
859 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000860 // shl nuw can't remove any non-zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000861 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000862 if (BO->hasNoUnsignedWrap())
863 return isKnownNonZero(X, TD, Depth);
864
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000865 APInt KnownZero(BitWidth, 0);
866 APInt KnownOne(BitWidth, 0);
Duncan Sands91367822011-01-29 13:27:00 +0000867 ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Depth);
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000868 if (KnownOne[0])
869 return true;
870 }
Duncan Sands91367822011-01-29 13:27:00 +0000871 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000872 // defined if the sign bit is shifted off the end.
873 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000874 // shr exact can only shift out zero bits.
Duncan Sands32a43cc2011-10-27 19:16:21 +0000875 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000876 if (BO->isExact())
877 return isKnownNonZero(X, TD, Depth);
878
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000879 bool XKnownNonNegative, XKnownNegative;
880 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
881 if (XKnownNegative)
882 return true;
883 }
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000884 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000885 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
886 return isKnownNonZero(X, TD, Depth);
Nick Lewycky3dfd9872011-02-28 08:02:21 +0000887 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000888 // X + Y.
889 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
890 bool XKnownNonNegative, XKnownNegative;
891 bool YKnownNonNegative, YKnownNegative;
892 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
893 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
894
895 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands227fba12011-01-25 15:14:15 +0000896 // zero unless both X and Y are zero.
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000897 if (XKnownNonNegative && YKnownNonNegative)
Duncan Sands227fba12011-01-25 15:14:15 +0000898 if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
899 return true;
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000900
901 // If X and Y are both negative (as signed values) then their sum is not
902 // zero unless both X and Y equal INT_MIN.
903 if (BitWidth && XKnownNegative && YKnownNegative) {
904 APInt KnownZero(BitWidth, 0);
905 APInt KnownOne(BitWidth, 0);
906 APInt Mask = APInt::getSignedMaxValue(BitWidth);
907 // The sign bit of X is set. If some other bit is set then X is not equal
908 // to INT_MIN.
909 ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
910 if ((KnownOne & Mask) != 0)
911 return true;
912 // The sign bit of Y is set. If some other bit is set then Y is not equal
913 // to INT_MIN.
914 ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
915 if ((KnownOne & Mask) != 0)
916 return true;
917 }
918
919 // The sum of a non-negative number and a power of two is not zero.
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000920 if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000921 return true;
Duncan Sandsdd3149d2011-10-26 20:55:21 +0000922 if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000923 return true;
924 }
Duncan Sands32a43cc2011-10-27 19:16:21 +0000925 // X * Y.
926 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
927 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
928 // If X and Y are non-zero then so is X * Y as long as the multiplication
929 // does not overflow.
930 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
931 isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
932 return true;
933 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +0000934 // (C ? X : Y) != 0 if X != 0 and Y != 0.
935 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
936 if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
937 isKnownNonZero(SI->getFalseValue(), TD, Depth))
938 return true;
939 }
940
941 if (!BitWidth) return false;
942 APInt KnownZero(BitWidth, 0);
943 APInt KnownOne(BitWidth, 0);
944 ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownOne,
945 TD, Depth);
946 return KnownOne != 0;
947}
948
Chris Lattner173234a2008-06-02 01:18:21 +0000949/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
950/// this predicate to simplify operations downstream. Mask is known to be zero
951/// for bits that V cannot have.
Chris Lattnercf5128e2009-09-08 00:06:16 +0000952///
953/// This function is defined on values with integer type, values with pointer
954/// type (but only if TD is non-null), and vectors of integers. In the case
955/// where V is a vector, the mask, known zero, and known one values are the
956/// same width as the vector element, and the bit is set only if it is true
957/// for all of the elements in the vector.
Chris Lattner173234a2008-06-02 01:18:21 +0000958bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
Dan Gohman846a2f22009-08-27 17:51:25 +0000959 const TargetData *TD, unsigned Depth) {
Chris Lattner173234a2008-06-02 01:18:21 +0000960 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
961 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
962 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
963 return (KnownZero & Mask) == Mask;
964}
965
966
967
968/// ComputeNumSignBits - Return the number of times the sign bit of the
969/// register is replicated into the other bits. We know that at least 1 bit
970/// is always equal to the sign bit (itself), but other cases can give us
971/// information. For example, immediately after an "ashr X, 2", we know that
972/// the top 3 bits are all equal to each other, so we return 3.
973///
974/// 'Op' must have a scalar integer type.
975///
Dan Gohman846a2f22009-08-27 17:51:25 +0000976unsigned llvm::ComputeNumSignBits(Value *V, const TargetData *TD,
977 unsigned Depth) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000978 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000979 "ComputeNumSignBits requires a TargetData object to operate "
980 "on non-integer values!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000981 Type *Ty = V->getType();
Dan Gohmanbd5ce522009-06-22 22:02:32 +0000982 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
983 Ty->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000984 unsigned Tmp, Tmp2;
985 unsigned FirstAnswer = 1;
986
Chris Lattnerd82e5112008-06-02 18:39:07 +0000987 // Note that ConstantInt is handled by the general ComputeMaskedBits case
988 // below.
989
Chris Lattner173234a2008-06-02 01:18:21 +0000990 if (Depth == 6)
991 return 1; // Limit search depth.
992
Dan Gohmanca178902009-07-17 20:47:02 +0000993 Operator *U = dyn_cast<Operator>(V);
994 switch (Operator::getOpcode(V)) {
Chris Lattner173234a2008-06-02 01:18:21 +0000995 default: break;
996 case Instruction::SExt:
Mon P Wang69a00802009-12-02 04:59:58 +0000997 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattner173234a2008-06-02 01:18:21 +0000998 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
999
Chris Lattner6b0dc922012-01-26 21:37:55 +00001000 case Instruction::AShr: {
Chris Lattner173234a2008-06-02 01:18:21 +00001001 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001002 // ashr X, C -> adds C sign bits. Vectors too.
1003 const APInt *ShAmt;
1004 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1005 Tmp += ShAmt->getZExtValue();
Chris Lattner173234a2008-06-02 01:18:21 +00001006 if (Tmp > TyBits) Tmp = TyBits;
1007 }
1008 return Tmp;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001009 }
1010 case Instruction::Shl: {
1011 const APInt *ShAmt;
1012 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner173234a2008-06-02 01:18:21 +00001013 // shl destroys sign bits.
1014 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
Chris Lattner6b0dc922012-01-26 21:37:55 +00001015 Tmp2 = ShAmt->getZExtValue();
1016 if (Tmp2 >= TyBits || // Bad shift.
1017 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1018 return Tmp - Tmp2;
Chris Lattner173234a2008-06-02 01:18:21 +00001019 }
1020 break;
Chris Lattner6b0dc922012-01-26 21:37:55 +00001021 }
Chris Lattner173234a2008-06-02 01:18:21 +00001022 case Instruction::And:
1023 case Instruction::Or:
1024 case Instruction::Xor: // NOT is handled here.
1025 // Logical binary ops preserve the number of sign bits at the worst.
1026 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1027 if (Tmp != 1) {
1028 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1029 FirstAnswer = std::min(Tmp, Tmp2);
1030 // We computed what we know about the sign bits as our first
1031 // answer. Now proceed to the generic code that uses
1032 // ComputeMaskedBits, and pick whichever answer is better.
1033 }
1034 break;
1035
1036 case Instruction::Select:
1037 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1038 if (Tmp == 1) return 1; // Early out.
1039 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
1040 return std::min(Tmp, Tmp2);
1041
1042 case Instruction::Add:
1043 // Add can have at most one carry bit. Thus we know that the output
1044 // is, at worst, one more bit than the inputs.
1045 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1046 if (Tmp == 1) return 1; // Early out.
1047
1048 // Special case decrementing a value (ADD X, -1):
Dan Gohman0001e562009-02-24 02:00:40 +00001049 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner173234a2008-06-02 01:18:21 +00001050 if (CRHS->isAllOnesValue()) {
1051 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1052 APInt Mask = APInt::getAllOnesValue(TyBits);
1053 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
1054 Depth+1);
1055
1056 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1057 // sign bits set.
1058 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1059 return TyBits;
1060
1061 // If we are subtracting one from a positive number, there is no carry
1062 // out of the result.
1063 if (KnownZero.isNegative())
1064 return Tmp;
1065 }
1066
1067 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1068 if (Tmp2 == 1) return 1;
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001069 return std::min(Tmp, Tmp2)-1;
Chris Lattner173234a2008-06-02 01:18:21 +00001070
1071 case Instruction::Sub:
1072 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
1073 if (Tmp2 == 1) return 1;
1074
1075 // Handle NEG.
1076 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1077 if (CLHS->isNullValue()) {
1078 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1079 APInt Mask = APInt::getAllOnesValue(TyBits);
1080 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,
1081 TD, Depth+1);
1082 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1083 // sign bits set.
1084 if ((KnownZero | APInt(TyBits, 1)) == Mask)
1085 return TyBits;
1086
1087 // If the input is known to be positive (the sign bit is known clear),
1088 // the output of the NEG has the same number of sign bits as the input.
1089 if (KnownZero.isNegative())
1090 return Tmp2;
1091
1092 // Otherwise, we treat this like a SUB.
1093 }
1094
1095 // Sub can have at most one carry bit. Thus we know that the output
1096 // is, at worst, one more bit than the inputs.
1097 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
1098 if (Tmp == 1) return 1; // Early out.
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001099 return std::min(Tmp, Tmp2)-1;
1100
1101 case Instruction::PHI: {
1102 PHINode *PN = cast<PHINode>(U);
1103 // Don't analyze large in-degree PHIs.
1104 if (PN->getNumIncomingValues() > 4) break;
1105
1106 // Take the minimum of all incoming values. This can't infinitely loop
1107 // because of our depth threshold.
1108 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
1109 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1110 if (Tmp == 1) return Tmp;
1111 Tmp = std::min(Tmp,
Evan Cheng0af20d82010-03-13 02:20:29 +00001112 ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
Chris Lattner8d10f9d2010-01-07 23:44:37 +00001113 }
1114 return Tmp;
1115 }
1116
Chris Lattner173234a2008-06-02 01:18:21 +00001117 case Instruction::Trunc:
1118 // FIXME: it's tricky to do anything useful for this, but it is an important
1119 // case for targets like X86.
1120 break;
1121 }
1122
1123 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1124 // use this information.
1125 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
1126 APInt Mask = APInt::getAllOnesValue(TyBits);
1127 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
1128
1129 if (KnownZero.isNegative()) { // sign bit is 0
1130 Mask = KnownZero;
1131 } else if (KnownOne.isNegative()) { // sign bit is 1;
1132 Mask = KnownOne;
1133 } else {
1134 // Nothing known.
1135 return FirstAnswer;
1136 }
1137
1138 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1139 // the number of identical bits in the top of the input value.
1140 Mask = ~Mask;
1141 Mask <<= Mask.getBitWidth()-TyBits;
1142 // Return # leading zeros. We use 'min' here in case Val was zero before
1143 // shifting. We don't want to return '64' as for an i32 "0".
1144 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1145}
Chris Lattner833f25d2008-06-02 01:29:46 +00001146
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001147/// ComputeMultiple - This function computes the integer multiple of Base that
1148/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001149/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001150/// through SExt instructions only if LookThroughSExt is true.
1151bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001152 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001153 const unsigned MaxDepth = 6;
1154
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001155 assert(V && "No Value?");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001156 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001157 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001158
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001159 Type *T = V->getType();
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001160
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001161 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001162
1163 if (Base == 0)
1164 return false;
1165
1166 if (Base == 1) {
1167 Multiple = V;
1168 return true;
1169 }
1170
1171 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1172 Constant *BaseVal = ConstantInt::get(T, Base);
1173 if (CO && CO == BaseVal) {
1174 // Multiple is 1.
1175 Multiple = ConstantInt::get(T, 1);
1176 return true;
1177 }
1178
1179 if (CI && CI->getZExtValue() % Base == 0) {
1180 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
1181 return true;
1182 }
1183
1184 if (Depth == MaxDepth) return false; // Limit search depth.
1185
1186 Operator *I = dyn_cast<Operator>(V);
1187 if (!I) return false;
1188
1189 switch (I->getOpcode()) {
1190 default: break;
Chris Lattner11fe7262009-11-26 01:50:12 +00001191 case Instruction::SExt:
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001192 if (!LookThroughSExt) return false;
1193 // otherwise fall through to ZExt
Chris Lattner11fe7262009-11-26 01:50:12 +00001194 case Instruction::ZExt:
Dan Gohman3dbb9e62009-11-18 00:58:27 +00001195 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1196 LookThroughSExt, Depth+1);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001197 case Instruction::Shl:
1198 case Instruction::Mul: {
1199 Value *Op0 = I->getOperand(0);
1200 Value *Op1 = I->getOperand(1);
1201
1202 if (I->getOpcode() == Instruction::Shl) {
1203 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1204 if (!Op1CI) return false;
1205 // Turn Op0 << Op1 into Op0 * 2^Op1
1206 APInt Op1Int = Op1CI->getValue();
1207 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foada99793c2010-11-30 09:02:01 +00001208 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad7a874dd2010-12-01 08:53:58 +00001209 API.setBit(BitToSet);
Jay Foada99793c2010-11-30 09:02:01 +00001210 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001211 }
1212
1213 Value *Mul0 = NULL;
Chris Lattnere9711312010-09-05 17:20:46 +00001214 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1215 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1216 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
1217 if (Op1C->getType()->getPrimitiveSizeInBits() <
1218 MulC->getType()->getPrimitiveSizeInBits())
1219 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
1220 if (Op1C->getType()->getPrimitiveSizeInBits() >
1221 MulC->getType()->getPrimitiveSizeInBits())
1222 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
1223
1224 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1225 Multiple = ConstantExpr::getMul(MulC, Op1C);
1226 return true;
1227 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001228
1229 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1230 if (Mul0CI->getValue() == 1) {
1231 // V == Base * Op1, so return Op1
1232 Multiple = Op1;
1233 return true;
1234 }
1235 }
1236
Chris Lattnere9711312010-09-05 17:20:46 +00001237 Value *Mul1 = NULL;
1238 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1239 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1240 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
1241 if (Op0C->getType()->getPrimitiveSizeInBits() <
1242 MulC->getType()->getPrimitiveSizeInBits())
1243 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
1244 if (Op0C->getType()->getPrimitiveSizeInBits() >
1245 MulC->getType()->getPrimitiveSizeInBits())
1246 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
1247
1248 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1249 Multiple = ConstantExpr::getMul(MulC, Op0C);
1250 return true;
1251 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001252
1253 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1254 if (Mul1CI->getValue() == 1) {
1255 // V == Base * Op0, so return Op0
1256 Multiple = Op0;
1257 return true;
1258 }
1259 }
Victor Hernandez2b6705f2009-11-10 08:28:35 +00001260 }
1261 }
1262
1263 // We could not determine if V is a multiple of Base.
1264 return false;
1265}
1266
Chris Lattner833f25d2008-06-02 01:29:46 +00001267/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1268/// value is never equal to -0.0.
1269///
1270/// NOTE: this function will need to be revisited when we support non-default
1271/// rounding modes!
1272///
1273bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1274 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1275 return !CFP->getValueAPF().isNegZero();
1276
1277 if (Depth == 6)
1278 return 1; // Limit search depth.
1279
Dan Gohmanca178902009-07-17 20:47:02 +00001280 const Operator *I = dyn_cast<Operator>(V);
Chris Lattner833f25d2008-06-02 01:29:46 +00001281 if (I == 0) return false;
1282
1283 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001284 if (I->getOpcode() == Instruction::FAdd &&
Chris Lattner833f25d2008-06-02 01:29:46 +00001285 isa<ConstantFP>(I->getOperand(1)) &&
1286 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1287 return true;
1288
1289 // sitofp and uitofp turn into +0.0 for zero.
1290 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1291 return true;
1292
1293 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1294 // sqrt(-0.0) = -0.0, no other negative results are possible.
1295 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif71339c92010-06-23 23:38:07 +00001296 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001297
1298 if (const CallInst *CI = dyn_cast<CallInst>(I))
1299 if (const Function *F = CI->getCalledFunction()) {
1300 if (F->isDeclaration()) {
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001301 // abs(x) != -0.0
1302 if (F->getName() == "abs") return true;
Dale Johannesen9d061752009-09-25 20:54:50 +00001303 // fabs[lf](x) != -0.0
1304 if (F->getName() == "fabs") return true;
1305 if (F->getName() == "fabsf") return true;
1306 if (F->getName() == "fabsl") return true;
1307 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1308 F->getName() == "sqrtl")
Gabor Greif71339c92010-06-23 23:38:07 +00001309 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattner833f25d2008-06-02 01:29:46 +00001310 }
1311 }
1312
1313 return false;
1314}
1315
Chris Lattnerbb897102010-12-26 20:15:01 +00001316/// isBytewiseValue - If the specified value can be set by repeating the same
1317/// byte in memory, return the i8 value that it is represented with. This is
1318/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1319/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1320/// byte store (e.g. i16 0x1234), return null.
1321Value *llvm::isBytewiseValue(Value *V) {
1322 // All byte-wide stores are splatable, even of arbitrary variables.
1323 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattner41bfbb02011-02-19 19:35:49 +00001324
1325 // Handle 'null' ConstantArrayZero etc.
1326 if (Constant *C = dyn_cast<Constant>(V))
1327 if (C->isNullValue())
1328 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Chris Lattnerbb897102010-12-26 20:15:01 +00001329
1330 // Constant float and double values can be handled as integer values if the
1331 // corresponding integer value is "byteable". An important case is 0.0.
1332 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1333 if (CFP->getType()->isFloatTy())
1334 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
1335 if (CFP->getType()->isDoubleTy())
1336 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
1337 // Don't handle long double formats, which have strange constraints.
1338 }
1339
1340 // We can handle constant integers that are power of two in size and a
1341 // multiple of 8 bits.
1342 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1343 unsigned Width = CI->getBitWidth();
1344 if (isPowerOf2_32(Width) && Width > 8) {
1345 // We can handle this value if the recursive binary decomposition is the
1346 // same at all levels.
1347 APInt Val = CI->getValue();
1348 APInt Val2;
1349 while (Val.getBitWidth() != 8) {
1350 unsigned NextWidth = Val.getBitWidth()/2;
1351 Val2 = Val.lshr(NextWidth);
1352 Val2 = Val2.trunc(Val.getBitWidth()/2);
1353 Val = Val.trunc(Val.getBitWidth()/2);
1354
1355 // If the top/bottom halves aren't the same, reject it.
1356 if (Val != Val2)
1357 return 0;
1358 }
1359 return ConstantInt::get(V->getContext(), Val);
1360 }
1361 }
1362
Chris Lattner18c7f802012-02-05 02:29:43 +00001363 // A ConstantDataArray/Vector is splatable if all its members are equal and
1364 // also splatable.
1365 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
1366 Value *Elt = CA->getElementAsConstant(0);
1367 Value *Val = isBytewiseValue(Elt);
Chris Lattnerbb897102010-12-26 20:15:01 +00001368 if (!Val)
1369 return 0;
1370
Chris Lattner18c7f802012-02-05 02:29:43 +00001371 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
1372 if (CA->getElementAsConstant(I) != Elt)
Chris Lattnerbb897102010-12-26 20:15:01 +00001373 return 0;
1374
1375 return Val;
1376 }
Chad Rosierdce42b72011-12-06 00:19:08 +00001377
Chris Lattnerbb897102010-12-26 20:15:01 +00001378 // Conceptually, we could handle things like:
1379 // %a = zext i8 %X to i16
1380 // %b = shl i16 %a, 8
1381 // %c = or i16 %a, %b
1382 // but until there is an example that actually needs this, it doesn't seem
1383 // worth worrying about.
1384 return 0;
1385}
1386
1387
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001388// This is the recursive version of BuildSubAggregate. It takes a few different
1389// arguments. Idxs is the index within the nested struct From that we are
1390// looking at now (which is of type IndexedType). IdxSkip is the number of
1391// indices from Idxs that should be left out when inserting into the resulting
1392// struct. To is the result struct built so far, new insertvalue instructions
1393// build on that.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001394static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Dan Gohman7db949d2009-08-07 01:32:21 +00001395 SmallVector<unsigned, 10> &Idxs,
1396 unsigned IdxSkip,
Dan Gohman7db949d2009-08-07 01:32:21 +00001397 Instruction *InsertBefore) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001398 llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001399 if (STy) {
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001400 // Save the original To argument so we can modify it
1401 Value *OrigTo = To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001402 // General case, the type indexed by Idxs is a struct
1403 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1404 // Process each struct element recursively
1405 Idxs.push_back(i);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001406 Value *PrevTo = To;
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001407 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001408 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001409 Idxs.pop_back();
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001410 if (!To) {
1411 // Couldn't find any inserted value for this index? Cleanup
1412 while (PrevTo != OrigTo) {
1413 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
1414 PrevTo = Del->getAggregateOperand();
1415 Del->eraseFromParent();
1416 }
1417 // Stop processing elements
1418 break;
1419 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001420 }
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001421 // If we successfully found a value for each of our subaggregates
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001422 if (To)
1423 return To;
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001424 }
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001425 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
1426 // the struct's elements had a value that was inserted directly. In the latter
1427 // case, perhaps we can't determine each of the subelements individually, but
1428 // we might be able to find the complete struct somewhere.
1429
1430 // Find the value that is at that particular spot
Jay Foadfc6d3a42011-07-13 10:26:04 +00001431 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001432
1433 if (!V)
1434 return NULL;
1435
1436 // Insert the value in the new (sub) aggregrate
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001437 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001438 "tmp", InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001439}
1440
1441// This helper takes a nested struct and extracts a part of it (which is again a
1442// struct) into a new value. For example, given the struct:
1443// { a, { b, { c, d }, e } }
1444// and the indices "1, 1" this returns
1445// { c, d }.
1446//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001447// It does this by inserting an insertvalue for each element in the resulting
1448// struct, as opposed to just inserting a single struct. This will only work if
1449// each of the elements of the substruct are known (ie, inserted into From by an
1450// insertvalue instruction somewhere).
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001451//
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001452// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foadfc6d3a42011-07-13 10:26:04 +00001453static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohman7db949d2009-08-07 01:32:21 +00001454 Instruction *InsertBefore) {
Matthijs Kooijman97728912008-06-16 13:28:31 +00001455 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001456 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001457 idx_range);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001458 Value *To = UndefValue::get(IndexedType);
Jay Foadfc6d3a42011-07-13 10:26:04 +00001459 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001460 unsigned IdxSkip = Idxs.size();
1461
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001462 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001463}
1464
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001465/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
1466/// the scalar value indexed is already around as a register, for example if it
1467/// were inserted directly into the aggregrate.
Matthijs Kooijman0a9aaf42008-06-16 14:13:46 +00001468///
1469/// If InsertBefore is not null, this function will duplicate (modified)
1470/// insertvalues when a part of a nested struct is extracted.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001471Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
1472 Instruction *InsertBefore) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001473 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerdf390282012-01-24 07:54:10 +00001474 // recursion).
Jay Foadfc6d3a42011-07-13 10:26:04 +00001475 if (idx_range.empty())
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001476 return V;
Chris Lattnerdf390282012-01-24 07:54:10 +00001477 // We have indices, so V should have an indexable type.
1478 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
1479 "Not looking at a struct or array?");
1480 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
1481 "Invalid indices for type?");
Owen Anderson76f600b2009-07-06 22:37:39 +00001482
Chris Lattnera1f00f42012-01-25 06:48:06 +00001483 if (Constant *C = dyn_cast<Constant>(V)) {
1484 C = C->getAggregateElement(idx_range[0]);
1485 if (C == 0) return 0;
1486 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
1487 }
Chris Lattnerdf390282012-01-24 07:54:10 +00001488
1489 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001490 // Loop the indices for the insertvalue instruction in parallel with the
1491 // requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001492 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001493 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
1494 i != e; ++i, ++req_idx) {
Jay Foadfc6d3a42011-07-13 10:26:04 +00001495 if (req_idx == idx_range.end()) {
Chris Lattnerdf390282012-01-24 07:54:10 +00001496 // We can't handle this without inserting insertvalues
1497 if (!InsertBefore)
Matthijs Kooijman97728912008-06-16 13:28:31 +00001498 return 0;
Chris Lattnerdf390282012-01-24 07:54:10 +00001499
1500 // The requested index identifies a part of a nested aggregate. Handle
1501 // this specially. For example,
1502 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
1503 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
1504 // %C = extractvalue {i32, { i32, i32 } } %B, 1
1505 // This can be changed into
1506 // %A = insertvalue {i32, i32 } undef, i32 10, 0
1507 // %C = insertvalue {i32, i32 } %A, i32 11, 1
1508 // which allows the unused 0,0 element from the nested struct to be
1509 // removed.
1510 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
1511 InsertBefore);
Duncan Sands9954c762008-06-19 08:47:31 +00001512 }
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001513
1514 // This insert value inserts something else than what we are looking for.
1515 // See if the (aggregrate) value inserted into has the value we are
1516 // looking for, then.
1517 if (*req_idx != *i)
Jay Foadfc6d3a42011-07-13 10:26:04 +00001518 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001519 InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001520 }
1521 // If we end up here, the indices of the insertvalue match with those
1522 // requested (though possibly only partially). Now we recursively look at
1523 // the inserted value, passing any remaining indices.
Jay Foadfc6d3a42011-07-13 10:26:04 +00001524 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001525 makeArrayRef(req_idx, idx_range.end()),
Nick Lewyckyae3d8022009-11-23 03:29:18 +00001526 InsertBefore);
Chris Lattnerdf390282012-01-24 07:54:10 +00001527 }
1528
1529 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001530 // If we're extracting a value from an aggregrate that was extracted from
1531 // something else, we can extract from that something else directly instead.
1532 // However, we will need to chain I's indices with the requested indices.
1533
1534 // Calculate the number of indices required
Jay Foadfc6d3a42011-07-13 10:26:04 +00001535 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001536 // Allocate some space to put the new indices in
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001537 SmallVector<unsigned, 5> Idxs;
1538 Idxs.reserve(size);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001539 // Add indices from the extract value instruction
Jay Foadfc6d3a42011-07-13 10:26:04 +00001540 Idxs.append(I->idx_begin(), I->idx_end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001541
1542 // Add requested indices
Jay Foadfc6d3a42011-07-13 10:26:04 +00001543 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001544
Matthijs Kooijman3faf9df2008-06-17 08:24:37 +00001545 assert(Idxs.size() == size
Matthijs Kooijman710eb232008-06-16 12:57:37 +00001546 && "Number of indices added not correct?");
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001547
Jay Foadfc6d3a42011-07-13 10:26:04 +00001548 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmanb23d5ad2008-06-16 12:48:21 +00001549 }
1550 // Otherwise, we don't know (such as, extracting from a function return value
1551 // or load instruction)
1552 return 0;
1553}
Evan Cheng0ff39b32008-06-30 07:31:25 +00001554
Chris Lattnered58a6f2010-11-30 22:25:26 +00001555/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
1556/// it can be expressed as a base pointer plus a constant offset. Return the
1557/// base and offset to the caller.
1558Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1559 const TargetData &TD) {
1560 Operator *PtrOp = dyn_cast<Operator>(Ptr);
Nadav Rotem16087692011-12-05 06:29:09 +00001561 if (PtrOp == 0 || Ptr->getType()->isVectorTy())
1562 return Ptr;
Chris Lattnered58a6f2010-11-30 22:25:26 +00001563
1564 // Just look through bitcasts.
1565 if (PtrOp->getOpcode() == Instruction::BitCast)
1566 return GetPointerBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1567
1568 // If this is a GEP with constant indices, we can look through it.
1569 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1570 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1571
1572 gep_type_iterator GTI = gep_type_begin(GEP);
1573 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1574 ++I, ++GTI) {
1575 ConstantInt *OpC = cast<ConstantInt>(*I);
1576 if (OpC->isZero()) continue;
1577
1578 // Handle a struct and array indices which add their offset to the pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001579 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattnered58a6f2010-11-30 22:25:26 +00001580 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1581 } else {
1582 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1583 Offset += OpC->getSExtValue()*Size;
1584 }
1585 }
1586
1587 // Re-sign extend from the pointer size if needed to get overflow edge cases
1588 // right.
1589 unsigned PtrSize = TD.getPointerSizeInBits();
1590 if (PtrSize < 64)
1591 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1592
1593 return GetPointerBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1594}
1595
1596
Chris Lattner18c7f802012-02-05 02:29:43 +00001597/// getConstantStringInfo - This function computes the length of a
Evan Cheng0ff39b32008-06-30 07:31:25 +00001598/// null-terminated C string pointed to by V. If successful, it returns true
1599/// and returns the string in Str. If unsuccessful, it returns false.
Chris Lattner18c7f802012-02-05 02:29:43 +00001600bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
1601 uint64_t Offset, bool TrimAtNul) {
1602 assert(V);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001603
Chris Lattner18c7f802012-02-05 02:29:43 +00001604 // Look through bitcast instructions and geps.
1605 V = V->stripPointerCasts();
Bill Wendling0582ae92009-03-13 04:39:26 +00001606
Chris Lattner18c7f802012-02-05 02:29:43 +00001607 // If the value is a GEP instructionor constant expression, treat it as an
1608 // offset.
1609 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001610 // Make sure the GEP has exactly three arguments.
Bill Wendling0582ae92009-03-13 04:39:26 +00001611 if (GEP->getNumOperands() != 3)
1612 return false;
1613
Evan Cheng0ff39b32008-06-30 07:31:25 +00001614 // Make sure the index-ee is a pointer to array of i8.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001615 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
1616 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001617 if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
Bill Wendling0582ae92009-03-13 04:39:26 +00001618 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001619
1620 // Check to make sure that the first operand of the GEP is an integer and
1621 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0a60fa32010-04-14 22:20:45 +00001622 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Bill Wendling0582ae92009-03-13 04:39:26 +00001623 if (FirstIdx == 0 || !FirstIdx->isZero())
1624 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001625
1626 // If the second index isn't a ConstantInt, then this is a variable index
1627 // into the array. If this occurs, we can't say anything meaningful about
1628 // the string.
1629 uint64_t StartIdx = 0;
Dan Gohman0a60fa32010-04-14 22:20:45 +00001630 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Cheng0ff39b32008-06-30 07:31:25 +00001631 StartIdx = CI->getZExtValue();
Bill Wendling0582ae92009-03-13 04:39:26 +00001632 else
1633 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001634 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Cheng0ff39b32008-06-30 07:31:25 +00001635 }
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001636
Evan Cheng0ff39b32008-06-30 07:31:25 +00001637 // The GEP instruction, constant or instruction, must reference a global
1638 // variable that is a constant and is initialized. The referenced constant
1639 // initializer is the array that we'll use for optimization.
Chris Lattner18c7f802012-02-05 02:29:43 +00001640 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman82555732009-08-19 18:20:44 +00001641 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendling0582ae92009-03-13 04:39:26 +00001642 return false;
Chris Lattner18c7f802012-02-05 02:29:43 +00001643
Nick Lewycky0cd0fee2011-10-20 00:34:35 +00001644 // Handle the all-zeros case
Chris Lattner18c7f802012-02-05 02:29:43 +00001645 if (GV->getInitializer()->isNullValue()) {
Evan Cheng0ff39b32008-06-30 07:31:25 +00001646 // This is a degenerate case. The initializer is constant zero so the
1647 // length of the string must be zero.
Chris Lattner18c7f802012-02-05 02:29:43 +00001648 Str = "";
Bill Wendling0582ae92009-03-13 04:39:26 +00001649 return true;
1650 }
Evan Cheng0ff39b32008-06-30 07:31:25 +00001651
1652 // Must be a Constant Array
Chris Lattner18c7f802012-02-05 02:29:43 +00001653 const ConstantDataArray *Array =
1654 dyn_cast<ConstantDataArray>(GV->getInitializer());
1655 if (Array == 0 || !Array->isString())
Bill Wendling0582ae92009-03-13 04:39:26 +00001656 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001657
1658 // Get the number of elements in the array
Chris Lattner18c7f802012-02-05 02:29:43 +00001659 uint64_t NumElts = Array->getType()->getArrayNumElements();
1660
1661 // Start out with the entire array in the StringRef.
1662 Str = Array->getAsString();
1663
Bill Wendling0582ae92009-03-13 04:39:26 +00001664 if (Offset > NumElts)
1665 return false;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001666
Chris Lattner18c7f802012-02-05 02:29:43 +00001667 // Skip over 'offset' bytes.
1668 Str = Str.substr(Offset);
Argyrios Kyrtzidis91766fe2012-02-01 04:51:17 +00001669
Chris Lattner18c7f802012-02-05 02:29:43 +00001670 if (TrimAtNul) {
1671 // Trim off the \0 and anything after it. If the array is not nul
1672 // terminated, we just return the whole end of string. The client may know
1673 // some other way that the string is length-bound.
1674 Str = Str.substr(0, Str.find('\0'));
1675 }
Bill Wendling0582ae92009-03-13 04:39:26 +00001676 return true;
Evan Cheng0ff39b32008-06-30 07:31:25 +00001677}
Eric Christopher25ec4832010-03-05 06:58:57 +00001678
1679// These next two are very similar to the above, but also look through PHI
1680// nodes.
1681// TODO: See if we can integrate these two together.
1682
1683/// GetStringLengthH - If we can compute the length of the string pointed to by
1684/// the specified pointer, return 'len+1'. If we can't, return 0.
1685static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
1686 // Look through noop bitcast instructions.
Chris Lattner18c7f802012-02-05 02:29:43 +00001687 V = V->stripPointerCasts();
Eric Christopher25ec4832010-03-05 06:58:57 +00001688
1689 // If this is a PHI node, there are two cases: either we have already seen it
1690 // or we haven't.
1691 if (PHINode *PN = dyn_cast<PHINode>(V)) {
1692 if (!PHIs.insert(PN))
1693 return ~0ULL; // already in the set.
1694
1695 // If it was new, see if all the input strings are the same length.
1696 uint64_t LenSoFar = ~0ULL;
1697 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1698 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
1699 if (Len == 0) return 0; // Unknown length -> unknown.
1700
1701 if (Len == ~0ULL) continue;
1702
1703 if (Len != LenSoFar && LenSoFar != ~0ULL)
1704 return 0; // Disagree -> unknown.
1705 LenSoFar = Len;
1706 }
1707
1708 // Success, all agree.
1709 return LenSoFar;
1710 }
1711
1712 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
1713 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1714 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
1715 if (Len1 == 0) return 0;
1716 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
1717 if (Len2 == 0) return 0;
1718 if (Len1 == ~0ULL) return Len2;
1719 if (Len2 == ~0ULL) return Len1;
1720 if (Len1 != Len2) return 0;
1721 return Len1;
1722 }
Chris Lattner18c7f802012-02-05 02:29:43 +00001723
1724 // Otherwise, see if we can read the string.
1725 StringRef StrData;
1726 if (!getConstantStringInfo(V, StrData))
Eric Christopher25ec4832010-03-05 06:58:57 +00001727 return 0;
1728
Chris Lattner18c7f802012-02-05 02:29:43 +00001729 return StrData.size()+1;
Eric Christopher25ec4832010-03-05 06:58:57 +00001730}
1731
1732/// GetStringLength - If we can compute the length of the string pointed to by
1733/// the specified pointer, return 'len+1'. If we can't, return 0.
1734uint64_t llvm::GetStringLength(Value *V) {
1735 if (!V->getType()->isPointerTy()) return 0;
1736
1737 SmallPtrSet<PHINode*, 32> PHIs;
1738 uint64_t Len = GetStringLengthH(V, PHIs);
1739 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
1740 // an empty string as a length.
1741 return Len == ~0ULL ? 1 : Len;
1742}
Dan Gohman5034dd32010-12-15 20:02:24 +00001743
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001744Value *
1745llvm::GetUnderlyingObject(Value *V, const TargetData *TD, unsigned MaxLookup) {
Dan Gohman5034dd32010-12-15 20:02:24 +00001746 if (!V->getType()->isPointerTy())
1747 return V;
1748 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
1749 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1750 V = GEP->getPointerOperand();
1751 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1752 V = cast<Operator>(V)->getOperand(0);
1753 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1754 if (GA->mayBeOverridden())
1755 return V;
1756 V = GA->getAliasee();
1757 } else {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001758 // See if InstructionSimplify knows any relevant tricks.
1759 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001760 // TODO: Acquire a DominatorTree and use it.
Dan Gohmanbd1801b2011-01-24 18:53:32 +00001761 if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
Dan Gohmanc01895c2010-12-15 20:49:55 +00001762 V = Simplified;
1763 continue;
1764 }
1765
Dan Gohman5034dd32010-12-15 20:02:24 +00001766 return V;
1767 }
1768 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1769 }
1770 return V;
1771}
Nick Lewycky99e0b2a2011-06-27 04:20:45 +00001772
1773/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
1774/// are lifetime markers.
1775///
1776bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
1777 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
1778 UI != UE; ++UI) {
1779 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
1780 if (!II) return false;
1781
1782 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1783 II->getIntrinsicID() != Intrinsic::lifetime_end)
1784 return false;
1785 }
1786 return true;
1787}
Dan Gohmanf0426602011-12-14 23:49:11 +00001788
Dan Gohmanfebaf842012-01-04 23:01:09 +00001789bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Dan Gohmanf0426602011-12-14 23:49:11 +00001790 const TargetData *TD) {
Dan Gohmanfebaf842012-01-04 23:01:09 +00001791 const Operator *Inst = dyn_cast<Operator>(V);
1792 if (!Inst)
1793 return false;
1794
Dan Gohmanf0426602011-12-14 23:49:11 +00001795 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
1796 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
1797 if (C->canTrap())
1798 return false;
1799
1800 switch (Inst->getOpcode()) {
1801 default:
1802 return true;
1803 case Instruction::UDiv:
1804 case Instruction::URem:
1805 // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
1806 return isKnownNonZero(Inst->getOperand(1), TD);
1807 case Instruction::SDiv:
1808 case Instruction::SRem: {
1809 Value *Op = Inst->getOperand(1);
1810 // x / y is undefined if y == 0
1811 if (!isKnownNonZero(Op, TD))
1812 return false;
1813 // x / y might be undefined if y == -1
1814 unsigned BitWidth = getBitWidth(Op->getType(), TD);
1815 if (BitWidth == 0)
1816 return false;
1817 APInt KnownZero(BitWidth, 0);
1818 APInt KnownOne(BitWidth, 0);
1819 ComputeMaskedBits(Op, APInt::getAllOnesValue(BitWidth),
1820 KnownZero, KnownOne, TD);
1821 return !!KnownZero;
1822 }
1823 case Instruction::Load: {
1824 const LoadInst *LI = cast<LoadInst>(Inst);
1825 if (!LI->isUnordered())
1826 return false;
1827 return LI->getPointerOperand()->isDereferenceablePointer();
1828 }
Nick Lewycky83696872011-12-21 05:52:02 +00001829 case Instruction::Call: {
1830 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1831 switch (II->getIntrinsicID()) {
1832 case Intrinsic::bswap:
1833 case Intrinsic::ctlz:
1834 case Intrinsic::ctpop:
1835 case Intrinsic::cttz:
1836 case Intrinsic::objectsize:
1837 case Intrinsic::sadd_with_overflow:
1838 case Intrinsic::smul_with_overflow:
1839 case Intrinsic::ssub_with_overflow:
1840 case Intrinsic::uadd_with_overflow:
1841 case Intrinsic::umul_with_overflow:
1842 case Intrinsic::usub_with_overflow:
1843 return true;
1844 // TODO: some fp intrinsics are marked as having the same error handling
1845 // as libm. They're safe to speculate when they won't error.
1846 // TODO: are convert_{from,to}_fp16 safe?
1847 // TODO: can we list target-specific intrinsics here?
1848 default: break;
1849 }
1850 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001851 return false; // The called function could have undefined behavior or
Nick Lewycky83696872011-12-21 05:52:02 +00001852 // side-effects, even if marked readnone nounwind.
1853 }
Dan Gohmanf0426602011-12-14 23:49:11 +00001854 case Instruction::VAArg:
1855 case Instruction::Alloca:
1856 case Instruction::Invoke:
1857 case Instruction::PHI:
1858 case Instruction::Store:
1859 case Instruction::Ret:
1860 case Instruction::Br:
1861 case Instruction::IndirectBr:
1862 case Instruction::Switch:
Dan Gohmanf0426602011-12-14 23:49:11 +00001863 case Instruction::Unreachable:
1864 case Instruction::Fence:
1865 case Instruction::LandingPad:
1866 case Instruction::AtomicRMW:
1867 case Instruction::AtomicCmpXchg:
1868 case Instruction::Resume:
1869 return false; // Misc instructions which have effects
1870 }
1871}