blob: 74c862a88dd69f81c9df7d6c0f6b27abf7184e99 [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"
Hal Finkel60db0582014-09-07 18:57:58 +000016#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.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
42/// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
43/// unknown returns 0). For vector types, returns the element type's bitwidth.
Micah Villmowcdfe20b2012-10-08 16:38:25 +000044static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
Duncan Sandsd3951082011-01-25 09:38:29 +000045 if (unsigned BitWidth = Ty->getScalarSizeInBits())
46 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000047
48 return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
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
61// Simplifying using an assume can only be done in a particular control-flow
62// context (the context instruction provides that context). If an assume and
63// the context instruction are not in the same block then the DT helps in
64// figuring out if we can use it.
65struct Query {
66 ExclInvsSet ExclInvs;
67 AssumptionTracker *AT;
68 const Instruction *CxtI;
69 const DominatorTree *DT;
70
71 Query(AssumptionTracker *AT = nullptr, const Instruction *CxtI = nullptr,
72 const DominatorTree *DT = nullptr)
73 : AT(AT), CxtI(CxtI), DT(DT) {}
74
75 Query(const Query &Q, const Value *NewExcl)
76 : ExclInvs(Q.ExclInvs), AT(Q.AT), CxtI(Q.CxtI), DT(Q.DT) {
77 ExclInvs.insert(NewExcl);
78 }
79};
80
81// Given the provided Value and, potentially, a context instruction, returned
82// the preferred context instruction (if any).
83static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
84 // If we've been provided with a context instruction, then use that (provided
85 // it has been inserted).
86 if (CxtI && CxtI->getParent())
87 return CxtI;
88
89 // If the value is really an already-inserted instruction, then use that.
90 CxtI = dyn_cast<Instruction>(V);
91 if (CxtI && CxtI->getParent())
92 return CxtI;
93
94 return nullptr;
95}
96
97static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
98 const DataLayout *TD, unsigned Depth,
99 const Query &Q);
100
101void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
102 const DataLayout *TD, unsigned Depth,
103 AssumptionTracker *AT, const Instruction *CxtI,
104 const DominatorTree *DT) {
105 ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
106 Query(AT, safeCxtI(V, CxtI), DT));
107}
108
109static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
110 const DataLayout *TD, unsigned Depth,
111 const Query &Q);
112
113void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
114 const DataLayout *TD, unsigned Depth,
115 AssumptionTracker *AT, const Instruction *CxtI,
116 const DominatorTree *DT) {
117 ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
118 Query(AT, safeCxtI(V, CxtI), DT));
119}
120
121static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
122 const Query &Q);
123
124bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
125 AssumptionTracker *AT,
126 const Instruction *CxtI,
127 const DominatorTree *DT) {
128 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
129 Query(AT, safeCxtI(V, CxtI), DT));
130}
131
132static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
133 const Query &Q);
134
135bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
136 AssumptionTracker *AT, const Instruction *CxtI,
137 const DominatorTree *DT) {
138 return ::isKnownNonZero(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
139}
140
141static bool MaskedValueIsZero(Value *V, const APInt &Mask,
142 const DataLayout *TD, unsigned Depth,
143 const Query &Q);
144
145bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
146 const DataLayout *TD, unsigned Depth,
147 AssumptionTracker *AT, const Instruction *CxtI,
148 const DominatorTree *DT) {
149 return ::MaskedValueIsZero(V, Mask, TD, Depth,
150 Query(AT, safeCxtI(V, CxtI), DT));
151}
152
153static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
154 unsigned Depth, const Query &Q);
155
156unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
157 unsigned Depth, AssumptionTracker *AT,
158 const Instruction *CxtI,
159 const DominatorTree *DT) {
160 return ::ComputeNumSignBits(V, TD, Depth, Query(AT, safeCxtI(V, CxtI), DT));
161}
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,
Hal Finkel60db0582014-09-07 18:57:58 +0000166 const DataLayout *TD, unsigned Depth,
167 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);
178 computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
179
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);
Hal Finkel60db0582014-09-07 18:57:58 +0000197 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
198 computeKnownBits(Op1, KnownZero2, KnownOne2, TD, 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,
Hal Finkel60db0582014-09-07 18:57:58 +0000246 const DataLayout *TD, unsigned Depth,
247 const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000248 unsigned BitWidth = KnownZero.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000249 computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
250 computeKnownBits(Op0, KnownZero2, KnownOne2, TD, 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 &&
Hal Finkel60db0582014-09-07 18:57:58 +0000271 isKnownNonZero(Op0, TD, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000272 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Hal Finkel60db0582014-09-07 18:57:58 +0000273 isKnownNonZero(Op1, TD, 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) {
313 ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
314 ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
315 ConstantRange Range(Lower->getValue(), Upper->getValue());
316 if (Range.isWrappedSet())
317 MinLeadingZeros = 0; // -1 has no zeros
318 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
319 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
320 }
321
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000322 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
Rafael Espindola53190532012-03-30 15:52:11 +0000323}
Jay Foad5a29c362014-05-15 12:12:55 +0000324
Hal Finkel60db0582014-09-07 18:57:58 +0000325static bool isEphemeralValueOf(Instruction *I, const Value *E) {
326 SmallVector<const Value *, 16> WorkSet(1, I);
327 SmallPtrSet<const Value *, 32> Visited;
328 SmallPtrSet<const Value *, 16> EphValues;
329
330 while (!WorkSet.empty()) {
331 const Value *V = WorkSet.pop_back_val();
332 if (!Visited.insert(V))
333 continue;
334
335 // If all uses of this value are ephemeral, then so is this value.
336 bool FoundNEUse = false;
337 for (const User *I : V->users())
338 if (!EphValues.count(I)) {
339 FoundNEUse = true;
340 break;
341 }
342
343 if (!FoundNEUse) {
344 if (V == E)
345 return true;
346
347 EphValues.insert(V);
348 if (const User *U = dyn_cast<User>(V))
349 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
350 J != JE; ++J) {
351 if (isSafeToSpeculativelyExecute(*J))
352 WorkSet.push_back(*J);
353 }
354 }
355 }
356
357 return false;
358}
359
360// Is this an intrinsic that cannot be speculated but also cannot trap?
361static bool isAssumeLikeIntrinsic(const Instruction *I) {
362 if (const CallInst *CI = dyn_cast<CallInst>(I))
363 if (Function *F = CI->getCalledFunction())
364 switch (F->getIntrinsicID()) {
365 default: break;
366 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
367 case Intrinsic::assume:
368 case Intrinsic::dbg_declare:
369 case Intrinsic::dbg_value:
370 case Intrinsic::invariant_start:
371 case Intrinsic::invariant_end:
372 case Intrinsic::lifetime_start:
373 case Intrinsic::lifetime_end:
374 case Intrinsic::objectsize:
375 case Intrinsic::ptr_annotation:
376 case Intrinsic::var_annotation:
377 return true;
378 }
379
380 return false;
381}
382
383static bool isValidAssumeForContext(Value *V, const Query &Q,
384 const DataLayout *DL) {
385 Instruction *Inv = cast<Instruction>(V);
386
387 // There are two restrictions on the use of an assume:
388 // 1. The assume must dominate the context (or the control flow must
389 // reach the assume whenever it reaches the context).
390 // 2. The context must not be in the assume's set of ephemeral values
391 // (otherwise we will use the assume to prove that the condition
392 // feeding the assume is trivially true, thus causing the removal of
393 // the assume).
394
395 if (Q.DT) {
396 if (Q.DT->dominates(Inv, Q.CxtI)) {
397 return true;
398 } else if (Inv->getParent() == Q.CxtI->getParent()) {
399 // The context comes first, but they're both in the same block. Make sure
400 // there is nothing in between that might interrupt the control flow.
401 for (BasicBlock::const_iterator I =
402 std::next(BasicBlock::const_iterator(Q.CxtI)),
403 IE(Inv); I != IE; ++I)
404 if (!isSafeToSpeculativelyExecute(I, DL) &&
405 !isAssumeLikeIntrinsic(I))
406 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)
429 if (!isSafeToSpeculativelyExecute(I, DL) &&
430 !isAssumeLikeIntrinsic(I))
431 return false;
432
433 return !isEphemeralValueOf(Inv, Q.CxtI);
434 }
435
436 return false;
437}
438
439bool llvm::isValidAssumeForContext(const Instruction *I,
440 const Instruction *CxtI,
441 const DataLayout *DL,
442 const DominatorTree *DT) {
443 return ::isValidAssumeForContext(const_cast<Instruction*>(I),
444 Query(nullptr, CxtI, DT), DL);
445}
446
447template<typename LHS, typename RHS>
448inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
449 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
450m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
451 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
452}
453
454template<typename LHS, typename RHS>
455inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
456 BinaryOp_match<RHS, LHS, Instruction::And>>
457m_c_And(const LHS &L, const RHS &R) {
458 return m_CombineOr(m_And(L, R), m_And(R, L));
459}
460
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000461template<typename LHS, typename RHS>
462inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
463 BinaryOp_match<RHS, LHS, Instruction::Or>>
464m_c_Or(const LHS &L, const RHS &R) {
465 return m_CombineOr(m_Or(L, R), m_Or(R, L));
466}
467
468template<typename LHS, typename RHS>
469inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
470 BinaryOp_match<RHS, LHS, Instruction::Xor>>
471m_c_Xor(const LHS &L, const RHS &R) {
472 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
473}
474
Hal Finkel60db0582014-09-07 18:57:58 +0000475static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
476 APInt &KnownOne,
477 const DataLayout *DL,
478 unsigned Depth, const Query &Q) {
479 // Use of assumptions is context-sensitive. If we don't have a context, we
480 // cannot use them!
481 if (!Q.AT || !Q.CxtI)
482 return;
483
484 unsigned BitWidth = KnownZero.getBitWidth();
485
486 Function *F = const_cast<Function*>(Q.CxtI->getParent()->getParent());
487 for (auto &CI : Q.AT->assumptions(F)) {
488 CallInst *I = CI;
489 if (Q.ExclInvs.count(I))
490 continue;
491
492 if (match(I, m_Intrinsic<Intrinsic::assume>(m_Specific(V))) &&
493 isValidAssumeForContext(I, Q, DL)) {
494 assert(BitWidth == 1 && "assume operand is not i1?");
495 KnownZero.clearAllBits();
496 KnownOne.setAllBits();
497 return;
498 }
499
500 Value *A, *B;
501 auto m_V = m_CombineOr(m_Specific(V),
502 m_CombineOr(m_PtrToInt(m_Specific(V)),
503 m_BitCast(m_Specific(V))));
504
505 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000506 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000507 // assume(v = a)
508 if (match(I, m_Intrinsic<Intrinsic::assume>(
509 m_c_ICmp(Pred, m_V, m_Value(A)))) &&
510 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
511 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
512 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
513 KnownZero |= RHSKnownZero;
514 KnownOne |= RHSKnownOne;
515 // assume(v & b = a)
516 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
517 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) &&
518 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
519 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
520 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
521 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
522 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
523
524 // For those bits in the mask that are known to be one, we can propagate
525 // known bits from the RHS to V.
526 KnownZero |= RHSKnownZero & MaskKnownOne;
527 KnownOne |= RHSKnownOne & MaskKnownOne;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000528 // assume(~(v & b) = a)
529 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
530 m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
531 m_Value(A)))) &&
532 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
533 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
534 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
535 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
536 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
537
538 // For those bits in the mask that are known to be one, we can propagate
539 // inverted known bits from the RHS to V.
540 KnownZero |= RHSKnownOne & MaskKnownOne;
541 KnownOne |= RHSKnownZero & MaskKnownOne;
542 // assume(v | b = a)
543 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
544 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A)))) &&
545 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
546 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
547 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
548 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
549 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
550
551 // For those bits in B that are known to be zero, we can propagate known
552 // bits from the RHS to V.
553 KnownZero |= RHSKnownZero & BKnownZero;
554 KnownOne |= RHSKnownOne & BKnownZero;
555 // assume(~(v | b) = a)
556 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
557 m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
558 m_Value(A)))) &&
559 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
560 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
561 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
562 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
563 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
564
565 // For those bits in B that are known to be zero, we can propagate
566 // inverted known bits from the RHS to V.
567 KnownZero |= RHSKnownOne & BKnownZero;
568 KnownOne |= RHSKnownZero & BKnownZero;
569 // assume(v ^ b = a)
570 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
571 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A)))) &&
572 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
573 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
574 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
575 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
576 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
577
578 // For those bits in B that are known to be zero, we can propagate known
579 // bits from the RHS to V. For those bits in B that are known to be one,
580 // we can propagate inverted known bits from the RHS to V.
581 KnownZero |= RHSKnownZero & BKnownZero;
582 KnownOne |= RHSKnownOne & BKnownZero;
583 KnownZero |= RHSKnownOne & BKnownOne;
584 KnownOne |= RHSKnownZero & BKnownOne;
585 // assume(~(v ^ b) = a)
586 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
587 m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
588 m_Value(A)))) &&
589 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
590 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
591 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
592 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
593 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
594
595 // For those bits in B that are known to be zero, we can propagate
596 // inverted known bits from the RHS to V. For those bits in B that are
597 // known to be one, we can propagate known bits from the RHS to V.
598 KnownZero |= RHSKnownOne & BKnownZero;
599 KnownOne |= RHSKnownZero & BKnownZero;
600 KnownZero |= RHSKnownZero & BKnownOne;
601 KnownOne |= RHSKnownOne & BKnownOne;
602 // assume(v << c = a)
603 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
604 m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
605 m_Value(A)))) &&
606 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
607 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
608 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
609 // For those bits in RHS that are known, we can propagate them to known
610 // bits in V shifted to the right by C.
611 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
612 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
613 // assume(~(v << c) = a)
614 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
615 m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
616 m_Value(A)))) &&
617 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
618 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
619 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
620 // For those bits in RHS that are known, we can propagate them inverted
621 // to known bits in V shifted to the right by C.
622 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
623 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
624 // assume(v >> c = a)
625 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
626 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
627 m_AShr(m_V,
628 m_ConstantInt(C))),
629 m_Value(A)))) &&
630 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
631 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
632 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
633 // For those bits in RHS that are known, we can propagate them to known
634 // bits in V shifted to the right by C.
635 KnownZero |= RHSKnownZero << C->getZExtValue();
636 KnownOne |= RHSKnownOne << C->getZExtValue();
637 // assume(~(v >> c) = a)
638 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
639 m_c_ICmp(Pred, m_Not(m_CombineOr(
640 m_LShr(m_V, m_ConstantInt(C)),
641 m_AShr(m_V, m_ConstantInt(C)))),
642 m_Value(A)))) &&
643 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
644 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
645 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
646 // For those bits in RHS that are known, we can propagate them inverted
647 // to known bits in V shifted to the right by C.
648 KnownZero |= RHSKnownOne << C->getZExtValue();
649 KnownOne |= RHSKnownZero << C->getZExtValue();
650 // assume(v >=_s c) where c is non-negative
651 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
652 m_ICmp(Pred, m_V, m_Value(A)))) &&
653 Pred == ICmpInst::ICMP_SGE &&
654 isValidAssumeForContext(I, Q, DL)) {
655 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
656 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
657
658 if (RHSKnownZero.isNegative()) {
659 // We know that the sign bit is zero.
660 KnownZero |= APInt::getSignBit(BitWidth);
661 }
662 // assume(v >_s c) where c is at least -1.
663 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
664 m_ICmp(Pred, m_V, m_Value(A)))) &&
665 Pred == ICmpInst::ICMP_SGT &&
666 isValidAssumeForContext(I, Q, DL)) {
667 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
668 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
669
670 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
671 // We know that the sign bit is zero.
672 KnownZero |= APInt::getSignBit(BitWidth);
673 }
674 // assume(v <=_s c) where c is negative
675 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
676 m_ICmp(Pred, m_V, m_Value(A)))) &&
677 Pred == ICmpInst::ICMP_SLE &&
678 isValidAssumeForContext(I, Q, DL)) {
679 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
680 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
681
682 if (RHSKnownOne.isNegative()) {
683 // We know that the sign bit is one.
684 KnownOne |= APInt::getSignBit(BitWidth);
685 }
686 // assume(v <_s c) where c is non-positive
687 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
688 m_ICmp(Pred, m_V, m_Value(A)))) &&
689 Pred == ICmpInst::ICMP_SLT &&
690 isValidAssumeForContext(I, Q, DL)) {
691 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
692 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
693
694 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
695 // We know that the sign bit is one.
696 KnownOne |= APInt::getSignBit(BitWidth);
697 }
698 // assume(v <=_u c)
699 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
700 m_ICmp(Pred, m_V, m_Value(A)))) &&
701 Pred == ICmpInst::ICMP_ULE &&
702 isValidAssumeForContext(I, Q, DL)) {
703 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
704 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
705
706 // Whatever high bits in c are zero are known to be zero.
707 KnownZero |=
708 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
709 // assume(v <_u c)
710 } else if (match(I, m_Intrinsic<Intrinsic::assume>(
711 m_ICmp(Pred, m_V, m_Value(A)))) &&
712 Pred == ICmpInst::ICMP_ULT &&
713 isValidAssumeForContext(I, Q, DL)) {
714 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
715 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
716
717 // Whatever high bits in c are zero are known to be zero (if c is a power
718 // of 2, then one more).
719 if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
720 KnownZero |=
721 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
722 else
723 KnownZero |=
724 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000725 }
726 }
727}
728
Jay Foada0653a32014-05-14 21:14:37 +0000729/// Determine which bits of V are known to be either zero or one and return
730/// them in the KnownZero/KnownOne bit sets.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000731///
Chris Lattner965c7692008-06-02 01:18:21 +0000732/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
733/// we cannot optimize based on the assumption that it is zero without changing
734/// it to be an explicit zero. If we don't change it to zero, other code could
735/// optimized based on the contradictory assumption that it is non-zero.
736/// Because instcombine aggressively folds operations with undef args anyway,
737/// this won't lose us code quality.
Chris Lattner4bc28252009-09-08 00:06:16 +0000738///
739/// This function is defined on values with integer type, values with pointer
740/// type (but only if TD is non-null), and vectors of integers. In the case
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000741/// where V is a vector, known zero, and known one values are the
Chris Lattner4bc28252009-09-08 00:06:16 +0000742/// same width as the vector element, and the bit is set only if it is true
743/// for all of the elements in the vector.
Hal Finkel60db0582014-09-07 18:57:58 +0000744void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
745 const DataLayout *TD, unsigned Depth,
746 const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +0000747 assert(V && "No Value?");
Dan Gohmanbf0002e2009-05-21 02:28:33 +0000748 assert(Depth <= MaxDepth && "Limit Search Depth");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000749 unsigned BitWidth = KnownZero.getBitWidth();
750
Nadav Rotem3924cb02011-12-05 06:29:09 +0000751 assert((V->getType()->isIntOrIntVectorTy() ||
752 V->getType()->getScalarType()->isPointerTy()) &&
753 "Not integer or pointer type!");
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000754 assert((!TD ||
755 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000756 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000757 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem3924cb02011-12-05 06:29:09 +0000758 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner965c7692008-06-02 01:18:21 +0000759 KnownOne.getBitWidth() == BitWidth &&
Jay Foade48d9e82014-05-14 08:00:07 +0000760 "V, KnownOne and KnownZero should have same BitWidth");
Chris Lattner965c7692008-06-02 01:18:21 +0000761
762 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
763 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000764 KnownOne = CI->getValue();
765 KnownZero = ~KnownOne;
Chris Lattner965c7692008-06-02 01:18:21 +0000766 return;
767 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000768 // Null and aggregate-zero are all-zeros.
769 if (isa<ConstantPointerNull>(V) ||
770 isa<ConstantAggregateZero>(V)) {
Jay Foad25a5e4c2010-12-01 08:53:58 +0000771 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000772 KnownZero = APInt::getAllOnesValue(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000773 return;
774 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000775 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner8213c8a2012-02-06 21:56:39 +0000776 // each element. There is no real need to handle ConstantVector here, because
777 // we don't handle undef in any particularly useful way.
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000778 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
779 // We know that CDS must be a vector of integers. Take the intersection of
780 // each element.
781 KnownZero.setAllBits(); KnownOne.setAllBits();
782 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner9be59592012-01-25 01:27:20 +0000783 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000784 Elt = CDS->getElementAsInteger(i);
785 KnownZero &= ~Elt;
Craig Topper1bef2c82012-12-22 19:15:35 +0000786 KnownOne &= Elt;
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000787 }
788 return;
789 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000790
Chris Lattner965c7692008-06-02 01:18:21 +0000791 // The address of an aligned GlobalValue has trailing zeros.
792 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
793 unsigned Align = GV->getAlignment();
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000794 if (Align == 0 && TD) {
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000795 if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
796 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000797 if (ObjectType->isSized()) {
798 // If the object is defined in the current Module, we'll be giving
799 // it the preferred alignment. Otherwise, we have to assume that it
800 // may only have the minimum ABI alignment.
801 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
802 Align = TD->getPreferredAlignment(GVar);
803 else
804 Align = TD->getABITypeAlignment(ObjectType);
805 }
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000806 }
Dan Gohmana72f8562009-08-11 15:50:03 +0000807 }
Chris Lattner965c7692008-06-02 01:18:21 +0000808 if (Align > 0)
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000809 KnownZero = APInt::getLowBitsSet(BitWidth,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000810 countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +0000811 else
Jay Foad25a5e4c2010-12-01 08:53:58 +0000812 KnownZero.clearAllBits();
813 KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +0000814 return;
815 }
Dan Gohman94262db2009-09-15 16:14:44 +0000816 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
817 // the bits of its aliasee.
818 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
819 if (GA->mayBeOverridden()) {
Jay Foad25a5e4c2010-12-01 08:53:58 +0000820 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Dan Gohman94262db2009-09-15 16:14:44 +0000821 } else {
Hal Finkel60db0582014-09-07 18:57:58 +0000822 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1, Q);
Dan Gohman94262db2009-09-15 16:14:44 +0000823 }
824 return;
825 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000826
Chris Lattner83791ce2011-05-23 00:03:39 +0000827 if (Argument *A = dyn_cast<Argument>(V)) {
Hal Finkelccc70902014-07-22 16:58:55 +0000828 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
Duncan Sands271ea6c2012-10-04 13:36:31 +0000829
Hal Finkelccc70902014-07-22 16:58:55 +0000830 if (!Align && TD && A->hasStructRetAttr()) {
Duncan Sands271ea6c2012-10-04 13:36:31 +0000831 // An sret parameter has at least the ABI alignment of the return type.
832 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
833 if (EltTy->isSized())
834 Align = TD->getABITypeAlignment(EltTy);
835 }
836
837 if (Align)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000838 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Hal Finkel60db0582014-09-07 18:57:58 +0000839
840 // Don't give up yet... there might be an assumption that provides more
841 // information...
842 computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
Chris Lattner83791ce2011-05-23 00:03:39 +0000843 return;
844 }
Chris Lattner965c7692008-06-02 01:18:21 +0000845
Chris Lattner83791ce2011-05-23 00:03:39 +0000846 // Start out not knowing anything.
847 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +0000848
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000849 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +0000850 return; // Limit search depth.
851
Hal Finkel60db0582014-09-07 18:57:58 +0000852 // Check whether a nearby assume intrinsic can determine some known bits.
853 computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
854
Dan Gohman80ca01c2009-07-17 20:47:02 +0000855 Operator *I = dyn_cast<Operator>(V);
Chris Lattner965c7692008-06-02 01:18:21 +0000856 if (!I) return;
857
858 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000859 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000860 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000861 case Instruction::Load:
862 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +0000863 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
Jay Foad5a29c362014-05-15 12:12:55 +0000864 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000865 case Instruction::And: {
866 // If either the LHS or the RHS are Zero, the result is zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000867 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
868 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000869
Chris Lattner965c7692008-06-02 01:18:21 +0000870 // Output known-1 bits are only known if set in both the LHS & RHS.
871 KnownOne &= KnownOne2;
872 // Output known-0 are known to be clear if zero in either the LHS | RHS.
873 KnownZero |= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +0000874 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000875 }
876 case Instruction::Or: {
Hal Finkel60db0582014-09-07 18:57:58 +0000877 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
878 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000879
Chris Lattner965c7692008-06-02 01:18:21 +0000880 // Output known-0 bits are only known if clear in both the LHS & RHS.
881 KnownZero &= KnownZero2;
882 // Output known-1 are known to be set if set in either the LHS | RHS.
883 KnownOne |= KnownOne2;
Jay Foad5a29c362014-05-15 12:12:55 +0000884 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000885 }
886 case Instruction::Xor: {
Hal Finkel60db0582014-09-07 18:57:58 +0000887 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
888 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000889
Chris Lattner965c7692008-06-02 01:18:21 +0000890 // Output known-0 bits are known if clear or set in both the LHS & RHS.
891 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
892 // Output known-1 are known to be set if set in only one of the LHS, RHS.
893 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
894 KnownZero = KnownZeroOut;
Jay Foad5a29c362014-05-15 12:12:55 +0000895 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000896 }
897 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000898 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +0000899 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
Hal Finkel60db0582014-09-07 18:57:58 +0000900 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
901 Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000902 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000903 }
904 case Instruction::UDiv: {
905 // For the purposes of computing leading zeros we can conservatively
906 // treat a udiv as a logical right shift by the power of 2 known to
907 // be less than the denominator.
Hal Finkel60db0582014-09-07 18:57:58 +0000908 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000909 unsigned LeadZ = KnownZero2.countLeadingOnes();
910
Jay Foad25a5e4c2010-12-01 08:53:58 +0000911 KnownOne2.clearAllBits();
912 KnownZero2.clearAllBits();
Hal Finkel60db0582014-09-07 18:57:58 +0000913 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000914 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
915 if (RHSUnknownLeadingOnes != BitWidth)
916 LeadZ = std::min(BitWidth,
917 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
918
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000919 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000920 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000921 }
922 case Instruction::Select:
Hal Finkel60db0582014-09-07 18:57:58 +0000923 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
924 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +0000925
926 // Only known if known in both the LHS and RHS.
927 KnownOne &= KnownOne2;
928 KnownZero &= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +0000929 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000930 case Instruction::FPTrunc:
931 case Instruction::FPExt:
932 case Instruction::FPToUI:
933 case Instruction::FPToSI:
934 case Instruction::SIToFP:
935 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +0000936 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +0000937 case Instruction::PtrToInt:
938 case Instruction::IntToPtr:
Matt Arsenaultf1a7e622014-07-15 01:55:03 +0000939 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
Chris Lattner965c7692008-06-02 01:18:21 +0000940 // We can't handle these if we don't know the pointer size.
Jay Foad5a29c362014-05-15 12:12:55 +0000941 if (!TD) break;
Chris Lattner965c7692008-06-02 01:18:21 +0000942 // FALL THROUGH and handle them the same as zext/trunc.
943 case Instruction::ZExt:
944 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +0000945 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +0000946
Chris Lattner0cdbc7a2009-09-08 00:13:52 +0000947 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +0000948 // Note that we handle pointer operands here because of inttoptr/ptrtoint
949 // which fall through here.
Nadav Rotem11350aa2012-12-19 20:47:04 +0000950 if(TD) {
951 SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
952 } else {
953 SrcBitWidth = SrcTy->getScalarSizeInBits();
Jay Foad5a29c362014-05-15 12:12:55 +0000954 if (!SrcBitWidth) break;
Nadav Rotem11350aa2012-12-19 20:47:04 +0000955 }
Nadav Rotem15198e92012-10-26 17:17:05 +0000956
957 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Jay Foad583abbc2010-12-07 08:25:19 +0000958 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
959 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +0000960 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +0000961 KnownZero = KnownZero.zextOrTrunc(BitWidth);
962 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000963 // Any top bits are known to be zero.
964 if (BitWidth > SrcBitWidth)
965 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +0000966 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000967 }
968 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +0000969 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +0000970 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +0000971 // TODO: For now, not handling conversions like:
972 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +0000973 !I->getType()->isVectorTy()) {
Hal Finkel60db0582014-09-07 18:57:58 +0000974 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +0000975 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000976 }
977 break;
978 }
979 case Instruction::SExt: {
980 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +0000981 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +0000982
Jay Foad583abbc2010-12-07 08:25:19 +0000983 KnownZero = KnownZero.trunc(SrcBitWidth);
984 KnownOne = KnownOne.trunc(SrcBitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +0000985 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +0000986 KnownZero = KnownZero.zext(BitWidth);
987 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000988
989 // If the sign bit of the input is known set or clear, then we know the
990 // top bits of the result.
991 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
992 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
993 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
994 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +0000995 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000996 }
997 case Instruction::Shl:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000998 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Chris Lattner965c7692008-06-02 01:18:21 +0000999 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Hal Finkel60db0582014-09-07 18:57:58 +00001001 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001002 KnownZero <<= ShiftAmt;
1003 KnownOne <<= ShiftAmt;
1004 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Jay Foad5a29c362014-05-15 12:12:55 +00001005 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001006 }
1007 break;
1008 case Instruction::LShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001009 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001010 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1011 // Compute the new bits that are at the top now.
1012 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Craig Topper1bef2c82012-12-22 19:15:35 +00001013
Chris Lattner965c7692008-06-02 01:18:21 +00001014 // Unsigned shift right.
Hal Finkel60db0582014-09-07 18:57:58 +00001015 computeKnownBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001016 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1017 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1018 // high bits known zero.
1019 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Jay Foad5a29c362014-05-15 12:12:55 +00001020 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001021 }
1022 break;
1023 case Instruction::AShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001024 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001025 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1026 // Compute the new bits that are at the top now.
Chris Lattnerc86e67e2011-01-04 18:19:15 +00001027 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Craig Topper1bef2c82012-12-22 19:15:35 +00001028
Chris Lattner965c7692008-06-02 01:18:21 +00001029 // Signed shift right.
Hal Finkel60db0582014-09-07 18:57:58 +00001030 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001031 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1032 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Craig Topper1bef2c82012-12-22 19:15:35 +00001033
Chris Lattner965c7692008-06-02 01:18:21 +00001034 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1035 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1036 KnownZero |= HighBits;
1037 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1038 KnownOne |= HighBits;
Jay Foad5a29c362014-05-15 12:12:55 +00001039 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001040 }
1041 break;
1042 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001043 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001044 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001045 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001046 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001047 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001048 }
Chris Lattner965c7692008-06-02 01:18:21 +00001049 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001050 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001051 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001052 KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001053 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001054 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001055 }
1056 case Instruction::SRem:
1057 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001058 APInt RA = Rem->getValue().abs();
1059 if (RA.isPowerOf2()) {
1060 APInt LowBits = RA - 1;
Hal Finkel60db0582014-09-07 18:57:58 +00001061 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
1062 Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001063
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001064 // The low bits of the first operand are unchanged by the srem.
1065 KnownZero = KnownZero2 & LowBits;
1066 KnownOne = KnownOne2 & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001067
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001068 // If the first operand is non-negative or has all low bits zero, then
1069 // the upper bits are all zero.
1070 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1071 KnownZero |= ~LowBits;
1072
1073 // If the first operand is negative and not all low bits are zero, then
1074 // the upper bits are all one.
1075 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1076 KnownOne |= ~LowBits;
1077
Craig Topper1bef2c82012-12-22 19:15:35 +00001078 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001079 }
1080 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001081
1082 // The sign bit is the LHS's sign bit, except when the result of the
1083 // remainder is zero.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001084 if (KnownZero.isNonNegative()) {
Nick Lewyckye4679792011-03-07 01:50:10 +00001085 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +00001086 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001087 Depth+1, Q);
Nick Lewyckye4679792011-03-07 01:50:10 +00001088 // If it's known zero, our sign bit is also zero.
1089 if (LHSKnownZero.isNegative())
Duncan Sands34c48692012-04-30 11:56:58 +00001090 KnownZero.setBit(BitWidth - 1);
Nick Lewyckye4679792011-03-07 01:50:10 +00001091 }
1092
Chris Lattner965c7692008-06-02 01:18:21 +00001093 break;
1094 case Instruction::URem: {
1095 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1096 APInt RA = Rem->getValue();
1097 if (RA.isPowerOf2()) {
1098 APInt LowBits = (RA - 1);
Jay Foada0653a32014-05-14 21:14:37 +00001099 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001100 Depth+1, Q);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001101 KnownZero |= ~LowBits;
1102 KnownOne &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001103 break;
1104 }
1105 }
1106
1107 // Since the result is less than or equal to either operand, any leading
1108 // zero bits in either operand must also exist in the result.
Hal Finkel60db0582014-09-07 18:57:58 +00001109 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
1110 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001111
Chris Lattner4612ae12009-01-20 18:22:57 +00001112 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner965c7692008-06-02 01:18:21 +00001113 KnownZero2.countLeadingOnes());
Jay Foad25a5e4c2010-12-01 08:53:58 +00001114 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001115 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001116 break;
1117 }
1118
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001119 case Instruction::Alloca: {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001120 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001121 unsigned Align = AI->getAlignment();
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001122 if (Align == 0 && TD)
1123 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001124
Chris Lattner965c7692008-06-02 01:18:21 +00001125 if (Align > 0)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001126 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001127 break;
1128 }
1129 case Instruction::GetElementPtr: {
1130 // Analyze all of the subscripts of this getelementptr instruction
1131 // to determine if we can prove known low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001132 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +00001133 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001134 Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001135 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1136
1137 gep_type_iterator GTI = gep_type_begin(I);
1138 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1139 Value *Index = I->getOperand(i);
Chris Lattner229907c2011-07-18 04:54:35 +00001140 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001141 // Handle struct member offset arithmetic.
Jay Foad5a29c362014-05-15 12:12:55 +00001142 if (!TD) {
1143 TrailZ = 0;
1144 break;
1145 }
Matt Arsenault74742a12013-08-19 21:43:16 +00001146
1147 // Handle case when index is vector zeroinitializer
1148 Constant *CIndex = cast<Constant>(Index);
1149 if (CIndex->isZeroValue())
1150 continue;
1151
1152 if (CIndex->getType()->isVectorTy())
1153 Index = CIndex->getSplatValue();
1154
Chris Lattner965c7692008-06-02 01:18:21 +00001155 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matt Arsenault74742a12013-08-19 21:43:16 +00001156 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001157 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001158 TrailZ = std::min<unsigned>(TrailZ,
1159 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001160 } else {
1161 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001162 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001163 if (!IndexedTy->isSized()) {
1164 TrailZ = 0;
1165 break;
1166 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001167 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001168 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
Chris Lattner965c7692008-06-02 01:18:21 +00001169 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001170 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001171 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001172 unsigned(countTrailingZeros(TypeSize) +
Chris Lattner4612ae12009-01-20 18:22:57 +00001173 LocalKnownZero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001174 }
1175 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001176
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001177 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001178 break;
1179 }
1180 case Instruction::PHI: {
1181 PHINode *P = cast<PHINode>(I);
1182 // Handle the case of a simple two-predecessor recurrence PHI.
1183 // There's a lot more that could theoretically be done here, but
1184 // this is sufficient to catch some interesting cases.
1185 if (P->getNumIncomingValues() == 2) {
1186 for (unsigned i = 0; i != 2; ++i) {
1187 Value *L = P->getIncomingValue(i);
1188 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001189 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001190 if (!LU)
1191 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001192 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001193 // Check for operations that have the property that if
1194 // both their operands have low zero bits, the result
1195 // will have low zero bits.
1196 if (Opcode == Instruction::Add ||
1197 Opcode == Instruction::Sub ||
1198 Opcode == Instruction::And ||
1199 Opcode == Instruction::Or ||
1200 Opcode == Instruction::Mul) {
1201 Value *LL = LU->getOperand(0);
1202 Value *LR = LU->getOperand(1);
1203 // Find a recurrence.
1204 if (LL == I)
1205 L = LR;
1206 else if (LR == I)
1207 L = LL;
1208 else
1209 break;
1210 // Ok, we have a PHI of the form L op= R. Check for low
1211 // zero bits.
Hal Finkel60db0582014-09-07 18:57:58 +00001212 computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001213
1214 // We need to take the minimum number of known bits
1215 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
Hal Finkel60db0582014-09-07 18:57:58 +00001216 computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001217
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001218 KnownZero = APInt::getLowBitsSet(BitWidth,
David Greeneaebd9e02008-10-27 23:24:03 +00001219 std::min(KnownZero2.countTrailingOnes(),
1220 KnownZero3.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001221 break;
1222 }
1223 }
1224 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001225
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001226 // Unreachable blocks may have zero-operand PHI nodes.
1227 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001228 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001229
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001230 // Otherwise take the unions of the known bit sets of the operands,
1231 // taking conservative care to avoid excessive recursion.
1232 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001233 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001234 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001235 break;
1236
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001237 KnownZero = APInt::getAllOnesValue(BitWidth);
1238 KnownOne = APInt::getAllOnesValue(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001239 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1240 // Skip direct self references.
1241 if (P->getIncomingValue(i) == P) continue;
1242
1243 KnownZero2 = APInt(BitWidth, 0);
1244 KnownOne2 = APInt(BitWidth, 0);
1245 // Recurse, but cap the recursion to one level, because we don't
1246 // want to waste time spinning around in loops.
Jay Foada0653a32014-05-14 21:14:37 +00001247 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
Hal Finkel60db0582014-09-07 18:57:58 +00001248 MaxDepth-1, Q);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001249 KnownZero &= KnownZero2;
1250 KnownOne &= KnownOne2;
1251 // If all bits have been ruled out, there's no need to check
1252 // more operands.
1253 if (!KnownZero && !KnownOne)
1254 break;
1255 }
1256 }
Chris Lattner965c7692008-06-02 01:18:21 +00001257 break;
1258 }
1259 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001260 case Instruction::Invoke:
1261 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1262 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1263 // If a range metadata is attached to this IntrinsicInst, intersect the
1264 // explicit range specified by the metadata and the implicit range of
1265 // the intrinsic.
Chris Lattner965c7692008-06-02 01:18:21 +00001266 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1267 switch (II->getIntrinsicID()) {
1268 default: break;
Chris Lattner965c7692008-06-02 01:18:21 +00001269 case Intrinsic::ctlz:
1270 case Intrinsic::cttz: {
1271 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001272 // If this call is undefined for 0, the result will be less than 2^n.
1273 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1274 LowBits -= 1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001275 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001276 break;
1277 }
1278 case Intrinsic::ctpop: {
1279 unsigned LowBits = Log2_32(BitWidth)+1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001280 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner965c7692008-06-02 01:18:21 +00001281 break;
1282 }
Chad Rosierb3628842011-05-26 23:13:19 +00001283 case Intrinsic::x86_sse42_crc32_64_64:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001284 KnownZero |= APInt::getHighBitsSet(64, 32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001285 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001286 }
1287 }
1288 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001289 case Instruction::ExtractValue:
1290 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1291 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1292 if (EVI->getNumIndices() != 1) break;
1293 if (EVI->getIndices()[0] == 0) {
1294 switch (II->getIntrinsicID()) {
1295 default: break;
1296 case Intrinsic::uadd_with_overflow:
1297 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001298 computeKnownBitsAddSub(true, II->getArgOperand(0),
1299 II->getArgOperand(1), false, KnownZero,
Hal Finkel60db0582014-09-07 18:57:58 +00001300 KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001301 break;
1302 case Intrinsic::usub_with_overflow:
1303 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001304 computeKnownBitsAddSub(false, II->getArgOperand(0),
1305 II->getArgOperand(1), false, KnownZero,
Hal Finkel60db0582014-09-07 18:57:58 +00001306 KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001307 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001308 case Intrinsic::umul_with_overflow:
1309 case Intrinsic::smul_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001310 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
1311 false, KnownZero, KnownOne,
Hal Finkel60db0582014-09-07 18:57:58 +00001312 KnownZero2, KnownOne2, TD, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001313 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001314 }
1315 }
1316 }
Chris Lattner965c7692008-06-02 01:18:21 +00001317 }
Jay Foad5a29c362014-05-15 12:12:55 +00001318
1319 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001320}
1321
Duncan Sandsd3951082011-01-25 09:38:29 +00001322/// ComputeSignBit - Determine whether the sign bit is known to be zero or
Jay Foada0653a32014-05-14 21:14:37 +00001323/// one. Convenience wrapper around computeKnownBits.
Hal Finkel60db0582014-09-07 18:57:58 +00001324void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1325 const DataLayout *TD, unsigned Depth,
1326 const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001327 unsigned BitWidth = getBitWidth(V->getType(), TD);
1328 if (!BitWidth) {
1329 KnownZero = false;
1330 KnownOne = false;
1331 return;
1332 }
1333 APInt ZeroBits(BitWidth, 0);
1334 APInt OneBits(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001335 computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001336 KnownOne = OneBits[BitWidth - 1];
1337 KnownZero = ZeroBits[BitWidth - 1];
1338}
1339
Rafael Espindola319f74c2012-12-13 03:37:24 +00001340/// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001341/// bit set when defined. For vectors return true if every element is known to
1342/// be a power of two when defined. Supports values with integer or pointer
1343/// types and vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001344bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1345 const Query &Q) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001346 if (Constant *C = dyn_cast<Constant>(V)) {
1347 if (C->isNullValue())
1348 return OrZero;
1349 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1350 return CI->getValue().isPowerOf2();
1351 // TODO: Handle vector constants.
1352 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001353
1354 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1355 // it is shifted off the end then the result is undefined.
1356 if (match(V, m_Shl(m_One(), m_Value())))
1357 return true;
1358
1359 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1360 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands4b397fc2011-02-01 08:50:33 +00001361 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001362 return true;
1363
1364 // The remaining tests are all recursive, so bail out if we hit the limit.
1365 if (Depth++ == MaxDepth)
1366 return false;
1367
Craig Topper9f008862014-04-15 04:59:12 +00001368 Value *X = nullptr, *Y = nullptr;
Duncan Sands985ba632011-10-28 18:30:05 +00001369 // A shift of a power of two is a power of two or zero.
1370 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1371 match(V, m_Shr(m_Value(X), m_Value()))))
Hal Finkel60db0582014-09-07 18:57:58 +00001372 return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001373
Duncan Sandsd3951082011-01-25 09:38:29 +00001374 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Hal Finkel60db0582014-09-07 18:57:58 +00001375 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001376
1377 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Hal Finkel60db0582014-09-07 18:57:58 +00001378 return
1379 isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1380 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001381
Duncan Sandsba286d72011-10-26 20:55:21 +00001382 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1383 // A power of two and'd with anything is a power of two or zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001384 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
1385 isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001386 return true;
1387 // X & (-X) is always a power of two or zero.
1388 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1389 return true;
1390 return false;
1391 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001392
David Majnemerb7d54092013-07-30 21:01:36 +00001393 // Adding a power-of-two or zero to the same power-of-two or zero yields
1394 // either the original power-of-two, a larger power-of-two or zero.
1395 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1396 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1397 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1398 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1399 match(X, m_And(m_Value(), m_Specific(Y))))
Hal Finkel60db0582014-09-07 18:57:58 +00001400 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001401 return true;
1402 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1403 match(Y, m_And(m_Value(), m_Specific(X))))
Hal Finkel60db0582014-09-07 18:57:58 +00001404 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001405 return true;
1406
1407 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1408 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001409 computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001410
1411 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001412 computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001413 // If i8 V is a power of two or zero:
1414 // ZeroBits: 1 1 1 0 1 1 1 1
1415 // ~ZeroBits: 0 0 0 1 0 0 0 0
1416 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1417 // If OrZero isn't set, we cannot give back a zero result.
1418 // Make sure either the LHS or RHS has a bit set.
1419 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1420 return true;
1421 }
1422 }
David Majnemerbeab5672013-05-18 19:30:37 +00001423
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001424 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001425 // is a power of two only if the first operand is a power of two and not
1426 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001427 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1428 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001429 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1430 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001431 }
1432
Duncan Sandsd3951082011-01-25 09:38:29 +00001433 return false;
1434}
1435
Chandler Carruth80d3e562012-12-07 02:08:58 +00001436/// \brief Test whether a GEP's result is known to be non-null.
1437///
1438/// Uses properties inherent in a GEP to try to determine whether it is known
1439/// to be non-null.
1440///
1441/// Currently this routine does not support vector GEPs.
1442static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001443 unsigned Depth, const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001444 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1445 return false;
1446
1447 // FIXME: Support vector-GEPs.
1448 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1449
1450 // If the base pointer is non-null, we cannot walk to a null address with an
1451 // inbounds GEP in address space zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001452 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001453 return true;
1454
1455 // Past this, if we don't have DataLayout, we can't do much.
1456 if (!DL)
1457 return false;
1458
1459 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1460 // If so, then the GEP cannot produce a null pointer, as doing so would
1461 // inherently violate the inbounds contract within address space zero.
1462 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1463 GTI != GTE; ++GTI) {
1464 // Struct types are easy -- they must always be indexed by a constant.
1465 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1466 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1467 unsigned ElementIdx = OpC->getZExtValue();
1468 const StructLayout *SL = DL->getStructLayout(STy);
1469 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1470 if (ElementOffset > 0)
1471 return true;
1472 continue;
1473 }
1474
1475 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1476 if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
1477 continue;
1478
1479 // Fast path the constant operand case both for efficiency and so we don't
1480 // increment Depth when just zipping down an all-constant GEP.
1481 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1482 if (!OpC->isZero())
1483 return true;
1484 continue;
1485 }
1486
1487 // We post-increment Depth here because while isKnownNonZero increments it
1488 // as well, when we pop back up that increment won't persist. We don't want
1489 // to recurse 10k times just because we have 10k GEP operands. We don't
1490 // bail completely out because we want to handle constant GEPs regardless
1491 // of depth.
1492 if (Depth++ >= MaxDepth)
1493 continue;
1494
Hal Finkel60db0582014-09-07 18:57:58 +00001495 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001496 return true;
1497 }
1498
1499 return false;
1500}
1501
Duncan Sandsd3951082011-01-25 09:38:29 +00001502/// isKnownNonZero - Return true if the given value is known to be non-zero
1503/// when defined. For vectors return true if every element is known to be
1504/// non-zero when defined. Supports values with integer or pointer type and
1505/// vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001506bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
1507 const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001508 if (Constant *C = dyn_cast<Constant>(V)) {
1509 if (C->isNullValue())
1510 return false;
1511 if (isa<ConstantInt>(C))
1512 // Must be non-zero due to null test above.
1513 return true;
1514 // TODO: Handle vectors
1515 return false;
1516 }
1517
1518 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001519 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001520 return false;
1521
Chandler Carruth80d3e562012-12-07 02:08:58 +00001522 // Check for pointer simplifications.
1523 if (V->getType()->isPointerTy()) {
Manman Ren12171122013-03-18 21:23:25 +00001524 if (isKnownNonNull(V))
1525 return true;
Chandler Carruth80d3e562012-12-07 02:08:58 +00001526 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +00001527 if (isGEPKnownNonNull(GEP, TD, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001528 return true;
1529 }
1530
Nadav Rotemaa3e2a92012-12-14 20:43:49 +00001531 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
Duncan Sandsd3951082011-01-25 09:38:29 +00001532
1533 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001534 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001535 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Hal Finkel60db0582014-09-07 18:57:58 +00001536 return isKnownNonZero(X, TD, Depth, Q) ||
1537 isKnownNonZero(Y, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001538
1539 // ext X != 0 if X != 0.
1540 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Hal Finkel60db0582014-09-07 18:57:58 +00001541 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001542
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001543 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001544 // if the lowest bit is shifted off the end.
1545 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001546 // shl nuw can't remove any non-zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001547 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001548 if (BO->hasNoUnsignedWrap())
Hal Finkel60db0582014-09-07 18:57:58 +00001549 return isKnownNonZero(X, TD, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001550
Duncan Sandsd3951082011-01-25 09:38:29 +00001551 APInt KnownZero(BitWidth, 0);
1552 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001553 computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001554 if (KnownOne[0])
1555 return true;
1556 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001557 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001558 // defined if the sign bit is shifted off the end.
1559 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001560 // shr exact can only shift out zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001561 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001562 if (BO->isExact())
Hal Finkel60db0582014-09-07 18:57:58 +00001563 return isKnownNonZero(X, TD, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001564
Duncan Sandsd3951082011-01-25 09:38:29 +00001565 bool XKnownNonNegative, XKnownNegative;
Hal Finkel60db0582014-09-07 18:57:58 +00001566 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001567 if (XKnownNegative)
1568 return true;
1569 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001570 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001571 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001572 return isKnownNonZero(X, TD, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001573 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001574 // X + Y.
1575 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1576 bool XKnownNonNegative, XKnownNegative;
1577 bool YKnownNonNegative, YKnownNegative;
Hal Finkel60db0582014-09-07 18:57:58 +00001578 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
1579 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001580
1581 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001582 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001583 if (XKnownNonNegative && YKnownNonNegative)
Hal Finkel60db0582014-09-07 18:57:58 +00001584 if (isKnownNonZero(X, TD, Depth, Q) ||
1585 isKnownNonZero(Y, TD, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001586 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001587
1588 // If X and Y are both negative (as signed values) then their sum is not
1589 // zero unless both X and Y equal INT_MIN.
1590 if (BitWidth && XKnownNegative && YKnownNegative) {
1591 APInt KnownZero(BitWidth, 0);
1592 APInt KnownOne(BitWidth, 0);
1593 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1594 // The sign bit of X is set. If some other bit is set then X is not equal
1595 // to INT_MIN.
Hal Finkel60db0582014-09-07 18:57:58 +00001596 computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001597 if ((KnownOne & Mask) != 0)
1598 return true;
1599 // The sign bit of Y is set. If some other bit is set then Y is not equal
1600 // to INT_MIN.
Hal Finkel60db0582014-09-07 18:57:58 +00001601 computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001602 if ((KnownOne & Mask) != 0)
1603 return true;
1604 }
1605
1606 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001607 if (XKnownNonNegative &&
1608 isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001609 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00001610 if (YKnownNonNegative &&
1611 isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001612 return true;
1613 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001614 // X * Y.
1615 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1616 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1617 // If X and Y are non-zero then so is X * Y as long as the multiplication
1618 // does not overflow.
1619 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Hal Finkel60db0582014-09-07 18:57:58 +00001620 isKnownNonZero(X, TD, Depth, Q) &&
1621 isKnownNonZero(Y, TD, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001622 return true;
1623 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001624 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1625 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
Hal Finkel60db0582014-09-07 18:57:58 +00001626 if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
1627 isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001628 return true;
1629 }
1630
1631 if (!BitWidth) return false;
1632 APInt KnownZero(BitWidth, 0);
1633 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001634 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001635 return KnownOne != 0;
1636}
1637
Chris Lattner965c7692008-06-02 01:18:21 +00001638/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1639/// this predicate to simplify operations downstream. Mask is known to be zero
1640/// for bits that V cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001641///
1642/// This function is defined on values with integer type, values with pointer
1643/// type (but only if TD is non-null), and vectors of integers. In the case
1644/// where V is a vector, the mask, known zero, and known one values are the
1645/// same width as the vector element, and the bit is set only if it is true
1646/// for all of the elements in the vector.
Hal Finkel60db0582014-09-07 18:57:58 +00001647bool MaskedValueIsZero(Value *V, const APInt &Mask,
1648 const DataLayout *TD, unsigned Depth,
1649 const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +00001650 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001651 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001652 return (KnownZero & Mask) == Mask;
1653}
1654
1655
1656
1657/// ComputeNumSignBits - Return the number of times the sign bit of the
1658/// register is replicated into the other bits. We know that at least 1 bit
1659/// is always equal to the sign bit (itself), but other cases can give us
1660/// information. For example, immediately after an "ashr X, 2", we know that
1661/// the top 3 bits are all equal to each other, so we return 3.
1662///
1663/// 'Op' must have a scalar integer type.
1664///
Hal Finkel60db0582014-09-07 18:57:58 +00001665unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
1666 unsigned Depth, const Query &Q) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001667 assert((TD || V->getType()->isIntOrIntVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001668 "ComputeNumSignBits requires a DataLayout object to operate "
Dan Gohman26366932009-06-22 22:02:32 +00001669 "on non-integer values!");
Chris Lattner229907c2011-07-18 04:54:35 +00001670 Type *Ty = V->getType();
Dan Gohman26366932009-06-22 22:02:32 +00001671 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
1672 Ty->getScalarSizeInBits();
Chris Lattner965c7692008-06-02 01:18:21 +00001673 unsigned Tmp, Tmp2;
1674 unsigned FirstAnswer = 1;
1675
Jay Foada0653a32014-05-14 21:14:37 +00001676 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00001677 // below.
1678
Chris Lattner965c7692008-06-02 01:18:21 +00001679 if (Depth == 6)
1680 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001681
Dan Gohman80ca01c2009-07-17 20:47:02 +00001682 Operator *U = dyn_cast<Operator>(V);
1683 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001684 default: break;
1685 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00001686 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Hal Finkel60db0582014-09-07 18:57:58 +00001687 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00001688
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001689 case Instruction::AShr: {
Hal Finkel60db0582014-09-07 18:57:58 +00001690 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001691 // ashr X, C -> adds C sign bits. Vectors too.
1692 const APInt *ShAmt;
1693 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1694 Tmp += ShAmt->getZExtValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001695 if (Tmp > TyBits) Tmp = TyBits;
1696 }
1697 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001698 }
1699 case Instruction::Shl: {
1700 const APInt *ShAmt;
1701 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00001702 // shl destroys sign bits.
Hal Finkel60db0582014-09-07 18:57:58 +00001703 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001704 Tmp2 = ShAmt->getZExtValue();
1705 if (Tmp2 >= TyBits || // Bad shift.
1706 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1707 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00001708 }
1709 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001710 }
Chris Lattner965c7692008-06-02 01:18:21 +00001711 case Instruction::And:
1712 case Instruction::Or:
1713 case Instruction::Xor: // NOT is handled here.
1714 // Logical binary ops preserve the number of sign bits at the worst.
Hal Finkel60db0582014-09-07 18:57:58 +00001715 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001716 if (Tmp != 1) {
Hal Finkel60db0582014-09-07 18:57:58 +00001717 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001718 FirstAnswer = std::min(Tmp, Tmp2);
1719 // We computed what we know about the sign bits as our first
1720 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00001721 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00001722 }
1723 break;
1724
1725 case Instruction::Select:
Hal Finkel60db0582014-09-07 18:57:58 +00001726 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001727 if (Tmp == 1) return 1; // Early out.
Hal Finkel60db0582014-09-07 18:57:58 +00001728 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001729 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00001730
Chris Lattner965c7692008-06-02 01:18:21 +00001731 case Instruction::Add:
1732 // Add can have at most one carry bit. Thus we know that the output
1733 // is, at worst, one more bit than the inputs.
Hal Finkel60db0582014-09-07 18:57:58 +00001734 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001735 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00001736
Chris Lattner965c7692008-06-02 01:18:21 +00001737 // Special case decrementing a value (ADD X, -1):
Dan Gohman4f356bb2009-02-24 02:00:40 +00001738 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00001739 if (CRHS->isAllOnesValue()) {
1740 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001741 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001742
Chris Lattner965c7692008-06-02 01:18:21 +00001743 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1744 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001745 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00001746 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00001747
Chris Lattner965c7692008-06-02 01:18:21 +00001748 // If we are subtracting one from a positive number, there is no carry
1749 // out of the result.
1750 if (KnownZero.isNegative())
1751 return Tmp;
1752 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001753
Hal Finkel60db0582014-09-07 18:57:58 +00001754 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001755 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001756 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001757
Chris Lattner965c7692008-06-02 01:18:21 +00001758 case Instruction::Sub:
Hal Finkel60db0582014-09-07 18:57:58 +00001759 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001760 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001761
Chris Lattner965c7692008-06-02 01:18:21 +00001762 // Handle NEG.
1763 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
1764 if (CLHS->isNullValue()) {
1765 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001766 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001767 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1768 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001769 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00001770 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00001771
Chris Lattner965c7692008-06-02 01:18:21 +00001772 // If the input is known to be positive (the sign bit is known clear),
1773 // the output of the NEG has the same number of sign bits as the input.
1774 if (KnownZero.isNegative())
1775 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00001776
Chris Lattner965c7692008-06-02 01:18:21 +00001777 // Otherwise, we treat this like a SUB.
1778 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001779
Chris Lattner965c7692008-06-02 01:18:21 +00001780 // Sub can have at most one carry bit. Thus we know that the output
1781 // is, at worst, one more bit than the inputs.
Hal Finkel60db0582014-09-07 18:57:58 +00001782 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001783 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001784 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00001785
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001786 case Instruction::PHI: {
1787 PHINode *PN = cast<PHINode>(U);
1788 // Don't analyze large in-degree PHIs.
1789 if (PN->getNumIncomingValues() > 4) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00001790
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001791 // Take the minimum of all incoming values. This can't infinitely loop
1792 // because of our depth threshold.
Hal Finkel60db0582014-09-07 18:57:58 +00001793 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001794 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
1795 if (Tmp == 1) return Tmp;
1796 Tmp = std::min(Tmp,
Hal Finkel60db0582014-09-07 18:57:58 +00001797 ComputeNumSignBits(PN->getIncomingValue(i), TD,
1798 Depth+1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00001799 }
1800 return Tmp;
1801 }
1802
Chris Lattner965c7692008-06-02 01:18:21 +00001803 case Instruction::Trunc:
1804 // FIXME: it's tricky to do anything useful for this, but it is an important
1805 // case for targets like X86.
1806 break;
1807 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001808
Chris Lattner965c7692008-06-02 01:18:21 +00001809 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1810 // use this information.
1811 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001812 APInt Mask;
Hal Finkel60db0582014-09-07 18:57:58 +00001813 computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001814
Chris Lattner965c7692008-06-02 01:18:21 +00001815 if (KnownZero.isNegative()) { // sign bit is 0
1816 Mask = KnownZero;
1817 } else if (KnownOne.isNegative()) { // sign bit is 1;
1818 Mask = KnownOne;
1819 } else {
1820 // Nothing known.
1821 return FirstAnswer;
1822 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001823
Chris Lattner965c7692008-06-02 01:18:21 +00001824 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1825 // the number of identical bits in the top of the input value.
1826 Mask = ~Mask;
1827 Mask <<= Mask.getBitWidth()-TyBits;
1828 // Return # leading zeros. We use 'min' here in case Val was zero before
1829 // shifting. We don't want to return '64' as for an i32 "0".
1830 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
1831}
Chris Lattnera12a6de2008-06-02 01:29:46 +00001832
Victor Hernandez47444882009-11-10 08:28:35 +00001833/// ComputeMultiple - This function computes the integer multiple of Base that
1834/// equals V. If successful, it returns true and returns the multiple in
Dan Gohman6a976bb2009-11-18 00:58:27 +00001835/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00001836/// through SExt instructions only if LookThroughSExt is true.
1837bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00001838 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00001839 const unsigned MaxDepth = 6;
1840
Dan Gohman6a976bb2009-11-18 00:58:27 +00001841 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00001842 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00001843 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00001844
Chris Lattner229907c2011-07-18 04:54:35 +00001845 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00001846
Dan Gohman6a976bb2009-11-18 00:58:27 +00001847 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00001848
1849 if (Base == 0)
1850 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00001851
Victor Hernandez47444882009-11-10 08:28:35 +00001852 if (Base == 1) {
1853 Multiple = V;
1854 return true;
1855 }
1856
1857 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
1858 Constant *BaseVal = ConstantInt::get(T, Base);
1859 if (CO && CO == BaseVal) {
1860 // Multiple is 1.
1861 Multiple = ConstantInt::get(T, 1);
1862 return true;
1863 }
1864
1865 if (CI && CI->getZExtValue() % Base == 0) {
1866 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00001867 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00001868 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001869
Victor Hernandez47444882009-11-10 08:28:35 +00001870 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001871
Victor Hernandez47444882009-11-10 08:28:35 +00001872 Operator *I = dyn_cast<Operator>(V);
1873 if (!I) return false;
1874
1875 switch (I->getOpcode()) {
1876 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00001877 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00001878 if (!LookThroughSExt) return false;
1879 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00001880 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00001881 return ComputeMultiple(I->getOperand(0), Base, Multiple,
1882 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00001883 case Instruction::Shl:
1884 case Instruction::Mul: {
1885 Value *Op0 = I->getOperand(0);
1886 Value *Op1 = I->getOperand(1);
1887
1888 if (I->getOpcode() == Instruction::Shl) {
1889 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
1890 if (!Op1CI) return false;
1891 // Turn Op0 << Op1 into Op0 * 2^Op1
1892 APInt Op1Int = Op1CI->getValue();
1893 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00001894 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00001895 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00001896 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00001897 }
1898
Craig Topper9f008862014-04-15 04:59:12 +00001899 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00001900 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
1901 if (Constant *Op1C = dyn_cast<Constant>(Op1))
1902 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00001903 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00001904 MulC->getType()->getPrimitiveSizeInBits())
1905 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001906 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00001907 MulC->getType()->getPrimitiveSizeInBits())
1908 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001909
Chris Lattner72d283c2010-09-05 17:20:46 +00001910 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
1911 Multiple = ConstantExpr::getMul(MulC, Op1C);
1912 return true;
1913 }
Victor Hernandez47444882009-11-10 08:28:35 +00001914
1915 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
1916 if (Mul0CI->getValue() == 1) {
1917 // V == Base * Op1, so return Op1
1918 Multiple = Op1;
1919 return true;
1920 }
1921 }
1922
Craig Topper9f008862014-04-15 04:59:12 +00001923 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00001924 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
1925 if (Constant *Op0C = dyn_cast<Constant>(Op0))
1926 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00001927 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00001928 MulC->getType()->getPrimitiveSizeInBits())
1929 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001930 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00001931 MulC->getType()->getPrimitiveSizeInBits())
1932 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001933
Chris Lattner72d283c2010-09-05 17:20:46 +00001934 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
1935 Multiple = ConstantExpr::getMul(MulC, Op0C);
1936 return true;
1937 }
Victor Hernandez47444882009-11-10 08:28:35 +00001938
1939 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
1940 if (Mul1CI->getValue() == 1) {
1941 // V == Base * Op0, so return Op0
1942 Multiple = Op0;
1943 return true;
1944 }
1945 }
Victor Hernandez47444882009-11-10 08:28:35 +00001946 }
1947 }
1948
1949 // We could not determine if V is a multiple of Base.
1950 return false;
1951}
1952
Craig Topper1bef2c82012-12-22 19:15:35 +00001953/// CannotBeNegativeZero - Return true if we can prove that the specified FP
Chris Lattnera12a6de2008-06-02 01:29:46 +00001954/// value is never equal to -0.0.
1955///
1956/// NOTE: this function will need to be revisited when we support non-default
1957/// rounding modes!
1958///
1959bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
1960 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1961 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00001962
Chris Lattnera12a6de2008-06-02 01:29:46 +00001963 if (Depth == 6)
1964 return 1; // Limit search depth.
1965
Dan Gohman80ca01c2009-07-17 20:47:02 +00001966 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00001967 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00001968
1969 // Check if the nsz fast-math flag is set
1970 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
1971 if (FPO->hasNoSignedZeros())
1972 return true;
1973
Chris Lattnera12a6de2008-06-02 01:29:46 +00001974 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00001975 if (I->getOpcode() == Instruction::FAdd)
1976 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
1977 if (CFP->isNullValue())
1978 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00001979
Chris Lattnera12a6de2008-06-02 01:29:46 +00001980 // sitofp and uitofp turn into +0.0 for zero.
1981 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
1982 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00001983
Chris Lattnera12a6de2008-06-02 01:29:46 +00001984 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1985 // sqrt(-0.0) = -0.0, no other negative results are possible.
1986 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif1abbde32010-06-23 23:38:07 +00001987 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Craig Topper1bef2c82012-12-22 19:15:35 +00001988
Chris Lattnera12a6de2008-06-02 01:29:46 +00001989 if (const CallInst *CI = dyn_cast<CallInst>(I))
1990 if (const Function *F = CI->getCalledFunction()) {
1991 if (F->isDeclaration()) {
Daniel Dunbarca414c72009-07-26 08:34:35 +00001992 // abs(x) != -0.0
1993 if (F->getName() == "abs") return true;
Dale Johannesenf6a987b2009-09-25 20:54:50 +00001994 // fabs[lf](x) != -0.0
1995 if (F->getName() == "fabs") return true;
1996 if (F->getName() == "fabsf") return true;
1997 if (F->getName() == "fabsl") return true;
1998 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
1999 F->getName() == "sqrtl")
Gabor Greif1abbde32010-06-23 23:38:07 +00002000 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattnera12a6de2008-06-02 01:29:46 +00002001 }
2002 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002003
Chris Lattnera12a6de2008-06-02 01:29:46 +00002004 return false;
2005}
2006
Chris Lattner9cb10352010-12-26 20:15:01 +00002007/// isBytewiseValue - If the specified value can be set by repeating the same
2008/// byte in memory, return the i8 value that it is represented with. This is
2009/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2010/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2011/// byte store (e.g. i16 0x1234), return null.
2012Value *llvm::isBytewiseValue(Value *V) {
2013 // All byte-wide stores are splatable, even of arbitrary variables.
2014 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002015
2016 // Handle 'null' ConstantArrayZero etc.
2017 if (Constant *C = dyn_cast<Constant>(V))
2018 if (C->isNullValue())
2019 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002020
Chris Lattner9cb10352010-12-26 20:15:01 +00002021 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002022 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002023 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2024 if (CFP->getType()->isFloatTy())
2025 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2026 if (CFP->getType()->isDoubleTy())
2027 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2028 // Don't handle long double formats, which have strange constraints.
2029 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002030
2031 // We can handle constant integers that are power of two in size and a
Chris Lattner9cb10352010-12-26 20:15:01 +00002032 // multiple of 8 bits.
2033 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2034 unsigned Width = CI->getBitWidth();
2035 if (isPowerOf2_32(Width) && Width > 8) {
2036 // We can handle this value if the recursive binary decomposition is the
2037 // same at all levels.
2038 APInt Val = CI->getValue();
2039 APInt Val2;
2040 while (Val.getBitWidth() != 8) {
2041 unsigned NextWidth = Val.getBitWidth()/2;
2042 Val2 = Val.lshr(NextWidth);
2043 Val2 = Val2.trunc(Val.getBitWidth()/2);
2044 Val = Val.trunc(Val.getBitWidth()/2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002045
Chris Lattner9cb10352010-12-26 20:15:01 +00002046 // If the top/bottom halves aren't the same, reject it.
2047 if (Val != Val2)
Craig Topper9f008862014-04-15 04:59:12 +00002048 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002049 }
2050 return ConstantInt::get(V->getContext(), Val);
2051 }
2052 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002053
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002054 // A ConstantDataArray/Vector is splatable if all its members are equal and
2055 // also splatable.
2056 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2057 Value *Elt = CA->getElementAsConstant(0);
2058 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002059 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002060 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002061
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002062 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2063 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002064 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002065
Chris Lattner9cb10352010-12-26 20:15:01 +00002066 return Val;
2067 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002068
Chris Lattner9cb10352010-12-26 20:15:01 +00002069 // Conceptually, we could handle things like:
2070 // %a = zext i8 %X to i16
2071 // %b = shl i16 %a, 8
2072 // %c = or i16 %a, %b
2073 // but until there is an example that actually needs this, it doesn't seem
2074 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002075 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002076}
2077
2078
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002079// This is the recursive version of BuildSubAggregate. It takes a few different
2080// arguments. Idxs is the index within the nested struct From that we are
2081// looking at now (which is of type IndexedType). IdxSkip is the number of
2082// indices from Idxs that should be left out when inserting into the resulting
2083// struct. To is the result struct built so far, new insertvalue instructions
2084// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002085static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002086 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002087 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002088 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002089 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002090 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002091 // Save the original To argument so we can modify it
2092 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002093 // General case, the type indexed by Idxs is a struct
2094 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2095 // Process each struct element recursively
2096 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002097 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002098 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002099 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002100 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002101 if (!To) {
2102 // Couldn't find any inserted value for this index? Cleanup
2103 while (PrevTo != OrigTo) {
2104 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2105 PrevTo = Del->getAggregateOperand();
2106 Del->eraseFromParent();
2107 }
2108 // Stop processing elements
2109 break;
2110 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002111 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002112 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002113 if (To)
2114 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002115 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002116 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2117 // the struct's elements had a value that was inserted directly. In the latter
2118 // case, perhaps we can't determine each of the subelements individually, but
2119 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002120
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002121 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002122 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002123
2124 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002125 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002126
2127 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002128 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002129 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002130}
2131
2132// This helper takes a nested struct and extracts a part of it (which is again a
2133// struct) into a new value. For example, given the struct:
2134// { a, { b, { c, d }, e } }
2135// and the indices "1, 1" this returns
2136// { c, d }.
2137//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002138// It does this by inserting an insertvalue for each element in the resulting
2139// struct, as opposed to just inserting a single struct. This will only work if
2140// each of the elements of the substruct are known (ie, inserted into From by an
2141// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002142//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002143// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002144static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002145 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002146 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002147 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002148 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002149 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002150 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002151 unsigned IdxSkip = Idxs.size();
2152
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002153 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002154}
2155
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002156/// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
2157/// the scalar value indexed is already around as a register, for example if it
2158/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002159///
2160/// If InsertBefore is not null, this function will duplicate (modified)
2161/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002162Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2163 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002164 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002165 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002166 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002167 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002168 // We have indices, so V should have an indexable type.
2169 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2170 "Not looking at a struct or array?");
2171 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2172 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002173
Chris Lattner67058832012-01-25 06:48:06 +00002174 if (Constant *C = dyn_cast<Constant>(V)) {
2175 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002176 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002177 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2178 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002179
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002180 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002181 // Loop the indices for the insertvalue instruction in parallel with the
2182 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002183 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002184 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2185 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002186 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002187 // We can't handle this without inserting insertvalues
2188 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002189 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002190
2191 // The requested index identifies a part of a nested aggregate. Handle
2192 // this specially. For example,
2193 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2194 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2195 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2196 // This can be changed into
2197 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2198 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2199 // which allows the unused 0,0 element from the nested struct to be
2200 // removed.
2201 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2202 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002203 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002204
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002205 // This insert value inserts something else than what we are looking for.
2206 // See if the (aggregrate) value inserted into has the value we are
2207 // looking for, then.
2208 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002209 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002210 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002211 }
2212 // If we end up here, the indices of the insertvalue match with those
2213 // requested (though possibly only partially). Now we recursively look at
2214 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002215 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002216 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002217 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002218 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002219
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002220 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002221 // If we're extracting a value from an aggregrate that was extracted from
2222 // something else, we can extract from that something else directly instead.
2223 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002224
2225 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002226 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002227 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002228 SmallVector<unsigned, 5> Idxs;
2229 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002230 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002231 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002232
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002233 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002234 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002235
Craig Topper1bef2c82012-12-22 19:15:35 +00002236 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002237 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002238
Jay Foad57aa6362011-07-13 10:26:04 +00002239 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002240 }
2241 // Otherwise, we don't know (such as, extracting from a function return value
2242 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002243 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002244}
Evan Chengda3db112008-06-30 07:31:25 +00002245
Chris Lattnere28618d2010-11-30 22:25:26 +00002246/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
2247/// it can be expressed as a base pointer plus a constant offset. Return the
2248/// base and offset to the caller.
2249Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002250 const DataLayout *DL) {
Dan Gohman20a2ae92013-01-31 02:00:45 +00002251 // Without DataLayout, conservatively assume 64-bit offsets, which is
2252 // the widest we support.
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002253 unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
Nuno Lopes368c4d02012-12-31 20:48:35 +00002254 APInt ByteOffset(BitWidth, 0);
2255 while (1) {
2256 if (Ptr->getType()->isVectorTy())
2257 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002258
Nuno Lopes368c4d02012-12-31 20:48:35 +00002259 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002260 if (DL) {
2261 APInt GEPOffset(BitWidth, 0);
2262 if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
2263 break;
2264
2265 ByteOffset += GEPOffset;
2266 }
2267
Nuno Lopes368c4d02012-12-31 20:48:35 +00002268 Ptr = GEP->getPointerOperand();
Matt Arsenaultfd78d0c2014-07-14 22:39:22 +00002269 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2270 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002271 Ptr = cast<Operator>(Ptr)->getOperand(0);
2272 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2273 if (GA->mayBeOverridden())
2274 break;
2275 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002276 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002277 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002278 }
2279 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002280 Offset = ByteOffset.getSExtValue();
2281 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002282}
2283
2284
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002285/// getConstantStringInfo - This function computes the length of a
Evan Chengda3db112008-06-30 07:31:25 +00002286/// null-terminated C string pointed to by V. If successful, it returns true
2287/// and returns the string in Str. If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002288bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2289 uint64_t Offset, bool TrimAtNul) {
2290 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002291
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002292 // Look through bitcast instructions and geps.
2293 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002294
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002295 // If the value is a GEP instructionor constant expression, treat it as an
2296 // offset.
2297 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Chengda3db112008-06-30 07:31:25 +00002298 // Make sure the GEP has exactly three arguments.
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002299 if (GEP->getNumOperands() != 3)
2300 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002301
Evan Chengda3db112008-06-30 07:31:25 +00002302 // Make sure the index-ee is a pointer to array of i8.
Chris Lattner229907c2011-07-18 04:54:35 +00002303 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2304 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Craig Topper9f008862014-04-15 04:59:12 +00002305 if (!AT || !AT->getElementType()->isIntegerTy(8))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002306 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002307
Evan Chengda3db112008-06-30 07:31:25 +00002308 // Check to make sure that the first operand of the GEP is an integer and
2309 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0b4df042010-04-14 22:20:45 +00002310 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Craig Topper9f008862014-04-15 04:59:12 +00002311 if (!FirstIdx || !FirstIdx->isZero())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002312 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002313
Evan Chengda3db112008-06-30 07:31:25 +00002314 // If the second index isn't a ConstantInt, then this is a variable index
2315 // into the array. If this occurs, we can't say anything meaningful about
2316 // the string.
2317 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002318 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002319 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002320 else
2321 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002322 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
Evan Chengda3db112008-06-30 07:31:25 +00002323 }
Nick Lewycky46209882011-10-20 00:34:35 +00002324
Evan Chengda3db112008-06-30 07:31:25 +00002325 // The GEP instruction, constant or instruction, must reference a global
2326 // variable that is a constant and is initialized. The referenced constant
2327 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002328 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002329 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002330 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002331
Nick Lewycky46209882011-10-20 00:34:35 +00002332 // Handle the all-zeros case
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002333 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00002334 // This is a degenerate case. The initializer is constant zero so the
2335 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002336 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002337 return true;
2338 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002339
Evan Chengda3db112008-06-30 07:31:25 +00002340 // Must be a Constant Array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002341 const ConstantDataArray *Array =
2342 dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00002343 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002344 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002345
Evan Chengda3db112008-06-30 07:31:25 +00002346 // Get the number of elements in the array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002347 uint64_t NumElts = Array->getType()->getArrayNumElements();
2348
2349 // Start out with the entire array in the StringRef.
2350 Str = Array->getAsString();
2351
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002352 if (Offset > NumElts)
2353 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002354
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002355 // Skip over 'offset' bytes.
2356 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00002357
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002358 if (TrimAtNul) {
2359 // Trim off the \0 and anything after it. If the array is not nul
2360 // terminated, we just return the whole end of string. The client may know
2361 // some other way that the string is length-bound.
2362 Str = Str.substr(0, Str.find('\0'));
2363 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002364 return true;
Evan Chengda3db112008-06-30 07:31:25 +00002365}
Eric Christopher4899cbc2010-03-05 06:58:57 +00002366
2367// These next two are very similar to the above, but also look through PHI
2368// nodes.
2369// TODO: See if we can integrate these two together.
2370
2371/// GetStringLengthH - If we can compute the length of the string pointed to by
2372/// the specified pointer, return 'len+1'. If we can't, return 0.
Craig Topper71b7b682014-08-21 05:55:13 +00002373static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00002374 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002375 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00002376
2377 // If this is a PHI node, there are two cases: either we have already seen it
2378 // or we haven't.
2379 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2380 if (!PHIs.insert(PN))
2381 return ~0ULL; // already in the set.
2382
2383 // If it was new, see if all the input strings are the same length.
2384 uint64_t LenSoFar = ~0ULL;
2385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2386 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2387 if (Len == 0) return 0; // Unknown length -> unknown.
2388
2389 if (Len == ~0ULL) continue;
2390
2391 if (Len != LenSoFar && LenSoFar != ~0ULL)
2392 return 0; // Disagree -> unknown.
2393 LenSoFar = Len;
2394 }
2395
2396 // Success, all agree.
2397 return LenSoFar;
2398 }
2399
2400 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2401 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2402 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2403 if (Len1 == 0) return 0;
2404 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2405 if (Len2 == 0) return 0;
2406 if (Len1 == ~0ULL) return Len2;
2407 if (Len2 == ~0ULL) return Len1;
2408 if (Len1 != Len2) return 0;
2409 return Len1;
2410 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002411
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002412 // Otherwise, see if we can read the string.
2413 StringRef StrData;
2414 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00002415 return 0;
2416
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002417 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00002418}
2419
2420/// GetStringLength - If we can compute the length of the string pointed to by
2421/// the specified pointer, return 'len+1'. If we can't, return 0.
2422uint64_t llvm::GetStringLength(Value *V) {
2423 if (!V->getType()->isPointerTy()) return 0;
2424
2425 SmallPtrSet<PHINode*, 32> PHIs;
2426 uint64_t Len = GetStringLengthH(V, PHIs);
2427 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2428 // an empty string as a length.
2429 return Len == ~0ULL ? 1 : Len;
2430}
Dan Gohmana4fcd242010-12-15 20:02:24 +00002431
Dan Gohman0f124e12011-01-24 18:53:32 +00002432Value *
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002433llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002434 if (!V->getType()->isPointerTy())
2435 return V;
2436 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2437 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2438 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00002439 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2440 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002441 V = cast<Operator>(V)->getOperand(0);
2442 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2443 if (GA->mayBeOverridden())
2444 return V;
2445 V = GA->getAliasee();
2446 } else {
Dan Gohman05b18f12010-12-15 20:49:55 +00002447 // See if InstructionSimplify knows any relevant tricks.
2448 if (Instruction *I = dyn_cast<Instruction>(V))
Hal Finkel60db0582014-09-07 18:57:58 +00002449 // TODO: Acquire a DominatorTree and AssumptionTracker and use them.
Craig Topper9f008862014-04-15 04:59:12 +00002450 if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00002451 V = Simplified;
2452 continue;
2453 }
2454
Dan Gohmana4fcd242010-12-15 20:02:24 +00002455 return V;
2456 }
2457 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2458 }
2459 return V;
2460}
Nick Lewycky3e334a42011-06-27 04:20:45 +00002461
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002462void
2463llvm::GetUnderlyingObjects(Value *V,
2464 SmallVectorImpl<Value *> &Objects,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002465 const DataLayout *TD,
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002466 unsigned MaxLookup) {
2467 SmallPtrSet<Value *, 4> Visited;
2468 SmallVector<Value *, 4> Worklist;
2469 Worklist.push_back(V);
2470 do {
2471 Value *P = Worklist.pop_back_val();
2472 P = GetUnderlyingObject(P, TD, MaxLookup);
2473
2474 if (!Visited.insert(P))
2475 continue;
2476
2477 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2478 Worklist.push_back(SI->getTrueValue());
2479 Worklist.push_back(SI->getFalseValue());
2480 continue;
2481 }
2482
2483 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2484 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2485 Worklist.push_back(PN->getIncomingValue(i));
2486 continue;
2487 }
2488
2489 Objects.push_back(P);
2490 } while (!Worklist.empty());
2491}
2492
Nick Lewycky3e334a42011-06-27 04:20:45 +00002493/// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
2494/// are lifetime markers.
2495///
2496bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002497 for (const User *U : V->users()) {
2498 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00002499 if (!II) return false;
2500
2501 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2502 II->getIntrinsicID() != Intrinsic::lifetime_end)
2503 return false;
2504 }
2505 return true;
2506}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002507
Dan Gohman7ac046a2012-01-04 23:01:09 +00002508bool llvm::isSafeToSpeculativelyExecute(const Value *V,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002509 const DataLayout *TD) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00002510 const Operator *Inst = dyn_cast<Operator>(V);
2511 if (!Inst)
2512 return false;
2513
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002514 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2515 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2516 if (C->canTrap())
2517 return false;
2518
2519 switch (Inst->getOpcode()) {
2520 default:
2521 return true;
2522 case Instruction::UDiv:
2523 case Instruction::URem:
Sanjay Patel784a5a42014-07-06 23:24:53 +00002524 // x / y is undefined if y == 0, but calculations like x / 3 are safe.
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002525 return isKnownNonZero(Inst->getOperand(1), TD);
2526 case Instruction::SDiv:
2527 case Instruction::SRem: {
2528 Value *Op = Inst->getOperand(1);
2529 // x / y is undefined if y == 0
2530 if (!isKnownNonZero(Op, TD))
2531 return false;
2532 // x / y might be undefined if y == -1
2533 unsigned BitWidth = getBitWidth(Op->getType(), TD);
2534 if (BitWidth == 0)
2535 return false;
2536 APInt KnownZero(BitWidth, 0);
2537 APInt KnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +00002538 computeKnownBits(Op, KnownZero, KnownOne, TD);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002539 return !!KnownZero;
2540 }
2541 case Instruction::Load: {
2542 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00002543 if (!LI->isUnordered() ||
2544 // Speculative load may create a race that did not exist in the source.
2545 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002546 return false;
Hal Finkel2e42c342014-07-10 05:27:53 +00002547 return LI->getPointerOperand()->isDereferenceablePointer(TD);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002548 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002549 case Instruction::Call: {
2550 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2551 switch (II->getIntrinsicID()) {
Sanjay Patel784a5a42014-07-06 23:24:53 +00002552 // These synthetic intrinsics have no side-effects and just mark
Chandler Carruth28192c92012-04-07 19:22:18 +00002553 // information about their operands.
2554 // FIXME: There are other no-op synthetic instructions that potentially
2555 // should be considered at least *safe* to speculate...
2556 case Intrinsic::dbg_declare:
2557 case Intrinsic::dbg_value:
2558 return true;
2559
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002560 case Intrinsic::bswap:
2561 case Intrinsic::ctlz:
2562 case Intrinsic::ctpop:
2563 case Intrinsic::cttz:
2564 case Intrinsic::objectsize:
2565 case Intrinsic::sadd_with_overflow:
2566 case Intrinsic::smul_with_overflow:
2567 case Intrinsic::ssub_with_overflow:
2568 case Intrinsic::uadd_with_overflow:
2569 case Intrinsic::umul_with_overflow:
2570 case Intrinsic::usub_with_overflow:
2571 return true;
Matt Arsenaultee364ee2014-01-31 00:09:00 +00002572 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2573 // errno like libm sqrt would.
2574 case Intrinsic::sqrt:
2575 case Intrinsic::fma:
2576 case Intrinsic::fmuladd:
Matt Arsenault85cbc7e2014-08-29 16:01:17 +00002577 case Intrinsic::fabs:
Matt Arsenaultee364ee2014-01-31 00:09:00 +00002578 return true;
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002579 // TODO: some fp intrinsics are marked as having the same error handling
2580 // as libm. They're safe to speculate when they won't error.
2581 // TODO: are convert_{from,to}_fp16 safe?
2582 // TODO: can we list target-specific intrinsics here?
2583 default: break;
2584 }
2585 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002586 return false; // The called function could have undefined behavior or
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002587 // side-effects, even if marked readnone nounwind.
2588 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002589 case Instruction::VAArg:
2590 case Instruction::Alloca:
2591 case Instruction::Invoke:
2592 case Instruction::PHI:
2593 case Instruction::Store:
2594 case Instruction::Ret:
2595 case Instruction::Br:
2596 case Instruction::IndirectBr:
2597 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002598 case Instruction::Unreachable:
2599 case Instruction::Fence:
2600 case Instruction::LandingPad:
2601 case Instruction::AtomicRMW:
2602 case Instruction::AtomicCmpXchg:
2603 case Instruction::Resume:
2604 return false; // Misc instructions which have effects
2605 }
2606}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002607
2608/// isKnownNonNull - Return true if we know that the specified value is never
2609/// null.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002610bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002611 // Alloca never returns null, malloc might.
2612 if (isa<AllocaInst>(V)) return true;
2613
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002614 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002615 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002616 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002617
2618 // Global values are not null unless extern weak.
2619 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2620 return !GV->hasExternalWeakLinkage();
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002621
Nick Lewyckyec373542014-05-20 05:13:21 +00002622 if (ImmutableCallSite CS = V)
Hal Finkelb0407ba2014-07-18 15:51:28 +00002623 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00002624 return true;
2625
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002626 // operator new never returns null.
2627 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2628 return true;
2629
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002630 return false;
2631}