blob: cf6b92d74f93914280ace572716393ee2f53161d [file] [log] [blame]
Chris Lattner965c7692008-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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000018#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000019#include "llvm/Analysis/MemoryBuiltins.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000020#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000021#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000034#include "llvm/Support/Debug.h"
Chris Lattner965c7692008-06-02 01:18:21 +000035#include "llvm/Support/MathExtras.h"
Chris Lattner64496902008-06-04 04:46:14 +000036#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000037using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000038using namespace llvm::PatternMatch;
39
40const unsigned MaxDepth = 6;
41
Sanjay Patelaee84212014-11-04 16:27:42 +000042/// Returns the bitwidth of the given scalar or pointer type (if unknown returns
43/// 0). For vector types, returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000044static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000045 if (unsigned BitWidth = Ty->getScalarSizeInBits())
46 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000047
Mehdi Aminia28d91d2015-03-10 02:37:25 +000048 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000049}
Chris Lattner965c7692008-06-02 01:18:21 +000050
Hal Finkel60db0582014-09-07 18:57:58 +000051// Many of these functions have internal versions that take an assumption
52// exclusion set. This is because of the potential for mutual recursion to
53// cause computeKnownBits to repeatedly visit the same assume intrinsic. The
54// classic case of this is assume(x = y), which will attempt to determine
55// bits in x from bits in y, which will attempt to determine bits in y from
56// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
57// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
58// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
59typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
60
Benjamin Kramercfd8d902014-09-12 08:56:53 +000061namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000062// Simplifying using an assume can only be done in a particular control-flow
63// context (the context instruction provides that context). If an assume and
64// the context instruction are not in the same block then the DT helps in
65// figuring out if we can use it.
66struct Query {
67 ExclInvsSet ExclInvs;
Chandler Carruth66b31302015-01-04 12:03:27 +000068 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000069 const Instruction *CxtI;
70 const DominatorTree *DT;
71
Chandler Carruth66b31302015-01-04 12:03:27 +000072 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
Hal Finkel60db0582014-09-07 18:57:58 +000073 const DominatorTree *DT = nullptr)
Chandler Carruth66b31302015-01-04 12:03:27 +000074 : AC(AC), CxtI(CxtI), DT(DT) {}
Hal Finkel60db0582014-09-07 18:57:58 +000075
76 Query(const Query &Q, const Value *NewExcl)
Chandler Carruth66b31302015-01-04 12:03:27 +000077 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
Hal Finkel60db0582014-09-07 18:57:58 +000078 ExclInvs.insert(NewExcl);
79 }
80};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000081} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +000082
Sanjay Patel547e9752014-11-04 16:09:50 +000083// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +000084// the preferred context instruction (if any).
85static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
86 // If we've been provided with a context instruction, then use that (provided
87 // it has been inserted).
88 if (CxtI && CxtI->getParent())
89 return CxtI;
90
91 // If the value is really an already-inserted instruction, then use that.
92 CxtI = dyn_cast<Instruction>(V);
93 if (CxtI && CxtI->getParent())
94 return CxtI;
95
96 return nullptr;
97}
98
99static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000100 const DataLayout &DL, unsigned Depth,
101 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000102
103void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000104 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000105 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000106 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000107 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000108 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000109}
110
111static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000112 const DataLayout &DL, unsigned Depth,
113 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000114
115void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000116 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000117 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000118 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000119 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000120 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000121}
122
123static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000124 const Query &Q, const DataLayout &DL);
Hal Finkel60db0582014-09-07 18:57:58 +0000125
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000126bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
Chandler Carruth66b31302015-01-04 12:03:27 +0000127 unsigned Depth, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000128 const Instruction *CxtI,
129 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
131 Query(AC, safeCxtI(V, CxtI), DT), DL);
132}
133
134static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
135 const Query &Q);
136
137bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
138 AssumptionCache *AC, const Instruction *CxtI,
139 const DominatorTree *DT) {
140 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
141}
142
143static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
144 unsigned Depth, const Query &Q);
145
146bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
147 unsigned Depth, AssumptionCache *AC,
148 const Instruction *CxtI, const DominatorTree *DT) {
149 return ::MaskedValueIsZero(V, Mask, DL, Depth,
150 Query(AC, safeCxtI(V, CxtI), DT));
151}
152
153static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
154 unsigned Depth, const Query &Q);
155
156unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
157 unsigned Depth, AssumptionCache *AC,
158 const Instruction *CxtI,
159 const DominatorTree *DT) {
160 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000161}
162
Jay Foada0653a32014-05-14 21:14:37 +0000163static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
164 APInt &KnownZero, APInt &KnownOne,
165 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000167 const Query &Q) {
168 if (!Add) {
169 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
170 // We know that the top bits of C-X are clear if X contains less bits
171 // than C (i.e. no wrap-around can happen). For example, 20-X is
172 // positive if we can prove that X is >= 0 and < 16.
173 if (!CLHS->getValue().isNegative()) {
174 unsigned BitWidth = KnownZero.getBitWidth();
175 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
176 // NLZ can't be BitWidth with no sign bit
177 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000178 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000179
180 // If all of the MaskV bits are known to be zero, then we know the
181 // output top bits are zero, because we now know that the output is
182 // from [0-C].
183 if ((KnownZero2 & MaskV) == MaskV) {
184 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
185 // Top bits known zero.
186 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
187 }
188 }
189 }
190 }
191
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000192 unsigned BitWidth = KnownZero.getBitWidth();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000193
David Majnemer97ddca32014-08-22 00:40:43 +0000194 // If an initial sequence of bits in the result is not needed, the
195 // corresponding bits in the operands are not needed.
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000196 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000197 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
198 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000199
David Majnemer97ddca32014-08-22 00:40:43 +0000200 // Carry in a 1 for a subtract, rather than a 0.
201 APInt CarryIn(BitWidth, 0);
202 if (!Add) {
203 // Sum = LHS + ~RHS + 1
204 std::swap(KnownZero2, KnownOne2);
205 CarryIn.setBit(0);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000206 }
207
David Majnemer97ddca32014-08-22 00:40:43 +0000208 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
209 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
210
211 // Compute known bits of the carry.
212 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
213 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
214
215 // Compute set of known bits (where all three relevant bits are known).
216 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
217 APInt RHSKnown = KnownZero2 | KnownOne2;
218 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
219 APInt Known = LHSKnown & RHSKnown & CarryKnown;
220
221 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
222 "known bits of sum differ");
223
224 // Compute known bits of the result.
225 KnownZero = ~PossibleSumOne & Known;
226 KnownOne = PossibleSumOne & Known;
227
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000228 // Are we still trying to solve for the sign bit?
David Majnemer97ddca32014-08-22 00:40:43 +0000229 if (!Known.isNegative()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000230 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000231 // Adding two non-negative numbers, or subtracting a negative number from
232 // a non-negative one, can't wrap into negative.
233 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
234 KnownZero |= APInt::getSignBit(BitWidth);
235 // Adding two negative numbers, or subtracting a non-negative number from
236 // a negative one, can't wrap into non-negative.
237 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
238 KnownOne |= APInt::getSignBit(BitWidth);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000239 }
240 }
241}
242
Jay Foada0653a32014-05-14 21:14:37 +0000243static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
244 APInt &KnownZero, APInt &KnownOne,
245 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000247 const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000248 unsigned BitWidth = KnownZero.getBitWidth();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
250 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000251
252 bool isKnownNegative = false;
253 bool isKnownNonNegative = false;
254 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000255 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000256 if (Op0 == Op1) {
257 // The product of a number with itself is non-negative.
258 isKnownNonNegative = true;
259 } else {
260 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
261 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
262 bool isKnownNegativeOp1 = KnownOne.isNegative();
263 bool isKnownNegativeOp0 = KnownOne2.isNegative();
264 // The product of two numbers with the same sign is non-negative.
265 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
266 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
267 // The product of a negative number and a non-negative number is either
268 // negative or zero.
269 if (!isKnownNonNegative)
270 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000271 isKnownNonZero(Op0, DL, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000272 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000273 isKnownNonZero(Op1, DL, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000274 }
275 }
276
277 // If low bits are zero in either operand, output low known-0 bits.
278 // Also compute a conserative estimate for high known-0 bits.
279 // More trickiness is possible, but this is sufficient for the
280 // interesting case of alignment computation.
281 KnownOne.clearAllBits();
282 unsigned TrailZ = KnownZero.countTrailingOnes() +
283 KnownZero2.countTrailingOnes();
284 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
285 KnownZero2.countLeadingOnes(),
286 BitWidth) - BitWidth;
287
288 TrailZ = std::min(TrailZ, BitWidth);
289 LeadZ = std::min(LeadZ, BitWidth);
290 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
291 APInt::getHighBitsSet(BitWidth, LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000292
293 // Only make use of no-wrap flags if we failed to compute the sign bit
294 // directly. This matters if the multiplication always overflows, in
295 // which case we prefer to follow the result of the direct computation,
296 // though as the program is invoking undefined behaviour we can choose
297 // whatever we like here.
298 if (isKnownNonNegative && !KnownOne.isNegative())
299 KnownZero.setBit(BitWidth - 1);
300 else if (isKnownNegative && !KnownZero.isNegative())
301 KnownOne.setBit(BitWidth - 1);
302}
303
Jingyue Wu37fcb592014-06-19 16:50:16 +0000304void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
305 APInt &KnownZero) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000306 unsigned BitWidth = KnownZero.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000307 unsigned NumRanges = Ranges.getNumOperands() / 2;
308 assert(NumRanges >= 1);
309
310 // Use the high end of the ranges to find leading zeros.
311 unsigned MinLeadingZeros = BitWidth;
312 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 ConstantInt *Lower =
314 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
315 ConstantInt *Upper =
316 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000317 ConstantRange Range(Lower->getValue(), Upper->getValue());
318 if (Range.isWrappedSet())
319 MinLeadingZeros = 0; // -1 has no zeros
320 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
321 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
322 }
323
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000324 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
Rafael Espindola53190532012-03-30 15:52:11 +0000325}
Jay Foad5a29c362014-05-15 12:12:55 +0000326
Hal Finkel60db0582014-09-07 18:57:58 +0000327static bool isEphemeralValueOf(Instruction *I, const Value *E) {
328 SmallVector<const Value *, 16> WorkSet(1, I);
329 SmallPtrSet<const Value *, 32> Visited;
330 SmallPtrSet<const Value *, 16> EphValues;
331
332 while (!WorkSet.empty()) {
333 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000334 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000335 continue;
336
337 // If all uses of this value are ephemeral, then so is this value.
338 bool FoundNEUse = false;
339 for (const User *I : V->users())
340 if (!EphValues.count(I)) {
341 FoundNEUse = true;
342 break;
343 }
344
345 if (!FoundNEUse) {
346 if (V == E)
347 return true;
348
349 EphValues.insert(V);
350 if (const User *U = dyn_cast<User>(V))
351 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
352 J != JE; ++J) {
353 if (isSafeToSpeculativelyExecute(*J))
354 WorkSet.push_back(*J);
355 }
356 }
357 }
358
359 return false;
360}
361
362// Is this an intrinsic that cannot be speculated but also cannot trap?
363static bool isAssumeLikeIntrinsic(const Instruction *I) {
364 if (const CallInst *CI = dyn_cast<CallInst>(I))
365 if (Function *F = CI->getCalledFunction())
366 switch (F->getIntrinsicID()) {
367 default: break;
368 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
369 case Intrinsic::assume:
370 case Intrinsic::dbg_declare:
371 case Intrinsic::dbg_value:
372 case Intrinsic::invariant_start:
373 case Intrinsic::invariant_end:
374 case Intrinsic::lifetime_start:
375 case Intrinsic::lifetime_end:
376 case Intrinsic::objectsize:
377 case Intrinsic::ptr_annotation:
378 case Intrinsic::var_annotation:
379 return true;
380 }
381
382 return false;
383}
384
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000385static bool isValidAssumeForContext(Value *V, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000386 Instruction *Inv = cast<Instruction>(V);
387
388 // There are two restrictions on the use of an assume:
389 // 1. The assume must dominate the context (or the control flow must
390 // reach the assume whenever it reaches the context).
391 // 2. The context must not be in the assume's set of ephemeral values
392 // (otherwise we will use the assume to prove that the condition
393 // feeding the assume is trivially true, thus causing the removal of
394 // the assume).
395
396 if (Q.DT) {
397 if (Q.DT->dominates(Inv, Q.CxtI)) {
398 return true;
399 } else if (Inv->getParent() == Q.CxtI->getParent()) {
400 // The context comes first, but they're both in the same block. Make sure
401 // there is nothing in between that might interrupt the control flow.
402 for (BasicBlock::const_iterator I =
403 std::next(BasicBlock::const_iterator(Q.CxtI)),
404 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000406 return false;
407
408 return !isEphemeralValueOf(Inv, Q.CxtI);
409 }
410
411 return false;
412 }
413
414 // When we don't have a DT, we do a limited search...
415 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
416 return true;
417 } else if (Inv->getParent() == Q.CxtI->getParent()) {
418 // Search forward from the assume until we reach the context (or the end
419 // of the block); the common case is that the assume will come first.
420 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
421 IE = Inv->getParent()->end(); I != IE; ++I)
422 if (I == Q.CxtI)
423 return true;
424
425 // The context must come first...
426 for (BasicBlock::const_iterator I =
427 std::next(BasicBlock::const_iterator(Q.CxtI)),
428 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000430 return false;
431
432 return !isEphemeralValueOf(Inv, Q.CxtI);
433 }
434
435 return false;
436}
437
438bool llvm::isValidAssumeForContext(const Instruction *I,
439 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000440 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
442 Query(nullptr, CxtI, DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000443}
444
445template<typename LHS, typename RHS>
446inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
447 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
448m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
449 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
450}
451
452template<typename LHS, typename RHS>
453inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
454 BinaryOp_match<RHS, LHS, Instruction::And>>
455m_c_And(const LHS &L, const RHS &R) {
456 return m_CombineOr(m_And(L, R), m_And(R, L));
457}
458
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000459template<typename LHS, typename RHS>
460inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
461 BinaryOp_match<RHS, LHS, Instruction::Or>>
462m_c_Or(const LHS &L, const RHS &R) {
463 return m_CombineOr(m_Or(L, R), m_Or(R, L));
464}
465
466template<typename LHS, typename RHS>
467inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
468 BinaryOp_match<RHS, LHS, Instruction::Xor>>
469m_c_Xor(const LHS &L, const RHS &R) {
470 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
471}
472
Hal Finkel60db0582014-09-07 18:57:58 +0000473static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 APInt &KnownOne, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +0000475 unsigned Depth, const Query &Q) {
476 // Use of assumptions is context-sensitive. If we don't have a context, we
477 // cannot use them!
Chandler Carruth66b31302015-01-04 12:03:27 +0000478 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000479 return;
480
481 unsigned BitWidth = KnownZero.getBitWidth();
482
Chandler Carruth66b31302015-01-04 12:03:27 +0000483 for (auto &AssumeVH : Q.AC->assumptions()) {
484 if (!AssumeVH)
485 continue;
486 CallInst *I = cast<CallInst>(AssumeVH);
Chandler Carruth75c11b82015-01-04 23:13:57 +0000487 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
Chandler Carruth66b31302015-01-04 12:03:27 +0000488 "Got assumption for the wrong function!");
Hal Finkel60db0582014-09-07 18:57:58 +0000489 if (Q.ExclInvs.count(I))
490 continue;
491
Philip Reames00d3b272014-11-24 23:44:28 +0000492 // Warning: This loop can end up being somewhat performance sensetive.
493 // We're running this loop for once for each value queried resulting in a
494 // runtime of ~O(#assumes * #values).
495
496 assert(isa<IntrinsicInst>(I) &&
497 dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
498 "must be an assume intrinsic");
499
500 Value *Arg = I->getArgOperand(0);
501
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502 if (Arg == V && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000503 assert(BitWidth == 1 && "assume operand is not i1?");
504 KnownZero.clearAllBits();
505 KnownOne.setAllBits();
506 return;
507 }
508
David Majnemer9b609752014-12-12 23:59:29 +0000509 // The remaining tests are all recursive, so bail out if we hit the limit.
510 if (Depth == MaxDepth)
511 continue;
512
Hal Finkel60db0582014-09-07 18:57:58 +0000513 Value *A, *B;
514 auto m_V = m_CombineOr(m_Specific(V),
515 m_CombineOr(m_PtrToInt(m_Specific(V)),
516 m_BitCast(m_Specific(V))));
517
518 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000519 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000520 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000521 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000522 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000523 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
524 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
525 KnownZero |= RHSKnownZero;
526 KnownOne |= RHSKnownOne;
527 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000528 } else if (match(Arg,
529 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
530 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000531 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
532 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
533 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
534 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
535
536 // For those bits in the mask that are known to be one, we can propagate
537 // known bits from the RHS to V.
538 KnownZero |= RHSKnownZero & MaskKnownOne;
539 KnownOne |= RHSKnownOne & MaskKnownOne;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000540 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000541 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
542 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000543 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000544 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
545 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
546 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
547 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
548
549 // For those bits in the mask that are known to be one, we can propagate
550 // inverted known bits from the RHS to V.
551 KnownZero |= RHSKnownOne & MaskKnownOne;
552 KnownOne |= RHSKnownZero & MaskKnownOne;
553 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000554 } else if (match(Arg,
555 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
556 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000557 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
558 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
559 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
560 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
561
562 // For those bits in B that are known to be zero, we can propagate known
563 // bits from the RHS to V.
564 KnownZero |= RHSKnownZero & BKnownZero;
565 KnownOne |= RHSKnownOne & BKnownZero;
566 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000567 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
568 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000569 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000570 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
571 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
572 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
573 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
574
575 // For those bits in B that are known to be zero, we can propagate
576 // inverted known bits from the RHS to V.
577 KnownZero |= RHSKnownOne & BKnownZero;
578 KnownOne |= RHSKnownZero & BKnownZero;
579 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000580 } else if (match(Arg,
581 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
582 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000583 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
584 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
585 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
586 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
587
588 // For those bits in B that are known to be zero, we can propagate known
589 // bits from the RHS to V. For those bits in B that are known to be one,
590 // we can propagate inverted known bits from the RHS to V.
591 KnownZero |= RHSKnownZero & BKnownZero;
592 KnownOne |= RHSKnownOne & BKnownZero;
593 KnownZero |= RHSKnownOne & BKnownOne;
594 KnownOne |= RHSKnownZero & BKnownOne;
595 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000596 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
597 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000598 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000599 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
600 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
601 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
602 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
603
604 // For those bits in B that are known to be zero, we can propagate
605 // inverted known bits from the RHS to V. For those bits in B that are
606 // known to be one, we can propagate known bits from the RHS to V.
607 KnownZero |= RHSKnownOne & BKnownZero;
608 KnownOne |= RHSKnownZero & BKnownZero;
609 KnownZero |= RHSKnownZero & BKnownOne;
610 KnownOne |= RHSKnownOne & BKnownOne;
611 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000612 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
613 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000614 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000615 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
616 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
617 // For those bits in RHS that are known, we can propagate them to known
618 // bits in V shifted to the right by C.
619 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
620 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
621 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000622 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
623 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000624 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000625 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
626 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
627 // For those bits in RHS that are known, we can propagate them inverted
628 // to known bits in V shifted to the right by C.
629 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
630 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
631 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000632 } else if (match(Arg,
633 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000634 m_AShr(m_V, m_ConstantInt(C))),
635 m_Value(A))) &&
636 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000637 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
638 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
639 // For those bits in RHS that are known, we can propagate them to known
640 // bits in V shifted to the right by C.
641 KnownZero |= RHSKnownZero << C->getZExtValue();
642 KnownOne |= RHSKnownOne << C->getZExtValue();
643 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000644 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 m_LShr(m_V, m_ConstantInt(C)),
646 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000647 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000648 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000649 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
650 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
651 // For those bits in RHS that are known, we can propagate them inverted
652 // to known bits in V shifted to the right by C.
653 KnownZero |= RHSKnownOne << C->getZExtValue();
654 KnownOne |= RHSKnownZero << C->getZExtValue();
655 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000656 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000657 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000658 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
659 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
660
661 if (RHSKnownZero.isNegative()) {
662 // We know that the sign bit is zero.
663 KnownZero |= APInt::getSignBit(BitWidth);
664 }
665 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000666 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000667 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000668 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
669 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
670
671 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
672 // We know that the sign bit is zero.
673 KnownZero |= APInt::getSignBit(BitWidth);
674 }
675 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000676 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000677 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000678 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
679 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
680
681 if (RHSKnownOne.isNegative()) {
682 // We know that the sign bit is one.
683 KnownOne |= APInt::getSignBit(BitWidth);
684 }
685 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000686 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000687 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000688 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
689 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
690
691 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
692 // We know that the sign bit is one.
693 KnownOne |= APInt::getSignBit(BitWidth);
694 }
695 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000696 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000697 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
699 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
700
701 // Whatever high bits in c are zero are known to be zero.
702 KnownZero |=
703 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
704 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000705 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000706 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000707 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
708 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
709
710 // Whatever high bits in c are zero are known to be zero (if c is a power
711 // of 2, then one more).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000713 KnownZero |=
714 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
715 else
716 KnownZero |=
717 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000718 }
719 }
720}
721
Jay Foada0653a32014-05-14 21:14:37 +0000722/// Determine which bits of V are known to be either zero or one and return
723/// them in the KnownZero/KnownOne bit sets.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000724///
Chris Lattner965c7692008-06-02 01:18:21 +0000725/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
726/// we cannot optimize based on the assumption that it is zero without changing
727/// it to be an explicit zero. If we don't change it to zero, other code could
728/// optimized based on the contradictory assumption that it is non-zero.
729/// Because instcombine aggressively folds operations with undef args anyway,
730/// this won't lose us code quality.
Chris Lattner4bc28252009-09-08 00:06:16 +0000731///
732/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733/// type, and vectors of integers. In the case
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000734/// where V is a vector, known zero, and known one values are the
Chris Lattner4bc28252009-09-08 00:06:16 +0000735/// same width as the vector element, and the bit is set only if it is true
736/// for all of the elements in the vector.
Hal Finkel60db0582014-09-07 18:57:58 +0000737void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000738 const DataLayout &DL, unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +0000739 assert(V && "No Value?");
Dan Gohmanbf0002e2009-05-21 02:28:33 +0000740 assert(Depth <= MaxDepth && "Limit Search Depth");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000741 unsigned BitWidth = KnownZero.getBitWidth();
742
Nadav Rotem3924cb02011-12-05 06:29:09 +0000743 assert((V->getType()->isIntOrIntVectorTy() ||
744 V->getType()->getScalarType()->isPointerTy()) &&
745 "Not integer or pointer type!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000746 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000747 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000748 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem3924cb02011-12-05 06:29:09 +0000749 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner965c7692008-06-02 01:18:21 +0000750 KnownOne.getBitWidth() == BitWidth &&
Jay Foade48d9e82014-05-14 08:00:07 +0000751 "V, KnownOne and KnownZero should have same BitWidth");
Chris Lattner965c7692008-06-02 01:18:21 +0000752
753 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
754 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000755 KnownOne = CI->getValue();
756 KnownZero = ~KnownOne;
Chris Lattner965c7692008-06-02 01:18:21 +0000757 return;
758 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000759 // Null and aggregate-zero are all-zeros.
760 if (isa<ConstantPointerNull>(V) ||
761 isa<ConstantAggregateZero>(V)) {
Jay Foad25a5e4c2010-12-01 08:53:58 +0000762 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000763 KnownZero = APInt::getAllOnesValue(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000764 return;
765 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000766 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner8213c8a2012-02-06 21:56:39 +0000767 // each element. There is no real need to handle ConstantVector here, because
768 // we don't handle undef in any particularly useful way.
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000769 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
770 // We know that CDS must be a vector of integers. Take the intersection of
771 // each element.
772 KnownZero.setAllBits(); KnownOne.setAllBits();
773 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner9be59592012-01-25 01:27:20 +0000774 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000775 Elt = CDS->getElementAsInteger(i);
776 KnownZero &= ~Elt;
Craig Topper1bef2c82012-12-22 19:15:35 +0000777 KnownOne &= Elt;
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000778 }
779 return;
780 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000781
Chris Lattner965c7692008-06-02 01:18:21 +0000782 // The address of an aligned GlobalValue has trailing zeros.
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000783 if (auto *GO = dyn_cast<GlobalObject>(V)) {
784 unsigned Align = GO->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000785 if (Align == 0) {
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000786 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000787 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000788 if (ObjectType->isSized()) {
789 // If the object is defined in the current Module, we'll be giving
790 // it the preferred alignment. Otherwise, we have to assume that it
791 // may only have the minimum ABI alignment.
792 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000793 Align = DL.getPreferredAlignment(GVar);
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000794 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 Align = DL.getABITypeAlignment(ObjectType);
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000796 }
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000797 }
Dan Gohmana72f8562009-08-11 15:50:03 +0000798 }
Chris Lattner965c7692008-06-02 01:18:21 +0000799 if (Align > 0)
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000800 KnownZero = APInt::getLowBitsSet(BitWidth,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000801 countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +0000802 else
Jay Foad25a5e4c2010-12-01 08:53:58 +0000803 KnownZero.clearAllBits();
804 KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +0000805 return;
806 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000807
Chris Lattner83791ce2011-05-23 00:03:39 +0000808 if (Argument *A = dyn_cast<Argument>(V)) {
Hal Finkelccc70902014-07-22 16:58:55 +0000809 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
Duncan Sands271ea6c2012-10-04 13:36:31 +0000810
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000811 if (!Align && A->hasStructRetAttr()) {
Duncan Sands271ea6c2012-10-04 13:36:31 +0000812 // An sret parameter has at least the ABI alignment of the return type.
813 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
814 if (EltTy->isSized())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000815 Align = DL.getABITypeAlignment(EltTy);
Duncan Sands271ea6c2012-10-04 13:36:31 +0000816 }
817
818 if (Align)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000819 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
David Majnemer8df46c92015-01-03 02:33:25 +0000820 else
821 KnownZero.clearAllBits();
822 KnownOne.clearAllBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000823
824 // Don't give up yet... there might be an assumption that provides more
825 // information...
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000826 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Chris Lattner83791ce2011-05-23 00:03:39 +0000827 return;
828 }
Chris Lattner965c7692008-06-02 01:18:21 +0000829
Chris Lattner83791ce2011-05-23 00:03:39 +0000830 // Start out not knowing anything.
831 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +0000832
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000833 // Limit search depth.
834 // All recursive calls that increase depth must come after this.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000835 if (Depth == MaxDepth)
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000836 return;
837
838 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
839 // the bits of its aliasee.
840 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
841 if (!GA->mayBeOverridden())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000842 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000843 return;
844 }
Chris Lattner965c7692008-06-02 01:18:21 +0000845
Hal Finkel60db0582014-09-07 18:57:58 +0000846 // Check whether a nearby assume intrinsic can determine some known bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000847 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000848
Dan Gohman80ca01c2009-07-17 20:47:02 +0000849 Operator *I = dyn_cast<Operator>(V);
Chris Lattner965c7692008-06-02 01:18:21 +0000850 if (!I) return;
851
852 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000853 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000854 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000855 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000856 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +0000857 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
Jay Foad5a29c362014-05-15 12:12:55 +0000858 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000859 case Instruction::And: {
860 // If either the LHS or the RHS are Zero, the result is zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000861 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
862 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000863
Chris Lattner965c7692008-06-02 01:18:21 +0000864 // Output known-1 bits are only known if set in both the LHS & RHS.
865 KnownOne &= KnownOne2;
866 // Output known-0 are known to be clear if zero in either the LHS | RHS.
867 KnownZero |= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +0000868 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000869 }
870 case Instruction::Or: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000871 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
872 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000873
Chris Lattner965c7692008-06-02 01:18:21 +0000874 // Output known-0 bits are only known if clear in both the LHS & RHS.
875 KnownZero &= KnownZero2;
876 // Output known-1 are known to be set if set in either the LHS | RHS.
877 KnownOne |= KnownOne2;
Jay Foad5a29c362014-05-15 12:12:55 +0000878 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000879 }
880 case Instruction::Xor: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000881 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
882 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000883
Chris Lattner965c7692008-06-02 01:18:21 +0000884 // Output known-0 bits are known if clear or set in both the LHS & RHS.
885 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
886 // Output known-1 are known to be set if set in only one of the LHS, RHS.
887 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
888 KnownZero = KnownZeroOut;
Jay Foad5a29c362014-05-15 12:12:55 +0000889 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000890 }
891 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000892 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000893 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
894 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000895 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000896 }
897 case Instruction::UDiv: {
898 // For the purposes of computing leading zeros we can conservatively
899 // treat a udiv as a logical right shift by the power of 2 known to
900 // be less than the denominator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000901 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000902 unsigned LeadZ = KnownZero2.countLeadingOnes();
903
Jay Foad25a5e4c2010-12-01 08:53:58 +0000904 KnownOne2.clearAllBits();
905 KnownZero2.clearAllBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000906 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000907 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
908 if (RHSUnknownLeadingOnes != BitWidth)
909 LeadZ = std::min(BitWidth,
910 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
911
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000912 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000913 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000914 }
915 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000916 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
917 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000918
919 // Only known if known in both the LHS and RHS.
920 KnownOne &= KnownOne2;
921 KnownZero &= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +0000922 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000923 case Instruction::FPTrunc:
924 case Instruction::FPExt:
925 case Instruction::FPToUI:
926 case Instruction::FPToSI:
927 case Instruction::SIToFP:
928 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +0000929 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +0000930 case Instruction::PtrToInt:
931 case Instruction::IntToPtr:
Matt Arsenaultf1a7e622014-07-15 01:55:03 +0000932 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
Chris Lattner965c7692008-06-02 01:18:21 +0000933 // FALL THROUGH and handle them the same as zext/trunc.
934 case Instruction::ZExt:
935 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +0000936 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +0000937
Chris Lattner0cdbc7a2009-09-08 00:13:52 +0000938 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +0000939 // Note that we handle pointer operands here because of inttoptr/ptrtoint
940 // which fall through here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000941 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +0000942
943 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Jay Foad583abbc2010-12-07 08:25:19 +0000944 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
945 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000946 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +0000947 KnownZero = KnownZero.zextOrTrunc(BitWidth);
948 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000949 // Any top bits are known to be zero.
950 if (BitWidth > SrcBitWidth)
951 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +0000952 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000953 }
954 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +0000955 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +0000956 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +0000957 // TODO: For now, not handling conversions like:
958 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +0000959 !I->getType()->isVectorTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000960 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +0000961 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000962 }
963 break;
964 }
965 case Instruction::SExt: {
966 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +0000967 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +0000968
Jay Foad583abbc2010-12-07 08:25:19 +0000969 KnownZero = KnownZero.trunc(SrcBitWidth);
970 KnownOne = KnownOne.trunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +0000972 KnownZero = KnownZero.zext(BitWidth);
973 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000974
975 // If the sign bit of the input is known set or clear, then we know the
976 // top bits of the result.
977 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
978 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
979 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
980 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +0000981 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000982 }
983 case Instruction::Shl:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000984 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Chris Lattner965c7692008-06-02 01:18:21 +0000985 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
986 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000987 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000988 KnownZero <<= ShiftAmt;
989 KnownOne <<= ShiftAmt;
990 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Chris Lattner965c7692008-06-02 01:18:21 +0000991 }
992 break;
993 case Instruction::LShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000994 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +0000995 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
996 // Compute the new bits that are at the top now.
997 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Craig Topper1bef2c82012-12-22 19:15:35 +0000998
Chris Lattner965c7692008-06-02 01:18:21 +0000999 // Unsigned shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001000 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001001 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1002 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1003 // high bits known zero.
1004 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Chris Lattner965c7692008-06-02 01:18:21 +00001005 }
1006 break;
1007 case Instruction::AShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001008 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001009 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1010 // Compute the new bits that are at the top now.
Chris Lattnerc86e67e2011-01-04 18:19:15 +00001011 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Craig Topper1bef2c82012-12-22 19:15:35 +00001012
Chris Lattner965c7692008-06-02 01:18:21 +00001013 // Signed shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001014 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001015 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1016 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Craig Topper1bef2c82012-12-22 19:15:35 +00001017
Chris Lattner965c7692008-06-02 01:18:21 +00001018 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1019 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1020 KnownZero |= HighBits;
1021 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1022 KnownOne |= HighBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001023 }
1024 break;
1025 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001026 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001027 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001028 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1029 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001030 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001031 }
Chris Lattner965c7692008-06-02 01:18:21 +00001032 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001033 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001034 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001035 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1036 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001037 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001038 }
1039 case Instruction::SRem:
1040 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001041 APInt RA = Rem->getValue().abs();
1042 if (RA.isPowerOf2()) {
1043 APInt LowBits = RA - 1;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001044 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1045 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001046
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001047 // The low bits of the first operand are unchanged by the srem.
1048 KnownZero = KnownZero2 & LowBits;
1049 KnownOne = KnownOne2 & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001050
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001051 // If the first operand is non-negative or has all low bits zero, then
1052 // the upper bits are all zero.
1053 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1054 KnownZero |= ~LowBits;
1055
1056 // If the first operand is negative and not all low bits are zero, then
1057 // the upper bits are all one.
1058 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1059 KnownOne |= ~LowBits;
1060
Craig Topper1bef2c82012-12-22 19:15:35 +00001061 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001062 }
1063 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001064
1065 // The sign bit is the LHS's sign bit, except when the result of the
1066 // remainder is zero.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001067 if (KnownZero.isNonNegative()) {
Nick Lewyckye4679792011-03-07 01:50:10 +00001068 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001069 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1070 Depth + 1, Q);
Nick Lewyckye4679792011-03-07 01:50:10 +00001071 // If it's known zero, our sign bit is also zero.
1072 if (LHSKnownZero.isNegative())
Duncan Sands34c48692012-04-30 11:56:58 +00001073 KnownZero.setBit(BitWidth - 1);
Nick Lewyckye4679792011-03-07 01:50:10 +00001074 }
1075
Chris Lattner965c7692008-06-02 01:18:21 +00001076 break;
1077 case Instruction::URem: {
1078 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1079 APInt RA = Rem->getValue();
1080 if (RA.isPowerOf2()) {
1081 APInt LowBits = (RA - 1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001082 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1083 Q);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001084 KnownZero |= ~LowBits;
1085 KnownOne &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001086 break;
1087 }
1088 }
1089
1090 // Since the result is less than or equal to either operand, any leading
1091 // zero bits in either operand must also exist in the result.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001092 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1093 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001094
Chris Lattner4612ae12009-01-20 18:22:57 +00001095 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner965c7692008-06-02 01:18:21 +00001096 KnownZero2.countLeadingOnes());
Jay Foad25a5e4c2010-12-01 08:53:58 +00001097 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001098 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001099 break;
1100 }
1101
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001102 case Instruction::Alloca: {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001103 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001104 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001105 if (Align == 0)
1106 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001107
Chris Lattner965c7692008-06-02 01:18:21 +00001108 if (Align > 0)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001109 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001110 break;
1111 }
1112 case Instruction::GetElementPtr: {
1113 // Analyze all of the subscripts of this getelementptr instruction
1114 // to determine if we can prove known low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001115 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001116 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1117 Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001118 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1119
1120 gep_type_iterator GTI = gep_type_begin(I);
1121 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1122 Value *Index = I->getOperand(i);
Chris Lattner229907c2011-07-18 04:54:35 +00001123 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001124 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001125
1126 // Handle case when index is vector zeroinitializer
1127 Constant *CIndex = cast<Constant>(Index);
1128 if (CIndex->isZeroValue())
1129 continue;
1130
1131 if (CIndex->getType()->isVectorTy())
1132 Index = CIndex->getSplatValue();
1133
Chris Lattner965c7692008-06-02 01:18:21 +00001134 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001135 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001136 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001137 TrailZ = std::min<unsigned>(TrailZ,
1138 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001139 } else {
1140 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001141 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001142 if (!IndexedTy->isSized()) {
1143 TrailZ = 0;
1144 break;
1145 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001146 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001147 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
Chris Lattner965c7692008-06-02 01:18:21 +00001148 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001149 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1150 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001151 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001152 unsigned(countTrailingZeros(TypeSize) +
Chris Lattner4612ae12009-01-20 18:22:57 +00001153 LocalKnownZero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001154 }
1155 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001156
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001157 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001158 break;
1159 }
1160 case Instruction::PHI: {
1161 PHINode *P = cast<PHINode>(I);
1162 // Handle the case of a simple two-predecessor recurrence PHI.
1163 // There's a lot more that could theoretically be done here, but
1164 // this is sufficient to catch some interesting cases.
1165 if (P->getNumIncomingValues() == 2) {
1166 for (unsigned i = 0; i != 2; ++i) {
1167 Value *L = P->getIncomingValue(i);
1168 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001169 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001170 if (!LU)
1171 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001172 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001173 // Check for operations that have the property that if
1174 // both their operands have low zero bits, the result
1175 // will have low zero bits.
1176 if (Opcode == Instruction::Add ||
1177 Opcode == Instruction::Sub ||
1178 Opcode == Instruction::And ||
1179 Opcode == Instruction::Or ||
1180 Opcode == Instruction::Mul) {
1181 Value *LL = LU->getOperand(0);
1182 Value *LR = LU->getOperand(1);
1183 // Find a recurrence.
1184 if (LL == I)
1185 L = LR;
1186 else if (LR == I)
1187 L = LL;
1188 else
1189 break;
1190 // Ok, we have a PHI of the form L op= R. Check for low
1191 // zero bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001192 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001193
1194 // We need to take the minimum number of known bits
1195 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001196 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001197
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001198 KnownZero = APInt::getLowBitsSet(BitWidth,
David Greeneaebd9e02008-10-27 23:24:03 +00001199 std::min(KnownZero2.countTrailingOnes(),
1200 KnownZero3.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001201 break;
1202 }
1203 }
1204 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001205
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001206 // Unreachable blocks may have zero-operand PHI nodes.
1207 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001208 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001209
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001210 // Otherwise take the unions of the known bit sets of the operands,
1211 // taking conservative care to avoid excessive recursion.
1212 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001213 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001214 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001215 break;
1216
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001217 KnownZero = APInt::getAllOnesValue(BitWidth);
1218 KnownOne = APInt::getAllOnesValue(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001219 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1220 // Skip direct self references.
1221 if (P->getIncomingValue(i) == P) continue;
1222
1223 KnownZero2 = APInt(BitWidth, 0);
1224 KnownOne2 = APInt(BitWidth, 0);
1225 // Recurse, but cap the recursion to one level, because we don't
1226 // want to waste time spinning around in loops.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001227 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, DL,
1228 MaxDepth - 1, Q);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001229 KnownZero &= KnownZero2;
1230 KnownOne &= KnownOne2;
1231 // If all bits have been ruled out, there's no need to check
1232 // more operands.
1233 if (!KnownZero && !KnownOne)
1234 break;
1235 }
1236 }
Chris Lattner965c7692008-06-02 01:18:21 +00001237 break;
1238 }
1239 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001240 case Instruction::Invoke:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001241 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +00001242 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1243 // If a range metadata is attached to this IntrinsicInst, intersect the
1244 // explicit range specified by the metadata and the implicit range of
1245 // the intrinsic.
Chris Lattner965c7692008-06-02 01:18:21 +00001246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1247 switch (II->getIntrinsicID()) {
1248 default: break;
Chris Lattner965c7692008-06-02 01:18:21 +00001249 case Intrinsic::ctlz:
1250 case Intrinsic::cttz: {
1251 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001252 // If this call is undefined for 0, the result will be less than 2^n.
1253 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1254 LowBits -= 1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001255 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001256 break;
1257 }
1258 case Intrinsic::ctpop: {
1259 unsigned LowBits = Log2_32(BitWidth)+1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001260 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner965c7692008-06-02 01:18:21 +00001261 break;
1262 }
Chad Rosierb3628842011-05-26 23:13:19 +00001263 case Intrinsic::x86_sse42_crc32_64_64:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001264 KnownZero |= APInt::getHighBitsSet(64, 32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001265 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001266 }
1267 }
1268 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001269 case Instruction::ExtractValue:
1270 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1271 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1272 if (EVI->getNumIndices() != 1) break;
1273 if (EVI->getIndices()[0] == 0) {
1274 switch (II->getIntrinsicID()) {
1275 default: break;
1276 case Intrinsic::uadd_with_overflow:
1277 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001278 computeKnownBitsAddSub(true, II->getArgOperand(0),
1279 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001280 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001281 break;
1282 case Intrinsic::usub_with_overflow:
1283 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001284 computeKnownBitsAddSub(false, II->getArgOperand(0),
1285 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001286 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001287 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001288 case Intrinsic::umul_with_overflow:
1289 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001290 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1291 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1292 Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001293 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001294 }
1295 }
1296 }
Chris Lattner965c7692008-06-02 01:18:21 +00001297 }
Jay Foad5a29c362014-05-15 12:12:55 +00001298
1299 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001300}
1301
Sanjay Patelaee84212014-11-04 16:27:42 +00001302/// Determine whether the sign bit is known to be zero or one.
1303/// Convenience wrapper around computeKnownBits.
Hal Finkel60db0582014-09-07 18:57:58 +00001304void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001305 const DataLayout &DL, unsigned Depth, const Query &Q) {
1306 unsigned BitWidth = getBitWidth(V->getType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001307 if (!BitWidth) {
1308 KnownZero = false;
1309 KnownOne = false;
1310 return;
1311 }
1312 APInt ZeroBits(BitWidth, 0);
1313 APInt OneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001314 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001315 KnownOne = OneBits[BitWidth - 1];
1316 KnownZero = ZeroBits[BitWidth - 1];
1317}
1318
Sanjay Patelaee84212014-11-04 16:27:42 +00001319/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001320/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001321/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001322/// types and vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001323bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001324 const Query &Q, const DataLayout &DL) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001325 if (Constant *C = dyn_cast<Constant>(V)) {
1326 if (C->isNullValue())
1327 return OrZero;
1328 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1329 return CI->getValue().isPowerOf2();
1330 // TODO: Handle vector constants.
1331 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001332
1333 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1334 // it is shifted off the end then the result is undefined.
1335 if (match(V, m_Shl(m_One(), m_Value())))
1336 return true;
1337
1338 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1339 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands4b397fc2011-02-01 08:50:33 +00001340 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001341 return true;
1342
1343 // The remaining tests are all recursive, so bail out if we hit the limit.
1344 if (Depth++ == MaxDepth)
1345 return false;
1346
Craig Topper9f008862014-04-15 04:59:12 +00001347 Value *X = nullptr, *Y = nullptr;
Duncan Sands985ba632011-10-28 18:30:05 +00001348 // A shift of a power of two is a power of two or zero.
1349 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1350 match(V, m_Shr(m_Value(X), m_Value()))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001351 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
Duncan Sands985ba632011-10-28 18:30:05 +00001352
Duncan Sandsd3951082011-01-25 09:38:29 +00001353 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001354 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001355
1356 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001357 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1358 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
Duncan Sandsba286d72011-10-26 20:55:21 +00001359
Duncan Sandsba286d72011-10-26 20:55:21 +00001360 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1361 // A power of two and'd with anything is a power of two or zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001362 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1363 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
Duncan Sandsba286d72011-10-26 20:55:21 +00001364 return true;
1365 // X & (-X) is always a power of two or zero.
1366 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1367 return true;
1368 return false;
1369 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001370
David Majnemerb7d54092013-07-30 21:01:36 +00001371 // Adding a power-of-two or zero to the same power-of-two or zero yields
1372 // either the original power-of-two, a larger power-of-two or zero.
1373 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1374 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1375 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1376 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1377 match(X, m_And(m_Value(), m_Specific(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001378 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001379 return true;
1380 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1381 match(Y, m_And(m_Value(), m_Specific(X))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001382 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001383 return true;
1384
1385 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1386 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001387 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001388
1389 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001390 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001391 // If i8 V is a power of two or zero:
1392 // ZeroBits: 1 1 1 0 1 1 1 1
1393 // ~ZeroBits: 0 0 0 1 0 0 0 0
1394 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1395 // If OrZero isn't set, we cannot give back a zero result.
1396 // Make sure either the LHS or RHS has a bit set.
1397 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1398 return true;
1399 }
1400 }
David Majnemerbeab5672013-05-18 19:30:37 +00001401
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001402 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001403 // is a power of two only if the first operand is a power of two and not
1404 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001405 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1406 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001407 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408 Depth, Q, DL);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001409 }
1410
Duncan Sandsd3951082011-01-25 09:38:29 +00001411 return false;
1412}
1413
Chandler Carruth80d3e562012-12-07 02:08:58 +00001414/// \brief Test whether a GEP's result is known to be non-null.
1415///
1416/// Uses properties inherent in a GEP to try to determine whether it is known
1417/// to be non-null.
1418///
1419/// Currently this routine does not support vector GEPs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001420static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001421 unsigned Depth, const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001422 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1423 return false;
1424
1425 // FIXME: Support vector-GEPs.
1426 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1427
1428 // If the base pointer is non-null, we cannot walk to a null address with an
1429 // inbounds GEP in address space zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001430 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001431 return true;
1432
Chandler Carruth80d3e562012-12-07 02:08:58 +00001433 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1434 // If so, then the GEP cannot produce a null pointer, as doing so would
1435 // inherently violate the inbounds contract within address space zero.
1436 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1437 GTI != GTE; ++GTI) {
1438 // Struct types are easy -- they must always be indexed by a constant.
1439 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1440 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1441 unsigned ElementIdx = OpC->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001442 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001443 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1444 if (ElementOffset > 0)
1445 return true;
1446 continue;
1447 }
1448
1449 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001450 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001451 continue;
1452
1453 // Fast path the constant operand case both for efficiency and so we don't
1454 // increment Depth when just zipping down an all-constant GEP.
1455 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1456 if (!OpC->isZero())
1457 return true;
1458 continue;
1459 }
1460
1461 // We post-increment Depth here because while isKnownNonZero increments it
1462 // as well, when we pop back up that increment won't persist. We don't want
1463 // to recurse 10k times just because we have 10k GEP operands. We don't
1464 // bail completely out because we want to handle constant GEPs regardless
1465 // of depth.
1466 if (Depth++ >= MaxDepth)
1467 continue;
1468
Hal Finkel60db0582014-09-07 18:57:58 +00001469 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001470 return true;
1471 }
1472
1473 return false;
1474}
1475
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001476/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1477/// ensure that the value it's attached to is never Value? 'RangeType' is
1478/// is the type of the value described by the range.
1479static bool rangeMetadataExcludesValue(MDNode* Ranges,
1480 const APInt& Value) {
1481 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1482 assert(NumRanges >= 1);
1483 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001484 ConstantInt *Lower =
1485 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1486 ConstantInt *Upper =
1487 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001488 ConstantRange Range(Lower->getValue(), Upper->getValue());
1489 if (Range.contains(Value))
1490 return false;
1491 }
1492 return true;
1493}
1494
Sanjay Patelaee84212014-11-04 16:27:42 +00001495/// Return true if the given value is known to be non-zero when defined.
1496/// For vectors return true if every element is known to be non-zero when
1497/// defined. Supports values with integer or pointer type and vectors of
1498/// integers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001499bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +00001500 const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001501 if (Constant *C = dyn_cast<Constant>(V)) {
1502 if (C->isNullValue())
1503 return false;
1504 if (isa<ConstantInt>(C))
1505 // Must be non-zero due to null test above.
1506 return true;
1507 // TODO: Handle vectors
1508 return false;
1509 }
1510
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001511 if (Instruction* I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001512 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001513 // If the possible ranges don't contain zero, then the value is
1514 // definitely non-zero.
1515 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1516 const APInt ZeroValue(Ty->getBitWidth(), 0);
1517 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1518 return true;
1519 }
1520 }
1521 }
1522
Duncan Sandsd3951082011-01-25 09:38:29 +00001523 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001524 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001525 return false;
1526
Chandler Carruth80d3e562012-12-07 02:08:58 +00001527 // Check for pointer simplifications.
1528 if (V->getType()->isPointerTy()) {
Manman Ren12171122013-03-18 21:23:25 +00001529 if (isKnownNonNull(V))
1530 return true;
Chandler Carruth80d3e562012-12-07 02:08:58 +00001531 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001532 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001533 return true;
1534 }
1535
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001536 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001537
1538 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001539 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001540 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001541 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001542
1543 // ext X != 0 if X != 0.
1544 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001545 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001546
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001547 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001548 // if the lowest bit is shifted off the end.
1549 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001550 // shl nuw can't remove any non-zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001551 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001552 if (BO->hasNoUnsignedWrap())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001553 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001554
Duncan Sandsd3951082011-01-25 09:38:29 +00001555 APInt KnownZero(BitWidth, 0);
1556 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001557 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001558 if (KnownOne[0])
1559 return true;
1560 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001561 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001562 // defined if the sign bit is shifted off the end.
1563 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001564 // shr exact can only shift out zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001565 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001566 if (BO->isExact())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001568
Duncan Sandsd3951082011-01-25 09:38:29 +00001569 bool XKnownNonNegative, XKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001570 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001571 if (XKnownNegative)
1572 return true;
1573 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001574 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001575 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001576 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001577 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001578 // X + Y.
1579 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1580 bool XKnownNonNegative, XKnownNegative;
1581 bool YKnownNonNegative, YKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001582 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1583 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001584
1585 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001586 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001587 if (XKnownNonNegative && YKnownNonNegative)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001588 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001589 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001590
1591 // If X and Y are both negative (as signed values) then their sum is not
1592 // zero unless both X and Y equal INT_MIN.
1593 if (BitWidth && XKnownNegative && YKnownNegative) {
1594 APInt KnownZero(BitWidth, 0);
1595 APInt KnownOne(BitWidth, 0);
1596 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1597 // The sign bit of X is set. If some other bit is set then X is not equal
1598 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001599 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001600 if ((KnownOne & Mask) != 0)
1601 return true;
1602 // The sign bit of Y is set. If some other bit is set then Y is not equal
1603 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001604 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001605 if ((KnownOne & Mask) != 0)
1606 return true;
1607 }
1608
1609 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001610 if (XKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001611 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001612 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00001613 if (YKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001614 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001615 return true;
1616 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001617 // X * Y.
1618 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1619 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1620 // If X and Y are non-zero then so is X * Y as long as the multiplication
1621 // does not overflow.
1622 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001623 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001624 return true;
1625 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001626 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1627 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001628 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1629 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001630 return true;
1631 }
1632
1633 if (!BitWidth) return false;
1634 APInt KnownZero(BitWidth, 0);
1635 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001636 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001637 return KnownOne != 0;
1638}
1639
Sanjay Patelaee84212014-11-04 16:27:42 +00001640/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1641/// simplify operations downstream. Mask is known to be zero for bits that V
1642/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001643///
1644/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001645/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00001646/// where V is a vector, the mask, known zero, and known one values are the
1647/// same width as the vector element, and the bit is set only if it is true
1648/// for all of the elements in the vector.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001649bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1650 unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +00001651 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001652 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001653 return (KnownZero & Mask) == Mask;
1654}
1655
1656
1657
Sanjay Patelaee84212014-11-04 16:27:42 +00001658/// Return the number of times the sign bit of the register is replicated into
1659/// the other bits. We know that at least 1 bit is always equal to the sign bit
1660/// (itself), but other cases can give us information. For example, immediately
1661/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1662/// other, so we return 3.
Chris Lattner965c7692008-06-02 01:18:21 +00001663///
1664/// 'Op' must have a scalar integer type.
1665///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001666unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1667 const Query &Q) {
1668 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00001669 unsigned Tmp, Tmp2;
1670 unsigned FirstAnswer = 1;
1671
Jay Foada0653a32014-05-14 21:14:37 +00001672 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00001673 // below.
1674
Chris Lattner965c7692008-06-02 01:18:21 +00001675 if (Depth == 6)
1676 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001677
Dan Gohman80ca01c2009-07-17 20:47:02 +00001678 Operator *U = dyn_cast<Operator>(V);
1679 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001680 default: break;
1681 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00001682 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001683 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00001684
Nadav Rotemc99a3872015-03-06 00:23:58 +00001685 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00001686 const APInt *Denominator;
1687 // sdiv X, C -> adds log(C) sign bits.
1688 if (match(U->getOperand(1), m_APInt(Denominator))) {
1689
1690 // Ignore non-positive denominator.
1691 if (!Denominator->isStrictlyPositive())
1692 break;
1693
1694 // Calculate the incoming numerator bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001695 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00001696
1697 // Add floor(log(C)) bits to the numerator bits.
1698 return std::min(TyBits, NumBits + Denominator->logBase2());
1699 }
1700 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00001701 }
1702
1703 case Instruction::SRem: {
1704 const APInt *Denominator;
1705 // srem X, C -> we know that the result is within 0..C-1 when C is a
1706 // positive constant and the sign bits are at most TypeBits - log2(C).
1707 if (match(U->getOperand(1), m_APInt(Denominator))) {
1708
1709 // Ignore non-positive denominator.
1710 if (!Denominator->isStrictlyPositive())
1711 break;
1712
1713 // Calculate the incoming numerator bits. SRem by a positive constant
1714 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001715 unsigned NumrBits =
1716 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00001717
1718 // Calculate the leading sign bit constraints by examining the
1719 // denominator. The remainder is in the range 0..C-1, which is
1720 // calculated by the log2(denominator). The sign bits are the bit-width
1721 // minus this value. The result of this subtraction has to be positive.
1722 unsigned ResBits = TyBits - Denominator->logBase2();
1723
1724 return std::max(NumrBits, ResBits);
1725 }
1726 break;
1727 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00001728
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001729 case Instruction::AShr: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001730 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001731 // ashr X, C -> adds C sign bits. Vectors too.
1732 const APInt *ShAmt;
1733 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1734 Tmp += ShAmt->getZExtValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001735 if (Tmp > TyBits) Tmp = TyBits;
1736 }
1737 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001738 }
1739 case Instruction::Shl: {
1740 const APInt *ShAmt;
1741 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00001742 // shl destroys sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001743 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001744 Tmp2 = ShAmt->getZExtValue();
1745 if (Tmp2 >= TyBits || // Bad shift.
1746 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1747 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00001748 }
1749 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001750 }
Chris Lattner965c7692008-06-02 01:18:21 +00001751 case Instruction::And:
1752 case Instruction::Or:
1753 case Instruction::Xor: // NOT is handled here.
1754 // Logical binary ops preserve the number of sign bits at the worst.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001755 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001756 if (Tmp != 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001757 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001758 FirstAnswer = std::min(Tmp, Tmp2);
1759 // We computed what we know about the sign bits as our first
1760 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00001761 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00001762 }
1763 break;
1764
1765 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001766 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001767 if (Tmp == 1) return 1; // Early out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001768 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001769 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00001770
Chris Lattner965c7692008-06-02 01:18:21 +00001771 case Instruction::Add:
1772 // Add can have at most one carry bit. Thus we know that the output
1773 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001774 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001775 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00001776
Chris Lattner965c7692008-06-02 01:18:21 +00001777 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00001778 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00001779 if (CRHS->isAllOnesValue()) {
1780 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001781 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1782 Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001783
Chris Lattner965c7692008-06-02 01:18:21 +00001784 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1785 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001786 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00001787 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00001788
Chris Lattner965c7692008-06-02 01:18:21 +00001789 // If we are subtracting one from a positive number, there is no carry
1790 // out of the result.
1791 if (KnownZero.isNegative())
1792 return Tmp;
1793 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001794
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001795 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001796 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001797 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001798
Chris Lattner965c7692008-06-02 01:18:21 +00001799 case Instruction::Sub:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001800 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001801 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001802
Chris Lattner965c7692008-06-02 01:18:21 +00001803 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00001804 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00001805 if (CLHS->isNullValue()) {
1806 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001807 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
1808 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001809 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1810 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001811 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00001812 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00001813
Chris Lattner965c7692008-06-02 01:18:21 +00001814 // If the input is known to be positive (the sign bit is known clear),
1815 // the output of the NEG has the same number of sign bits as the input.
1816 if (KnownZero.isNegative())
1817 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00001818
Chris Lattner965c7692008-06-02 01:18:21 +00001819 // Otherwise, we treat this like a SUB.
1820 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001821
Chris Lattner965c7692008-06-02 01:18:21 +00001822 // Sub can have at most one carry bit. Thus we know that the output
1823 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001824 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001825 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001826 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001827
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001828 case Instruction::PHI: {
1829 PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00001830 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001831 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00001832 if (NumIncomingValues > 4) break;
1833 // Unreachable blocks may have zero-operand PHI nodes.
1834 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00001835
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001836 // Take the minimum of all incoming values. This can't infinitely loop
1837 // because of our depth threshold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001838 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00001839 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001840 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001841 Tmp = std::min(
1842 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001843 }
1844 return Tmp;
1845 }
1846
Chris Lattner965c7692008-06-02 01:18:21 +00001847 case Instruction::Trunc:
1848 // FIXME: it's tricky to do anything useful for this, but it is an important
1849 // case for targets like X86.
1850 break;
1851 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001852
Chris Lattner965c7692008-06-02 01:18:21 +00001853 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1854 // use this information.
1855 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001856 APInt Mask;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001857 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001858
Chris Lattner965c7692008-06-02 01:18:21 +00001859 if (KnownZero.isNegative()) { // sign bit is 0
1860 Mask = KnownZero;
1861 } else if (KnownOne.isNegative()) { // sign bit is 1;
1862 Mask = KnownOne;
1863 } else {
1864 // Nothing known.
1865 return FirstAnswer;
1866 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001867
Chris Lattner965c7692008-06-02 01:18:21 +00001868 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1869 // the number of identical bits in the top of the input value.
1870 Mask = ~Mask;
1871 Mask <<= Mask.getBitWidth()-TyBits;
1872 // Return # leading zeros. We use 'min' here in case Val was zero before
1873 // shifting. We don't want to return '64' as for an i32 "0".
1874 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1875}
Chris Lattnera12a6de2008-06-02 01:29:46 +00001876
Sanjay Patelaee84212014-11-04 16:27:42 +00001877/// This function computes the integer multiple of Base that equals V.
1878/// If successful, it returns true and returns the multiple in
1879/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00001880/// through SExt instructions only if LookThroughSExt is true.
1881bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00001882 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00001883 const unsigned MaxDepth = 6;
1884
Dan Gohman6a976bb2009-11-18 00:58:27 +00001885 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00001886 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001887 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00001888
Chris Lattner229907c2011-07-18 04:54:35 +00001889 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00001890
Dan Gohman6a976bb2009-11-18 00:58:27 +00001891 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00001892
1893 if (Base == 0)
1894 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00001895
Victor Hernandez47444882009-11-10 08:28:35 +00001896 if (Base == 1) {
1897 Multiple = V;
1898 return true;
1899 }
1900
1901 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1902 Constant *BaseVal = ConstantInt::get(T, Base);
1903 if (CO && CO == BaseVal) {
1904 // Multiple is 1.
1905 Multiple = ConstantInt::get(T, 1);
1906 return true;
1907 }
1908
1909 if (CI && CI->getZExtValue() % Base == 0) {
1910 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00001911 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00001912 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001913
Victor Hernandez47444882009-11-10 08:28:35 +00001914 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001915
Victor Hernandez47444882009-11-10 08:28:35 +00001916 Operator *I = dyn_cast<Operator>(V);
1917 if (!I) return false;
1918
1919 switch (I->getOpcode()) {
1920 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00001921 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00001922 if (!LookThroughSExt) return false;
1923 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00001924 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00001925 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1926 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00001927 case Instruction::Shl:
1928 case Instruction::Mul: {
1929 Value *Op0 = I->getOperand(0);
1930 Value *Op1 = I->getOperand(1);
1931
1932 if (I->getOpcode() == Instruction::Shl) {
1933 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1934 if (!Op1CI) return false;
1935 // Turn Op0 << Op1 into Op0 * 2^Op1
1936 APInt Op1Int = Op1CI->getValue();
1937 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00001938 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00001939 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00001940 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00001941 }
1942
Craig Topper9f008862014-04-15 04:59:12 +00001943 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00001944 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1945 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1946 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00001947 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00001948 MulC->getType()->getPrimitiveSizeInBits())
1949 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001950 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00001951 MulC->getType()->getPrimitiveSizeInBits())
1952 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001953
Chris Lattner72d283c2010-09-05 17:20:46 +00001954 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1955 Multiple = ConstantExpr::getMul(MulC, Op1C);
1956 return true;
1957 }
Victor Hernandez47444882009-11-10 08:28:35 +00001958
1959 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1960 if (Mul0CI->getValue() == 1) {
1961 // V == Base * Op1, so return Op1
1962 Multiple = Op1;
1963 return true;
1964 }
1965 }
1966
Craig Topper9f008862014-04-15 04:59:12 +00001967 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00001968 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1969 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1970 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00001971 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00001972 MulC->getType()->getPrimitiveSizeInBits())
1973 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001974 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00001975 MulC->getType()->getPrimitiveSizeInBits())
1976 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001977
Chris Lattner72d283c2010-09-05 17:20:46 +00001978 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1979 Multiple = ConstantExpr::getMul(MulC, Op0C);
1980 return true;
1981 }
Victor Hernandez47444882009-11-10 08:28:35 +00001982
1983 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1984 if (Mul1CI->getValue() == 1) {
1985 // V == Base * Op0, so return Op0
1986 Multiple = Op0;
1987 return true;
1988 }
1989 }
Victor Hernandez47444882009-11-10 08:28:35 +00001990 }
1991 }
1992
1993 // We could not determine if V is a multiple of Base.
1994 return false;
1995}
1996
Sanjay Patelaee84212014-11-04 16:27:42 +00001997/// Return true if we can prove that the specified FP value is never equal to
1998/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00001999///
2000/// NOTE: this function will need to be revisited when we support non-default
2001/// rounding modes!
2002///
2003bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2004 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2005 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002006
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002007 // FIXME: Magic number! At the least, this should be given a name because it's
2008 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2009 // expose it as a parameter, so it can be used for testing / experimenting.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002010 if (Depth == 6)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002011 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002012
Dan Gohman80ca01c2009-07-17 20:47:02 +00002013 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002014 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002015
2016 // Check if the nsz fast-math flag is set
2017 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2018 if (FPO->hasNoSignedZeros())
2019 return true;
2020
Chris Lattnera12a6de2008-06-02 01:29:46 +00002021 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002022 if (I->getOpcode() == Instruction::FAdd)
2023 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2024 if (CFP->isNullValue())
2025 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002026
Chris Lattnera12a6de2008-06-02 01:29:46 +00002027 // sitofp and uitofp turn into +0.0 for zero.
2028 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2029 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002030
Chris Lattnera12a6de2008-06-02 01:29:46 +00002031 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2032 // sqrt(-0.0) = -0.0, no other negative results are possible.
2033 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif1abbde32010-06-23 23:38:07 +00002034 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Craig Topper1bef2c82012-12-22 19:15:35 +00002035
Chris Lattnera12a6de2008-06-02 01:29:46 +00002036 if (const CallInst *CI = dyn_cast<CallInst>(I))
2037 if (const Function *F = CI->getCalledFunction()) {
2038 if (F->isDeclaration()) {
Daniel Dunbarca414c72009-07-26 08:34:35 +00002039 // abs(x) != -0.0
2040 if (F->getName() == "abs") return true;
Dale Johannesenf6a987b2009-09-25 20:54:50 +00002041 // fabs[lf](x) != -0.0
2042 if (F->getName() == "fabs") return true;
2043 if (F->getName() == "fabsf") return true;
2044 if (F->getName() == "fabsl") return true;
2045 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2046 F->getName() == "sqrtl")
Gabor Greif1abbde32010-06-23 23:38:07 +00002047 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattnera12a6de2008-06-02 01:29:46 +00002048 }
2049 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002050
Chris Lattnera12a6de2008-06-02 01:29:46 +00002051 return false;
2052}
2053
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002054bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2055 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2056 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2057
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002058 // FIXME: Magic number! At the least, this should be given a name because it's
2059 // used similarly in CannotBeNegativeZero(). A better fix may be to
2060 // expose it as a parameter, so it can be used for testing / experimenting.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002061 if (Depth == 6)
2062 return false; // Limit search depth.
2063
2064 const Operator *I = dyn_cast<Operator>(V);
2065 if (!I) return false;
2066
2067 switch (I->getOpcode()) {
2068 default: break;
2069 case Instruction::FMul:
2070 // x*x is always non-negative or a NaN.
2071 if (I->getOperand(0) == I->getOperand(1))
2072 return true;
2073 // Fall through
2074 case Instruction::FAdd:
2075 case Instruction::FDiv:
2076 case Instruction::FRem:
2077 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2078 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2079 case Instruction::FPExt:
2080 case Instruction::FPTrunc:
2081 // Widening/narrowing never change sign.
2082 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2083 case Instruction::Call:
2084 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2085 switch (II->getIntrinsicID()) {
2086 default: break;
2087 case Intrinsic::exp:
2088 case Intrinsic::exp2:
2089 case Intrinsic::fabs:
2090 case Intrinsic::sqrt:
2091 return true;
2092 case Intrinsic::powi:
2093 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2094 // powi(x,n) is non-negative if n is even.
2095 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2096 return true;
2097 }
2098 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2099 case Intrinsic::fma:
2100 case Intrinsic::fmuladd:
2101 // x*x+y is non-negative if y is non-negative.
2102 return I->getOperand(0) == I->getOperand(1) &&
2103 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2104 }
2105 break;
2106 }
2107 return false;
2108}
2109
Sanjay Patelaee84212014-11-04 16:27:42 +00002110/// If the specified value can be set by repeating the same byte in memory,
2111/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002112/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2113/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2114/// byte store (e.g. i16 0x1234), return null.
2115Value *llvm::isBytewiseValue(Value *V) {
2116 // All byte-wide stores are splatable, even of arbitrary variables.
2117 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002118
2119 // Handle 'null' ConstantArrayZero etc.
2120 if (Constant *C = dyn_cast<Constant>(V))
2121 if (C->isNullValue())
2122 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002123
Chris Lattner9cb10352010-12-26 20:15:01 +00002124 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002125 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002126 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2127 if (CFP->getType()->isFloatTy())
2128 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2129 if (CFP->getType()->isDoubleTy())
2130 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2131 // Don't handle long double formats, which have strange constraints.
2132 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002133
Benjamin Kramer17d90152015-02-07 19:29:02 +00002134 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002135 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002136 if (CI->getBitWidth() % 8 == 0) {
2137 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002138
Benjamin Kramer17d90152015-02-07 19:29:02 +00002139 // We can check that all bytes of an integer are equal by making use of a
2140 // little trick: rotate by 8 and check if it's still the same value.
2141 if (CI->getValue() != CI->getValue().rotl(8))
2142 return nullptr;
2143 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002144 }
2145 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002146
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002147 // A ConstantDataArray/Vector is splatable if all its members are equal and
2148 // also splatable.
2149 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2150 Value *Elt = CA->getElementAsConstant(0);
2151 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002152 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002153 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002154
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002155 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2156 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002157 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002158
Chris Lattner9cb10352010-12-26 20:15:01 +00002159 return Val;
2160 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002161
Chris Lattner9cb10352010-12-26 20:15:01 +00002162 // Conceptually, we could handle things like:
2163 // %a = zext i8 %X to i16
2164 // %b = shl i16 %a, 8
2165 // %c = or i16 %a, %b
2166 // but until there is an example that actually needs this, it doesn't seem
2167 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002168 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002169}
2170
2171
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002172// This is the recursive version of BuildSubAggregate. It takes a few different
2173// arguments. Idxs is the index within the nested struct From that we are
2174// looking at now (which is of type IndexedType). IdxSkip is the number of
2175// indices from Idxs that should be left out when inserting into the resulting
2176// struct. To is the result struct built so far, new insertvalue instructions
2177// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002178static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002179 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002180 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002181 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002182 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002183 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002184 // Save the original To argument so we can modify it
2185 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002186 // General case, the type indexed by Idxs is a struct
2187 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2188 // Process each struct element recursively
2189 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002190 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002191 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002192 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002193 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002194 if (!To) {
2195 // Couldn't find any inserted value for this index? Cleanup
2196 while (PrevTo != OrigTo) {
2197 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2198 PrevTo = Del->getAggregateOperand();
2199 Del->eraseFromParent();
2200 }
2201 // Stop processing elements
2202 break;
2203 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002204 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002205 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002206 if (To)
2207 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002208 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002209 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2210 // the struct's elements had a value that was inserted directly. In the latter
2211 // case, perhaps we can't determine each of the subelements individually, but
2212 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002213
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002214 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002215 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002216
2217 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002218 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002219
2220 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002221 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002222 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002223}
2224
2225// This helper takes a nested struct and extracts a part of it (which is again a
2226// struct) into a new value. For example, given the struct:
2227// { a, { b, { c, d }, e } }
2228// and the indices "1, 1" this returns
2229// { c, d }.
2230//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002231// It does this by inserting an insertvalue for each element in the resulting
2232// struct, as opposed to just inserting a single struct. This will only work if
2233// each of the elements of the substruct are known (ie, inserted into From by an
2234// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002235//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002236// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002237static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002238 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002239 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002240 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002241 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002242 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002243 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002244 unsigned IdxSkip = Idxs.size();
2245
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002246 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002247}
2248
Sanjay Patelaee84212014-11-04 16:27:42 +00002249/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002250/// the scalar value indexed is already around as a register, for example if it
2251/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002252///
2253/// If InsertBefore is not null, this function will duplicate (modified)
2254/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002255Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2256 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002257 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002258 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002259 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002260 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002261 // We have indices, so V should have an indexable type.
2262 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2263 "Not looking at a struct or array?");
2264 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2265 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002266
Chris Lattner67058832012-01-25 06:48:06 +00002267 if (Constant *C = dyn_cast<Constant>(V)) {
2268 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002269 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002270 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2271 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002272
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002273 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002274 // Loop the indices for the insertvalue instruction in parallel with the
2275 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002276 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002277 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2278 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002279 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002280 // We can't handle this without inserting insertvalues
2281 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002282 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002283
2284 // The requested index identifies a part of a nested aggregate. Handle
2285 // this specially. For example,
2286 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2287 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2288 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2289 // This can be changed into
2290 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2291 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2292 // which allows the unused 0,0 element from the nested struct to be
2293 // removed.
2294 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2295 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002296 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002297
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002298 // This insert value inserts something else than what we are looking for.
2299 // See if the (aggregrate) value inserted into has the value we are
2300 // looking for, then.
2301 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002302 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002303 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002304 }
2305 // If we end up here, the indices of the insertvalue match with those
2306 // requested (though possibly only partially). Now we recursively look at
2307 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002308 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002309 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002310 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002311 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002312
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002313 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002314 // If we're extracting a value from an aggregrate that was extracted from
2315 // something else, we can extract from that something else directly instead.
2316 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002317
2318 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002319 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002320 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002321 SmallVector<unsigned, 5> Idxs;
2322 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002323 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002324 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002325
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002326 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002327 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002328
Craig Topper1bef2c82012-12-22 19:15:35 +00002329 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002330 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002331
Jay Foad57aa6362011-07-13 10:26:04 +00002332 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002333 }
2334 // Otherwise, we don't know (such as, extracting from a function return value
2335 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002336 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002337}
Evan Chengda3db112008-06-30 07:31:25 +00002338
Sanjay Patelaee84212014-11-04 16:27:42 +00002339/// Analyze the specified pointer to see if it can be expressed as a base
2340/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002341Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002342 const DataLayout &DL) {
2343 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002344 APInt ByteOffset(BitWidth, 0);
2345 while (1) {
2346 if (Ptr->getType()->isVectorTy())
2347 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002348
Nuno Lopes368c4d02012-12-31 20:48:35 +00002349 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002350 APInt GEPOffset(BitWidth, 0);
2351 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2352 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002353
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002354 ByteOffset += GEPOffset;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002355
Nuno Lopes368c4d02012-12-31 20:48:35 +00002356 Ptr = GEP->getPointerOperand();
Matt Arsenaultfd78d0c2014-07-14 22:39:22 +00002357 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2358 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002359 Ptr = cast<Operator>(Ptr)->getOperand(0);
2360 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2361 if (GA->mayBeOverridden())
2362 break;
2363 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002364 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002365 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002366 }
2367 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002368 Offset = ByteOffset.getSExtValue();
2369 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002370}
2371
2372
Sanjay Patelaee84212014-11-04 16:27:42 +00002373/// This function computes the length of a null-terminated C string pointed to
2374/// by V. If successful, it returns true and returns the string in Str.
2375/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002376bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2377 uint64_t Offset, bool TrimAtNul) {
2378 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002379
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002380 // Look through bitcast instructions and geps.
2381 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002382
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002383 // If the value is a GEP instructionor constant expression, treat it as an
2384 // offset.
2385 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Chengda3db112008-06-30 07:31:25 +00002386 // Make sure the GEP has exactly three arguments.
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002387 if (GEP->getNumOperands() != 3)
2388 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002389
Evan Chengda3db112008-06-30 07:31:25 +00002390 // Make sure the index-ee is a pointer to array of i8.
Chris Lattner229907c2011-07-18 04:54:35 +00002391 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2392 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Craig Topper9f008862014-04-15 04:59:12 +00002393 if (!AT || !AT->getElementType()->isIntegerTy(8))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002394 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002395
Evan Chengda3db112008-06-30 07:31:25 +00002396 // Check to make sure that the first operand of the GEP is an integer and
2397 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0b4df042010-04-14 22:20:45 +00002398 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Craig Topper9f008862014-04-15 04:59:12 +00002399 if (!FirstIdx || !FirstIdx->isZero())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002400 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002401
Evan Chengda3db112008-06-30 07:31:25 +00002402 // If the second index isn't a ConstantInt, then this is a variable index
2403 // into the array. If this occurs, we can't say anything meaningful about
2404 // the string.
2405 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002406 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002407 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002408 else
2409 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002410 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Chengda3db112008-06-30 07:31:25 +00002411 }
Nick Lewycky46209882011-10-20 00:34:35 +00002412
Evan Chengda3db112008-06-30 07:31:25 +00002413 // The GEP instruction, constant or instruction, must reference a global
2414 // variable that is a constant and is initialized. The referenced constant
2415 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002416 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002417 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002418 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002419
Nick Lewycky46209882011-10-20 00:34:35 +00002420 // Handle the all-zeros case
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002421 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00002422 // This is a degenerate case. The initializer is constant zero so the
2423 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002424 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002425 return true;
2426 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002427
Evan Chengda3db112008-06-30 07:31:25 +00002428 // Must be a Constant Array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002429 const ConstantDataArray *Array =
2430 dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00002431 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002432 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002433
Evan Chengda3db112008-06-30 07:31:25 +00002434 // Get the number of elements in the array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002435 uint64_t NumElts = Array->getType()->getArrayNumElements();
2436
2437 // Start out with the entire array in the StringRef.
2438 Str = Array->getAsString();
2439
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002440 if (Offset > NumElts)
2441 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002442
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002443 // Skip over 'offset' bytes.
2444 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00002445
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002446 if (TrimAtNul) {
2447 // Trim off the \0 and anything after it. If the array is not nul
2448 // terminated, we just return the whole end of string. The client may know
2449 // some other way that the string is length-bound.
2450 Str = Str.substr(0, Str.find('\0'));
2451 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002452 return true;
Evan Chengda3db112008-06-30 07:31:25 +00002453}
Eric Christopher4899cbc2010-03-05 06:58:57 +00002454
2455// These next two are very similar to the above, but also look through PHI
2456// nodes.
2457// TODO: See if we can integrate these two together.
2458
Sanjay Patelaee84212014-11-04 16:27:42 +00002459/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002460/// the specified pointer, return 'len+1'. If we can't, return 0.
Craig Topper71b7b682014-08-21 05:55:13 +00002461static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00002462 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002463 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00002464
2465 // If this is a PHI node, there are two cases: either we have already seen it
2466 // or we haven't.
2467 if (PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00002468 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00002469 return ~0ULL; // already in the set.
2470
2471 // If it was new, see if all the input strings are the same length.
2472 uint64_t LenSoFar = ~0ULL;
2473 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2474 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2475 if (Len == 0) return 0; // Unknown length -> unknown.
2476
2477 if (Len == ~0ULL) continue;
2478
2479 if (Len != LenSoFar && LenSoFar != ~0ULL)
2480 return 0; // Disagree -> unknown.
2481 LenSoFar = Len;
2482 }
2483
2484 // Success, all agree.
2485 return LenSoFar;
2486 }
2487
2488 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2489 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2490 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2491 if (Len1 == 0) return 0;
2492 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2493 if (Len2 == 0) return 0;
2494 if (Len1 == ~0ULL) return Len2;
2495 if (Len2 == ~0ULL) return Len1;
2496 if (Len1 != Len2) return 0;
2497 return Len1;
2498 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002499
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002500 // Otherwise, see if we can read the string.
2501 StringRef StrData;
2502 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00002503 return 0;
2504
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002505 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00002506}
2507
Sanjay Patelaee84212014-11-04 16:27:42 +00002508/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002509/// the specified pointer, return 'len+1'. If we can't, return 0.
2510uint64_t llvm::GetStringLength(Value *V) {
2511 if (!V->getType()->isPointerTy()) return 0;
2512
2513 SmallPtrSet<PHINode*, 32> PHIs;
2514 uint64_t Len = GetStringLengthH(V, PHIs);
2515 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2516 // an empty string as a length.
2517 return Len == ~0ULL ? 1 : Len;
2518}
Dan Gohmana4fcd242010-12-15 20:02:24 +00002519
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002520Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2521 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002522 if (!V->getType()->isPointerTy())
2523 return V;
2524 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2525 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2526 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00002527 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2528 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002529 V = cast<Operator>(V)->getOperand(0);
2530 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2531 if (GA->mayBeOverridden())
2532 return V;
2533 V = GA->getAliasee();
2534 } else {
Dan Gohman05b18f12010-12-15 20:49:55 +00002535 // See if InstructionSimplify knows any relevant tricks.
2536 if (Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +00002537 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002538 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00002539 V = Simplified;
2540 continue;
2541 }
2542
Dan Gohmana4fcd242010-12-15 20:02:24 +00002543 return V;
2544 }
2545 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2546 }
2547 return V;
2548}
Nick Lewycky3e334a42011-06-27 04:20:45 +00002549
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002550void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
2551 const DataLayout &DL, unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002552 SmallPtrSet<Value *, 4> Visited;
2553 SmallVector<Value *, 4> Worklist;
2554 Worklist.push_back(V);
2555 do {
2556 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002557 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002558
David Blaikie70573dc2014-11-19 07:49:26 +00002559 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002560 continue;
2561
2562 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2563 Worklist.push_back(SI->getTrueValue());
2564 Worklist.push_back(SI->getFalseValue());
2565 continue;
2566 }
2567
2568 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2569 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2570 Worklist.push_back(PN->getIncomingValue(i));
2571 continue;
2572 }
2573
2574 Objects.push_back(P);
2575 } while (!Worklist.empty());
2576}
2577
Sanjay Patelaee84212014-11-04 16:27:42 +00002578/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00002579bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002580 for (const User *U : V->users()) {
2581 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00002582 if (!II) return false;
2583
2584 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2585 II->getIntrinsicID() != Intrinsic::lifetime_end)
2586 return false;
2587 }
2588 return true;
2589}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002590
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002591bool llvm::isSafeToSpeculativelyExecute(const Value *V) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00002592 const Operator *Inst = dyn_cast<Operator>(V);
2593 if (!Inst)
2594 return false;
2595
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002596 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2597 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2598 if (C->canTrap())
2599 return false;
2600
2601 switch (Inst->getOpcode()) {
2602 default:
2603 return true;
2604 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00002605 case Instruction::URem: {
2606 // x / y is undefined if y == 0.
2607 const APInt *V;
2608 if (match(Inst->getOperand(1), m_APInt(V)))
2609 return *V != 0;
2610 return false;
2611 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002612 case Instruction::SDiv:
2613 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00002614 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00002615 const APInt *Numerator, *Denominator;
2616 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
2617 return false;
2618 // We cannot hoist this division if the denominator is 0.
2619 if (*Denominator == 0)
2620 return false;
2621 // It's safe to hoist if the denominator is not 0 or -1.
2622 if (*Denominator != -1)
2623 return true;
2624 // At this point we know that the denominator is -1. It is safe to hoist as
2625 // long we know that the numerator is not INT_MIN.
2626 if (match(Inst->getOperand(0), m_APInt(Numerator)))
2627 return !Numerator->isMinSignedValue();
2628 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00002629 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002630 }
2631 case Instruction::Load: {
2632 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00002633 if (!LI->isUnordered() ||
2634 // Speculative load may create a race that did not exist in the source.
2635 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002636 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002637 const DataLayout &DL = LI->getModule()->getDataLayout();
2638 return LI->getPointerOperand()->isDereferenceablePointer(DL);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002639 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002640 case Instruction::Call: {
Michael Liao736bac62014-11-06 19:05:57 +00002641 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2642 switch (II->getIntrinsicID()) {
2643 // These synthetic intrinsics have no side-effects and just mark
2644 // information about their operands.
2645 // FIXME: There are other no-op synthetic instructions that potentially
2646 // should be considered at least *safe* to speculate...
2647 case Intrinsic::dbg_declare:
2648 case Intrinsic::dbg_value:
2649 return true;
Chandler Carruth28192c92012-04-07 19:22:18 +00002650
Michael Liao736bac62014-11-06 19:05:57 +00002651 case Intrinsic::bswap:
2652 case Intrinsic::ctlz:
2653 case Intrinsic::ctpop:
2654 case Intrinsic::cttz:
2655 case Intrinsic::objectsize:
2656 case Intrinsic::sadd_with_overflow:
2657 case Intrinsic::smul_with_overflow:
2658 case Intrinsic::ssub_with_overflow:
2659 case Intrinsic::uadd_with_overflow:
2660 case Intrinsic::umul_with_overflow:
2661 case Intrinsic::usub_with_overflow:
2662 return true;
2663 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2664 // errno like libm sqrt would.
2665 case Intrinsic::sqrt:
2666 case Intrinsic::fma:
2667 case Intrinsic::fmuladd:
2668 case Intrinsic::fabs:
2669 case Intrinsic::minnum:
2670 case Intrinsic::maxnum:
2671 return true;
2672 // TODO: some fp intrinsics are marked as having the same error handling
2673 // as libm. They're safe to speculate when they won't error.
2674 // TODO: are convert_{from,to}_fp16 safe?
2675 // TODO: can we list target-specific intrinsics here?
2676 default: break;
2677 }
2678 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002679 return false; // The called function could have undefined behavior or
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002680 // side-effects, even if marked readnone nounwind.
2681 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002682 case Instruction::VAArg:
2683 case Instruction::Alloca:
2684 case Instruction::Invoke:
2685 case Instruction::PHI:
2686 case Instruction::Store:
2687 case Instruction::Ret:
2688 case Instruction::Br:
2689 case Instruction::IndirectBr:
2690 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002691 case Instruction::Unreachable:
2692 case Instruction::Fence:
2693 case Instruction::LandingPad:
2694 case Instruction::AtomicRMW:
2695 case Instruction::AtomicCmpXchg:
2696 case Instruction::Resume:
2697 return false; // Misc instructions which have effects
2698 }
2699}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002700
Sanjay Patelaee84212014-11-04 16:27:42 +00002701/// Return true if we know that the specified value is never null.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002702bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002703 // Alloca never returns null, malloc might.
2704 if (isa<AllocaInst>(V)) return true;
2705
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002706 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002707 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002708 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002709
2710 // Global values are not null unless extern weak.
2711 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2712 return !GV->hasExternalWeakLinkage();
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002713
Philip Reamescdb72f32014-10-20 22:40:55 +00002714 // A Load tagged w/nonnull metadata is never null.
2715 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00002716 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00002717
Nick Lewyckyec373542014-05-20 05:13:21 +00002718 if (ImmutableCallSite CS = V)
Hal Finkelb0407ba2014-07-18 15:51:28 +00002719 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00002720 return true;
2721
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002722 // operator new never returns null.
2723 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2724 return true;
2725
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002726 return false;
2727}
David Majnemer491331a2015-01-02 07:29:43 +00002728
2729OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002730 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00002731 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00002732 const Instruction *CxtI,
2733 const DominatorTree *DT) {
2734 // Multiplying n * m significant bits yields a result of n + m significant
2735 // bits. If the total number of significant bits does not exceed the
2736 // result bit width (minus 1), there is no overflow.
2737 // This means if we have enough leading zero bits in the operands
2738 // we can guarantee that the result does not overflow.
2739 // Ref: "Hacker's Delight" by Henry Warren
2740 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
2741 APInt LHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00002742 APInt LHSKnownOne(BitWidth, 0);
David Majnemer491331a2015-01-02 07:29:43 +00002743 APInt RHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00002744 APInt RHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00002745 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2746 DT);
2747 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2748 DT);
David Majnemer491331a2015-01-02 07:29:43 +00002749 // Note that underestimating the number of zero bits gives a more
2750 // conservative answer.
2751 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
2752 RHSKnownZero.countLeadingOnes();
2753 // First handle the easy case: if we have enough zero bits there's
2754 // definitely no overflow.
2755 if (ZeroBits >= BitWidth)
2756 return OverflowResult::NeverOverflows;
2757
2758 // Get the largest possible values for each operand.
2759 APInt LHSMax = ~LHSKnownZero;
2760 APInt RHSMax = ~RHSKnownZero;
2761
2762 // We know the multiply operation doesn't overflow if the maximum values for
2763 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00002764 bool MaxOverflow;
2765 LHSMax.umul_ov(RHSMax, MaxOverflow);
2766 if (!MaxOverflow)
2767 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00002768
David Majnemerc8a576b2015-01-02 07:29:47 +00002769 // We know it always overflows if multiplying the smallest possible values for
2770 // the operands also results in overflow.
2771 bool MinOverflow;
2772 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
2773 if (MinOverflow)
2774 return OverflowResult::AlwaysOverflows;
2775
2776 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00002777}
David Majnemer5310c1e2015-01-07 00:39:50 +00002778
2779OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002780 const DataLayout &DL,
David Majnemer5310c1e2015-01-07 00:39:50 +00002781 AssumptionCache *AC,
2782 const Instruction *CxtI,
2783 const DominatorTree *DT) {
2784 bool LHSKnownNonNegative, LHSKnownNegative;
2785 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
2786 AC, CxtI, DT);
2787 if (LHSKnownNonNegative || LHSKnownNegative) {
2788 bool RHSKnownNonNegative, RHSKnownNegative;
2789 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
2790 AC, CxtI, DT);
2791
2792 if (LHSKnownNegative && RHSKnownNegative) {
2793 // The sign bit is set in both cases: this MUST overflow.
2794 // Create a simple add instruction, and insert it into the struct.
2795 return OverflowResult::AlwaysOverflows;
2796 }
2797
2798 if (LHSKnownNonNegative && RHSKnownNonNegative) {
2799 // The sign bit is clear in both cases: this CANNOT overflow.
2800 // Create a simple add instruction, and insert it into the struct.
2801 return OverflowResult::NeverOverflows;
2802 }
2803 }
2804
2805 return OverflowResult::MayOverflow;
2806}