1 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/MemoryBuiltins.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/ConstantRange.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #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"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Statepoint.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
39 using namespace llvm::PatternMatch;
41 const unsigned MaxDepth = 6;
43 /// Enable an experimental feature to leverage information about dominating
44 /// conditions to compute known bits. The individual options below control how
45 /// hard we search. The defaults are choosen to be fairly aggressive. If you
46 /// run into compile time problems when testing, scale them back and report
48 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
49 cl::Hidden, cl::init(false));
51 // This is expensive, so we only do it for the top level query value.
52 // (TODO: evaluate cost vs profit, consider higher thresholds)
53 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
54 cl::Hidden, cl::init(1));
56 /// How many dominating blocks should be scanned looking for dominating
58 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
62 // Controls the number of uses of the value searched for possible
63 // dominating comparisons.
64 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
65 cl::Hidden, cl::init(2000));
67 // If true, don't consider only compares whose only use is a branch.
68 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
69 cl::Hidden, cl::init(false));
71 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
72 /// 0). For vector types, returns the element type's bitwidth.
73 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
74 if (unsigned BitWidth = Ty->getScalarSizeInBits())
77 return DL.getPointerTypeSizeInBits(Ty);
80 // Many of these functions have internal versions that take an assumption
81 // exclusion set. This is because of the potential for mutual recursion to
82 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
83 // classic case of this is assume(x = y), which will attempt to determine
84 // bits in x from bits in y, which will attempt to determine bits in y from
85 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
86 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
87 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
88 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
91 // Simplifying using an assume can only be done in a particular control-flow
92 // context (the context instruction provides that context). If an assume and
93 // the context instruction are not in the same block then the DT helps in
94 // figuring out if we can use it.
98 const Instruction *CxtI;
99 const DominatorTree *DT;
101 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
102 const DominatorTree *DT = nullptr)
103 : AC(AC), CxtI(CxtI), DT(DT) {}
105 Query(const Query &Q, const Value *NewExcl)
106 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
107 ExclInvs.insert(NewExcl);
110 } // end anonymous namespace
112 // Given the provided Value and, potentially, a context instruction, return
113 // the preferred context instruction (if any).
114 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
115 // If we've been provided with a context instruction, then use that (provided
116 // it has been inserted).
117 if (CxtI && CxtI->getParent())
120 // If the value is really an already-inserted instruction, then use that.
121 CxtI = dyn_cast<Instruction>(V);
122 if (CxtI && CxtI->getParent())
128 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
129 const DataLayout &DL, unsigned Depth,
132 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
133 const DataLayout &DL, unsigned Depth,
134 AssumptionCache *AC, const Instruction *CxtI,
135 const DominatorTree *DT) {
136 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
137 Query(AC, safeCxtI(V, CxtI), DT));
140 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
141 const DataLayout &DL, unsigned Depth,
144 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
145 const DataLayout &DL, unsigned Depth,
146 AssumptionCache *AC, const Instruction *CxtI,
147 const DominatorTree *DT) {
148 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
149 Query(AC, safeCxtI(V, CxtI), DT));
152 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
153 const Query &Q, const DataLayout &DL);
155 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
156 unsigned Depth, AssumptionCache *AC,
157 const Instruction *CxtI,
158 const DominatorTree *DT) {
159 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
160 Query(AC, safeCxtI(V, CxtI), DT), DL);
163 static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
166 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
167 AssumptionCache *AC, const Instruction *CxtI,
168 const DominatorTree *DT) {
169 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
172 static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
173 unsigned Depth, const Query &Q);
175 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
176 unsigned Depth, AssumptionCache *AC,
177 const Instruction *CxtI, const DominatorTree *DT) {
178 return ::MaskedValueIsZero(V, Mask, DL, Depth,
179 Query(AC, safeCxtI(V, CxtI), DT));
182 static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
183 unsigned Depth, const Query &Q);
185 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
186 unsigned Depth, AssumptionCache *AC,
187 const Instruction *CxtI,
188 const DominatorTree *DT) {
189 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
192 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
193 APInt &KnownZero, APInt &KnownOne,
194 APInt &KnownZero2, APInt &KnownOne2,
195 const DataLayout &DL, unsigned Depth,
198 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
199 // We know that the top bits of C-X are clear if X contains less bits
200 // than C (i.e. no wrap-around can happen). For example, 20-X is
201 // positive if we can prove that X is >= 0 and < 16.
202 if (!CLHS->getValue().isNegative()) {
203 unsigned BitWidth = KnownZero.getBitWidth();
204 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
205 // NLZ can't be BitWidth with no sign bit
206 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
207 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
209 // If all of the MaskV bits are known to be zero, then we know the
210 // output top bits are zero, because we now know that the output is
212 if ((KnownZero2 & MaskV) == MaskV) {
213 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
214 // Top bits known zero.
215 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
221 unsigned BitWidth = KnownZero.getBitWidth();
223 // If an initial sequence of bits in the result is not needed, the
224 // corresponding bits in the operands are not needed.
225 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
226 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
227 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
229 // Carry in a 1 for a subtract, rather than a 0.
230 APInt CarryIn(BitWidth, 0);
232 // Sum = LHS + ~RHS + 1
233 std::swap(KnownZero2, KnownOne2);
237 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
238 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
240 // Compute known bits of the carry.
241 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
242 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
244 // Compute set of known bits (where all three relevant bits are known).
245 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
246 APInt RHSKnown = KnownZero2 | KnownOne2;
247 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
248 APInt Known = LHSKnown & RHSKnown & CarryKnown;
250 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
251 "known bits of sum differ");
253 // Compute known bits of the result.
254 KnownZero = ~PossibleSumOne & Known;
255 KnownOne = PossibleSumOne & Known;
257 // Are we still trying to solve for the sign bit?
258 if (!Known.isNegative()) {
260 // Adding two non-negative numbers, or subtracting a negative number from
261 // a non-negative one, can't wrap into negative.
262 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
263 KnownZero |= APInt::getSignBit(BitWidth);
264 // Adding two negative numbers, or subtracting a non-negative number from
265 // a negative one, can't wrap into non-negative.
266 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
267 KnownOne |= APInt::getSignBit(BitWidth);
272 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
273 APInt &KnownZero, APInt &KnownOne,
274 APInt &KnownZero2, APInt &KnownOne2,
275 const DataLayout &DL, unsigned Depth,
277 unsigned BitWidth = KnownZero.getBitWidth();
278 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
279 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
281 bool isKnownNegative = false;
282 bool isKnownNonNegative = false;
283 // If the multiplication is known not to overflow, compute the sign bit.
286 // The product of a number with itself is non-negative.
287 isKnownNonNegative = true;
289 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
290 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
291 bool isKnownNegativeOp1 = KnownOne.isNegative();
292 bool isKnownNegativeOp0 = KnownOne2.isNegative();
293 // The product of two numbers with the same sign is non-negative.
294 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
295 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
296 // The product of a negative number and a non-negative number is either
298 if (!isKnownNonNegative)
299 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
300 isKnownNonZero(Op0, DL, Depth, Q)) ||
301 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
302 isKnownNonZero(Op1, DL, Depth, Q));
306 // If low bits are zero in either operand, output low known-0 bits.
307 // Also compute a conserative estimate for high known-0 bits.
308 // More trickiness is possible, but this is sufficient for the
309 // interesting case of alignment computation.
310 KnownOne.clearAllBits();
311 unsigned TrailZ = KnownZero.countTrailingOnes() +
312 KnownZero2.countTrailingOnes();
313 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
314 KnownZero2.countLeadingOnes(),
315 BitWidth) - BitWidth;
317 TrailZ = std::min(TrailZ, BitWidth);
318 LeadZ = std::min(LeadZ, BitWidth);
319 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
320 APInt::getHighBitsSet(BitWidth, LeadZ);
322 // Only make use of no-wrap flags if we failed to compute the sign bit
323 // directly. This matters if the multiplication always overflows, in
324 // which case we prefer to follow the result of the direct computation,
325 // though as the program is invoking undefined behaviour we can choose
326 // whatever we like here.
327 if (isKnownNonNegative && !KnownOne.isNegative())
328 KnownZero.setBit(BitWidth - 1);
329 else if (isKnownNegative && !KnownZero.isNegative())
330 KnownOne.setBit(BitWidth - 1);
333 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
335 unsigned BitWidth = KnownZero.getBitWidth();
336 unsigned NumRanges = Ranges.getNumOperands() / 2;
337 assert(NumRanges >= 1);
339 // Use the high end of the ranges to find leading zeros.
340 unsigned MinLeadingZeros = BitWidth;
341 for (unsigned i = 0; i < NumRanges; ++i) {
343 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
345 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
346 ConstantRange Range(Lower->getValue(), Upper->getValue());
347 if (Range.isWrappedSet())
348 MinLeadingZeros = 0; // -1 has no zeros
349 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
350 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
353 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
356 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
357 SmallVector<const Value *, 16> WorkSet(1, I);
358 SmallPtrSet<const Value *, 32> Visited;
359 SmallPtrSet<const Value *, 16> EphValues;
361 while (!WorkSet.empty()) {
362 const Value *V = WorkSet.pop_back_val();
363 if (!Visited.insert(V).second)
366 // If all uses of this value are ephemeral, then so is this value.
367 bool FoundNEUse = false;
368 for (const User *I : V->users())
369 if (!EphValues.count(I)) {
379 if (const User *U = dyn_cast<User>(V))
380 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
382 if (isSafeToSpeculativelyExecute(*J))
383 WorkSet.push_back(*J);
391 // Is this an intrinsic that cannot be speculated but also cannot trap?
392 static bool isAssumeLikeIntrinsic(const Instruction *I) {
393 if (const CallInst *CI = dyn_cast<CallInst>(I))
394 if (Function *F = CI->getCalledFunction())
395 switch (F->getIntrinsicID()) {
397 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
398 case Intrinsic::assume:
399 case Intrinsic::dbg_declare:
400 case Intrinsic::dbg_value:
401 case Intrinsic::invariant_start:
402 case Intrinsic::invariant_end:
403 case Intrinsic::lifetime_start:
404 case Intrinsic::lifetime_end:
405 case Intrinsic::objectsize:
406 case Intrinsic::ptr_annotation:
407 case Intrinsic::var_annotation:
414 static bool isValidAssumeForContext(Value *V, const Query &Q) {
415 Instruction *Inv = cast<Instruction>(V);
417 // There are two restrictions on the use of an assume:
418 // 1. The assume must dominate the context (or the control flow must
419 // reach the assume whenever it reaches the context).
420 // 2. The context must not be in the assume's set of ephemeral values
421 // (otherwise we will use the assume to prove that the condition
422 // feeding the assume is trivially true, thus causing the removal of
426 if (Q.DT->dominates(Inv, Q.CxtI)) {
428 } else if (Inv->getParent() == Q.CxtI->getParent()) {
429 // The context comes first, but they're both in the same block. Make sure
430 // there is nothing in between that might interrupt the control flow.
431 for (BasicBlock::const_iterator I =
432 std::next(BasicBlock::const_iterator(Q.CxtI)),
433 IE(Inv); I != IE; ++I)
434 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
437 return !isEphemeralValueOf(Inv, Q.CxtI);
443 // When we don't have a DT, we do a limited search...
444 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
446 } else if (Inv->getParent() == Q.CxtI->getParent()) {
447 // Search forward from the assume until we reach the context (or the end
448 // of the block); the common case is that the assume will come first.
449 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
450 IE = Inv->getParent()->end(); I != IE; ++I)
454 // The context must come first...
455 for (BasicBlock::const_iterator I =
456 std::next(BasicBlock::const_iterator(Q.CxtI)),
457 IE(Inv); I != IE; ++I)
458 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
461 return !isEphemeralValueOf(Inv, Q.CxtI);
467 bool llvm::isValidAssumeForContext(const Instruction *I,
468 const Instruction *CxtI,
469 const DominatorTree *DT) {
470 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
471 Query(nullptr, CxtI, DT));
474 template<typename LHS, typename RHS>
475 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
476 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
477 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
478 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
481 template<typename LHS, typename RHS>
482 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
483 BinaryOp_match<RHS, LHS, Instruction::And>>
484 m_c_And(const LHS &L, const RHS &R) {
485 return m_CombineOr(m_And(L, R), m_And(R, L));
488 template<typename LHS, typename RHS>
489 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
490 BinaryOp_match<RHS, LHS, Instruction::Or>>
491 m_c_Or(const LHS &L, const RHS &R) {
492 return m_CombineOr(m_Or(L, R), m_Or(R, L));
495 template<typename LHS, typename RHS>
496 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
497 BinaryOp_match<RHS, LHS, Instruction::Xor>>
498 m_c_Xor(const LHS &L, const RHS &R) {
499 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
502 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
503 /// true (at the context instruction.) This is mostly a utility function for
504 /// the prototype dominating conditions reasoning below.
505 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
508 const DataLayout &DL,
509 unsigned Depth, const Query &Q) {
510 Value *LHS = Cmp->getOperand(0);
511 Value *RHS = Cmp->getOperand(1);
512 // TODO: We could potentially be more aggressive here. This would be worth
513 // evaluating. If we can, explore commoning this code with the assume
515 if (LHS != V && RHS != V)
518 const unsigned BitWidth = KnownZero.getBitWidth();
520 switch (Cmp->getPredicate()) {
522 // We know nothing from this condition
524 // TODO: implement unsigned bound from below (known one bits)
525 // TODO: common condition check implementations with assumes
526 // TODO: implement other patterns from assume (e.g. V & B == A)
527 case ICmpInst::ICMP_SGT:
529 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
530 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
531 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
532 // We know that the sign bit is zero.
533 KnownZero |= APInt::getSignBit(BitWidth);
537 case ICmpInst::ICMP_EQ:
539 computeKnownBits(RHS, KnownZero, KnownOne, DL, Depth + 1, Q);
541 computeKnownBits(LHS, KnownZero, KnownOne, DL, Depth + 1, Q);
543 llvm_unreachable("missing use?");
545 case ICmpInst::ICMP_ULE:
547 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
548 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
549 // The known zero bits carry over
550 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
551 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
554 case ICmpInst::ICMP_ULT:
556 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
557 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
558 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
559 // power of 2, then one more).
560 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
561 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
563 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
569 /// Compute known bits in 'V' from conditions which are known to be true along
570 /// all paths leading to the context instruction. In particular, look for
571 /// cases where one branch of an interesting condition dominates the context
572 /// instruction. This does not do general dataflow.
573 /// NOTE: This code is EXPERIMENTAL and currently off by default.
574 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
576 const DataLayout &DL,
579 // Need both the dominator tree and the query location to do anything useful
580 if (!Q.DT || !Q.CxtI)
582 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
584 // Avoid useless work
585 if (auto VI = dyn_cast<Instruction>(V))
586 if (VI->getParent() == Cxt->getParent())
589 // Note: We currently implement two options. It's not clear which of these
590 // will survive long term, we need data for that.
591 // Option 1 - Try walking the dominator tree looking for conditions which
592 // might apply. This works well for local conditions (loop guards, etc..),
593 // but not as well for things far from the context instruction (presuming a
594 // low max blocks explored). If we can set an high enough limit, this would
596 // Option 2 - We restrict out search to those conditions which are uses of
597 // the value we're interested in. This is independent of dom structure,
598 // but is slightly less powerful without looking through lots of use chains.
599 // It does handle conditions far from the context instruction (e.g. early
600 // function exits on entry) really well though.
602 // Option 1 - Search the dom tree
603 unsigned NumBlocksExplored = 0;
604 BasicBlock *Current = Cxt->getParent();
606 // Stop searching if we've gone too far up the chain
607 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
611 if (!Q.DT->getNode(Current)->getIDom())
613 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
615 // found function entry
618 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
619 if (!BI || BI->isUnconditional())
621 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
625 // We're looking for conditions that are guaranteed to hold at the context
626 // instruction. Finding a condition where one path dominates the context
627 // isn't enough because both the true and false cases could merge before
628 // the context instruction we're actually interested in. Instead, we need
629 // to ensure that the taken *edge* dominates the context instruction.
630 BasicBlock *BB0 = BI->getSuccessor(0);
631 BasicBlockEdge Edge(BI->getParent(), BB0);
632 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
635 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
639 // Option 2 - Search the other uses of V
640 unsigned NumUsesExplored = 0;
641 for (auto U : V->users()) {
642 // Avoid massive lists
643 if (NumUsesExplored >= DomConditionsMaxUses)
646 // Consider only compare instructions uniquely controlling a branch
647 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
651 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
654 for (auto *CmpU : Cmp->users()) {
655 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
656 if (!BI || BI->isUnconditional())
658 // We're looking for conditions that are guaranteed to hold at the
659 // context instruction. Finding a condition where one path dominates
660 // the context isn't enough because both the true and false cases could
661 // merge before the context instruction we're actually interested in.
662 // Instead, we need to ensure that the taken *edge* dominates the context
664 BasicBlock *BB0 = BI->getSuccessor(0);
665 BasicBlockEdge Edge(BI->getParent(), BB0);
666 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
669 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
675 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
676 APInt &KnownOne, const DataLayout &DL,
677 unsigned Depth, const Query &Q) {
678 // Use of assumptions is context-sensitive. If we don't have a context, we
680 if (!Q.AC || !Q.CxtI)
683 unsigned BitWidth = KnownZero.getBitWidth();
685 for (auto &AssumeVH : Q.AC->assumptions()) {
688 CallInst *I = cast<CallInst>(AssumeVH);
689 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
690 "Got assumption for the wrong function!");
691 if (Q.ExclInvs.count(I))
694 // Warning: This loop can end up being somewhat performance sensetive.
695 // We're running this loop for once for each value queried resulting in a
696 // runtime of ~O(#assumes * #values).
698 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
699 "must be an assume intrinsic");
701 Value *Arg = I->getArgOperand(0);
703 if (Arg == V && isValidAssumeForContext(I, Q)) {
704 assert(BitWidth == 1 && "assume operand is not i1?");
705 KnownZero.clearAllBits();
706 KnownOne.setAllBits();
710 // The remaining tests are all recursive, so bail out if we hit the limit.
711 if (Depth == MaxDepth)
715 auto m_V = m_CombineOr(m_Specific(V),
716 m_CombineOr(m_PtrToInt(m_Specific(V)),
717 m_BitCast(m_Specific(V))));
719 CmpInst::Predicate Pred;
722 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
723 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
724 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
725 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
726 KnownZero |= RHSKnownZero;
727 KnownOne |= RHSKnownOne;
729 } else if (match(Arg,
730 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
731 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
732 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
733 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
734 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
735 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
737 // For those bits in the mask that are known to be one, we can propagate
738 // known bits from the RHS to V.
739 KnownZero |= RHSKnownZero & MaskKnownOne;
740 KnownOne |= RHSKnownOne & MaskKnownOne;
741 // assume(~(v & b) = a)
742 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
744 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
745 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
746 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
747 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
748 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
750 // For those bits in the mask that are known to be one, we can propagate
751 // inverted known bits from the RHS to V.
752 KnownZero |= RHSKnownOne & MaskKnownOne;
753 KnownOne |= RHSKnownZero & MaskKnownOne;
755 } else if (match(Arg,
756 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
757 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
758 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
759 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
760 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
761 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
763 // For those bits in B that are known to be zero, we can propagate known
764 // bits from the RHS to V.
765 KnownZero |= RHSKnownZero & BKnownZero;
766 KnownOne |= RHSKnownOne & BKnownZero;
767 // assume(~(v | b) = a)
768 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
770 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
771 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
772 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
773 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
774 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
776 // For those bits in B that are known to be zero, we can propagate
777 // inverted known bits from the RHS to V.
778 KnownZero |= RHSKnownOne & BKnownZero;
779 KnownOne |= RHSKnownZero & BKnownZero;
781 } else if (match(Arg,
782 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
783 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
784 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
785 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
786 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
787 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
789 // For those bits in B that are known to be zero, we can propagate known
790 // bits from the RHS to V. For those bits in B that are known to be one,
791 // we can propagate inverted known bits from the RHS to V.
792 KnownZero |= RHSKnownZero & BKnownZero;
793 KnownOne |= RHSKnownOne & BKnownZero;
794 KnownZero |= RHSKnownOne & BKnownOne;
795 KnownOne |= RHSKnownZero & BKnownOne;
796 // assume(~(v ^ b) = a)
797 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
799 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
800 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
801 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
802 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
803 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
805 // For those bits in B that are known to be zero, we can propagate
806 // inverted known bits from the RHS to V. For those bits in B that are
807 // known to be one, we can propagate known bits from the RHS to V.
808 KnownZero |= RHSKnownOne & BKnownZero;
809 KnownOne |= RHSKnownZero & BKnownZero;
810 KnownZero |= RHSKnownZero & BKnownOne;
811 KnownOne |= RHSKnownOne & BKnownOne;
812 // assume(v << c = a)
813 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
815 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
816 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
817 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
818 // For those bits in RHS that are known, we can propagate them to known
819 // bits in V shifted to the right by C.
820 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
821 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
822 // assume(~(v << c) = a)
823 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
825 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
826 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
827 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
828 // For those bits in RHS that are known, we can propagate them inverted
829 // to known bits in V shifted to the right by C.
830 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
831 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
832 // assume(v >> c = a)
833 } else if (match(Arg,
834 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
835 m_AShr(m_V, m_ConstantInt(C))),
837 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
838 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
839 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
840 // For those bits in RHS that are known, we can propagate them to known
841 // bits in V shifted to the right by C.
842 KnownZero |= RHSKnownZero << C->getZExtValue();
843 KnownOne |= RHSKnownOne << C->getZExtValue();
844 // assume(~(v >> c) = a)
845 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
846 m_LShr(m_V, m_ConstantInt(C)),
847 m_AShr(m_V, m_ConstantInt(C)))),
849 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
850 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
851 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
852 // For those bits in RHS that are known, we can propagate them inverted
853 // to known bits in V shifted to the right by C.
854 KnownZero |= RHSKnownOne << C->getZExtValue();
855 KnownOne |= RHSKnownZero << C->getZExtValue();
856 // assume(v >=_s c) where c is non-negative
857 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
858 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
859 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
860 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
862 if (RHSKnownZero.isNegative()) {
863 // We know that the sign bit is zero.
864 KnownZero |= APInt::getSignBit(BitWidth);
866 // assume(v >_s c) where c is at least -1.
867 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
868 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
869 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
870 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
872 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
873 // We know that the sign bit is zero.
874 KnownZero |= APInt::getSignBit(BitWidth);
876 // assume(v <=_s c) where c is negative
877 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
878 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
879 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
880 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
882 if (RHSKnownOne.isNegative()) {
883 // We know that the sign bit is one.
884 KnownOne |= APInt::getSignBit(BitWidth);
886 // assume(v <_s c) where c is non-positive
887 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
888 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
889 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
890 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
892 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
893 // We know that the sign bit is one.
894 KnownOne |= APInt::getSignBit(BitWidth);
897 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
898 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
899 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
900 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
902 // Whatever high bits in c are zero are known to be zero.
904 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
906 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
907 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
908 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
909 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
911 // Whatever high bits in c are zero are known to be zero (if c is a power
912 // of 2, then one more).
913 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
915 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
918 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
923 /// Determine which bits of V are known to be either zero or one and return
924 /// them in the KnownZero/KnownOne bit sets.
926 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
927 /// we cannot optimize based on the assumption that it is zero without changing
928 /// it to be an explicit zero. If we don't change it to zero, other code could
929 /// optimized based on the contradictory assumption that it is non-zero.
930 /// Because instcombine aggressively folds operations with undef args anyway,
931 /// this won't lose us code quality.
933 /// This function is defined on values with integer type, values with pointer
934 /// type, and vectors of integers. In the case
935 /// where V is a vector, known zero, and known one values are the
936 /// same width as the vector element, and the bit is set only if it is true
937 /// for all of the elements in the vector.
938 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
939 const DataLayout &DL, unsigned Depth, const Query &Q) {
940 assert(V && "No Value?");
941 assert(Depth <= MaxDepth && "Limit Search Depth");
942 unsigned BitWidth = KnownZero.getBitWidth();
944 assert((V->getType()->isIntOrIntVectorTy() ||
945 V->getType()->getScalarType()->isPointerTy()) &&
946 "Not integer or pointer type!");
947 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
948 (!V->getType()->isIntOrIntVectorTy() ||
949 V->getType()->getScalarSizeInBits() == BitWidth) &&
950 KnownZero.getBitWidth() == BitWidth &&
951 KnownOne.getBitWidth() == BitWidth &&
952 "V, KnownOne and KnownZero should have same BitWidth");
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
955 // We know all of the bits for a constant!
956 KnownOne = CI->getValue();
957 KnownZero = ~KnownOne;
960 // Null and aggregate-zero are all-zeros.
961 if (isa<ConstantPointerNull>(V) ||
962 isa<ConstantAggregateZero>(V)) {
963 KnownOne.clearAllBits();
964 KnownZero = APInt::getAllOnesValue(BitWidth);
967 // Handle a constant vector by taking the intersection of the known bits of
968 // each element. There is no real need to handle ConstantVector here, because
969 // we don't handle undef in any particularly useful way.
970 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
971 // We know that CDS must be a vector of integers. Take the intersection of
973 KnownZero.setAllBits(); KnownOne.setAllBits();
974 APInt Elt(KnownZero.getBitWidth(), 0);
975 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
976 Elt = CDS->getElementAsInteger(i);
983 // The address of an aligned GlobalValue has trailing zeros.
984 if (auto *GO = dyn_cast<GlobalObject>(V)) {
985 unsigned Align = GO->getAlignment();
987 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
988 Type *ObjectType = GVar->getType()->getElementType();
989 if (ObjectType->isSized()) {
990 // If the object is defined in the current Module, we'll be giving
991 // it the preferred alignment. Otherwise, we have to assume that it
992 // may only have the minimum ABI alignment.
993 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
994 Align = DL.getPreferredAlignment(GVar);
996 Align = DL.getABITypeAlignment(ObjectType);
1001 KnownZero = APInt::getLowBitsSet(BitWidth,
1002 countTrailingZeros(Align));
1004 KnownZero.clearAllBits();
1005 KnownOne.clearAllBits();
1009 if (Argument *A = dyn_cast<Argument>(V)) {
1010 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
1012 if (!Align && A->hasStructRetAttr()) {
1013 // An sret parameter has at least the ABI alignment of the return type.
1014 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1015 if (EltTy->isSized())
1016 Align = DL.getABITypeAlignment(EltTy);
1020 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1022 KnownZero.clearAllBits();
1023 KnownOne.clearAllBits();
1025 // Don't give up yet... there might be an assumption that provides more
1027 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1029 // Or a dominating condition for that matter
1030 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1031 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
1036 // Start out not knowing anything.
1037 KnownZero.clearAllBits(); KnownOne.clearAllBits();
1039 // Limit search depth.
1040 // All recursive calls that increase depth must come after this.
1041 if (Depth == MaxDepth)
1044 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1045 // the bits of its aliasee.
1046 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1047 if (!GA->mayBeOverridden())
1048 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
1052 // Check whether a nearby assume intrinsic can determine some known bits.
1053 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
1055 // Check whether there's a dominating condition which implies something about
1056 // this value at the given context.
1057 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1058 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1061 Operator *I = dyn_cast<Operator>(V);
1064 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
1065 switch (I->getOpcode()) {
1067 case Instruction::Load:
1068 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
1069 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1071 case Instruction::And: {
1072 // If either the LHS or the RHS are Zero, the result is zero.
1073 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1074 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1076 // Output known-1 bits are only known if set in both the LHS & RHS.
1077 KnownOne &= KnownOne2;
1078 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1079 KnownZero |= KnownZero2;
1082 case Instruction::Or: {
1083 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1084 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1086 // Output known-0 bits are only known if clear in both the LHS & RHS.
1087 KnownZero &= KnownZero2;
1088 // Output known-1 are known to be set if set in either the LHS | RHS.
1089 KnownOne |= KnownOne2;
1092 case Instruction::Xor: {
1093 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1094 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1096 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1097 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1098 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1099 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1100 KnownZero = KnownZeroOut;
1103 case Instruction::Mul: {
1104 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1105 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1106 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1109 case Instruction::UDiv: {
1110 // For the purposes of computing leading zeros we can conservatively
1111 // treat a udiv as a logical right shift by the power of 2 known to
1112 // be less than the denominator.
1113 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1114 unsigned LeadZ = KnownZero2.countLeadingOnes();
1116 KnownOne2.clearAllBits();
1117 KnownZero2.clearAllBits();
1118 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1119 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1120 if (RHSUnknownLeadingOnes != BitWidth)
1121 LeadZ = std::min(BitWidth,
1122 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1124 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1127 case Instruction::Select:
1128 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1129 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1131 // Only known if known in both the LHS and RHS.
1132 KnownOne &= KnownOne2;
1133 KnownZero &= KnownZero2;
1135 case Instruction::FPTrunc:
1136 case Instruction::FPExt:
1137 case Instruction::FPToUI:
1138 case Instruction::FPToSI:
1139 case Instruction::SIToFP:
1140 case Instruction::UIToFP:
1141 break; // Can't work with floating point.
1142 case Instruction::PtrToInt:
1143 case Instruction::IntToPtr:
1144 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
1145 // FALL THROUGH and handle them the same as zext/trunc.
1146 case Instruction::ZExt:
1147 case Instruction::Trunc: {
1148 Type *SrcTy = I->getOperand(0)->getType();
1150 unsigned SrcBitWidth;
1151 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1152 // which fall through here.
1153 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
1155 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1156 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1157 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1158 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1159 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1160 KnownOne = KnownOne.zextOrTrunc(BitWidth);
1161 // Any top bits are known to be zero.
1162 if (BitWidth > SrcBitWidth)
1163 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1166 case Instruction::BitCast: {
1167 Type *SrcTy = I->getOperand(0)->getType();
1168 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
1169 // TODO: For now, not handling conversions like:
1170 // (bitcast i64 %x to <2 x i32>)
1171 !I->getType()->isVectorTy()) {
1172 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1177 case Instruction::SExt: {
1178 // Compute the bits in the result that are not present in the input.
1179 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1181 KnownZero = KnownZero.trunc(SrcBitWidth);
1182 KnownOne = KnownOne.trunc(SrcBitWidth);
1183 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1184 KnownZero = KnownZero.zext(BitWidth);
1185 KnownOne = KnownOne.zext(BitWidth);
1187 // If the sign bit of the input is known set or clear, then we know the
1188 // top bits of the result.
1189 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1190 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1191 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1192 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1195 case Instruction::Shl:
1196 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1197 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1198 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1199 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1200 KnownZero <<= ShiftAmt;
1201 KnownOne <<= ShiftAmt;
1202 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
1205 case Instruction::LShr:
1206 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1207 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1208 // Compute the new bits that are at the top now.
1209 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1211 // Unsigned shift right.
1212 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1213 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1214 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1215 // high bits known zero.
1216 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
1219 case Instruction::AShr:
1220 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1221 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1222 // Compute the new bits that are at the top now.
1223 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
1225 // Signed shift right.
1226 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1227 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1228 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1232 KnownZero |= HighBits;
1233 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1234 KnownOne |= HighBits;
1237 case Instruction::Sub: {
1238 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1239 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1240 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1244 case Instruction::Add: {
1245 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1246 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1247 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1251 case Instruction::SRem:
1252 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1253 APInt RA = Rem->getValue().abs();
1254 if (RA.isPowerOf2()) {
1255 APInt LowBits = RA - 1;
1256 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1259 // The low bits of the first operand are unchanged by the srem.
1260 KnownZero = KnownZero2 & LowBits;
1261 KnownOne = KnownOne2 & LowBits;
1263 // If the first operand is non-negative or has all low bits zero, then
1264 // the upper bits are all zero.
1265 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1266 KnownZero |= ~LowBits;
1268 // If the first operand is negative and not all low bits are zero, then
1269 // the upper bits are all one.
1270 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1271 KnownOne |= ~LowBits;
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1277 // The sign bit is the LHS's sign bit, except when the result of the
1278 // remainder is zero.
1279 if (KnownZero.isNonNegative()) {
1280 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1281 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1283 // If it's known zero, our sign bit is also zero.
1284 if (LHSKnownZero.isNegative())
1285 KnownZero.setBit(BitWidth - 1);
1289 case Instruction::URem: {
1290 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1291 APInt RA = Rem->getValue();
1292 if (RA.isPowerOf2()) {
1293 APInt LowBits = (RA - 1);
1294 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1296 KnownZero |= ~LowBits;
1297 KnownOne &= LowBits;
1302 // Since the result is less than or equal to either operand, any leading
1303 // zero bits in either operand must also exist in the result.
1304 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1305 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
1307 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1308 KnownZero2.countLeadingOnes());
1309 KnownOne.clearAllBits();
1310 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1314 case Instruction::Alloca: {
1315 AllocaInst *AI = cast<AllocaInst>(V);
1316 unsigned Align = AI->getAlignment();
1318 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
1321 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1324 case Instruction::GetElementPtr: {
1325 // Analyze all of the subscripts of this getelementptr instruction
1326 // to determine if we can prove known low zero bits.
1327 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1328 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1330 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1332 gep_type_iterator GTI = gep_type_begin(I);
1333 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1334 Value *Index = I->getOperand(i);
1335 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1336 // Handle struct member offset arithmetic.
1338 // Handle case when index is vector zeroinitializer
1339 Constant *CIndex = cast<Constant>(Index);
1340 if (CIndex->isZeroValue())
1343 if (CIndex->getType()->isVectorTy())
1344 Index = CIndex->getSplatValue();
1346 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1347 const StructLayout *SL = DL.getStructLayout(STy);
1348 uint64_t Offset = SL->getElementOffset(Idx);
1349 TrailZ = std::min<unsigned>(TrailZ,
1350 countTrailingZeros(Offset));
1352 // Handle array index arithmetic.
1353 Type *IndexedTy = GTI.getIndexedType();
1354 if (!IndexedTy->isSized()) {
1358 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1359 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
1360 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1361 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1363 TrailZ = std::min(TrailZ,
1364 unsigned(countTrailingZeros(TypeSize) +
1365 LocalKnownZero.countTrailingOnes()));
1369 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1372 case Instruction::PHI: {
1373 PHINode *P = cast<PHINode>(I);
1374 // Handle the case of a simple two-predecessor recurrence PHI.
1375 // There's a lot more that could theoretically be done here, but
1376 // this is sufficient to catch some interesting cases.
1377 if (P->getNumIncomingValues() == 2) {
1378 for (unsigned i = 0; i != 2; ++i) {
1379 Value *L = P->getIncomingValue(i);
1380 Value *R = P->getIncomingValue(!i);
1381 Operator *LU = dyn_cast<Operator>(L);
1384 unsigned Opcode = LU->getOpcode();
1385 // Check for operations that have the property that if
1386 // both their operands have low zero bits, the result
1387 // will have low zero bits.
1388 if (Opcode == Instruction::Add ||
1389 Opcode == Instruction::Sub ||
1390 Opcode == Instruction::And ||
1391 Opcode == Instruction::Or ||
1392 Opcode == Instruction::Mul) {
1393 Value *LL = LU->getOperand(0);
1394 Value *LR = LU->getOperand(1);
1395 // Find a recurrence.
1402 // Ok, we have a PHI of the form L op= R. Check for low
1404 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
1406 // We need to take the minimum number of known bits
1407 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1408 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
1410 KnownZero = APInt::getLowBitsSet(BitWidth,
1411 std::min(KnownZero2.countTrailingOnes(),
1412 KnownZero3.countTrailingOnes()));
1418 // Unreachable blocks may have zero-operand PHI nodes.
1419 if (P->getNumIncomingValues() == 0)
1422 // Otherwise take the unions of the known bit sets of the operands,
1423 // taking conservative care to avoid excessive recursion.
1424 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1425 // Skip if every incoming value references to ourself.
1426 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1429 KnownZero = APInt::getAllOnesValue(BitWidth);
1430 KnownOne = APInt::getAllOnesValue(BitWidth);
1431 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1432 // Skip direct self references.
1433 if (P->getIncomingValue(i) == P) continue;
1435 KnownZero2 = APInt(BitWidth, 0);
1436 KnownOne2 = APInt(BitWidth, 0);
1437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
1439 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, DL,
1441 KnownZero &= KnownZero2;
1442 KnownOne &= KnownOne2;
1443 // If all bits have been ruled out, there's no need to check
1445 if (!KnownZero && !KnownOne)
1451 case Instruction::Call:
1452 case Instruction::Invoke:
1453 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1454 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1455 // If a range metadata is attached to this IntrinsicInst, intersect the
1456 // explicit range specified by the metadata and the implicit range of
1458 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1459 switch (II->getIntrinsicID()) {
1461 case Intrinsic::ctlz:
1462 case Intrinsic::cttz: {
1463 unsigned LowBits = Log2_32(BitWidth)+1;
1464 // If this call is undefined for 0, the result will be less than 2^n.
1465 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1467 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1470 case Intrinsic::ctpop: {
1471 unsigned LowBits = Log2_32(BitWidth)+1;
1472 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1475 case Intrinsic::x86_sse42_crc32_64_64:
1476 KnownZero |= APInt::getHighBitsSet(64, 32);
1481 case Instruction::ExtractValue:
1482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1483 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1484 if (EVI->getNumIndices() != 1) break;
1485 if (EVI->getIndices()[0] == 0) {
1486 switch (II->getIntrinsicID()) {
1488 case Intrinsic::uadd_with_overflow:
1489 case Intrinsic::sadd_with_overflow:
1490 computeKnownBitsAddSub(true, II->getArgOperand(0),
1491 II->getArgOperand(1), false, KnownZero,
1492 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1494 case Intrinsic::usub_with_overflow:
1495 case Intrinsic::ssub_with_overflow:
1496 computeKnownBitsAddSub(false, II->getArgOperand(0),
1497 II->getArgOperand(1), false, KnownZero,
1498 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
1500 case Intrinsic::umul_with_overflow:
1501 case Intrinsic::smul_with_overflow:
1502 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1503 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1511 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1514 /// Determine whether the sign bit is known to be zero or one.
1515 /// Convenience wrapper around computeKnownBits.
1516 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
1517 const DataLayout &DL, unsigned Depth, const Query &Q) {
1518 unsigned BitWidth = getBitWidth(V->getType(), DL);
1524 APInt ZeroBits(BitWidth, 0);
1525 APInt OneBits(BitWidth, 0);
1526 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
1527 KnownOne = OneBits[BitWidth - 1];
1528 KnownZero = ZeroBits[BitWidth - 1];
1531 /// Return true if the given value is known to have exactly one
1532 /// bit set when defined. For vectors return true if every element is known to
1533 /// be a power of two when defined. Supports values with integer or pointer
1534 /// types and vectors of integers.
1535 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
1536 const Query &Q, const DataLayout &DL) {
1537 if (Constant *C = dyn_cast<Constant>(V)) {
1538 if (C->isNullValue())
1540 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541 return CI->getValue().isPowerOf2();
1542 // TODO: Handle vector constants.
1545 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1546 // it is shifted off the end then the result is undefined.
1547 if (match(V, m_Shl(m_One(), m_Value())))
1550 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1551 // bottom. If it is shifted off the bottom then the result is undefined.
1552 if (match(V, m_LShr(m_SignBit(), m_Value())))
1555 // The remaining tests are all recursive, so bail out if we hit the limit.
1556 if (Depth++ == MaxDepth)
1559 Value *X = nullptr, *Y = nullptr;
1560 // A shift of a power of two is a power of two or zero.
1561 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1562 match(V, m_Shr(m_Value(X), m_Value()))))
1563 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
1565 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1566 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
1568 if (SelectInst *SI = dyn_cast<SelectInst>(V))
1569 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1570 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
1572 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1573 // A power of two and'd with anything is a power of two or zero.
1574 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1575 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
1577 // X & (-X) is always a power of two or zero.
1578 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1583 // Adding a power-of-two or zero to the same power-of-two or zero yields
1584 // either the original power-of-two, a larger power-of-two or zero.
1585 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1586 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1587 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1588 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1589 match(X, m_And(m_Value(), m_Specific(Y))))
1590 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
1592 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1593 match(Y, m_And(m_Value(), m_Specific(X))))
1594 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
1597 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1598 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1599 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
1601 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1602 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
1603 // If i8 V is a power of two or zero:
1604 // ZeroBits: 1 1 1 0 1 1 1 1
1605 // ~ZeroBits: 0 0 0 1 0 0 0 0
1606 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1607 // If OrZero isn't set, we cannot give back a zero result.
1608 // Make sure either the LHS or RHS has a bit set.
1609 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1614 // An exact divide or right shift can only shift off zero bits, so the result
1615 // is a power of two only if the first operand is a power of two and not
1616 // copying a sign bit (sdiv int_min, 2).
1617 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1618 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1619 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1626 /// \brief Test whether a GEP's result is known to be non-null.
1628 /// Uses properties inherent in a GEP to try to determine whether it is known
1631 /// Currently this routine does not support vector GEPs.
1632 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
1633 unsigned Depth, const Query &Q) {
1634 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1637 // FIXME: Support vector-GEPs.
1638 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1640 // If the base pointer is non-null, we cannot walk to a null address with an
1641 // inbounds GEP in address space zero.
1642 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
1645 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1646 // If so, then the GEP cannot produce a null pointer, as doing so would
1647 // inherently violate the inbounds contract within address space zero.
1648 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1649 GTI != GTE; ++GTI) {
1650 // Struct types are easy -- they must always be indexed by a constant.
1651 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1652 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1653 unsigned ElementIdx = OpC->getZExtValue();
1654 const StructLayout *SL = DL.getStructLayout(STy);
1655 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1656 if (ElementOffset > 0)
1661 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1662 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1665 // Fast path the constant operand case both for efficiency and so we don't
1666 // increment Depth when just zipping down an all-constant GEP.
1667 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1673 // We post-increment Depth here because while isKnownNonZero increments it
1674 // as well, when we pop back up that increment won't persist. We don't want
1675 // to recurse 10k times just because we have 10k GEP operands. We don't
1676 // bail completely out because we want to handle constant GEPs regardless
1678 if (Depth++ >= MaxDepth)
1681 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
1688 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1689 /// ensure that the value it's attached to is never Value? 'RangeType' is
1690 /// is the type of the value described by the range.
1691 static bool rangeMetadataExcludesValue(MDNode* Ranges,
1692 const APInt& Value) {
1693 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1694 assert(NumRanges >= 1);
1695 for (unsigned i = 0; i < NumRanges; ++i) {
1696 ConstantInt *Lower =
1697 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1698 ConstantInt *Upper =
1699 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1700 ConstantRange Range(Lower->getValue(), Upper->getValue());
1701 if (Range.contains(Value))
1707 /// Return true if the given value is known to be non-zero when defined.
1708 /// For vectors return true if every element is known to be non-zero when
1709 /// defined. Supports values with integer or pointer type and vectors of
1711 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
1713 if (Constant *C = dyn_cast<Constant>(V)) {
1714 if (C->isNullValue())
1716 if (isa<ConstantInt>(C))
1717 // Must be non-zero due to null test above.
1719 // TODO: Handle vectors
1723 if (Instruction* I = dyn_cast<Instruction>(V)) {
1724 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1725 // If the possible ranges don't contain zero, then the value is
1726 // definitely non-zero.
1727 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1728 const APInt ZeroValue(Ty->getBitWidth(), 0);
1729 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1735 // The remaining tests are all recursive, so bail out if we hit the limit.
1736 if (Depth++ >= MaxDepth)
1739 // Check for pointer simplifications.
1740 if (V->getType()->isPointerTy()) {
1741 if (isKnownNonNull(V))
1743 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1744 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
1748 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
1750 // X | Y != 0 if X != 0 or Y != 0.
1751 Value *X = nullptr, *Y = nullptr;
1752 if (match(V, m_Or(m_Value(X), m_Value(Y))))
1753 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
1755 // ext X != 0 if X != 0.
1756 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1757 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
1759 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
1760 // if the lowest bit is shifted off the end.
1761 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1762 // shl nuw can't remove any non-zero bits.
1763 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1764 if (BO->hasNoUnsignedWrap())
1765 return isKnownNonZero(X, DL, Depth, Q);
1767 APInt KnownZero(BitWidth, 0);
1768 APInt KnownOne(BitWidth, 0);
1769 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1773 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
1774 // defined if the sign bit is shifted off the end.
1775 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1776 // shr exact can only shift out zero bits.
1777 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1779 return isKnownNonZero(X, DL, Depth, Q);
1781 bool XKnownNonNegative, XKnownNegative;
1782 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1786 // div exact can only produce a zero if the dividend is zero.
1787 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1788 return isKnownNonZero(X, DL, Depth, Q);
1791 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1792 bool XKnownNonNegative, XKnownNegative;
1793 bool YKnownNonNegative, YKnownNegative;
1794 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1795 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
1797 // If X and Y are both non-negative (as signed values) then their sum is not
1798 // zero unless both X and Y are zero.
1799 if (XKnownNonNegative && YKnownNonNegative)
1800 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
1803 // If X and Y are both negative (as signed values) then their sum is not
1804 // zero unless both X and Y equal INT_MIN.
1805 if (BitWidth && XKnownNegative && YKnownNegative) {
1806 APInt KnownZero(BitWidth, 0);
1807 APInt KnownOne(BitWidth, 0);
1808 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1809 // The sign bit of X is set. If some other bit is set then X is not equal
1811 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
1812 if ((KnownOne & Mask) != 0)
1814 // The sign bit of Y is set. If some other bit is set then Y is not equal
1816 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
1817 if ((KnownOne & Mask) != 0)
1821 // The sum of a non-negative number and a power of two is not zero.
1822 if (XKnownNonNegative &&
1823 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
1825 if (YKnownNonNegative &&
1826 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
1830 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1831 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1832 // If X and Y are non-zero then so is X * Y as long as the multiplication
1833 // does not overflow.
1834 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1835 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
1838 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1839 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
1840 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1841 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
1845 if (!BitWidth) return false;
1846 APInt KnownZero(BitWidth, 0);
1847 APInt KnownOne(BitWidth, 0);
1848 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1849 return KnownOne != 0;
1852 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
1853 /// simplify operations downstream. Mask is known to be zero for bits that V
1856 /// This function is defined on values with integer type, values with pointer
1857 /// type, and vectors of integers. In the case
1858 /// where V is a vector, the mask, known zero, and known one values are the
1859 /// same width as the vector element, and the bit is set only if it is true
1860 /// for all of the elements in the vector.
1861 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1862 unsigned Depth, const Query &Q) {
1863 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1864 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
1865 return (KnownZero & Mask) == Mask;
1870 /// Return the number of times the sign bit of the register is replicated into
1871 /// the other bits. We know that at least 1 bit is always equal to the sign bit
1872 /// (itself), but other cases can give us information. For example, immediately
1873 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1874 /// other, so we return 3.
1876 /// 'Op' must have a scalar integer type.
1878 unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1880 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
1882 unsigned FirstAnswer = 1;
1884 // Note that ConstantInt is handled by the general computeKnownBits case
1888 return 1; // Limit search depth.
1890 Operator *U = dyn_cast<Operator>(V);
1891 switch (Operator::getOpcode(V)) {
1893 case Instruction::SExt:
1894 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
1895 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
1897 case Instruction::SDiv: {
1898 const APInt *Denominator;
1899 // sdiv X, C -> adds log(C) sign bits.
1900 if (match(U->getOperand(1), m_APInt(Denominator))) {
1902 // Ignore non-positive denominator.
1903 if (!Denominator->isStrictlyPositive())
1906 // Calculate the incoming numerator bits.
1907 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1909 // Add floor(log(C)) bits to the numerator bits.
1910 return std::min(TyBits, NumBits + Denominator->logBase2());
1915 case Instruction::SRem: {
1916 const APInt *Denominator;
1917 // srem X, C -> we know that the result is within [-C+1,C) when C is a
1918 // positive constant. This let us put a lower bound on the number of sign
1920 if (match(U->getOperand(1), m_APInt(Denominator))) {
1922 // Ignore non-positive denominator.
1923 if (!Denominator->isStrictlyPositive())
1926 // Calculate the incoming numerator bits. SRem by a positive constant
1927 // can't lower the number of sign bits.
1929 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1931 // Calculate the leading sign bit constraints by examining the
1932 // denominator. Given that the denominator is positive, there are two
1935 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
1936 // (1 << ceilLogBase2(C)).
1938 // 2. the numerator is negative. Then the result range is (-C,0] and
1939 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
1941 // Thus a lower bound on the number of sign bits is `TyBits -
1942 // ceilLogBase2(C)`.
1944 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
1945 return std::max(NumrBits, ResBits);
1950 case Instruction::AShr: {
1951 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1952 // ashr X, C -> adds C sign bits. Vectors too.
1954 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1955 Tmp += ShAmt->getZExtValue();
1956 if (Tmp > TyBits) Tmp = TyBits;
1960 case Instruction::Shl: {
1962 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1963 // shl destroys sign bits.
1964 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1965 Tmp2 = ShAmt->getZExtValue();
1966 if (Tmp2 >= TyBits || // Bad shift.
1967 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1972 case Instruction::And:
1973 case Instruction::Or:
1974 case Instruction::Xor: // NOT is handled here.
1975 // Logical binary ops preserve the number of sign bits at the worst.
1976 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1978 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
1979 FirstAnswer = std::min(Tmp, Tmp2);
1980 // We computed what we know about the sign bits as our first
1981 // answer. Now proceed to the generic code that uses
1982 // computeKnownBits, and pick whichever answer is better.
1986 case Instruction::Select:
1987 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
1988 if (Tmp == 1) return 1; // Early out.
1989 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
1990 return std::min(Tmp, Tmp2);
1992 case Instruction::Add:
1993 // Add can have at most one carry bit. Thus we know that the output
1994 // is, at worst, one more bit than the inputs.
1995 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
1996 if (Tmp == 1) return 1; // Early out.
1998 // Special case decrementing a value (ADD X, -1):
1999 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2000 if (CRHS->isAllOnesValue()) {
2001 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2002 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
2005 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2007 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2010 // If we are subtracting one from a positive number, there is no carry
2011 // out of the result.
2012 if (KnownZero.isNegative())
2016 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2017 if (Tmp2 == 1) return 1;
2018 return std::min(Tmp, Tmp2)-1;
2020 case Instruction::Sub:
2021 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
2022 if (Tmp2 == 1) return 1;
2025 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2026 if (CLHS->isNullValue()) {
2027 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2028 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2030 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2032 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2035 // If the input is known to be positive (the sign bit is known clear),
2036 // the output of the NEG has the same number of sign bits as the input.
2037 if (KnownZero.isNegative())
2040 // Otherwise, we treat this like a SUB.
2043 // Sub can have at most one carry bit. Thus we know that the output
2044 // is, at worst, one more bit than the inputs.
2045 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
2046 if (Tmp == 1) return 1; // Early out.
2047 return std::min(Tmp, Tmp2)-1;
2049 case Instruction::PHI: {
2050 PHINode *PN = cast<PHINode>(U);
2051 unsigned NumIncomingValues = PN->getNumIncomingValues();
2052 // Don't analyze large in-degree PHIs.
2053 if (NumIncomingValues > 4) break;
2054 // Unreachable blocks may have zero-operand PHI nodes.
2055 if (NumIncomingValues == 0) break;
2057 // Take the minimum of all incoming values. This can't infinitely loop
2058 // because of our depth threshold.
2059 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
2060 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2061 if (Tmp == 1) return Tmp;
2063 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
2068 case Instruction::Trunc:
2069 // FIXME: it's tricky to do anything useful for this, but it is an important
2070 // case for targets like X86.
2074 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2075 // use this information.
2076 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2078 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
2080 if (KnownZero.isNegative()) { // sign bit is 0
2082 } else if (KnownOne.isNegative()) { // sign bit is 1;
2089 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2090 // the number of identical bits in the top of the input value.
2092 Mask <<= Mask.getBitWidth()-TyBits;
2093 // Return # leading zeros. We use 'min' here in case Val was zero before
2094 // shifting. We don't want to return '64' as for an i32 "0".
2095 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2098 /// This function computes the integer multiple of Base that equals V.
2099 /// If successful, it returns true and returns the multiple in
2100 /// Multiple. If unsuccessful, it returns false. It looks
2101 /// through SExt instructions only if LookThroughSExt is true.
2102 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2103 bool LookThroughSExt, unsigned Depth) {
2104 const unsigned MaxDepth = 6;
2106 assert(V && "No Value?");
2107 assert(Depth <= MaxDepth && "Limit Search Depth");
2108 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2110 Type *T = V->getType();
2112 ConstantInt *CI = dyn_cast<ConstantInt>(V);
2122 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2123 Constant *BaseVal = ConstantInt::get(T, Base);
2124 if (CO && CO == BaseVal) {
2126 Multiple = ConstantInt::get(T, 1);
2130 if (CI && CI->getZExtValue() % Base == 0) {
2131 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2135 if (Depth == MaxDepth) return false; // Limit search depth.
2137 Operator *I = dyn_cast<Operator>(V);
2138 if (!I) return false;
2140 switch (I->getOpcode()) {
2142 case Instruction::SExt:
2143 if (!LookThroughSExt) return false;
2144 // otherwise fall through to ZExt
2145 case Instruction::ZExt:
2146 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2147 LookThroughSExt, Depth+1);
2148 case Instruction::Shl:
2149 case Instruction::Mul: {
2150 Value *Op0 = I->getOperand(0);
2151 Value *Op1 = I->getOperand(1);
2153 if (I->getOpcode() == Instruction::Shl) {
2154 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2155 if (!Op1CI) return false;
2156 // Turn Op0 << Op1 into Op0 * 2^Op1
2157 APInt Op1Int = Op1CI->getValue();
2158 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2159 APInt API(Op1Int.getBitWidth(), 0);
2160 API.setBit(BitToSet);
2161 Op1 = ConstantInt::get(V->getContext(), API);
2164 Value *Mul0 = nullptr;
2165 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2166 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2167 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2168 if (Op1C->getType()->getPrimitiveSizeInBits() <
2169 MulC->getType()->getPrimitiveSizeInBits())
2170 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2171 if (Op1C->getType()->getPrimitiveSizeInBits() >
2172 MulC->getType()->getPrimitiveSizeInBits())
2173 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2175 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2176 Multiple = ConstantExpr::getMul(MulC, Op1C);
2180 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2181 if (Mul0CI->getValue() == 1) {
2182 // V == Base * Op1, so return Op1
2188 Value *Mul1 = nullptr;
2189 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2190 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2191 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2192 if (Op0C->getType()->getPrimitiveSizeInBits() <
2193 MulC->getType()->getPrimitiveSizeInBits())
2194 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2195 if (Op0C->getType()->getPrimitiveSizeInBits() >
2196 MulC->getType()->getPrimitiveSizeInBits())
2197 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2199 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2200 Multiple = ConstantExpr::getMul(MulC, Op0C);
2204 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2205 if (Mul1CI->getValue() == 1) {
2206 // V == Base * Op0, so return Op0
2214 // We could not determine if V is a multiple of Base.
2218 /// Return true if we can prove that the specified FP value is never equal to
2221 /// NOTE: this function will need to be revisited when we support non-default
2224 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2225 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2226 return !CFP->getValueAPF().isNegZero();
2228 // FIXME: Magic number! At the least, this should be given a name because it's
2229 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2230 // expose it as a parameter, so it can be used for testing / experimenting.
2232 return false; // Limit search depth.
2234 const Operator *I = dyn_cast<Operator>(V);
2235 if (!I) return false;
2237 // Check if the nsz fast-math flag is set
2238 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2239 if (FPO->hasNoSignedZeros())
2242 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2243 if (I->getOpcode() == Instruction::FAdd)
2244 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2245 if (CFP->isNullValue())
2248 // sitofp and uitofp turn into +0.0 for zero.
2249 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2252 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2253 // sqrt(-0.0) = -0.0, no other negative results are possible.
2254 if (II->getIntrinsicID() == Intrinsic::sqrt)
2255 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
2257 if (const CallInst *CI = dyn_cast<CallInst>(I))
2258 if (const Function *F = CI->getCalledFunction()) {
2259 if (F->isDeclaration()) {
2261 if (F->getName() == "abs") return true;
2262 // fabs[lf](x) != -0.0
2263 if (F->getName() == "fabs") return true;
2264 if (F->getName() == "fabsf") return true;
2265 if (F->getName() == "fabsl") return true;
2266 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2267 F->getName() == "sqrtl")
2268 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
2275 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2276 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2277 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2279 // FIXME: Magic number! At the least, this should be given a name because it's
2280 // used similarly in CannotBeNegativeZero(). A better fix may be to
2281 // expose it as a parameter, so it can be used for testing / experimenting.
2283 return false; // Limit search depth.
2285 const Operator *I = dyn_cast<Operator>(V);
2286 if (!I) return false;
2288 switch (I->getOpcode()) {
2290 case Instruction::FMul:
2291 // x*x is always non-negative or a NaN.
2292 if (I->getOperand(0) == I->getOperand(1))
2295 case Instruction::FAdd:
2296 case Instruction::FDiv:
2297 case Instruction::FRem:
2298 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2299 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2300 case Instruction::FPExt:
2301 case Instruction::FPTrunc:
2302 // Widening/narrowing never change sign.
2303 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2304 case Instruction::Call:
2305 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2306 switch (II->getIntrinsicID()) {
2308 case Intrinsic::exp:
2309 case Intrinsic::exp2:
2310 case Intrinsic::fabs:
2311 case Intrinsic::sqrt:
2313 case Intrinsic::powi:
2314 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2315 // powi(x,n) is non-negative if n is even.
2316 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2319 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2320 case Intrinsic::fma:
2321 case Intrinsic::fmuladd:
2322 // x*x+y is non-negative if y is non-negative.
2323 return I->getOperand(0) == I->getOperand(1) &&
2324 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2331 /// If the specified value can be set by repeating the same byte in memory,
2332 /// return the i8 value that it is represented with. This is
2333 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2334 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2335 /// byte store (e.g. i16 0x1234), return null.
2336 Value *llvm::isBytewiseValue(Value *V) {
2337 // All byte-wide stores are splatable, even of arbitrary variables.
2338 if (V->getType()->isIntegerTy(8)) return V;
2340 // Handle 'null' ConstantArrayZero etc.
2341 if (Constant *C = dyn_cast<Constant>(V))
2342 if (C->isNullValue())
2343 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2345 // Constant float and double values can be handled as integer values if the
2346 // corresponding integer value is "byteable". An important case is 0.0.
2347 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2348 if (CFP->getType()->isFloatTy())
2349 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2350 if (CFP->getType()->isDoubleTy())
2351 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2352 // Don't handle long double formats, which have strange constraints.
2355 // We can handle constant integers that are multiple of 8 bits.
2356 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2357 if (CI->getBitWidth() % 8 == 0) {
2358 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2360 if (!CI->getValue().isSplat(8))
2362 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2366 // A ConstantDataArray/Vector is splatable if all its members are equal and
2368 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2369 Value *Elt = CA->getElementAsConstant(0);
2370 Value *Val = isBytewiseValue(Elt);
2374 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2375 if (CA->getElementAsConstant(I) != Elt)
2381 // Conceptually, we could handle things like:
2382 // %a = zext i8 %X to i16
2383 // %b = shl i16 %a, 8
2384 // %c = or i16 %a, %b
2385 // but until there is an example that actually needs this, it doesn't seem
2386 // worth worrying about.
2391 // This is the recursive version of BuildSubAggregate. It takes a few different
2392 // arguments. Idxs is the index within the nested struct From that we are
2393 // looking at now (which is of type IndexedType). IdxSkip is the number of
2394 // indices from Idxs that should be left out when inserting into the resulting
2395 // struct. To is the result struct built so far, new insertvalue instructions
2397 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2398 SmallVectorImpl<unsigned> &Idxs,
2400 Instruction *InsertBefore) {
2401 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2403 // Save the original To argument so we can modify it
2405 // General case, the type indexed by Idxs is a struct
2406 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2407 // Process each struct element recursively
2410 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2414 // Couldn't find any inserted value for this index? Cleanup
2415 while (PrevTo != OrigTo) {
2416 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2417 PrevTo = Del->getAggregateOperand();
2418 Del->eraseFromParent();
2420 // Stop processing elements
2424 // If we successfully found a value for each of our subaggregates
2428 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2429 // the struct's elements had a value that was inserted directly. In the latter
2430 // case, perhaps we can't determine each of the subelements individually, but
2431 // we might be able to find the complete struct somewhere.
2433 // Find the value that is at that particular spot
2434 Value *V = FindInsertedValue(From, Idxs);
2439 // Insert the value in the new (sub) aggregrate
2440 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2441 "tmp", InsertBefore);
2444 // This helper takes a nested struct and extracts a part of it (which is again a
2445 // struct) into a new value. For example, given the struct:
2446 // { a, { b, { c, d }, e } }
2447 // and the indices "1, 1" this returns
2450 // It does this by inserting an insertvalue for each element in the resulting
2451 // struct, as opposed to just inserting a single struct. This will only work if
2452 // each of the elements of the substruct are known (ie, inserted into From by an
2453 // insertvalue instruction somewhere).
2455 // All inserted insertvalue instructions are inserted before InsertBefore
2456 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2457 Instruction *InsertBefore) {
2458 assert(InsertBefore && "Must have someplace to insert!");
2459 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2461 Value *To = UndefValue::get(IndexedType);
2462 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2463 unsigned IdxSkip = Idxs.size();
2465 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2468 /// Given an aggregrate and an sequence of indices, see if
2469 /// the scalar value indexed is already around as a register, for example if it
2470 /// were inserted directly into the aggregrate.
2472 /// If InsertBefore is not null, this function will duplicate (modified)
2473 /// insertvalues when a part of a nested struct is extracted.
2474 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2475 Instruction *InsertBefore) {
2476 // Nothing to index? Just return V then (this is useful at the end of our
2478 if (idx_range.empty())
2480 // We have indices, so V should have an indexable type.
2481 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2482 "Not looking at a struct or array?");
2483 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2484 "Invalid indices for type?");
2486 if (Constant *C = dyn_cast<Constant>(V)) {
2487 C = C->getAggregateElement(idx_range[0]);
2488 if (!C) return nullptr;
2489 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2492 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2493 // Loop the indices for the insertvalue instruction in parallel with the
2494 // requested indices
2495 const unsigned *req_idx = idx_range.begin();
2496 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2497 i != e; ++i, ++req_idx) {
2498 if (req_idx == idx_range.end()) {
2499 // We can't handle this without inserting insertvalues
2503 // The requested index identifies a part of a nested aggregate. Handle
2504 // this specially. For example,
2505 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2506 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2507 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2508 // This can be changed into
2509 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2510 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2511 // which allows the unused 0,0 element from the nested struct to be
2513 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2517 // This insert value inserts something else than what we are looking for.
2518 // See if the (aggregrate) value inserted into has the value we are
2519 // looking for, then.
2521 return FindInsertedValue(I->getAggregateOperand(), idx_range,
2524 // If we end up here, the indices of the insertvalue match with those
2525 // requested (though possibly only partially). Now we recursively look at
2526 // the inserted value, passing any remaining indices.
2527 return FindInsertedValue(I->getInsertedValueOperand(),
2528 makeArrayRef(req_idx, idx_range.end()),
2532 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2533 // If we're extracting a value from an aggregrate that was extracted from
2534 // something else, we can extract from that something else directly instead.
2535 // However, we will need to chain I's indices with the requested indices.
2537 // Calculate the number of indices required
2538 unsigned size = I->getNumIndices() + idx_range.size();
2539 // Allocate some space to put the new indices in
2540 SmallVector<unsigned, 5> Idxs;
2542 // Add indices from the extract value instruction
2543 Idxs.append(I->idx_begin(), I->idx_end());
2545 // Add requested indices
2546 Idxs.append(idx_range.begin(), idx_range.end());
2548 assert(Idxs.size() == size
2549 && "Number of indices added not correct?");
2551 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2553 // Otherwise, we don't know (such as, extracting from a function return value
2554 // or load instruction)
2558 /// Analyze the specified pointer to see if it can be expressed as a base
2559 /// pointer plus a constant offset. Return the base and offset to the caller.
2560 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2561 const DataLayout &DL) {
2562 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2563 APInt ByteOffset(BitWidth, 0);
2565 if (Ptr->getType()->isVectorTy())
2568 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2569 APInt GEPOffset(BitWidth, 0);
2570 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2573 ByteOffset += GEPOffset;
2575 Ptr = GEP->getPointerOperand();
2576 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2577 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2578 Ptr = cast<Operator>(Ptr)->getOperand(0);
2579 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2580 if (GA->mayBeOverridden())
2582 Ptr = GA->getAliasee();
2587 Offset = ByteOffset.getSExtValue();
2592 /// This function computes the length of a null-terminated C string pointed to
2593 /// by V. If successful, it returns true and returns the string in Str.
2594 /// If unsuccessful, it returns false.
2595 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2596 uint64_t Offset, bool TrimAtNul) {
2599 // Look through bitcast instructions and geps.
2600 V = V->stripPointerCasts();
2602 // If the value is a GEP instruction or constant expression, treat it as an
2604 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2605 // Make sure the GEP has exactly three arguments.
2606 if (GEP->getNumOperands() != 3)
2609 // Make sure the index-ee is a pointer to array of i8.
2610 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2611 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
2612 if (!AT || !AT->getElementType()->isIntegerTy(8))
2615 // Check to make sure that the first operand of the GEP is an integer and
2616 // has value 0 so that we are sure we're indexing into the initializer.
2617 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2618 if (!FirstIdx || !FirstIdx->isZero())
2621 // If the second index isn't a ConstantInt, then this is a variable index
2622 // into the array. If this occurs, we can't say anything meaningful about
2624 uint64_t StartIdx = 0;
2625 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
2626 StartIdx = CI->getZExtValue();
2629 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2633 // The GEP instruction, constant or instruction, must reference a global
2634 // variable that is a constant and is initialized. The referenced constant
2635 // initializer is the array that we'll use for optimization.
2636 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2637 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
2640 // Handle the all-zeros case
2641 if (GV->getInitializer()->isNullValue()) {
2642 // This is a degenerate case. The initializer is constant zero so the
2643 // length of the string must be zero.
2648 // Must be a Constant Array
2649 const ConstantDataArray *Array =
2650 dyn_cast<ConstantDataArray>(GV->getInitializer());
2651 if (!Array || !Array->isString())
2654 // Get the number of elements in the array
2655 uint64_t NumElts = Array->getType()->getArrayNumElements();
2657 // Start out with the entire array in the StringRef.
2658 Str = Array->getAsString();
2660 if (Offset > NumElts)
2663 // Skip over 'offset' bytes.
2664 Str = Str.substr(Offset);
2667 // Trim off the \0 and anything after it. If the array is not nul
2668 // terminated, we just return the whole end of string. The client may know
2669 // some other way that the string is length-bound.
2670 Str = Str.substr(0, Str.find('\0'));
2675 // These next two are very similar to the above, but also look through PHI
2677 // TODO: See if we can integrate these two together.
2679 /// If we can compute the length of the string pointed to by
2680 /// the specified pointer, return 'len+1'. If we can't, return 0.
2681 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
2682 // Look through noop bitcast instructions.
2683 V = V->stripPointerCasts();
2685 // If this is a PHI node, there are two cases: either we have already seen it
2687 if (PHINode *PN = dyn_cast<PHINode>(V)) {
2688 if (!PHIs.insert(PN).second)
2689 return ~0ULL; // already in the set.
2691 // If it was new, see if all the input strings are the same length.
2692 uint64_t LenSoFar = ~0ULL;
2693 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2694 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2695 if (Len == 0) return 0; // Unknown length -> unknown.
2697 if (Len == ~0ULL) continue;
2699 if (Len != LenSoFar && LenSoFar != ~0ULL)
2700 return 0; // Disagree -> unknown.
2704 // Success, all agree.
2708 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2709 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2710 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2711 if (Len1 == 0) return 0;
2712 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2713 if (Len2 == 0) return 0;
2714 if (Len1 == ~0ULL) return Len2;
2715 if (Len2 == ~0ULL) return Len1;
2716 if (Len1 != Len2) return 0;
2720 // Otherwise, see if we can read the string.
2722 if (!getConstantStringInfo(V, StrData))
2725 return StrData.size()+1;
2728 /// If we can compute the length of the string pointed to by
2729 /// the specified pointer, return 'len+1'. If we can't, return 0.
2730 uint64_t llvm::GetStringLength(Value *V) {
2731 if (!V->getType()->isPointerTy()) return 0;
2733 SmallPtrSet<PHINode*, 32> PHIs;
2734 uint64_t Len = GetStringLengthH(V, PHIs);
2735 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2736 // an empty string as a length.
2737 return Len == ~0ULL ? 1 : Len;
2740 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2741 unsigned MaxLookup) {
2742 if (!V->getType()->isPointerTy())
2744 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2745 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2746 V = GEP->getPointerOperand();
2747 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2748 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
2749 V = cast<Operator>(V)->getOperand(0);
2750 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2751 if (GA->mayBeOverridden())
2753 V = GA->getAliasee();
2755 // See if InstructionSimplify knows any relevant tricks.
2756 if (Instruction *I = dyn_cast<Instruction>(V))
2757 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
2758 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
2765 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2770 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
2771 const DataLayout &DL, unsigned MaxLookup) {
2772 SmallPtrSet<Value *, 4> Visited;
2773 SmallVector<Value *, 4> Worklist;
2774 Worklist.push_back(V);
2776 Value *P = Worklist.pop_back_val();
2777 P = GetUnderlyingObject(P, DL, MaxLookup);
2779 if (!Visited.insert(P).second)
2782 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2783 Worklist.push_back(SI->getTrueValue());
2784 Worklist.push_back(SI->getFalseValue());
2788 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2789 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2790 Worklist.push_back(PN->getIncomingValue(i));
2794 Objects.push_back(P);
2795 } while (!Worklist.empty());
2798 /// Return true if the only users of this pointer are lifetime markers.
2799 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
2800 for (const User *U : V->users()) {
2801 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2802 if (!II) return false;
2804 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2805 II->getIntrinsicID() != Intrinsic::lifetime_end)
2811 static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
2812 Type *Ty, const DataLayout &DL) {
2813 assert(Offset.isNonNegative() && "offset can't be negative");
2814 assert(Ty->isSized() && "must be sized");
2816 APInt DerefBytes(Offset.getBitWidth(), 0);
2817 if (const Argument *A = dyn_cast<Argument>(BV)) {
2818 DerefBytes = A->getDereferenceableBytes();
2819 } else if (auto CS = ImmutableCallSite(BV)) {
2820 DerefBytes = CS.getDereferenceableBytes(0);
2823 if (DerefBytes.getBoolValue())
2824 if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
2830 static bool isDereferenceableFromAttribute(const Value *V,
2831 const DataLayout &DL) {
2832 Type *VTy = V->getType();
2833 Type *Ty = VTy->getPointerElementType();
2837 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
2838 return isDereferenceableFromAttribute(V, Offset, Ty, DL);
2841 /// Return true if Value is always a dereferenceable pointer.
2843 /// Test if V is always a pointer to allocated and suitably aligned memory for
2844 /// a simple load or store.
2845 static bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
2846 SmallPtrSetImpl<const Value *> &Visited) {
2847 // Note that it is not safe to speculate into a malloc'd region because
2848 // malloc may return null.
2850 // These are obviously ok.
2851 if (isa<AllocaInst>(V)) return true;
2853 // It's not always safe to follow a bitcast, for example:
2854 // bitcast i8* (alloca i8) to i32*
2855 // would result in a 4-byte load from a 1-byte alloca. However,
2856 // if we're casting from a pointer from a type of larger size
2857 // to a type of smaller size (or the same size), and the alignment
2858 // is at least as large as for the resulting pointer type, then
2859 // we can look through the bitcast.
2860 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
2861 Type *STy = BC->getSrcTy()->getPointerElementType(),
2862 *DTy = BC->getDestTy()->getPointerElementType();
2863 if (STy->isSized() && DTy->isSized() &&
2864 (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
2865 (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
2866 return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
2869 // Global variables which can't collapse to null are ok.
2870 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2871 return !GV->hasExternalWeakLinkage();
2873 // byval arguments are okay.
2874 if (const Argument *A = dyn_cast<Argument>(V))
2875 if (A->hasByValAttr())
2878 if (isDereferenceableFromAttribute(V, DL))
2881 // For GEPs, determine if the indexing lands within the allocated object.
2882 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2883 // Conservatively require that the base pointer be fully dereferenceable.
2884 if (!Visited.insert(GEP->getOperand(0)).second)
2886 if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
2888 // Check the indices.
2889 gep_type_iterator GTI = gep_type_begin(GEP);
2890 for (User::const_op_iterator I = GEP->op_begin()+1,
2891 E = GEP->op_end(); I != E; ++I) {
2894 // Struct indices can't be out of bounds.
2895 if (isa<StructType>(Ty))
2897 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
2900 // Zero is always ok.
2903 // Check to see that it's within the bounds of an array.
2904 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2907 if (CI->getValue().getActiveBits() > 64)
2909 if (CI->getZExtValue() >= ATy->getNumElements())
2912 // Indices check out; this is dereferenceable.
2916 // For gc.relocate, look through relocations
2917 if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
2918 if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
2919 GCRelocateOperands RelocateInst(I);
2920 return isDereferenceablePointer(RelocateInst.derivedPtr(), DL, Visited);
2923 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
2924 return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
2926 // If we don't know, assume the worst.
2930 bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL) {
2931 // When dereferenceability information is provided by a dereferenceable
2932 // attribute, we know exactly how many bytes are dereferenceable. If we can
2933 // determine the exact offset to the attributed variable, we can use that
2934 // information here.
2935 Type *VTy = V->getType();
2936 Type *Ty = VTy->getPointerElementType();
2937 if (Ty->isSized()) {
2938 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
2939 const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
2941 if (Offset.isNonNegative())
2942 if (isDereferenceableFromAttribute(BV, Offset, Ty, DL))
2946 SmallPtrSet<const Value *, 32> Visited;
2947 return ::isDereferenceablePointer(V, DL, Visited);
2950 bool llvm::isSafeToSpeculativelyExecute(const Value *V) {
2951 const Operator *Inst = dyn_cast<Operator>(V);
2955 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2956 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2960 switch (Inst->getOpcode()) {
2963 case Instruction::UDiv:
2964 case Instruction::URem: {
2965 // x / y is undefined if y == 0.
2967 if (match(Inst->getOperand(1), m_APInt(V)))
2971 case Instruction::SDiv:
2972 case Instruction::SRem: {
2973 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
2974 const APInt *Numerator, *Denominator;
2975 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
2977 // We cannot hoist this division if the denominator is 0.
2978 if (*Denominator == 0)
2980 // It's safe to hoist if the denominator is not 0 or -1.
2981 if (*Denominator != -1)
2983 // At this point we know that the denominator is -1. It is safe to hoist as
2984 // long we know that the numerator is not INT_MIN.
2985 if (match(Inst->getOperand(0), m_APInt(Numerator)))
2986 return !Numerator->isMinSignedValue();
2987 // The numerator *might* be MinSignedValue.
2990 case Instruction::Load: {
2991 const LoadInst *LI = cast<LoadInst>(Inst);
2992 if (!LI->isUnordered() ||
2993 // Speculative load may create a race that did not exist in the source.
2994 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
2996 const DataLayout &DL = LI->getModule()->getDataLayout();
2997 return isDereferenceablePointer(LI->getPointerOperand(), DL);
2999 case Instruction::Call: {
3000 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3001 switch (II->getIntrinsicID()) {
3002 // These synthetic intrinsics have no side-effects and just mark
3003 // information about their operands.
3004 // FIXME: There are other no-op synthetic instructions that potentially
3005 // should be considered at least *safe* to speculate...
3006 case Intrinsic::dbg_declare:
3007 case Intrinsic::dbg_value:
3010 case Intrinsic::bswap:
3011 case Intrinsic::ctlz:
3012 case Intrinsic::ctpop:
3013 case Intrinsic::cttz:
3014 case Intrinsic::objectsize:
3015 case Intrinsic::sadd_with_overflow:
3016 case Intrinsic::smul_with_overflow:
3017 case Intrinsic::ssub_with_overflow:
3018 case Intrinsic::uadd_with_overflow:
3019 case Intrinsic::umul_with_overflow:
3020 case Intrinsic::usub_with_overflow:
3022 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3023 // errno like libm sqrt would.
3024 case Intrinsic::sqrt:
3025 case Intrinsic::fma:
3026 case Intrinsic::fmuladd:
3027 case Intrinsic::fabs:
3028 case Intrinsic::minnum:
3029 case Intrinsic::maxnum:
3031 // TODO: some fp intrinsics are marked as having the same error handling
3032 // as libm. They're safe to speculate when they won't error.
3033 // TODO: are convert_{from,to}_fp16 safe?
3034 // TODO: can we list target-specific intrinsics here?
3038 return false; // The called function could have undefined behavior or
3039 // side-effects, even if marked readnone nounwind.
3041 case Instruction::VAArg:
3042 case Instruction::Alloca:
3043 case Instruction::Invoke:
3044 case Instruction::PHI:
3045 case Instruction::Store:
3046 case Instruction::Ret:
3047 case Instruction::Br:
3048 case Instruction::IndirectBr:
3049 case Instruction::Switch:
3050 case Instruction::Unreachable:
3051 case Instruction::Fence:
3052 case Instruction::LandingPad:
3053 case Instruction::AtomicRMW:
3054 case Instruction::AtomicCmpXchg:
3055 case Instruction::Resume:
3056 return false; // Misc instructions which have effects
3060 /// Return true if we know that the specified value is never null.
3061 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
3062 // Alloca never returns null, malloc might.
3063 if (isa<AllocaInst>(V)) return true;
3065 // A byval, inalloca, or nonnull argument is never null.
3066 if (const Argument *A = dyn_cast<Argument>(V))
3067 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3069 // Global values are not null unless extern weak.
3070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3071 return !GV->hasExternalWeakLinkage();
3073 // A Load tagged w/nonnull metadata is never null.
3074 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3075 return LI->getMetadata(LLVMContext::MD_nonnull);
3077 if (auto CS = ImmutableCallSite(V))
3078 if (CS.isReturnNonNull())
3081 // operator new never returns null.
3082 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
3088 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
3089 const DataLayout &DL,
3090 AssumptionCache *AC,
3091 const Instruction *CxtI,
3092 const DominatorTree *DT) {
3093 // Multiplying n * m significant bits yields a result of n + m significant
3094 // bits. If the total number of significant bits does not exceed the
3095 // result bit width (minus 1), there is no overflow.
3096 // This means if we have enough leading zero bits in the operands
3097 // we can guarantee that the result does not overflow.
3098 // Ref: "Hacker's Delight" by Henry Warren
3099 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3100 APInt LHSKnownZero(BitWidth, 0);
3101 APInt LHSKnownOne(BitWidth, 0);
3102 APInt RHSKnownZero(BitWidth, 0);
3103 APInt RHSKnownOne(BitWidth, 0);
3104 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3106 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3108 // Note that underestimating the number of zero bits gives a more
3109 // conservative answer.
3110 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3111 RHSKnownZero.countLeadingOnes();
3112 // First handle the easy case: if we have enough zero bits there's
3113 // definitely no overflow.
3114 if (ZeroBits >= BitWidth)
3115 return OverflowResult::NeverOverflows;
3117 // Get the largest possible values for each operand.
3118 APInt LHSMax = ~LHSKnownZero;
3119 APInt RHSMax = ~RHSKnownZero;
3121 // We know the multiply operation doesn't overflow if the maximum values for
3122 // each operand will not overflow after we multiply them together.
3124 LHSMax.umul_ov(RHSMax, MaxOverflow);
3126 return OverflowResult::NeverOverflows;
3128 // We know it always overflows if multiplying the smallest possible values for
3129 // the operands also results in overflow.
3131 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3133 return OverflowResult::AlwaysOverflows;
3135 return OverflowResult::MayOverflow;
3138 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
3139 const DataLayout &DL,
3140 AssumptionCache *AC,
3141 const Instruction *CxtI,
3142 const DominatorTree *DT) {
3143 bool LHSKnownNonNegative, LHSKnownNegative;
3144 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3146 if (LHSKnownNonNegative || LHSKnownNegative) {
3147 bool RHSKnownNonNegative, RHSKnownNegative;
3148 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3151 if (LHSKnownNegative && RHSKnownNegative) {
3152 // The sign bit is set in both cases: this MUST overflow.
3153 // Create a simple add instruction, and insert it into the struct.
3154 return OverflowResult::AlwaysOverflows;
3157 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3158 // The sign bit is clear in both cases: this CANNOT overflow.
3159 // Create a simple add instruction, and insert it into the struct.
3160 return OverflowResult::NeverOverflows;
3164 return OverflowResult::MayOverflow;