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/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/MemoryBuiltins.h"
21 #include "llvm/Analysis/Loads.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/VectorUtils.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/PatternMatch.h"
38 #include "llvm/IR/Statepoint.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/MathExtras.h"
45 using namespace llvm::PatternMatch;
47 const unsigned MaxDepth = 6;
49 // Controls the number of uses of the value searched for possible
50 // dominating comparisons.
51 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
52 cl::Hidden, cl::init(20));
54 // This optimization is known to cause performance regressions is some cases,
55 // keep it under a temporary flag for now.
57 DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
58 cl::Hidden, cl::init(true));
60 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
61 /// 0). For vector types, returns the element type's bitwidth.
62 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
63 if (unsigned BitWidth = Ty->getScalarSizeInBits())
66 return DL.getPointerTypeSizeInBits(Ty);
70 // Simplifying using an assume can only be done in a particular control-flow
71 // context (the context instruction provides that context). If an assume and
72 // the context instruction are not in the same block then the DT helps in
73 // figuring out if we can use it.
77 const Instruction *CxtI;
78 const DominatorTree *DT;
80 /// Set of assumptions that should be excluded from further queries.
81 /// This is because of the potential for mutual recursion to cause
82 /// 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
89 std::array<const Value *, MaxDepth> Excluded;
92 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
93 const DominatorTree *DT)
94 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), NumExcluded(0) {}
96 Query(const Query &Q, const Value *NewExcl)
97 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), NumExcluded(Q.NumExcluded) {
98 Excluded = Q.Excluded;
99 Excluded[NumExcluded++] = NewExcl;
100 assert(NumExcluded <= Excluded.size());
103 bool isExcluded(const Value *Value) const {
104 if (NumExcluded == 0)
106 auto End = Excluded.begin() + NumExcluded;
107 return std::find(Excluded.begin(), End, Value) != End;
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(const Value *V, APInt &KnownZero, APInt &KnownOne,
129 unsigned Depth, const Query &Q);
131 void llvm::computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne,
132 const DataLayout &DL, unsigned Depth,
133 AssumptionCache *AC, const Instruction *CxtI,
134 const DominatorTree *DT) {
135 ::computeKnownBits(V, KnownZero, KnownOne, Depth,
136 Query(DL, AC, safeCxtI(V, CxtI), DT));
139 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
140 const DataLayout &DL,
141 AssumptionCache *AC, const Instruction *CxtI,
142 const DominatorTree *DT) {
143 assert(LHS->getType() == RHS->getType() &&
144 "LHS and RHS should have the same type");
145 assert(LHS->getType()->isIntOrIntVectorTy() &&
146 "LHS and RHS should be integers");
147 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
148 APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
149 APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
150 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
151 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
152 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
155 static void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
156 unsigned Depth, const Query &Q);
158 void llvm::ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
159 const DataLayout &DL, unsigned Depth,
160 AssumptionCache *AC, const Instruction *CxtI,
161 const DominatorTree *DT) {
162 ::ComputeSignBit(V, KnownZero, KnownOne, Depth,
163 Query(DL, AC, safeCxtI(V, CxtI), DT));
166 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
169 bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
171 unsigned Depth, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT) {
174 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
175 Query(DL, AC, safeCxtI(V, CxtI), DT));
178 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
180 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
181 AssumptionCache *AC, const Instruction *CxtI,
182 const DominatorTree *DT) {
183 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
186 bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
188 AssumptionCache *AC, const Instruction *CxtI,
189 const DominatorTree *DT) {
190 bool NonNegative, Negative;
191 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
195 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
196 AssumptionCache *AC, const Instruction *CxtI,
197 const DominatorTree *DT) {
198 if (auto *CI = dyn_cast<ConstantInt>(V))
199 return CI->getValue().isStrictlyPositive();
201 // TODO: We'd doing two recursive queries here. We should factor this such
202 // that only a single query is needed.
203 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
204 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
207 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
208 AssumptionCache *AC, const Instruction *CxtI,
209 const DominatorTree *DT) {
210 bool NonNegative, Negative;
211 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
215 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
217 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
218 const DataLayout &DL,
219 AssumptionCache *AC, const Instruction *CxtI,
220 const DominatorTree *DT) {
221 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
222 safeCxtI(V1, safeCxtI(V2, CxtI)),
226 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
229 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
230 const DataLayout &DL,
231 unsigned Depth, AssumptionCache *AC,
232 const Instruction *CxtI, const DominatorTree *DT) {
233 return ::MaskedValueIsZero(V, Mask, Depth,
234 Query(DL, AC, safeCxtI(V, CxtI), DT));
237 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
240 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
241 unsigned Depth, AssumptionCache *AC,
242 const Instruction *CxtI,
243 const DominatorTree *DT) {
244 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
247 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
249 APInt &KnownZero, APInt &KnownOne,
250 APInt &KnownZero2, APInt &KnownOne2,
251 unsigned Depth, const Query &Q) {
253 if (const ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
254 // We know that the top bits of C-X are clear if X contains less bits
255 // than C (i.e. no wrap-around can happen). For example, 20-X is
256 // positive if we can prove that X is >= 0 and < 16.
257 if (!CLHS->getValue().isNegative()) {
258 unsigned BitWidth = KnownZero.getBitWidth();
259 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
260 // NLZ can't be BitWidth with no sign bit
261 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
262 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
264 // If all of the MaskV bits are known to be zero, then we know the
265 // output top bits are zero, because we now know that the output is
267 if ((KnownZero2 & MaskV) == MaskV) {
268 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
269 // Top bits known zero.
270 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
276 unsigned BitWidth = KnownZero.getBitWidth();
278 // If an initial sequence of bits in the result is not needed, the
279 // corresponding bits in the operands are not needed.
280 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
281 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, Depth + 1, Q);
282 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
284 // Carry in a 1 for a subtract, rather than a 0.
285 APInt CarryIn(BitWidth, 0);
287 // Sum = LHS + ~RHS + 1
288 std::swap(KnownZero2, KnownOne2);
292 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
293 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
295 // Compute known bits of the carry.
296 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
297 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
299 // Compute set of known bits (where all three relevant bits are known).
300 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
301 APInt RHSKnown = KnownZero2 | KnownOne2;
302 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
303 APInt Known = LHSKnown & RHSKnown & CarryKnown;
305 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
306 "known bits of sum differ");
308 // Compute known bits of the result.
309 KnownZero = ~PossibleSumOne & Known;
310 KnownOne = PossibleSumOne & Known;
312 // Are we still trying to solve for the sign bit?
313 if (!Known.isNegative()) {
315 // Adding two non-negative numbers, or subtracting a negative number from
316 // a non-negative one, can't wrap into negative.
317 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
318 KnownZero |= APInt::getSignBit(BitWidth);
319 // Adding two negative numbers, or subtracting a non-negative number from
320 // a negative one, can't wrap into non-negative.
321 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
322 KnownOne |= APInt::getSignBit(BitWidth);
327 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
328 APInt &KnownZero, APInt &KnownOne,
329 APInt &KnownZero2, APInt &KnownOne2,
330 unsigned Depth, const Query &Q) {
331 unsigned BitWidth = KnownZero.getBitWidth();
332 computeKnownBits(Op1, KnownZero, KnownOne, Depth + 1, Q);
333 computeKnownBits(Op0, KnownZero2, KnownOne2, Depth + 1, Q);
335 bool isKnownNegative = false;
336 bool isKnownNonNegative = false;
337 // If the multiplication is known not to overflow, compute the sign bit.
340 // The product of a number with itself is non-negative.
341 isKnownNonNegative = true;
343 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
344 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
345 bool isKnownNegativeOp1 = KnownOne.isNegative();
346 bool isKnownNegativeOp0 = KnownOne2.isNegative();
347 // The product of two numbers with the same sign is non-negative.
348 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
349 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
350 // The product of a negative number and a non-negative number is either
352 if (!isKnownNonNegative)
353 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
354 isKnownNonZero(Op0, Depth, Q)) ||
355 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
356 isKnownNonZero(Op1, Depth, Q));
360 // If low bits are zero in either operand, output low known-0 bits.
361 // Also compute a conservative estimate for high known-0 bits.
362 // More trickiness is possible, but this is sufficient for the
363 // interesting case of alignment computation.
364 KnownOne.clearAllBits();
365 unsigned TrailZ = KnownZero.countTrailingOnes() +
366 KnownZero2.countTrailingOnes();
367 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
368 KnownZero2.countLeadingOnes(),
369 BitWidth) - BitWidth;
371 TrailZ = std::min(TrailZ, BitWidth);
372 LeadZ = std::min(LeadZ, BitWidth);
373 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
374 APInt::getHighBitsSet(BitWidth, LeadZ);
376 // Only make use of no-wrap flags if we failed to compute the sign bit
377 // directly. This matters if the multiplication always overflows, in
378 // which case we prefer to follow the result of the direct computation,
379 // though as the program is invoking undefined behaviour we can choose
380 // whatever we like here.
381 if (isKnownNonNegative && !KnownOne.isNegative())
382 KnownZero.setBit(BitWidth - 1);
383 else if (isKnownNegative && !KnownZero.isNegative())
384 KnownOne.setBit(BitWidth - 1);
387 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
390 unsigned BitWidth = KnownZero.getBitWidth();
391 unsigned NumRanges = Ranges.getNumOperands() / 2;
392 assert(NumRanges >= 1);
394 KnownZero.setAllBits();
395 KnownOne.setAllBits();
397 for (unsigned i = 0; i < NumRanges; ++i) {
399 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
401 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
402 ConstantRange Range(Lower->getValue(), Upper->getValue());
404 // The first CommonPrefixBits of all values in Range are equal.
405 unsigned CommonPrefixBits =
406 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
408 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
409 KnownOne &= Range.getUnsignedMax() & Mask;
410 KnownZero &= ~Range.getUnsignedMax() & Mask;
414 static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
415 SmallVector<const Value *, 16> WorkSet(1, I);
416 SmallPtrSet<const Value *, 32> Visited;
417 SmallPtrSet<const Value *, 16> EphValues;
419 // The instruction defining an assumption's condition itself is always
420 // considered ephemeral to that assumption (even if it has other
421 // non-ephemeral users). See r246696's test case for an example.
422 if (is_contained(I->operands(), E))
425 while (!WorkSet.empty()) {
426 const Value *V = WorkSet.pop_back_val();
427 if (!Visited.insert(V).second)
430 // If all uses of this value are ephemeral, then so is this value.
431 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
436 if (const User *U = dyn_cast<User>(V))
437 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
439 if (isSafeToSpeculativelyExecute(*J))
440 WorkSet.push_back(*J);
448 // Is this an intrinsic that cannot be speculated but also cannot trap?
449 static bool isAssumeLikeIntrinsic(const Instruction *I) {
450 if (const CallInst *CI = dyn_cast<CallInst>(I))
451 if (Function *F = CI->getCalledFunction())
452 switch (F->getIntrinsicID()) {
454 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
455 case Intrinsic::assume:
456 case Intrinsic::dbg_declare:
457 case Intrinsic::dbg_value:
458 case Intrinsic::invariant_start:
459 case Intrinsic::invariant_end:
460 case Intrinsic::lifetime_start:
461 case Intrinsic::lifetime_end:
462 case Intrinsic::objectsize:
463 case Intrinsic::ptr_annotation:
464 case Intrinsic::var_annotation:
471 bool llvm::isValidAssumeForContext(const Instruction *Inv,
472 const Instruction *CxtI,
473 const DominatorTree *DT) {
475 // There are two restrictions on the use of an assume:
476 // 1. The assume must dominate the context (or the control flow must
477 // reach the assume whenever it reaches the context).
478 // 2. The context must not be in the assume's set of ephemeral values
479 // (otherwise we will use the assume to prove that the condition
480 // feeding the assume is trivially true, thus causing the removal of
484 if (DT->dominates(Inv, CxtI))
486 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
487 // We don't have a DT, but this trivially dominates.
491 // With or without a DT, the only remaining case we will check is if the
492 // instructions are in the same BB. Give up if that is not the case.
493 if (Inv->getParent() != CxtI->getParent())
496 // If we have a dom tree, then we now know that the assume doens't dominate
497 // the other instruction. If we don't have a dom tree then we can check if
498 // the assume is first in the BB.
500 // Search forward from the assume until we reach the context (or the end
501 // of the block); the common case is that the assume will come first.
502 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
503 IE = Inv->getParent()->end(); I != IE; ++I)
508 // The context comes first, but they're both in the same block. Make sure
509 // there is nothing in between that might interrupt the control flow.
510 for (BasicBlock::const_iterator I =
511 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
513 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
516 return !isEphemeralValueOf(Inv, CxtI);
519 static void computeKnownBitsFromAssume(const Value *V, APInt &KnownZero,
520 APInt &KnownOne, unsigned Depth,
522 // Use of assumptions is context-sensitive. If we don't have a context, we
524 if (!Q.AC || !Q.CxtI)
527 unsigned BitWidth = KnownZero.getBitWidth();
529 // Note that the patterns below need to be kept in sync with the code
530 // in AssumptionCache::updateAffectedValues.
532 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
535 CallInst *I = cast<CallInst>(AssumeVH);
536 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
537 "Got assumption for the wrong function!");
541 // Warning: This loop can end up being somewhat performance sensetive.
542 // We're running this loop for once for each value queried resulting in a
543 // runtime of ~O(#assumes * #values).
545 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
546 "must be an assume intrinsic");
548 Value *Arg = I->getArgOperand(0);
550 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
551 assert(BitWidth == 1 && "assume operand is not i1?");
552 KnownZero.clearAllBits();
553 KnownOne.setAllBits();
557 // The remaining tests are all recursive, so bail out if we hit the limit.
558 if (Depth == MaxDepth)
562 auto m_V = m_CombineOr(m_Specific(V),
563 m_CombineOr(m_PtrToInt(m_Specific(V)),
564 m_BitCast(m_Specific(V))));
566 CmpInst::Predicate Pred;
569 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
570 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
571 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
572 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
573 KnownZero |= RHSKnownZero;
574 KnownOne |= RHSKnownOne;
576 } else if (match(Arg,
577 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
578 Pred == ICmpInst::ICMP_EQ &&
579 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
580 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
581 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
582 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
583 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
585 // For those bits in the mask that are known to be one, we can propagate
586 // known bits from the RHS to V.
587 KnownZero |= RHSKnownZero & MaskKnownOne;
588 KnownOne |= RHSKnownOne & MaskKnownOne;
589 // assume(~(v & b) = a)
590 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
592 Pred == ICmpInst::ICMP_EQ &&
593 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
594 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
595 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
596 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
597 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
599 // For those bits in the mask that are known to be one, we can propagate
600 // inverted known bits from the RHS to V.
601 KnownZero |= RHSKnownOne & MaskKnownOne;
602 KnownOne |= RHSKnownZero & MaskKnownOne;
604 } else if (match(Arg,
605 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
606 Pred == ICmpInst::ICMP_EQ &&
607 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
608 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
609 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
610 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
611 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
613 // For those bits in B that are known to be zero, we can propagate known
614 // bits from the RHS to V.
615 KnownZero |= RHSKnownZero & BKnownZero;
616 KnownOne |= RHSKnownOne & BKnownZero;
617 // assume(~(v | b) = a)
618 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
620 Pred == ICmpInst::ICMP_EQ &&
621 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
622 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
623 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
624 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
625 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
627 // For those bits in B that are known to be zero, we can propagate
628 // inverted known bits from the RHS to V.
629 KnownZero |= RHSKnownOne & BKnownZero;
630 KnownOne |= RHSKnownZero & BKnownZero;
632 } else if (match(Arg,
633 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
634 Pred == ICmpInst::ICMP_EQ &&
635 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
636 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
637 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
638 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
639 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
641 // For those bits in B that are known to be zero, we can propagate known
642 // bits from the RHS to V. For those bits in B that are known to be one,
643 // we can propagate inverted known bits from the RHS to V.
644 KnownZero |= RHSKnownZero & BKnownZero;
645 KnownOne |= RHSKnownOne & BKnownZero;
646 KnownZero |= RHSKnownOne & BKnownOne;
647 KnownOne |= RHSKnownZero & BKnownOne;
648 // assume(~(v ^ b) = a)
649 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
651 Pred == ICmpInst::ICMP_EQ &&
652 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
653 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
654 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
655 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
656 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
658 // For those bits in B that are known to be zero, we can propagate
659 // inverted known bits from the RHS to V. For those bits in B that are
660 // known to be one, we can propagate known bits from the RHS to V.
661 KnownZero |= RHSKnownOne & BKnownZero;
662 KnownOne |= RHSKnownZero & BKnownZero;
663 KnownZero |= RHSKnownZero & BKnownOne;
664 KnownOne |= RHSKnownOne & BKnownOne;
665 // assume(v << c = a)
666 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
668 Pred == ICmpInst::ICMP_EQ &&
669 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
670 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
671 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
672 // For those bits in RHS that are known, we can propagate them to known
673 // bits in V shifted to the right by C.
674 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
675 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
676 // assume(~(v << c) = a)
677 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
679 Pred == ICmpInst::ICMP_EQ &&
680 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
681 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
682 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
683 // For those bits in RHS that are known, we can propagate them inverted
684 // to known bits in V shifted to the right by C.
685 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
686 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
687 // assume(v >> c = a)
688 } else if (match(Arg,
689 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
690 m_AShr(m_V, m_ConstantInt(C))),
692 Pred == ICmpInst::ICMP_EQ &&
693 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
694 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
695 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
696 // For those bits in RHS that are known, we can propagate them to known
697 // bits in V shifted to the right by C.
698 KnownZero |= RHSKnownZero << C->getZExtValue();
699 KnownOne |= RHSKnownOne << C->getZExtValue();
700 // assume(~(v >> c) = a)
701 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
702 m_LShr(m_V, m_ConstantInt(C)),
703 m_AShr(m_V, m_ConstantInt(C)))),
705 Pred == ICmpInst::ICMP_EQ &&
706 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
707 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
708 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
709 // For those bits in RHS that are known, we can propagate them inverted
710 // to known bits in V shifted to the right by C.
711 KnownZero |= RHSKnownOne << C->getZExtValue();
712 KnownOne |= RHSKnownZero << C->getZExtValue();
713 // assume(v >=_s c) where c is non-negative
714 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
715 Pred == ICmpInst::ICMP_SGE &&
716 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
717 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
718 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
720 if (RHSKnownZero.isNegative()) {
721 // We know that the sign bit is zero.
722 KnownZero |= APInt::getSignBit(BitWidth);
724 // assume(v >_s c) where c is at least -1.
725 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
726 Pred == ICmpInst::ICMP_SGT &&
727 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
728 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
729 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
731 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
732 // We know that the sign bit is zero.
733 KnownZero |= APInt::getSignBit(BitWidth);
735 // assume(v <=_s c) where c is negative
736 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
737 Pred == ICmpInst::ICMP_SLE &&
738 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
739 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
740 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
742 if (RHSKnownOne.isNegative()) {
743 // We know that the sign bit is one.
744 KnownOne |= APInt::getSignBit(BitWidth);
746 // assume(v <_s c) where c is non-positive
747 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
748 Pred == ICmpInst::ICMP_SLT &&
749 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
750 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
751 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
753 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
754 // We know that the sign bit is one.
755 KnownOne |= APInt::getSignBit(BitWidth);
758 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
759 Pred == ICmpInst::ICMP_ULE &&
760 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
761 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
762 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
764 // Whatever high bits in c are zero are known to be zero.
766 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
768 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
769 Pred == ICmpInst::ICMP_ULT &&
770 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
771 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
772 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
774 // Whatever high bits in c are zero are known to be zero (if c is a power
775 // of 2, then one more).
776 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
778 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
781 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
785 // If assumptions conflict with each other or previous known bits, then we
786 // have a logical fallacy. This should only happen when a program has
787 // undefined behavior. We can't assert/crash, so clear out the known bits and
788 // hope for the best.
790 // FIXME: Publish a warning/remark that we have encountered UB or the compiler
793 // FIXME: Implement a stronger version of "I give up" by invalidating/clearing
794 // the assumption cache. This should indicate that the cache is corrupted so
795 // future callers will not waste time repopulating it with faulty assumptions.
797 if ((KnownZero & KnownOne) != 0) {
798 KnownZero.clearAllBits();
799 KnownOne.clearAllBits();
803 // Compute known bits from a shift operator, including those with a
804 // non-constant shift amount. KnownZero and KnownOne are the outputs of this
805 // function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the
806 // same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific
807 // functors that, given the known-zero or known-one bits respectively, and a
808 // shift amount, compute the implied known-zero or known-one bits of the shift
809 // operator's result respectively for that shift amount. The results from calling
810 // KZF and KOF are conservatively combined for all permitted shift amounts.
811 static void computeKnownBitsFromShiftOperator(
812 const Operator *I, APInt &KnownZero, APInt &KnownOne, APInt &KnownZero2,
813 APInt &KnownOne2, unsigned Depth, const Query &Q,
814 function_ref<APInt(const APInt &, unsigned)> KZF,
815 function_ref<APInt(const APInt &, unsigned)> KOF) {
816 unsigned BitWidth = KnownZero.getBitWidth();
818 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
819 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
821 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
822 KnownZero = KZF(KnownZero, ShiftAmt);
823 KnownOne = KOF(KnownOne, ShiftAmt);
824 // If there is conflict between KnownZero and KnownOne, this must be an
825 // overflowing left shift, so the shift result is undefined. Clear KnownZero
826 // and KnownOne bits so that other code could propagate this undef.
827 if ((KnownZero & KnownOne) != 0) {
828 KnownZero.clearAllBits();
829 KnownOne.clearAllBits();
835 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
837 // Note: We cannot use KnownZero.getLimitedValue() here, because if
838 // BitWidth > 64 and any upper bits are known, we'll end up returning the
839 // limit value (which implies all bits are known).
840 uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue();
841 uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue();
843 // It would be more-clearly correct to use the two temporaries for this
844 // calculation. Reusing the APInts here to prevent unnecessary allocations.
845 KnownZero.clearAllBits();
846 KnownOne.clearAllBits();
848 // If we know the shifter operand is nonzero, we can sometimes infer more
849 // known bits. However this is expensive to compute, so be lazy about it and
850 // only compute it when absolutely necessary.
851 Optional<bool> ShifterOperandIsNonZero;
853 // Early exit if we can't constrain any well-defined shift amount.
854 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
855 ShifterOperandIsNonZero =
856 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
857 if (!*ShifterOperandIsNonZero)
861 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
863 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
864 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
865 // Combine the shifted known input bits only for those shift amounts
866 // compatible with its known constraints.
867 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
869 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
871 // If we know the shifter is nonzero, we may be able to infer more known
872 // bits. This check is sunk down as far as possible to avoid the expensive
873 // call to isKnownNonZero if the cheaper checks above fail.
875 if (!ShifterOperandIsNonZero.hasValue())
876 ShifterOperandIsNonZero =
877 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
878 if (*ShifterOperandIsNonZero)
882 KnownZero &= KZF(KnownZero2, ShiftAmt);
883 KnownOne &= KOF(KnownOne2, ShiftAmt);
886 // If there are no compatible shift amounts, then we've proven that the shift
887 // amount must be >= the BitWidth, and the result is undefined. We could
888 // return anything we'd like, but we need to make sure the sets of known bits
889 // stay disjoint (it should be better for some other code to actually
890 // propagate the undef than to pick a value here using known bits).
891 if ((KnownZero & KnownOne) != 0) {
892 KnownZero.clearAllBits();
893 KnownOne.clearAllBits();
897 static void computeKnownBitsFromOperator(const Operator *I, APInt &KnownZero,
898 APInt &KnownOne, unsigned Depth,
900 unsigned BitWidth = KnownZero.getBitWidth();
902 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
903 switch (I->getOpcode()) {
905 case Instruction::Load:
906 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
907 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
909 case Instruction::And: {
910 // If either the LHS or the RHS are Zero, the result is zero.
911 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
912 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
914 // Output known-1 bits are only known if set in both the LHS & RHS.
915 KnownOne &= KnownOne2;
916 // Output known-0 are known to be clear if zero in either the LHS | RHS.
917 KnownZero |= KnownZero2;
919 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
920 // here we handle the more general case of adding any odd number by
921 // matching the form add(x, add(x, y)) where y is odd.
922 // TODO: This could be generalized to clearing any bit set in y where the
923 // following bit is known to be unset in y.
925 if (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
927 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
929 APInt KnownZero3(BitWidth, 0), KnownOne3(BitWidth, 0);
930 computeKnownBits(Y, KnownZero3, KnownOne3, Depth + 1, Q);
931 if (KnownOne3.countTrailingOnes() > 0)
932 KnownZero |= APInt::getLowBitsSet(BitWidth, 1);
936 case Instruction::Or: {
937 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
938 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
940 // Output known-0 bits are only known if clear in both the LHS & RHS.
941 KnownZero &= KnownZero2;
942 // Output known-1 are known to be set if set in either the LHS | RHS.
943 KnownOne |= KnownOne2;
946 case Instruction::Xor: {
947 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
948 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
950 // Output known-0 bits are known if clear or set in both the LHS & RHS.
951 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
952 // Output known-1 are known to be set if set in only one of the LHS, RHS.
953 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
954 KnownZero = KnownZeroOut;
957 case Instruction::Mul: {
958 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
959 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
960 KnownOne, KnownZero2, KnownOne2, Depth, Q);
963 case Instruction::UDiv: {
964 // For the purposes of computing leading zeros we can conservatively
965 // treat a udiv as a logical right shift by the power of 2 known to
966 // be less than the denominator.
967 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
968 unsigned LeadZ = KnownZero2.countLeadingOnes();
970 KnownOne2.clearAllBits();
971 KnownZero2.clearAllBits();
972 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
973 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
974 if (RHSUnknownLeadingOnes != BitWidth)
975 LeadZ = std::min(BitWidth,
976 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
978 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
981 case Instruction::Select: {
982 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q);
983 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
987 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
988 if (SelectPatternResult::isMinOrMax(SPF)) {
989 computeKnownBits(RHS, KnownZero, KnownOne, Depth + 1, Q);
990 computeKnownBits(LHS, KnownZero2, KnownOne2, Depth + 1, Q);
992 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q);
993 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
996 unsigned MaxHighOnes = 0;
997 unsigned MaxHighZeros = 0;
998 if (SPF == SPF_SMAX) {
999 // If both sides are negative, the result is negative.
1000 if (KnownOne[BitWidth - 1] && KnownOne2[BitWidth - 1])
1001 // We can derive a lower bound on the result by taking the max of the
1002 // leading one bits.
1004 std::max(KnownOne.countLeadingOnes(), KnownOne2.countLeadingOnes());
1005 // If either side is non-negative, the result is non-negative.
1006 else if (KnownZero[BitWidth - 1] || KnownZero2[BitWidth - 1])
1008 } else if (SPF == SPF_SMIN) {
1009 // If both sides are non-negative, the result is non-negative.
1010 if (KnownZero[BitWidth - 1] && KnownZero2[BitWidth - 1])
1011 // We can derive an upper bound on the result by taking the max of the
1012 // leading zero bits.
1013 MaxHighZeros = std::max(KnownZero.countLeadingOnes(),
1014 KnownZero2.countLeadingOnes());
1015 // If either side is negative, the result is negative.
1016 else if (KnownOne[BitWidth - 1] || KnownOne2[BitWidth - 1])
1018 } else if (SPF == SPF_UMAX) {
1019 // We can derive a lower bound on the result by taking the max of the
1020 // leading one bits.
1022 std::max(KnownOne.countLeadingOnes(), KnownOne2.countLeadingOnes());
1023 } else if (SPF == SPF_UMIN) {
1024 // We can derive an upper bound on the result by taking the max of the
1025 // leading zero bits.
1027 std::max(KnownZero.countLeadingOnes(), KnownZero2.countLeadingOnes());
1030 // Only known if known in both the LHS and RHS.
1031 KnownOne &= KnownOne2;
1032 KnownZero &= KnownZero2;
1033 if (MaxHighOnes > 0)
1034 KnownOne |= APInt::getHighBitsSet(BitWidth, MaxHighOnes);
1035 if (MaxHighZeros > 0)
1036 KnownZero |= APInt::getHighBitsSet(BitWidth, MaxHighZeros);
1039 case Instruction::FPTrunc:
1040 case Instruction::FPExt:
1041 case Instruction::FPToUI:
1042 case Instruction::FPToSI:
1043 case Instruction::SIToFP:
1044 case Instruction::UIToFP:
1045 break; // Can't work with floating point.
1046 case Instruction::PtrToInt:
1047 case Instruction::IntToPtr:
1048 // Fall through and handle them the same as zext/trunc.
1050 case Instruction::ZExt:
1051 case Instruction::Trunc: {
1052 Type *SrcTy = I->getOperand(0)->getType();
1054 unsigned SrcBitWidth;
1055 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1056 // which fall through here.
1057 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
1059 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1060 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1061 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
1062 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1063 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1064 KnownOne = KnownOne.zextOrTrunc(BitWidth);
1065 // Any top bits are known to be zero.
1066 if (BitWidth > SrcBitWidth)
1067 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1070 case Instruction::BitCast: {
1071 Type *SrcTy = I->getOperand(0)->getType();
1072 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
1073 // TODO: For now, not handling conversions like:
1074 // (bitcast i64 %x to <2 x i32>)
1075 !I->getType()->isVectorTy()) {
1076 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1081 case Instruction::SExt: {
1082 // Compute the bits in the result that are not present in the input.
1083 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1085 KnownZero = KnownZero.trunc(SrcBitWidth);
1086 KnownOne = KnownOne.trunc(SrcBitWidth);
1087 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1088 KnownZero = KnownZero.zext(BitWidth);
1089 KnownOne = KnownOne.zext(BitWidth);
1091 // If the sign bit of the input is known set or clear, then we know the
1092 // top bits of the result.
1093 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1094 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1095 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1096 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1099 case Instruction::Shl: {
1100 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1101 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1102 auto KZF = [BitWidth, NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1104 (KnownZero << ShiftAmt) |
1105 APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0.
1106 // If this shift has "nsw" keyword, then the result is either a poison
1107 // value or has the same sign bit as the first operand.
1108 if (NSW && KnownZero.isNegative())
1109 KZResult.setBit(BitWidth - 1);
1113 auto KOF = [BitWidth, NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1114 APInt KOResult = KnownOne << ShiftAmt;
1115 if (NSW && KnownOne.isNegative())
1116 KOResult.setBit(BitWidth - 1);
1120 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1121 KnownZero2, KnownOne2, Depth, Q, KZF,
1125 case Instruction::LShr: {
1126 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1127 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1128 return APIntOps::lshr(KnownZero, ShiftAmt) |
1129 // High bits known zero.
1130 APInt::getHighBitsSet(BitWidth, ShiftAmt);
1133 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1134 return APIntOps::lshr(KnownOne, ShiftAmt);
1137 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1138 KnownZero2, KnownOne2, Depth, Q, KZF,
1142 case Instruction::AShr: {
1143 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1144 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
1145 return APIntOps::ashr(KnownZero, ShiftAmt);
1148 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
1149 return APIntOps::ashr(KnownOne, ShiftAmt);
1152 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
1153 KnownZero2, KnownOne2, Depth, Q, KZF,
1157 case Instruction::Sub: {
1158 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1159 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1160 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1164 case Instruction::Add: {
1165 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1166 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1167 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1171 case Instruction::SRem:
1172 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1173 APInt RA = Rem->getValue().abs();
1174 if (RA.isPowerOf2()) {
1175 APInt LowBits = RA - 1;
1176 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1,
1179 // The low bits of the first operand are unchanged by the srem.
1180 KnownZero = KnownZero2 & LowBits;
1181 KnownOne = KnownOne2 & LowBits;
1183 // If the first operand is non-negative or has all low bits zero, then
1184 // the upper bits are all zero.
1185 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1186 KnownZero |= ~LowBits;
1188 // If the first operand is negative and not all low bits are zero, then
1189 // the upper bits are all one.
1190 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1191 KnownOne |= ~LowBits;
1193 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1197 // The sign bit is the LHS's sign bit, except when the result of the
1198 // remainder is zero.
1199 if (KnownZero.isNonNegative()) {
1200 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1201 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
1203 // If it's known zero, our sign bit is also zero.
1204 if (LHSKnownZero.isNegative())
1205 KnownZero.setBit(BitWidth - 1);
1209 case Instruction::URem: {
1210 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1211 const APInt &RA = Rem->getValue();
1212 if (RA.isPowerOf2()) {
1213 APInt LowBits = (RA - 1);
1214 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1215 KnownZero |= ~LowBits;
1216 KnownOne &= LowBits;
1221 // Since the result is less than or equal to either operand, any leading
1222 // zero bits in either operand must also exist in the result.
1223 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1224 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
1226 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
1227 KnownZero2.countLeadingOnes());
1228 KnownOne.clearAllBits();
1229 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
1233 case Instruction::Alloca: {
1234 const AllocaInst *AI = cast<AllocaInst>(I);
1235 unsigned Align = AI->getAlignment();
1237 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
1240 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1243 case Instruction::GetElementPtr: {
1244 // Analyze all of the subscripts of this getelementptr instruction
1245 // to determine if we can prove known low zero bits.
1246 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1247 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, Depth + 1,
1249 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1251 gep_type_iterator GTI = gep_type_begin(I);
1252 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1253 Value *Index = I->getOperand(i);
1254 if (StructType *STy = GTI.getStructTypeOrNull()) {
1255 // Handle struct member offset arithmetic.
1257 // Handle case when index is vector zeroinitializer
1258 Constant *CIndex = cast<Constant>(Index);
1259 if (CIndex->isZeroValue())
1262 if (CIndex->getType()->isVectorTy())
1263 Index = CIndex->getSplatValue();
1265 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1266 const StructLayout *SL = Q.DL.getStructLayout(STy);
1267 uint64_t Offset = SL->getElementOffset(Idx);
1268 TrailZ = std::min<unsigned>(TrailZ,
1269 countTrailingZeros(Offset));
1271 // Handle array index arithmetic.
1272 Type *IndexedTy = GTI.getIndexedType();
1273 if (!IndexedTy->isSized()) {
1277 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
1278 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1279 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1280 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, Depth + 1, Q);
1281 TrailZ = std::min(TrailZ,
1282 unsigned(countTrailingZeros(TypeSize) +
1283 LocalKnownZero.countTrailingOnes()));
1287 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
1290 case Instruction::PHI: {
1291 const PHINode *P = cast<PHINode>(I);
1292 // Handle the case of a simple two-predecessor recurrence PHI.
1293 // There's a lot more that could theoretically be done here, but
1294 // this is sufficient to catch some interesting cases.
1295 if (P->getNumIncomingValues() == 2) {
1296 for (unsigned i = 0; i != 2; ++i) {
1297 Value *L = P->getIncomingValue(i);
1298 Value *R = P->getIncomingValue(!i);
1299 Operator *LU = dyn_cast<Operator>(L);
1302 unsigned Opcode = LU->getOpcode();
1303 // Check for operations that have the property that if
1304 // both their operands have low zero bits, the result
1305 // will have low zero bits.
1306 if (Opcode == Instruction::Add ||
1307 Opcode == Instruction::Sub ||
1308 Opcode == Instruction::And ||
1309 Opcode == Instruction::Or ||
1310 Opcode == Instruction::Mul) {
1311 Value *LL = LU->getOperand(0);
1312 Value *LR = LU->getOperand(1);
1313 // Find a recurrence.
1320 // Ok, we have a PHI of the form L op= R. Check for low
1322 computeKnownBits(R, KnownZero2, KnownOne2, Depth + 1, Q);
1324 // We need to take the minimum number of known bits
1325 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
1326 computeKnownBits(L, KnownZero3, KnownOne3, Depth + 1, Q);
1328 KnownZero = APInt::getLowBitsSet(
1329 BitWidth, std::min(KnownZero2.countTrailingOnes(),
1330 KnownZero3.countTrailingOnes()));
1332 if (DontImproveNonNegativePhiBits)
1335 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1336 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1337 // If initial value of recurrence is nonnegative, and we are adding
1338 // a nonnegative number with nsw, the result can only be nonnegative
1339 // or poison value regardless of the number of times we execute the
1340 // add in phi recurrence. If initial value is negative and we are
1341 // adding a negative number with nsw, the result can only be
1342 // negative or poison value. Similar arguments apply to sub and mul.
1344 // (add non-negative, non-negative) --> non-negative
1345 // (add negative, negative) --> negative
1346 if (Opcode == Instruction::Add) {
1347 if (KnownZero2.isNegative() && KnownZero3.isNegative())
1348 KnownZero.setBit(BitWidth - 1);
1349 else if (KnownOne2.isNegative() && KnownOne3.isNegative())
1350 KnownOne.setBit(BitWidth - 1);
1353 // (sub nsw non-negative, negative) --> non-negative
1354 // (sub nsw negative, non-negative) --> negative
1355 else if (Opcode == Instruction::Sub && LL == I) {
1356 if (KnownZero2.isNegative() && KnownOne3.isNegative())
1357 KnownZero.setBit(BitWidth - 1);
1358 else if (KnownOne2.isNegative() && KnownZero3.isNegative())
1359 KnownOne.setBit(BitWidth - 1);
1362 // (mul nsw non-negative, non-negative) --> non-negative
1363 else if (Opcode == Instruction::Mul && KnownZero2.isNegative() &&
1364 KnownZero3.isNegative())
1365 KnownZero.setBit(BitWidth - 1);
1373 // Unreachable blocks may have zero-operand PHI nodes.
1374 if (P->getNumIncomingValues() == 0)
1377 // Otherwise take the unions of the known bit sets of the operands,
1378 // taking conservative care to avoid excessive recursion.
1379 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
1380 // Skip if every incoming value references to ourself.
1381 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
1384 KnownZero = APInt::getAllOnesValue(BitWidth);
1385 KnownOne = APInt::getAllOnesValue(BitWidth);
1386 for (Value *IncValue : P->incoming_values()) {
1387 // Skip direct self references.
1388 if (IncValue == P) continue;
1390 KnownZero2 = APInt(BitWidth, 0);
1391 KnownOne2 = APInt(BitWidth, 0);
1392 // Recurse, but cap the recursion to one level, because we don't
1393 // want to waste time spinning around in loops.
1394 computeKnownBits(IncValue, KnownZero2, KnownOne2, MaxDepth - 1, Q);
1395 KnownZero &= KnownZero2;
1396 KnownOne &= KnownOne2;
1397 // If all bits have been ruled out, there's no need to check
1399 if (!KnownZero && !KnownOne)
1405 case Instruction::Call:
1406 case Instruction::Invoke:
1407 // If range metadata is attached to this call, set known bits from that,
1408 // and then intersect with known bits based on other properties of the
1410 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
1411 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
1412 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
1413 computeKnownBits(RV, KnownZero2, KnownOne2, Depth + 1, Q);
1414 KnownZero |= KnownZero2;
1415 KnownOne |= KnownOne2;
1417 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1418 switch (II->getIntrinsicID()) {
1420 case Intrinsic::bswap:
1421 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1422 KnownZero |= KnownZero2.byteSwap();
1423 KnownOne |= KnownOne2.byteSwap();
1425 case Intrinsic::ctlz:
1426 case Intrinsic::cttz: {
1427 unsigned LowBits = Log2_32(BitWidth)+1;
1428 // If this call is undefined for 0, the result will be less than 2^n.
1429 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1431 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1434 case Intrinsic::ctpop: {
1435 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
1436 // We can bound the space the count needs. Also, bits known to be zero
1437 // can't contribute to the population.
1438 unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation();
1439 unsigned LeadingZeros =
1440 APInt(BitWidth, BitsPossiblySet).countLeadingZeros();
1441 assert(LeadingZeros <= BitWidth);
1442 KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros);
1443 KnownOne &= ~KnownZero;
1444 // TODO: we could bound KnownOne using the lower bound on the number
1445 // of bits which might be set provided by popcnt KnownOne2.
1448 case Intrinsic::x86_sse42_crc32_64_64:
1449 KnownZero |= APInt::getHighBitsSet(64, 32);
1454 case Instruction::ExtractElement:
1455 // Look through extract element. At the moment we keep this simple and skip
1456 // tracking the specific element. But at least we might find information
1457 // valid for all elements of the vector (for example if vector is sign
1458 // extended, shifted, etc).
1459 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
1461 case Instruction::ExtractValue:
1462 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1463 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1464 if (EVI->getNumIndices() != 1) break;
1465 if (EVI->getIndices()[0] == 0) {
1466 switch (II->getIntrinsicID()) {
1468 case Intrinsic::uadd_with_overflow:
1469 case Intrinsic::sadd_with_overflow:
1470 computeKnownBitsAddSub(true, II->getArgOperand(0),
1471 II->getArgOperand(1), false, KnownZero,
1472 KnownOne, KnownZero2, KnownOne2, Depth, Q);
1474 case Intrinsic::usub_with_overflow:
1475 case Intrinsic::ssub_with_overflow:
1476 computeKnownBitsAddSub(false, II->getArgOperand(0),
1477 II->getArgOperand(1), false, KnownZero,
1478 KnownOne, KnownZero2, KnownOne2, Depth, Q);
1480 case Intrinsic::umul_with_overflow:
1481 case Intrinsic::smul_with_overflow:
1482 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1483 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
1492 /// Determine which bits of V are known to be either zero or one and return
1493 /// them in the KnownZero/KnownOne bit sets.
1495 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1496 /// we cannot optimize based on the assumption that it is zero without changing
1497 /// it to be an explicit zero. If we don't change it to zero, other code could
1498 /// optimized based on the contradictory assumption that it is non-zero.
1499 /// Because instcombine aggressively folds operations with undef args anyway,
1500 /// this won't lose us code quality.
1502 /// This function is defined on values with integer type, values with pointer
1503 /// type, and vectors of integers. In the case
1504 /// where V is a vector, known zero, and known one values are the
1505 /// same width as the vector element, and the bit is set only if it is true
1506 /// for all of the elements in the vector.
1507 void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne,
1508 unsigned Depth, const Query &Q) {
1509 assert(V && "No Value?");
1510 assert(Depth <= MaxDepth && "Limit Search Depth");
1511 unsigned BitWidth = KnownZero.getBitWidth();
1513 assert((V->getType()->isIntOrIntVectorTy() ||
1514 V->getType()->getScalarType()->isPointerTy()) &&
1515 "Not integer or pointer type!");
1516 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
1517 (!V->getType()->isIntOrIntVectorTy() ||
1518 V->getType()->getScalarSizeInBits() == BitWidth) &&
1519 KnownZero.getBitWidth() == BitWidth &&
1520 KnownOne.getBitWidth() == BitWidth &&
1521 "V, KnownOne and KnownZero should have same BitWidth");
1524 if (match(V, m_APInt(C))) {
1525 // We know all of the bits for a scalar constant or a splat vector constant!
1527 KnownZero = ~KnownOne;
1530 // Null and aggregate-zero are all-zeros.
1531 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1532 KnownOne.clearAllBits();
1533 KnownZero = APInt::getAllOnesValue(BitWidth);
1536 // Handle a constant vector by taking the intersection of the known bits of
1538 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
1539 // We know that CDS must be a vector of integers. Take the intersection of
1541 KnownZero.setAllBits(); KnownOne.setAllBits();
1542 APInt Elt(KnownZero.getBitWidth(), 0);
1543 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1544 Elt = CDS->getElementAsInteger(i);
1551 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1552 // We know that CV must be a vector of integers. Take the intersection of
1554 KnownZero.setAllBits(); KnownOne.setAllBits();
1555 APInt Elt(KnownZero.getBitWidth(), 0);
1556 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1557 Constant *Element = CV->getAggregateElement(i);
1558 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1560 KnownZero.clearAllBits();
1561 KnownOne.clearAllBits();
1564 Elt = ElementCI->getValue();
1571 // Start out not knowing anything.
1572 KnownZero.clearAllBits(); KnownOne.clearAllBits();
1574 // We can't imply anything about undefs.
1575 if (isa<UndefValue>(V))
1578 // There's no point in looking through other users of ConstantData for
1579 // assumptions. Confirm that we've handled them all.
1580 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1582 // Limit search depth.
1583 // All recursive calls that increase depth must come after this.
1584 if (Depth == MaxDepth)
1587 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1588 // the bits of its aliasee.
1589 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1590 if (!GA->isInterposable())
1591 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, Depth + 1, Q);
1595 if (const Operator *I = dyn_cast<Operator>(V))
1596 computeKnownBitsFromOperator(I, KnownZero, KnownOne, Depth, Q);
1598 // Aligned pointers have trailing zeros - refine KnownZero set
1599 if (V->getType()->isPointerTy()) {
1600 unsigned Align = V->getPointerAlignment(Q.DL);
1602 KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
1605 // computeKnownBitsFromAssume strictly refines KnownZero and
1606 // KnownOne. Therefore, we run them after computeKnownBitsFromOperator.
1608 // Check whether a nearby assume intrinsic can determine some known bits.
1609 computeKnownBitsFromAssume(V, KnownZero, KnownOne, Depth, Q);
1611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1614 /// Determine whether the sign bit is known to be zero or one.
1615 /// Convenience wrapper around computeKnownBits.
1616 void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
1617 unsigned Depth, const Query &Q) {
1618 unsigned BitWidth = getBitWidth(V->getType(), Q.DL);
1624 APInt ZeroBits(BitWidth, 0);
1625 APInt OneBits(BitWidth, 0);
1626 computeKnownBits(V, ZeroBits, OneBits, Depth, Q);
1627 KnownOne = OneBits[BitWidth - 1];
1628 KnownZero = ZeroBits[BitWidth - 1];
1631 /// Return true if the given value is known to have exactly one
1632 /// bit set when defined. For vectors return true if every element is known to
1633 /// be a power of two when defined. Supports values with integer or pointer
1634 /// types and vectors of integers.
1635 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1637 if (const Constant *C = dyn_cast<Constant>(V)) {
1638 if (C->isNullValue())
1641 const APInt *ConstIntOrConstSplatInt;
1642 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1643 return ConstIntOrConstSplatInt->isPowerOf2();
1646 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1647 // it is shifted off the end then the result is undefined.
1648 if (match(V, m_Shl(m_One(), m_Value())))
1651 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1652 // bottom. If it is shifted off the bottom then the result is undefined.
1653 if (match(V, m_LShr(m_SignBit(), m_Value())))
1656 // The remaining tests are all recursive, so bail out if we hit the limit.
1657 if (Depth++ == MaxDepth)
1660 Value *X = nullptr, *Y = nullptr;
1661 // A shift left or a logical shift right of a power of two is a power of two
1663 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1664 match(V, m_LShr(m_Value(X), m_Value()))))
1665 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
1667 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
1668 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
1670 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
1671 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1672 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
1674 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1675 // A power of two and'd with anything is a power of two or zero.
1676 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1677 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
1679 // X & (-X) is always a power of two or zero.
1680 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1685 // Adding a power-of-two or zero to the same power-of-two or zero yields
1686 // either the original power-of-two, a larger power-of-two or zero.
1687 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1688 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1689 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1690 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1691 match(X, m_And(m_Value(), m_Specific(Y))))
1692 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
1694 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1695 match(Y, m_And(m_Value(), m_Specific(X))))
1696 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
1699 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1700 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
1701 computeKnownBits(X, LHSZeroBits, LHSOneBits, Depth, Q);
1703 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
1704 computeKnownBits(Y, RHSZeroBits, RHSOneBits, Depth, Q);
1705 // If i8 V is a power of two or zero:
1706 // ZeroBits: 1 1 1 0 1 1 1 1
1707 // ~ZeroBits: 0 0 0 1 0 0 0 0
1708 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1709 // If OrZero isn't set, we cannot give back a zero result.
1710 // Make sure either the LHS or RHS has a bit set.
1711 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1716 // An exact divide or right shift can only shift off zero bits, so the result
1717 // is a power of two only if the first operand is a power of two and not
1718 // copying a sign bit (sdiv int_min, 2).
1719 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1720 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
1721 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
1728 /// \brief Test whether a GEP's result is known to be non-null.
1730 /// Uses properties inherent in a GEP to try to determine whether it is known
1733 /// Currently this routine does not support vector GEPs.
1734 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
1736 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1739 // FIXME: Support vector-GEPs.
1740 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1742 // If the base pointer is non-null, we cannot walk to a null address with an
1743 // inbounds GEP in address space zero.
1744 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
1747 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1748 // If so, then the GEP cannot produce a null pointer, as doing so would
1749 // inherently violate the inbounds contract within address space zero.
1750 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1751 GTI != GTE; ++GTI) {
1752 // Struct types are easy -- they must always be indexed by a constant.
1753 if (StructType *STy = GTI.getStructTypeOrNull()) {
1754 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1755 unsigned ElementIdx = OpC->getZExtValue();
1756 const StructLayout *SL = Q.DL.getStructLayout(STy);
1757 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1758 if (ElementOffset > 0)
1763 // If we have a zero-sized type, the index doesn't matter. Keep looping.
1764 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
1767 // Fast path the constant operand case both for efficiency and so we don't
1768 // increment Depth when just zipping down an all-constant GEP.
1769 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1775 // We post-increment Depth here because while isKnownNonZero increments it
1776 // as well, when we pop back up that increment won't persist. We don't want
1777 // to recurse 10k times just because we have 10k GEP operands. We don't
1778 // bail completely out because we want to handle constant GEPs regardless
1780 if (Depth++ >= MaxDepth)
1783 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
1790 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
1791 /// ensure that the value it's attached to is never Value? 'RangeType' is
1792 /// is the type of the value described by the range.
1793 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
1794 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1795 assert(NumRanges >= 1);
1796 for (unsigned i = 0; i < NumRanges; ++i) {
1797 ConstantInt *Lower =
1798 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1799 ConstantInt *Upper =
1800 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
1801 ConstantRange Range(Lower->getValue(), Upper->getValue());
1802 if (Range.contains(Value))
1808 /// Return true if the given value is known to be non-zero when defined.
1809 /// For vectors return true if every element is known to be non-zero when
1810 /// defined. Supports values with integer or pointer type and vectors of
1812 bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
1813 if (auto *C = dyn_cast<Constant>(V)) {
1814 if (C->isNullValue())
1816 if (isa<ConstantInt>(C))
1817 // Must be non-zero due to null test above.
1820 // For constant vectors, check that all elements are undefined or known
1821 // non-zero to determine that the whole vector is known non-zero.
1822 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1823 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1824 Constant *Elt = C->getAggregateElement(i);
1825 if (!Elt || Elt->isNullValue())
1827 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1836 if (auto *I = dyn_cast<Instruction>(V)) {
1837 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
1838 // If the possible ranges don't contain zero, then the value is
1839 // definitely non-zero.
1840 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
1841 const APInt ZeroValue(Ty->getBitWidth(), 0);
1842 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1848 // The remaining tests are all recursive, so bail out if we hit the limit.
1849 if (Depth++ >= MaxDepth)
1852 // Check for pointer simplifications.
1853 if (V->getType()->isPointerTy()) {
1854 if (isKnownNonNull(V))
1856 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
1857 if (isGEPKnownNonNull(GEP, Depth, Q))
1861 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
1863 // X | Y != 0 if X != 0 or Y != 0.
1864 Value *X = nullptr, *Y = nullptr;
1865 if (match(V, m_Or(m_Value(X), m_Value(Y))))
1866 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
1868 // ext X != 0 if X != 0.
1869 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
1870 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
1872 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
1873 // if the lowest bit is shifted off the end.
1874 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
1875 // shl nuw can't remove any non-zero bits.
1876 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1877 if (BO->hasNoUnsignedWrap())
1878 return isKnownNonZero(X, Depth, Q);
1880 APInt KnownZero(BitWidth, 0);
1881 APInt KnownOne(BitWidth, 0);
1882 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1886 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
1887 // defined if the sign bit is shifted off the end.
1888 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
1889 // shr exact can only shift out zero bits.
1890 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
1892 return isKnownNonZero(X, Depth, Q);
1894 bool XKnownNonNegative, XKnownNegative;
1895 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1899 // If the shifter operand is a constant, and all of the bits shifted
1900 // out are known to be zero, and X is known non-zero then at least one
1901 // non-zero bit must remain.
1902 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
1903 APInt KnownZero(BitWidth, 0);
1904 APInt KnownOne(BitWidth, 0);
1905 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1907 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1908 // Is there a known one in the portion not shifted out?
1909 if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal)
1911 // Are all the bits to be shifted out known zero?
1912 if (KnownZero.countTrailingOnes() >= ShiftVal)
1913 return isKnownNonZero(X, Depth, Q);
1916 // div exact can only produce a zero if the dividend is zero.
1917 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
1918 return isKnownNonZero(X, Depth, Q);
1921 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1922 bool XKnownNonNegative, XKnownNegative;
1923 bool YKnownNonNegative, YKnownNegative;
1924 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
1925 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q);
1927 // If X and Y are both non-negative (as signed values) then their sum is not
1928 // zero unless both X and Y are zero.
1929 if (XKnownNonNegative && YKnownNonNegative)
1930 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
1933 // If X and Y are both negative (as signed values) then their sum is not
1934 // zero unless both X and Y equal INT_MIN.
1935 if (BitWidth && XKnownNegative && YKnownNegative) {
1936 APInt KnownZero(BitWidth, 0);
1937 APInt KnownOne(BitWidth, 0);
1938 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1939 // The sign bit of X is set. If some other bit is set then X is not equal
1941 computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
1942 if ((KnownOne & Mask) != 0)
1944 // The sign bit of Y is set. If some other bit is set then Y is not equal
1946 computeKnownBits(Y, KnownZero, KnownOne, Depth, Q);
1947 if ((KnownOne & Mask) != 0)
1951 // The sum of a non-negative number and a power of two is not zero.
1952 if (XKnownNonNegative &&
1953 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
1955 if (YKnownNonNegative &&
1956 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
1960 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1961 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1962 // If X and Y are non-zero then so is X * Y as long as the multiplication
1963 // does not overflow.
1964 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
1965 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
1968 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1969 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
1970 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1971 isKnownNonZero(SI->getFalseValue(), Depth, Q))
1975 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
1976 // Try and detect a recurrence that monotonically increases from a
1977 // starting value, as these are common as induction variables.
1978 if (PN->getNumIncomingValues() == 2) {
1979 Value *Start = PN->getIncomingValue(0);
1980 Value *Induction = PN->getIncomingValue(1);
1981 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1982 std::swap(Start, Induction);
1983 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1984 if (!C->isZero() && !C->isNegative()) {
1986 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1987 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1993 // Check if all incoming values are non-zero constant.
1994 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1995 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
1997 if (AllNonZeroConstants)
2001 if (!BitWidth) return false;
2002 APInt KnownZero(BitWidth, 0);
2003 APInt KnownOne(BitWidth, 0);
2004 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2005 return KnownOne != 0;
2008 /// Return true if V2 == V1 + X, where X is known non-zero.
2009 static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2010 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2011 if (!BO || BO->getOpcode() != Instruction::Add)
2013 Value *Op = nullptr;
2014 if (V2 == BO->getOperand(0))
2015 Op = BO->getOperand(1);
2016 else if (V2 == BO->getOperand(1))
2017 Op = BO->getOperand(0);
2020 return isKnownNonZero(Op, 0, Q);
2023 /// Return true if it is known that V1 != V2.
2024 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
2025 if (V1->getType()->isVectorTy() || V1 == V2)
2027 if (V1->getType() != V2->getType())
2028 // We can't look through casts yet.
2030 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
2033 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
2034 // Are any known bits in V1 contradictory to known bits in V2? If V1
2035 // has a known zero where V2 has a known one, they must not be equal.
2036 auto BitWidth = Ty->getBitWidth();
2037 APInt KnownZero1(BitWidth, 0);
2038 APInt KnownOne1(BitWidth, 0);
2039 computeKnownBits(V1, KnownZero1, KnownOne1, 0, Q);
2040 APInt KnownZero2(BitWidth, 0);
2041 APInt KnownOne2(BitWidth, 0);
2042 computeKnownBits(V2, KnownZero2, KnownOne2, 0, Q);
2044 auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1);
2045 if (OppositeBits.getBoolValue())
2051 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
2052 /// simplify operations downstream. Mask is known to be zero for bits that V
2055 /// This function is defined on values with integer type, values with pointer
2056 /// type, and vectors of integers. In the case
2057 /// where V is a vector, the mask, known zero, and known one values are the
2058 /// same width as the vector element, and the bit is set only if it is true
2059 /// for all of the elements in the vector.
2060 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2062 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
2063 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2064 return (KnownZero & Mask) == Mask;
2067 /// For vector constants, loop over the elements and find the constant with the
2068 /// minimum number of sign bits. Return 0 if the value is not a vector constant
2069 /// or if any element was not analyzed; otherwise, return the count for the
2070 /// element with the minimum number of sign bits.
2071 static unsigned computeNumSignBitsVectorConstant(const Value *V,
2073 const auto *CV = dyn_cast<Constant>(V);
2074 if (!CV || !CV->getType()->isVectorTy())
2077 unsigned MinSignBits = TyBits;
2078 unsigned NumElts = CV->getType()->getVectorNumElements();
2079 for (unsigned i = 0; i != NumElts; ++i) {
2080 // If we find a non-ConstantInt, bail out.
2081 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2085 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2086 APInt EltVal = Elt->getValue();
2087 if (EltVal.isNegative())
2089 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2095 /// Return the number of times the sign bit of the register is replicated into
2096 /// the other bits. We know that at least 1 bit is always equal to the sign bit
2097 /// (itself), but other cases can give us information. For example, immediately
2098 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
2099 /// other, so we return 3. For vectors, return the number of sign bits for the
2100 /// vector element with the mininum number of known sign bits.
2101 unsigned ComputeNumSignBits(const Value *V, unsigned Depth, const Query &Q) {
2102 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
2104 unsigned FirstAnswer = 1;
2106 // Note that ConstantInt is handled by the general computeKnownBits case
2109 if (Depth == MaxDepth)
2110 return 1; // Limit search depth.
2112 const Operator *U = dyn_cast<Operator>(V);
2113 switch (Operator::getOpcode(V)) {
2115 case Instruction::SExt:
2116 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
2117 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
2119 case Instruction::SDiv: {
2120 const APInt *Denominator;
2121 // sdiv X, C -> adds log(C) sign bits.
2122 if (match(U->getOperand(1), m_APInt(Denominator))) {
2124 // Ignore non-positive denominator.
2125 if (!Denominator->isStrictlyPositive())
2128 // Calculate the incoming numerator bits.
2129 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2131 // Add floor(log(C)) bits to the numerator bits.
2132 return std::min(TyBits, NumBits + Denominator->logBase2());
2137 case Instruction::SRem: {
2138 const APInt *Denominator;
2139 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2140 // positive constant. This let us put a lower bound on the number of sign
2142 if (match(U->getOperand(1), m_APInt(Denominator))) {
2144 // Ignore non-positive denominator.
2145 if (!Denominator->isStrictlyPositive())
2148 // Calculate the incoming numerator bits. SRem by a positive constant
2149 // can't lower the number of sign bits.
2151 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2153 // Calculate the leading sign bit constraints by examining the
2154 // denominator. Given that the denominator is positive, there are two
2157 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2158 // (1 << ceilLogBase2(C)).
2160 // 2. the numerator is negative. Then the result range is (-C,0] and
2161 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2163 // Thus a lower bound on the number of sign bits is `TyBits -
2164 // ceilLogBase2(C)`.
2166 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
2167 return std::max(NumrBits, ResBits);
2172 case Instruction::AShr: {
2173 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2174 // ashr X, C -> adds C sign bits. Vectors too.
2176 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2177 Tmp += ShAmt->getZExtValue();
2178 if (Tmp > TyBits) Tmp = TyBits;
2182 case Instruction::Shl: {
2184 if (match(U->getOperand(1), m_APInt(ShAmt))) {
2185 // shl destroys sign bits.
2186 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2187 Tmp2 = ShAmt->getZExtValue();
2188 if (Tmp2 >= TyBits || // Bad shift.
2189 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2194 case Instruction::And:
2195 case Instruction::Or:
2196 case Instruction::Xor: // NOT is handled here.
2197 // Logical binary ops preserve the number of sign bits at the worst.
2198 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2200 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2201 FirstAnswer = std::min(Tmp, Tmp2);
2202 // We computed what we know about the sign bits as our first
2203 // answer. Now proceed to the generic code that uses
2204 // computeKnownBits, and pick whichever answer is better.
2208 case Instruction::Select:
2209 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2210 if (Tmp == 1) return 1; // Early out.
2211 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
2212 return std::min(Tmp, Tmp2);
2214 case Instruction::Add:
2215 // Add can have at most one carry bit. Thus we know that the output
2216 // is, at worst, one more bit than the inputs.
2217 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2218 if (Tmp == 1) return 1; // Early out.
2220 // Special case decrementing a value (ADD X, -1):
2221 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
2222 if (CRHS->isAllOnesValue()) {
2223 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2224 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
2226 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2228 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2231 // If we are subtracting one from a positive number, there is no carry
2232 // out of the result.
2233 if (KnownZero.isNegative())
2237 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2238 if (Tmp2 == 1) return 1;
2239 return std::min(Tmp, Tmp2)-1;
2241 case Instruction::Sub:
2242 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2243 if (Tmp2 == 1) return 1;
2246 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
2247 if (CLHS->isNullValue()) {
2248 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2249 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
2250 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2252 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
2255 // If the input is known to be positive (the sign bit is known clear),
2256 // the output of the NEG has the same number of sign bits as the input.
2257 if (KnownZero.isNegative())
2260 // Otherwise, we treat this like a SUB.
2263 // Sub can have at most one carry bit. Thus we know that the output
2264 // is, at worst, one more bit than the inputs.
2265 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2266 if (Tmp == 1) return 1; // Early out.
2267 return std::min(Tmp, Tmp2)-1;
2269 case Instruction::PHI: {
2270 const PHINode *PN = cast<PHINode>(U);
2271 unsigned NumIncomingValues = PN->getNumIncomingValues();
2272 // Don't analyze large in-degree PHIs.
2273 if (NumIncomingValues > 4) break;
2274 // Unreachable blocks may have zero-operand PHI nodes.
2275 if (NumIncomingValues == 0) break;
2277 // Take the minimum of all incoming values. This can't infinitely loop
2278 // because of our depth threshold.
2279 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
2280 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
2281 if (Tmp == 1) return Tmp;
2283 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
2288 case Instruction::Trunc:
2289 // FIXME: it's tricky to do anything useful for this, but it is an important
2290 // case for targets like X86.
2293 case Instruction::ExtractElement:
2294 // Look through extract element. At the moment we keep this simple and skip
2295 // tracking the specific element. But at least we might find information
2296 // valid for all elements of the vector (for example if vector is sign
2297 // extended, shifted, etc).
2298 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2301 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2302 // use this information.
2304 // If we can examine all elements of a vector constant successfully, we're
2305 // done (we can't do any better than that). If not, keep trying.
2306 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2309 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2310 computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
2312 // If we know that the sign bit is either zero or one, determine the number of
2313 // identical bits in the top of the input value.
2314 if (KnownZero.isNegative())
2315 return std::max(FirstAnswer, KnownZero.countLeadingOnes());
2317 if (KnownOne.isNegative())
2318 return std::max(FirstAnswer, KnownOne.countLeadingOnes());
2320 // computeKnownBits gave us no extra information about the top bits.
2324 /// This function computes the integer multiple of Base that equals V.
2325 /// If successful, it returns true and returns the multiple in
2326 /// Multiple. If unsuccessful, it returns false. It looks
2327 /// through SExt instructions only if LookThroughSExt is true.
2328 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
2329 bool LookThroughSExt, unsigned Depth) {
2330 const unsigned MaxDepth = 6;
2332 assert(V && "No Value?");
2333 assert(Depth <= MaxDepth && "Limit Search Depth");
2334 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
2336 Type *T = V->getType();
2338 ConstantInt *CI = dyn_cast<ConstantInt>(V);
2348 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2349 Constant *BaseVal = ConstantInt::get(T, Base);
2350 if (CO && CO == BaseVal) {
2352 Multiple = ConstantInt::get(T, 1);
2356 if (CI && CI->getZExtValue() % Base == 0) {
2357 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
2361 if (Depth == MaxDepth) return false; // Limit search depth.
2363 Operator *I = dyn_cast<Operator>(V);
2364 if (!I) return false;
2366 switch (I->getOpcode()) {
2368 case Instruction::SExt:
2369 if (!LookThroughSExt) return false;
2370 // otherwise fall through to ZExt
2371 case Instruction::ZExt:
2372 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2373 LookThroughSExt, Depth+1);
2374 case Instruction::Shl:
2375 case Instruction::Mul: {
2376 Value *Op0 = I->getOperand(0);
2377 Value *Op1 = I->getOperand(1);
2379 if (I->getOpcode() == Instruction::Shl) {
2380 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2381 if (!Op1CI) return false;
2382 // Turn Op0 << Op1 into Op0 * 2^Op1
2383 APInt Op1Int = Op1CI->getValue();
2384 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
2385 APInt API(Op1Int.getBitWidth(), 0);
2386 API.setBit(BitToSet);
2387 Op1 = ConstantInt::get(V->getContext(), API);
2390 Value *Mul0 = nullptr;
2391 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2392 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2393 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
2394 if (Op1C->getType()->getPrimitiveSizeInBits() <
2395 MulC->getType()->getPrimitiveSizeInBits())
2396 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
2397 if (Op1C->getType()->getPrimitiveSizeInBits() >
2398 MulC->getType()->getPrimitiveSizeInBits())
2399 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
2401 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2402 Multiple = ConstantExpr::getMul(MulC, Op1C);
2406 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2407 if (Mul0CI->getValue() == 1) {
2408 // V == Base * Op1, so return Op1
2414 Value *Mul1 = nullptr;
2415 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2416 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2417 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
2418 if (Op0C->getType()->getPrimitiveSizeInBits() <
2419 MulC->getType()->getPrimitiveSizeInBits())
2420 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
2421 if (Op0C->getType()->getPrimitiveSizeInBits() >
2422 MulC->getType()->getPrimitiveSizeInBits())
2423 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
2425 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2426 Multiple = ConstantExpr::getMul(MulC, Op0C);
2430 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2431 if (Mul1CI->getValue() == 1) {
2432 // V == Base * Op0, so return Op0
2440 // We could not determine if V is a multiple of Base.
2444 Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2445 const TargetLibraryInfo *TLI) {
2446 const Function *F = ICS.getCalledFunction();
2448 return Intrinsic::not_intrinsic;
2450 if (F->isIntrinsic())
2451 return F->getIntrinsicID();
2454 return Intrinsic::not_intrinsic;
2457 // We're going to make assumptions on the semantics of the functions, check
2458 // that the target knows that it's available in this environment and it does
2459 // not have local linkage.
2460 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2461 return Intrinsic::not_intrinsic;
2463 if (!ICS.onlyReadsMemory())
2464 return Intrinsic::not_intrinsic;
2466 // Otherwise check if we have a call to a function that can be turned into a
2467 // vector intrinsic.
2474 return Intrinsic::sin;
2478 return Intrinsic::cos;
2482 return Intrinsic::exp;
2484 case LibFunc::exp2f:
2485 case LibFunc::exp2l:
2486 return Intrinsic::exp2;
2490 return Intrinsic::log;
2491 case LibFunc::log10:
2492 case LibFunc::log10f:
2493 case LibFunc::log10l:
2494 return Intrinsic::log10;
2496 case LibFunc::log2f:
2497 case LibFunc::log2l:
2498 return Intrinsic::log2;
2500 case LibFunc::fabsf:
2501 case LibFunc::fabsl:
2502 return Intrinsic::fabs;
2504 case LibFunc::fminf:
2505 case LibFunc::fminl:
2506 return Intrinsic::minnum;
2508 case LibFunc::fmaxf:
2509 case LibFunc::fmaxl:
2510 return Intrinsic::maxnum;
2511 case LibFunc::copysign:
2512 case LibFunc::copysignf:
2513 case LibFunc::copysignl:
2514 return Intrinsic::copysign;
2515 case LibFunc::floor:
2516 case LibFunc::floorf:
2517 case LibFunc::floorl:
2518 return Intrinsic::floor;
2520 case LibFunc::ceilf:
2521 case LibFunc::ceill:
2522 return Intrinsic::ceil;
2523 case LibFunc::trunc:
2524 case LibFunc::truncf:
2525 case LibFunc::truncl:
2526 return Intrinsic::trunc;
2528 case LibFunc::rintf:
2529 case LibFunc::rintl:
2530 return Intrinsic::rint;
2531 case LibFunc::nearbyint:
2532 case LibFunc::nearbyintf:
2533 case LibFunc::nearbyintl:
2534 return Intrinsic::nearbyint;
2535 case LibFunc::round:
2536 case LibFunc::roundf:
2537 case LibFunc::roundl:
2538 return Intrinsic::round;
2542 return Intrinsic::pow;
2544 case LibFunc::sqrtf:
2545 case LibFunc::sqrtl:
2546 if (ICS->hasNoNaNs())
2547 return Intrinsic::sqrt;
2548 return Intrinsic::not_intrinsic;
2551 return Intrinsic::not_intrinsic;
2554 /// Return true if we can prove that the specified FP value is never equal to
2557 /// NOTE: this function will need to be revisited when we support non-default
2560 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2562 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2563 return !CFP->getValueAPF().isNegZero();
2565 if (Depth == MaxDepth)
2566 return false; // Limit search depth.
2568 const Operator *I = dyn_cast<Operator>(V);
2569 if (!I) return false;
2571 // Check if the nsz fast-math flag is set
2572 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2573 if (FPO->hasNoSignedZeros())
2576 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2577 if (I->getOpcode() == Instruction::FAdd)
2578 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2579 if (CFP->isNullValue())
2582 // sitofp and uitofp turn into +0.0 for zero.
2583 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2586 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
2587 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
2591 // sqrt(-0.0) = -0.0, no other negative results are possible.
2592 case Intrinsic::sqrt:
2593 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2595 case Intrinsic::fabs:
2603 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2604 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2605 /// bit despite comparing equal.
2606 static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2607 const TargetLibraryInfo *TLI,
2610 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2611 return !CFP->getValueAPF().isNegative() ||
2612 (!SignBitOnly && CFP->getValueAPF().isZero());
2615 if (Depth == MaxDepth)
2616 return false; // Limit search depth.
2618 const Operator *I = dyn_cast<Operator>(V);
2622 switch (I->getOpcode()) {
2625 // Unsigned integers are always nonnegative.
2626 case Instruction::UIToFP:
2628 case Instruction::FMul:
2629 // x*x is always non-negative or a NaN.
2630 if (I->getOperand(0) == I->getOperand(1) &&
2631 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
2635 case Instruction::FAdd:
2636 case Instruction::FDiv:
2637 case Instruction::FRem:
2638 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2640 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2642 case Instruction::Select:
2643 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2645 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2647 case Instruction::FPExt:
2648 case Instruction::FPTrunc:
2649 // Widening/narrowing never change sign.
2650 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2652 case Instruction::Call:
2653 Intrinsic::ID IID = getIntrinsicForCallSite(cast<CallInst>(I), TLI);
2657 case Intrinsic::maxnum:
2658 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2660 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2662 case Intrinsic::minnum:
2663 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2665 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2667 case Intrinsic::exp:
2668 case Intrinsic::exp2:
2669 case Intrinsic::fabs:
2670 case Intrinsic::sqrt:
2672 case Intrinsic::powi:
2673 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2674 // powi(x,n) is non-negative if n is even.
2675 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2678 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2680 case Intrinsic::fma:
2681 case Intrinsic::fmuladd:
2682 // x*x+y is non-negative if y is non-negative.
2683 return I->getOperand(0) == I->getOperand(1) &&
2684 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2685 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2693 bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2694 const TargetLibraryInfo *TLI) {
2695 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2698 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2699 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2702 /// If the specified value can be set by repeating the same byte in memory,
2703 /// return the i8 value that it is represented with. This is
2704 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2705 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2706 /// byte store (e.g. i16 0x1234), return null.
2707 Value *llvm::isBytewiseValue(Value *V) {
2708 // All byte-wide stores are splatable, even of arbitrary variables.
2709 if (V->getType()->isIntegerTy(8)) return V;
2711 // Handle 'null' ConstantArrayZero etc.
2712 if (Constant *C = dyn_cast<Constant>(V))
2713 if (C->isNullValue())
2714 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
2716 // Constant float and double values can be handled as integer values if the
2717 // corresponding integer value is "byteable". An important case is 0.0.
2718 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2719 if (CFP->getType()->isFloatTy())
2720 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2721 if (CFP->getType()->isDoubleTy())
2722 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2723 // Don't handle long double formats, which have strange constraints.
2726 // We can handle constant integers that are multiple of 8 bits.
2727 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2728 if (CI->getBitWidth() % 8 == 0) {
2729 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
2731 if (!CI->getValue().isSplat(8))
2733 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
2737 // A ConstantDataArray/Vector is splatable if all its members are equal and
2739 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2740 Value *Elt = CA->getElementAsConstant(0);
2741 Value *Val = isBytewiseValue(Elt);
2745 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2746 if (CA->getElementAsConstant(I) != Elt)
2752 // Conceptually, we could handle things like:
2753 // %a = zext i8 %X to i16
2754 // %b = shl i16 %a, 8
2755 // %c = or i16 %a, %b
2756 // but until there is an example that actually needs this, it doesn't seem
2757 // worth worrying about.
2762 // This is the recursive version of BuildSubAggregate. It takes a few different
2763 // arguments. Idxs is the index within the nested struct From that we are
2764 // looking at now (which is of type IndexedType). IdxSkip is the number of
2765 // indices from Idxs that should be left out when inserting into the resulting
2766 // struct. To is the result struct built so far, new insertvalue instructions
2768 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
2769 SmallVectorImpl<unsigned> &Idxs,
2771 Instruction *InsertBefore) {
2772 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
2774 // Save the original To argument so we can modify it
2776 // General case, the type indexed by Idxs is a struct
2777 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2778 // Process each struct element recursively
2781 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
2785 // Couldn't find any inserted value for this index? Cleanup
2786 while (PrevTo != OrigTo) {
2787 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2788 PrevTo = Del->getAggregateOperand();
2789 Del->eraseFromParent();
2791 // Stop processing elements
2795 // If we successfully found a value for each of our subaggregates
2799 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2800 // the struct's elements had a value that was inserted directly. In the latter
2801 // case, perhaps we can't determine each of the subelements individually, but
2802 // we might be able to find the complete struct somewhere.
2804 // Find the value that is at that particular spot
2805 Value *V = FindInsertedValue(From, Idxs);
2810 // Insert the value in the new (sub) aggregrate
2811 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2812 "tmp", InsertBefore);
2815 // This helper takes a nested struct and extracts a part of it (which is again a
2816 // struct) into a new value. For example, given the struct:
2817 // { a, { b, { c, d }, e } }
2818 // and the indices "1, 1" this returns
2821 // It does this by inserting an insertvalue for each element in the resulting
2822 // struct, as opposed to just inserting a single struct. This will only work if
2823 // each of the elements of the substruct are known (ie, inserted into From by an
2824 // insertvalue instruction somewhere).
2826 // All inserted insertvalue instructions are inserted before InsertBefore
2827 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
2828 Instruction *InsertBefore) {
2829 assert(InsertBefore && "Must have someplace to insert!");
2830 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
2832 Value *To = UndefValue::get(IndexedType);
2833 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
2834 unsigned IdxSkip = Idxs.size();
2836 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
2839 /// Given an aggregrate and an sequence of indices, see if
2840 /// the scalar value indexed is already around as a register, for example if it
2841 /// were inserted directly into the aggregrate.
2843 /// If InsertBefore is not null, this function will duplicate (modified)
2844 /// insertvalues when a part of a nested struct is extracted.
2845 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2846 Instruction *InsertBefore) {
2847 // Nothing to index? Just return V then (this is useful at the end of our
2849 if (idx_range.empty())
2851 // We have indices, so V should have an indexable type.
2852 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2853 "Not looking at a struct or array?");
2854 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2855 "Invalid indices for type?");
2857 if (Constant *C = dyn_cast<Constant>(V)) {
2858 C = C->getAggregateElement(idx_range[0]);
2859 if (!C) return nullptr;
2860 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2863 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
2864 // Loop the indices for the insertvalue instruction in parallel with the
2865 // requested indices
2866 const unsigned *req_idx = idx_range.begin();
2867 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2868 i != e; ++i, ++req_idx) {
2869 if (req_idx == idx_range.end()) {
2870 // We can't handle this without inserting insertvalues
2874 // The requested index identifies a part of a nested aggregate. Handle
2875 // this specially. For example,
2876 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2877 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2878 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2879 // This can be changed into
2880 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2881 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2882 // which allows the unused 0,0 element from the nested struct to be
2884 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2888 // This insert value inserts something else than what we are looking for.
2889 // See if the (aggregate) value inserted into has the value we are
2890 // looking for, then.
2892 return FindInsertedValue(I->getAggregateOperand(), idx_range,
2895 // If we end up here, the indices of the insertvalue match with those
2896 // requested (though possibly only partially). Now we recursively look at
2897 // the inserted value, passing any remaining indices.
2898 return FindInsertedValue(I->getInsertedValueOperand(),
2899 makeArrayRef(req_idx, idx_range.end()),
2903 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
2904 // If we're extracting a value from an aggregate that was extracted from
2905 // something else, we can extract from that something else directly instead.
2906 // However, we will need to chain I's indices with the requested indices.
2908 // Calculate the number of indices required
2909 unsigned size = I->getNumIndices() + idx_range.size();
2910 // Allocate some space to put the new indices in
2911 SmallVector<unsigned, 5> Idxs;
2913 // Add indices from the extract value instruction
2914 Idxs.append(I->idx_begin(), I->idx_end());
2916 // Add requested indices
2917 Idxs.append(idx_range.begin(), idx_range.end());
2919 assert(Idxs.size() == size
2920 && "Number of indices added not correct?");
2922 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
2924 // Otherwise, we don't know (such as, extracting from a function return value
2925 // or load instruction)
2929 /// Analyze the specified pointer to see if it can be expressed as a base
2930 /// pointer plus a constant offset. Return the base and offset to the caller.
2931 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
2932 const DataLayout &DL) {
2933 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
2934 APInt ByteOffset(BitWidth, 0);
2936 // We walk up the defs but use a visited set to handle unreachable code. In
2937 // that case, we stop after accumulating the cycle once (not that it
2939 SmallPtrSet<Value *, 16> Visited;
2940 while (Visited.insert(Ptr).second) {
2941 if (Ptr->getType()->isVectorTy())
2944 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
2945 // If one of the values we have visited is an addrspacecast, then
2946 // the pointer type of this GEP may be different from the type
2947 // of the Ptr parameter which was passed to this function. This
2948 // means when we construct GEPOffset, we need to use the size
2949 // of GEP's pointer type rather than the size of the original
2951 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
2952 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2955 ByteOffset += GEPOffset.getSExtValue();
2957 Ptr = GEP->getPointerOperand();
2958 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2959 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
2960 Ptr = cast<Operator>(Ptr)->getOperand(0);
2961 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2962 if (GA->isInterposable())
2964 Ptr = GA->getAliasee();
2969 Offset = ByteOffset.getSExtValue();
2973 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP) {
2974 // Make sure the GEP has exactly three arguments.
2975 if (GEP->getNumOperands() != 3)
2978 // Make sure the index-ee is a pointer to array of i8.
2979 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2980 if (!AT || !AT->getElementType()->isIntegerTy(8))
2983 // Check to make sure that the first operand of the GEP is an integer and
2984 // has value 0 so that we are sure we're indexing into the initializer.
2985 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2986 if (!FirstIdx || !FirstIdx->isZero())
2992 /// This function computes the length of a null-terminated C string pointed to
2993 /// by V. If successful, it returns true and returns the string in Str.
2994 /// If unsuccessful, it returns false.
2995 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2996 uint64_t Offset, bool TrimAtNul) {
2999 // Look through bitcast instructions and geps.
3000 V = V->stripPointerCasts();
3002 // If the value is a GEP instruction or constant expression, treat it as an
3004 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3005 // The GEP operator should be based on a pointer to string constant, and is
3006 // indexing into the string constant.
3007 if (!isGEPBasedOnPointerToString(GEP))
3010 // If the second index isn't a ConstantInt, then this is a variable index
3011 // into the array. If this occurs, we can't say anything meaningful about
3013 uint64_t StartIdx = 0;
3014 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
3015 StartIdx = CI->getZExtValue();
3018 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
3022 // The GEP instruction, constant or instruction, must reference a global
3023 // variable that is a constant and is initialized. The referenced constant
3024 // initializer is the array that we'll use for optimization.
3025 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3026 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
3029 // Handle the all-zeros case.
3030 if (GV->getInitializer()->isNullValue()) {
3031 // This is a degenerate case. The initializer is constant zero so the
3032 // length of the string must be zero.
3037 // This must be a ConstantDataArray.
3038 const auto *Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3039 if (!Array || !Array->isString())
3042 // Get the number of elements in the array.
3043 uint64_t NumElts = Array->getType()->getArrayNumElements();
3045 // Start out with the entire array in the StringRef.
3046 Str = Array->getAsString();
3048 if (Offset > NumElts)
3051 // Skip over 'offset' bytes.
3052 Str = Str.substr(Offset);
3055 // Trim off the \0 and anything after it. If the array is not nul
3056 // terminated, we just return the whole end of string. The client may know
3057 // some other way that the string is length-bound.
3058 Str = Str.substr(0, Str.find('\0'));
3063 // These next two are very similar to the above, but also look through PHI
3065 // TODO: See if we can integrate these two together.
3067 /// If we can compute the length of the string pointed to by
3068 /// the specified pointer, return 'len+1'. If we can't, return 0.
3069 static uint64_t GetStringLengthH(const Value *V,
3070 SmallPtrSetImpl<const PHINode*> &PHIs) {
3071 // Look through noop bitcast instructions.
3072 V = V->stripPointerCasts();
3074 // If this is a PHI node, there are two cases: either we have already seen it
3076 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
3077 if (!PHIs.insert(PN).second)
3078 return ~0ULL; // already in the set.
3080 // If it was new, see if all the input strings are the same length.
3081 uint64_t LenSoFar = ~0ULL;
3082 for (Value *IncValue : PN->incoming_values()) {
3083 uint64_t Len = GetStringLengthH(IncValue, PHIs);
3084 if (Len == 0) return 0; // Unknown length -> unknown.
3086 if (Len == ~0ULL) continue;
3088 if (Len != LenSoFar && LenSoFar != ~0ULL)
3089 return 0; // Disagree -> unknown.
3093 // Success, all agree.
3097 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
3098 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
3099 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
3100 if (Len1 == 0) return 0;
3101 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
3102 if (Len2 == 0) return 0;
3103 if (Len1 == ~0ULL) return Len2;
3104 if (Len2 == ~0ULL) return Len1;
3105 if (Len1 != Len2) return 0;
3109 // Otherwise, see if we can read the string.
3111 if (!getConstantStringInfo(V, StrData))
3114 return StrData.size()+1;
3117 /// If we can compute the length of the string pointed to by
3118 /// the specified pointer, return 'len+1'. If we can't, return 0.
3119 uint64_t llvm::GetStringLength(const Value *V) {
3120 if (!V->getType()->isPointerTy()) return 0;
3122 SmallPtrSet<const PHINode*, 32> PHIs;
3123 uint64_t Len = GetStringLengthH(V, PHIs);
3124 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3125 // an empty string as a length.
3126 return Len == ~0ULL ? 1 : Len;
3129 /// \brief \p PN defines a loop-variant pointer to an object. Check if the
3130 /// previous iteration of the loop was referring to the same object as \p PN.
3131 static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3132 const LoopInfo *LI) {
3133 // Find the loop-defined value.
3134 Loop *L = LI->getLoopFor(PN->getParent());
3135 if (PN->getNumIncomingValues() != 2)
3138 // Find the value from previous iteration.
3139 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3140 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3141 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3142 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3145 // If a new pointer is loaded in the loop, the pointer references a different
3146 // object in every iteration. E.g.:
3150 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3151 if (!L->isLoopInvariant(Load->getPointerOperand()))
3156 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3157 unsigned MaxLookup) {
3158 if (!V->getType()->isPointerTy())
3160 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3161 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3162 V = GEP->getPointerOperand();
3163 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3164 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
3165 V = cast<Operator>(V)->getOperand(0);
3166 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
3167 if (GA->isInterposable())
3169 V = GA->getAliasee();
3171 if (auto CS = CallSite(V))
3172 if (Value *RV = CS.getReturnedArgOperand()) {
3177 // See if InstructionSimplify knows any relevant tricks.
3178 if (Instruction *I = dyn_cast<Instruction>(V))
3179 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
3180 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
3187 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3192 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
3193 const DataLayout &DL, LoopInfo *LI,
3194 unsigned MaxLookup) {
3195 SmallPtrSet<Value *, 4> Visited;
3196 SmallVector<Value *, 4> Worklist;
3197 Worklist.push_back(V);
3199 Value *P = Worklist.pop_back_val();
3200 P = GetUnderlyingObject(P, DL, MaxLookup);
3202 if (!Visited.insert(P).second)
3205 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3206 Worklist.push_back(SI->getTrueValue());
3207 Worklist.push_back(SI->getFalseValue());
3211 if (PHINode *PN = dyn_cast<PHINode>(P)) {
3212 // If this PHI changes the underlying object in every iteration of the
3213 // loop, don't look through it. Consider:
3216 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3220 // Prev is tracking Curr one iteration behind so they refer to different
3221 // underlying objects.
3222 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3223 isSameUnderlyingObjectInLoop(PN, LI))
3224 for (Value *IncValue : PN->incoming_values())
3225 Worklist.push_back(IncValue);
3229 Objects.push_back(P);
3230 } while (!Worklist.empty());
3233 /// Return true if the only users of this pointer are lifetime markers.
3234 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
3235 for (const User *U : V->users()) {
3236 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
3237 if (!II) return false;
3239 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3240 II->getIntrinsicID() != Intrinsic::lifetime_end)
3246 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3247 const Instruction *CtxI,
3248 const DominatorTree *DT) {
3249 const Operator *Inst = dyn_cast<Operator>(V);
3253 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3254 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3258 switch (Inst->getOpcode()) {
3261 case Instruction::UDiv:
3262 case Instruction::URem: {
3263 // x / y is undefined if y == 0.
3265 if (match(Inst->getOperand(1), m_APInt(V)))
3269 case Instruction::SDiv:
3270 case Instruction::SRem: {
3271 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
3272 const APInt *Numerator, *Denominator;
3273 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3275 // We cannot hoist this division if the denominator is 0.
3276 if (*Denominator == 0)
3278 // It's safe to hoist if the denominator is not 0 or -1.
3279 if (*Denominator != -1)
3281 // At this point we know that the denominator is -1. It is safe to hoist as
3282 // long we know that the numerator is not INT_MIN.
3283 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3284 return !Numerator->isMinSignedValue();
3285 // The numerator *might* be MinSignedValue.
3288 case Instruction::Load: {
3289 const LoadInst *LI = cast<LoadInst>(Inst);
3290 if (!LI->isUnordered() ||
3291 // Speculative load may create a race that did not exist in the source.
3292 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
3293 // Speculative load may load data from dirty regions.
3294 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3296 const DataLayout &DL = LI->getModule()->getDataLayout();
3297 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3298 LI->getAlignment(), DL, CtxI, DT);
3300 case Instruction::Call: {
3301 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3302 switch (II->getIntrinsicID()) {
3303 // These synthetic intrinsics have no side-effects and just mark
3304 // information about their operands.
3305 // FIXME: There are other no-op synthetic instructions that potentially
3306 // should be considered at least *safe* to speculate...
3307 case Intrinsic::dbg_declare:
3308 case Intrinsic::dbg_value:
3311 case Intrinsic::bitreverse:
3312 case Intrinsic::bswap:
3313 case Intrinsic::ctlz:
3314 case Intrinsic::ctpop:
3315 case Intrinsic::cttz:
3316 case Intrinsic::objectsize:
3317 case Intrinsic::sadd_with_overflow:
3318 case Intrinsic::smul_with_overflow:
3319 case Intrinsic::ssub_with_overflow:
3320 case Intrinsic::uadd_with_overflow:
3321 case Intrinsic::umul_with_overflow:
3322 case Intrinsic::usub_with_overflow:
3324 // These intrinsics are defined to have the same behavior as libm
3325 // functions except for setting errno.
3326 case Intrinsic::sqrt:
3327 case Intrinsic::fma:
3328 case Intrinsic::fmuladd:
3330 // These intrinsics are defined to have the same behavior as libm
3331 // functions, and the corresponding libm functions never set errno.
3332 case Intrinsic::trunc:
3333 case Intrinsic::copysign:
3334 case Intrinsic::fabs:
3335 case Intrinsic::minnum:
3336 case Intrinsic::maxnum:
3338 // These intrinsics are defined to have the same behavior as libm
3339 // functions, which never overflow when operating on the IEEE754 types
3340 // that we support, and never set errno otherwise.
3341 case Intrinsic::ceil:
3342 case Intrinsic::floor:
3343 case Intrinsic::nearbyint:
3344 case Intrinsic::rint:
3345 case Intrinsic::round:
3347 // TODO: are convert_{from,to}_fp16 safe?
3348 // TODO: can we list target-specific intrinsics here?
3352 return false; // The called function could have undefined behavior or
3353 // side-effects, even if marked readnone nounwind.
3355 case Instruction::VAArg:
3356 case Instruction::Alloca:
3357 case Instruction::Invoke:
3358 case Instruction::PHI:
3359 case Instruction::Store:
3360 case Instruction::Ret:
3361 case Instruction::Br:
3362 case Instruction::IndirectBr:
3363 case Instruction::Switch:
3364 case Instruction::Unreachable:
3365 case Instruction::Fence:
3366 case Instruction::AtomicRMW:
3367 case Instruction::AtomicCmpXchg:
3368 case Instruction::LandingPad:
3369 case Instruction::Resume:
3370 case Instruction::CatchSwitch:
3371 case Instruction::CatchPad:
3372 case Instruction::CatchRet:
3373 case Instruction::CleanupPad:
3374 case Instruction::CleanupRet:
3375 return false; // Misc instructions which have effects
3379 bool llvm::mayBeMemoryDependent(const Instruction &I) {
3380 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3383 /// Return true if we know that the specified value is never null.
3384 bool llvm::isKnownNonNull(const Value *V) {
3385 assert(V->getType()->isPointerTy() && "V must be pointer type");
3387 // Alloca never returns null, malloc might.
3388 if (isa<AllocaInst>(V)) return true;
3390 // A byval, inalloca, or nonnull argument is never null.
3391 if (const Argument *A = dyn_cast<Argument>(V))
3392 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
3394 // A global variable in address space 0 is non null unless extern weak
3395 // or an absolute symbol reference. Other address spaces may have null as a
3396 // valid address for a global, so we can't assume anything.
3397 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3398 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3399 GV->getType()->getAddressSpace() == 0;
3401 // A Load tagged with nonnull metadata is never null.
3402 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
3403 return LI->getMetadata(LLVMContext::MD_nonnull);
3405 if (auto CS = ImmutableCallSite(V))
3406 if (CS.isReturnNonNull())
3412 static bool isKnownNonNullFromDominatingCondition(const Value *V,
3413 const Instruction *CtxI,
3414 const DominatorTree *DT) {
3415 assert(V->getType()->isPointerTy() && "V must be pointer type");
3416 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
3417 assert(CtxI && "Context instruction required for analysis");
3418 assert(DT && "Dominator tree required for analysis");
3420 unsigned NumUsesExplored = 0;
3421 for (auto *U : V->users()) {
3422 // Avoid massive lists
3423 if (NumUsesExplored >= DomConditionsMaxUses)
3426 // Consider only compare instructions uniquely controlling a branch
3427 CmpInst::Predicate Pred;
3428 if (!match(const_cast<User *>(U),
3429 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3430 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
3433 for (auto *CmpU : U->users()) {
3434 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3435 assert(BI->isConditional() && "uses a comparison!");
3437 BasicBlock *NonNullSuccessor =
3438 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3439 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3440 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3442 } else if (Pred == ICmpInst::ICMP_NE &&
3443 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3444 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
3453 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
3454 const DominatorTree *DT) {
3455 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3458 if (isKnownNonNull(V))
3464 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
3467 OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3469 const DataLayout &DL,
3470 AssumptionCache *AC,
3471 const Instruction *CxtI,
3472 const DominatorTree *DT) {
3473 // Multiplying n * m significant bits yields a result of n + m significant
3474 // bits. If the total number of significant bits does not exceed the
3475 // result bit width (minus 1), there is no overflow.
3476 // This means if we have enough leading zero bits in the operands
3477 // we can guarantee that the result does not overflow.
3478 // Ref: "Hacker's Delight" by Henry Warren
3479 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3480 APInt LHSKnownZero(BitWidth, 0);
3481 APInt LHSKnownOne(BitWidth, 0);
3482 APInt RHSKnownZero(BitWidth, 0);
3483 APInt RHSKnownOne(BitWidth, 0);
3484 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3486 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3488 // Note that underestimating the number of zero bits gives a more
3489 // conservative answer.
3490 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3491 RHSKnownZero.countLeadingOnes();
3492 // First handle the easy case: if we have enough zero bits there's
3493 // definitely no overflow.
3494 if (ZeroBits >= BitWidth)
3495 return OverflowResult::NeverOverflows;
3497 // Get the largest possible values for each operand.
3498 APInt LHSMax = ~LHSKnownZero;
3499 APInt RHSMax = ~RHSKnownZero;
3501 // We know the multiply operation doesn't overflow if the maximum values for
3502 // each operand will not overflow after we multiply them together.
3504 LHSMax.umul_ov(RHSMax, MaxOverflow);
3506 return OverflowResult::NeverOverflows;
3508 // We know it always overflows if multiplying the smallest possible values for
3509 // the operands also results in overflow.
3511 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3513 return OverflowResult::AlwaysOverflows;
3515 return OverflowResult::MayOverflow;
3518 OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3520 const DataLayout &DL,
3521 AssumptionCache *AC,
3522 const Instruction *CxtI,
3523 const DominatorTree *DT) {
3524 bool LHSKnownNonNegative, LHSKnownNegative;
3525 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3527 if (LHSKnownNonNegative || LHSKnownNegative) {
3528 bool RHSKnownNonNegative, RHSKnownNegative;
3529 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3532 if (LHSKnownNegative && RHSKnownNegative) {
3533 // The sign bit is set in both cases: this MUST overflow.
3534 // Create a simple add instruction, and insert it into the struct.
3535 return OverflowResult::AlwaysOverflows;
3538 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3539 // The sign bit is clear in both cases: this CANNOT overflow.
3540 // Create a simple add instruction, and insert it into the struct.
3541 return OverflowResult::NeverOverflows;
3545 return OverflowResult::MayOverflow;
3548 static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3550 const AddOperator *Add,
3551 const DataLayout &DL,
3552 AssumptionCache *AC,
3553 const Instruction *CxtI,
3554 const DominatorTree *DT) {
3555 if (Add && Add->hasNoSignedWrap()) {
3556 return OverflowResult::NeverOverflows;
3559 bool LHSKnownNonNegative, LHSKnownNegative;
3560 bool RHSKnownNonNegative, RHSKnownNegative;
3561 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3563 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3566 if ((LHSKnownNonNegative && RHSKnownNegative) ||
3567 (LHSKnownNegative && RHSKnownNonNegative)) {
3568 // The sign bits are opposite: this CANNOT overflow.
3569 return OverflowResult::NeverOverflows;
3572 // The remaining code needs Add to be available. Early returns if not so.
3574 return OverflowResult::MayOverflow;
3576 // If the sign of Add is the same as at least one of the operands, this add
3577 // CANNOT overflow. This is particularly useful when the sum is
3578 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3580 bool LHSOrRHSKnownNonNegative =
3581 (LHSKnownNonNegative || RHSKnownNonNegative);
3582 bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
3583 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
3584 bool AddKnownNonNegative, AddKnownNegative;
3585 ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
3586 /*Depth=*/0, AC, CxtI, DT);
3587 if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
3588 (AddKnownNegative && LHSOrRHSKnownNegative)) {
3589 return OverflowResult::NeverOverflows;
3593 return OverflowResult::MayOverflow;
3596 bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3597 const DominatorTree &DT) {
3599 auto IID = II->getIntrinsicID();
3600 assert((IID == Intrinsic::sadd_with_overflow ||
3601 IID == Intrinsic::uadd_with_overflow ||
3602 IID == Intrinsic::ssub_with_overflow ||
3603 IID == Intrinsic::usub_with_overflow ||
3604 IID == Intrinsic::smul_with_overflow ||
3605 IID == Intrinsic::umul_with_overflow) &&
3606 "Not an overflow intrinsic!");
3609 SmallVector<const BranchInst *, 2> GuardingBranches;
3610 SmallVector<const ExtractValueInst *, 2> Results;
3612 for (const User *U : II->users()) {
3613 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
3614 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3616 if (EVI->getIndices()[0] == 0)
3617 Results.push_back(EVI);
3619 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3621 for (const auto *U : EVI->users())
3622 if (const auto *B = dyn_cast<BranchInst>(U)) {
3623 assert(B->isConditional() && "How else is it using an i1?");
3624 GuardingBranches.push_back(B);
3628 // We are using the aggregate directly in a way we don't want to analyze
3629 // here (storing it to a global, say).
3634 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
3635 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3636 if (!NoWrapEdge.isSingleEdge())
3639 // Check if all users of the add are provably no-wrap.
3640 for (const auto *Result : Results) {
3641 // If the extractvalue itself is not executed on overflow, the we don't
3642 // need to check each use separately, since domination is transitive.
3643 if (DT.dominates(NoWrapEdge, Result->getParent()))
3646 for (auto &RU : Result->uses())
3647 if (!DT.dominates(NoWrapEdge, RU))
3654 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3658 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
3659 const DataLayout &DL,
3660 AssumptionCache *AC,
3661 const Instruction *CxtI,
3662 const DominatorTree *DT) {
3663 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
3664 Add, DL, AC, CxtI, DT);
3667 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3669 const DataLayout &DL,
3670 AssumptionCache *AC,
3671 const Instruction *CxtI,
3672 const DominatorTree *DT) {
3673 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
3676 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
3677 // A memory operation returns normally if it isn't volatile. A volatile
3678 // operation is allowed to trap.
3680 // An atomic operation isn't guaranteed to return in a reasonable amount of
3681 // time because it's possible for another thread to interfere with it for an
3682 // arbitrary length of time, but programs aren't allowed to rely on that.
3683 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3684 return !LI->isVolatile();
3685 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3686 return !SI->isVolatile();
3687 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3688 return !CXI->isVolatile();
3689 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3690 return !RMWI->isVolatile();
3691 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3692 return !MII->isVolatile();
3694 // If there is no successor, then execution can't transfer to it.
3695 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3696 return !CRI->unwindsToCaller();
3697 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3698 return !CatchSwitch->unwindsToCaller();
3699 if (isa<ResumeInst>(I))
3701 if (isa<ReturnInst>(I))
3704 // Calls can throw, or contain an infinite loop, or kill the process.
3705 if (auto CS = ImmutableCallSite(I)) {
3706 // Call sites that throw have implicit non-local control flow.
3707 if (!CS.doesNotThrow())
3710 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3711 // etc. and thus not return. However, LLVM already assumes that
3713 // - Thread exiting actions are modeled as writes to memory invisible to
3716 // - Loops that don't have side effects (side effects are volatile/atomic
3717 // stores and IO) always terminate (see http://llvm.org/PR965).
3718 // Furthermore IO itself is also modeled as writes to memory invisible to
3721 // We rely on those assumptions here, and use the memory effects of the call
3722 // target as a proxy for checking that it always returns.
3724 // FIXME: This isn't aggressive enough; a call which only writes to a global
3725 // is guaranteed to return.
3726 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3727 match(I, m_Intrinsic<Intrinsic::assume>());
3730 // Other instructions return normally.
3734 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3736 // The loop header is guaranteed to be executed for every iteration.
3738 // FIXME: Relax this constraint to cover all basic blocks that are
3739 // guaranteed to be executed at every iteration.
3740 if (I->getParent() != L->getHeader()) return false;
3742 for (const Instruction &LI : *L->getHeader()) {
3743 if (&LI == I) return true;
3744 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3746 llvm_unreachable("Instruction not contained in its own parent basic block.");
3749 bool llvm::propagatesFullPoison(const Instruction *I) {
3750 switch (I->getOpcode()) {
3751 case Instruction::Add:
3752 case Instruction::Sub:
3753 case Instruction::Xor:
3754 case Instruction::Trunc:
3755 case Instruction::BitCast:
3756 case Instruction::AddrSpaceCast:
3757 // These operations all propagate poison unconditionally. Note that poison
3758 // is not any particular value, so xor or subtraction of poison with
3759 // itself still yields poison, not zero.
3762 case Instruction::AShr:
3763 case Instruction::SExt:
3764 // For these operations, one bit of the input is replicated across
3765 // multiple output bits. A replicated poison bit is still poison.
3768 case Instruction::Shl: {
3769 // Left shift *by* a poison value is poison. The number of
3770 // positions to shift is unsigned, so no negative values are
3771 // possible there. Left shift by zero places preserves poison. So
3772 // it only remains to consider left shift of poison by a positive
3773 // number of places.
3775 // A left shift by a positive number of places leaves the lowest order bit
3776 // non-poisoned. However, if such a shift has a no-wrap flag, then we can
3777 // make the poison operand violate that flag, yielding a fresh full-poison
3779 auto *OBO = cast<OverflowingBinaryOperator>(I);
3780 return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
3783 case Instruction::Mul: {
3784 // A multiplication by zero yields a non-poison zero result, so we need to
3785 // rule out zero as an operand. Conservatively, multiplication by a
3786 // non-zero constant is not multiplication by zero.
3788 // Multiplication by a non-zero constant can leave some bits
3789 // non-poisoned. For example, a multiplication by 2 leaves the lowest
3790 // order bit unpoisoned. So we need to consider that.
3792 // Multiplication by 1 preserves poison. If the multiplication has a
3793 // no-wrap flag, then we can make the poison operand violate that flag
3794 // when multiplied by any integer other than 0 and 1.
3795 auto *OBO = cast<OverflowingBinaryOperator>(I);
3796 if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
3797 for (Value *V : OBO->operands()) {
3798 if (auto *CI = dyn_cast<ConstantInt>(V)) {
3799 // A ConstantInt cannot yield poison, so we can assume that it is
3800 // the other operand that is poison.
3801 return !CI->isZero();
3808 case Instruction::ICmp:
3809 // Comparing poison with any value yields poison. This is why, for
3810 // instance, x s< (x +nsw 1) can be folded to true.
3813 case Instruction::GetElementPtr:
3814 // A GEP implicitly represents a sequence of additions, subtractions,
3815 // truncations, sign extensions and multiplications. The multiplications
3816 // are by the non-zero sizes of some set of types, so we do not have to be
3817 // concerned with multiplication by zero. If the GEP is in-bounds, then
3818 // these operations are implicitly no-signed-wrap so poison is propagated
3819 // by the arguments above for Add, Sub, Trunc, SExt and Mul.
3820 return cast<GEPOperator>(I)->isInBounds();
3827 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3828 switch (I->getOpcode()) {
3829 case Instruction::Store:
3830 return cast<StoreInst>(I)->getPointerOperand();
3832 case Instruction::Load:
3833 return cast<LoadInst>(I)->getPointerOperand();
3835 case Instruction::AtomicCmpXchg:
3836 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3838 case Instruction::AtomicRMW:
3839 return cast<AtomicRMWInst>(I)->getPointerOperand();
3841 case Instruction::UDiv:
3842 case Instruction::SDiv:
3843 case Instruction::URem:
3844 case Instruction::SRem:
3845 return I->getOperand(1);
3852 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
3853 // We currently only look for uses of poison values within the same basic
3854 // block, as that makes it easier to guarantee that the uses will be
3855 // executed given that PoisonI is executed.
3857 // FIXME: Expand this to consider uses beyond the same basic block. To do
3858 // this, look out for the distinction between post-dominance and strong
3860 const BasicBlock *BB = PoisonI->getParent();
3862 // Set of instructions that we have proved will yield poison if PoisonI
3864 SmallSet<const Value *, 16> YieldsPoison;
3865 SmallSet<const BasicBlock *, 4> Visited;
3866 YieldsPoison.insert(PoisonI);
3867 Visited.insert(PoisonI->getParent());
3869 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
3872 while (Iter++ < MaxDepth) {
3873 for (auto &I : make_range(Begin, End)) {
3874 if (&I != PoisonI) {
3875 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3876 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3878 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3882 // Mark poison that propagates from I through uses of I.
3883 if (YieldsPoison.count(&I)) {
3884 for (const User *User : I.users()) {
3885 const Instruction *UserI = cast<Instruction>(User);
3886 if (propagatesFullPoison(UserI))
3887 YieldsPoison.insert(User);
3892 if (auto *NextBB = BB->getSingleSuccessor()) {
3893 if (Visited.insert(NextBB).second) {
3895 Begin = BB->getFirstNonPHI()->getIterator();
3906 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
3910 if (auto *C = dyn_cast<ConstantFP>(V))
3915 static bool isKnownNonZero(const Value *V) {
3916 if (auto *C = dyn_cast<ConstantFP>(V))
3917 return !C->isZero();
3921 /// Match non-obvious integer minimum and maximum sequences.
3922 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
3923 Value *CmpLHS, Value *CmpRHS,
3924 Value *TrueVal, Value *FalseVal,
3925 Value *&LHS, Value *&RHS) {
3926 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
3927 return {SPF_UNKNOWN, SPNB_NA, false};
3930 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
3931 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
3932 if (match(TrueVal, m_Zero()) &&
3933 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) {
3936 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
3940 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
3941 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
3942 if (match(FalseVal, m_Zero()) &&
3943 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) {
3946 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
3950 if (!match(CmpRHS, m_APInt(C1)))
3951 return {SPF_UNKNOWN, SPNB_NA, false};
3953 // An unsigned min/max can be written with a signed compare.
3955 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
3956 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
3957 // Is the sign bit set?
3958 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
3959 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
3960 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue()) {
3963 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
3966 // Is the sign bit clear?
3967 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
3968 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
3969 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
3970 C2->isMinSignedValue()) {
3973 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
3977 // Look through 'not' ops to find disguised signed min/max.
3978 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
3979 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
3980 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
3981 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2) {
3984 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
3987 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
3988 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
3989 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
3990 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2) {
3993 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
3996 return {SPF_UNKNOWN, SPNB_NA, false};
3999 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4001 Value *CmpLHS, Value *CmpRHS,
4002 Value *TrueVal, Value *FalseVal,
4003 Value *&LHS, Value *&RHS) {
4007 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4008 // return inconsistent results between implementations.
4009 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4010 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4011 // Therefore we behave conservatively and only proceed if at least one of the
4012 // operands is known to not be zero, or if we don't care about signed zeroes.
4015 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4016 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4017 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4018 !isKnownNonZero(CmpRHS))
4019 return {SPF_UNKNOWN, SPNB_NA, false};
4022 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4023 bool Ordered = false;
4025 // When given one NaN and one non-NaN input:
4026 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4027 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4028 // ordered comparison fails), which could be NaN or non-NaN.
4029 // so here we discover exactly what NaN behavior is required/accepted.
4030 if (CmpInst::isFPPredicate(Pred)) {
4031 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4032 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4034 if (LHSSafe && RHSSafe) {
4035 // Both operands are known non-NaN.
4036 NaNBehavior = SPNB_RETURNS_ANY;
4037 } else if (CmpInst::isOrdered(Pred)) {
4038 // An ordered comparison will return false when given a NaN, so it
4042 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
4043 NaNBehavior = SPNB_RETURNS_NAN;
4045 NaNBehavior = SPNB_RETURNS_OTHER;
4047 // Completely unsafe.
4048 return {SPF_UNKNOWN, SPNB_NA, false};
4051 // An unordered comparison will return true when given a NaN, so it
4054 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
4055 NaNBehavior = SPNB_RETURNS_OTHER;
4057 NaNBehavior = SPNB_RETURNS_NAN;
4059 // Completely unsafe.
4060 return {SPF_UNKNOWN, SPNB_NA, false};
4064 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
4065 std::swap(CmpLHS, CmpRHS);
4066 Pred = CmpInst::getSwappedPredicate(Pred);
4067 if (NaNBehavior == SPNB_RETURNS_NAN)
4068 NaNBehavior = SPNB_RETURNS_OTHER;
4069 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4070 NaNBehavior = SPNB_RETURNS_NAN;
4074 // ([if]cmp X, Y) ? X : Y
4075 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
4077 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
4078 case ICmpInst::ICMP_UGT:
4079 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
4080 case ICmpInst::ICMP_SGT:
4081 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
4082 case ICmpInst::ICMP_ULT:
4083 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
4084 case ICmpInst::ICMP_SLT:
4085 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4086 case FCmpInst::FCMP_UGT:
4087 case FCmpInst::FCMP_UGE:
4088 case FCmpInst::FCMP_OGT:
4089 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4090 case FCmpInst::FCMP_ULT:
4091 case FCmpInst::FCMP_ULE:
4092 case FCmpInst::FCMP_OLT:
4093 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
4098 if (match(CmpRHS, m_APInt(C1))) {
4099 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4100 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4102 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4103 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
4104 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
4105 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
4108 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4109 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
4110 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
4111 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
4116 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4119 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4120 Instruction::CastOps *CastOp) {
4121 CastInst *CI = dyn_cast<CastInst>(V1);
4122 Constant *C = dyn_cast<Constant>(V2);
4125 *CastOp = CI->getOpcode();
4127 if (auto *CI2 = dyn_cast<CastInst>(V2)) {
4128 // If V1 and V2 are both the same cast from the same type, we can look
4130 if (CI2->getOpcode() == CI->getOpcode() &&
4131 CI2->getSrcTy() == CI->getSrcTy())
4132 return CI2->getOperand(0);
4138 Constant *CastedTo = nullptr;
4140 if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
4141 CastedTo = ConstantExpr::getTrunc(C, CI->getSrcTy());
4143 if (isa<SExtInst>(CI) && CmpI->isSigned())
4144 CastedTo = ConstantExpr::getTrunc(C, CI->getSrcTy(), true);
4146 if (isa<TruncInst>(CI))
4147 CastedTo = ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
4149 if (isa<FPTruncInst>(CI))
4150 CastedTo = ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
4152 if (isa<FPExtInst>(CI))
4153 CastedTo = ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
4155 if (isa<FPToUIInst>(CI))
4156 CastedTo = ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
4158 if (isa<FPToSIInst>(CI))
4159 CastedTo = ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
4161 if (isa<UIToFPInst>(CI))
4162 CastedTo = ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
4164 if (isa<SIToFPInst>(CI))
4165 CastedTo = ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
4170 Constant *CastedBack =
4171 ConstantExpr::getCast(CI->getOpcode(), CastedTo, C->getType(), true);
4172 // Make sure the cast doesn't lose any information.
4173 if (CastedBack != C)
4179 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
4180 Instruction::CastOps *CastOp) {
4181 SelectInst *SI = dyn_cast<SelectInst>(V);
4182 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
4184 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4185 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
4187 CmpInst::Predicate Pred = CmpI->getPredicate();
4188 Value *CmpLHS = CmpI->getOperand(0);
4189 Value *CmpRHS = CmpI->getOperand(1);
4190 Value *TrueVal = SI->getTrueValue();
4191 Value *FalseVal = SI->getFalseValue();
4193 if (isa<FPMathOperator>(CmpI))
4194 FMF = CmpI->getFastMathFlags();
4197 if (CmpI->isEquality())
4198 return {SPF_UNKNOWN, SPNB_NA, false};
4200 // Deal with type mismatches.
4201 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
4202 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
4203 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4204 cast<CastInst>(TrueVal)->getOperand(0), C,
4206 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
4207 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
4208 C, cast<CastInst>(FalseVal)->getOperand(0),
4211 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
4215 /// Return true if "icmp Pred LHS RHS" is always true.
4216 static bool isTruePredicate(CmpInst::Predicate Pred,
4217 const Value *LHS, const Value *RHS,
4218 const DataLayout &DL, unsigned Depth,
4219 AssumptionCache *AC, const Instruction *CxtI,
4220 const DominatorTree *DT) {
4221 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
4222 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4229 case CmpInst::ICMP_SLE: {
4232 // LHS s<= LHS +_{nsw} C if C >= 0
4233 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
4234 return !C->isNegative();
4238 case CmpInst::ICMP_ULE: {
4241 // LHS u<= LHS +_{nuw} C for any C
4242 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
4245 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
4246 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4248 const APInt *&CA, const APInt *&CB) {
4249 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4250 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4253 // If X & C == 0 then (X | C) == X +_{nuw} C
4254 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4255 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
4256 unsigned BitWidth = CA->getBitWidth();
4257 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4258 computeKnownBits(X, KnownZero, KnownOne, DL, Depth + 1, AC, CxtI, DT);
4260 if ((KnownZero & *CA) == *CA && (KnownZero & *CB) == *CB)
4268 const APInt *CLHS, *CRHS;
4269 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4270 return CLHS->ule(*CRHS);
4277 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
4278 /// ALHS ARHS" is true. Otherwise, return None.
4279 static Optional<bool>
4280 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4281 const Value *ARHS, const Value *BLHS,
4282 const Value *BRHS, const DataLayout &DL,
4283 unsigned Depth, AssumptionCache *AC,
4284 const Instruction *CxtI, const DominatorTree *DT) {
4289 case CmpInst::ICMP_SLT:
4290 case CmpInst::ICMP_SLE:
4291 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
4293 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
4297 case CmpInst::ICMP_ULT:
4298 case CmpInst::ICMP_ULE:
4299 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
4301 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
4307 /// Return true if the operands of the two compares match. IsSwappedOps is true
4308 /// when the operands match, but are swapped.
4309 static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4310 const Value *BLHS, const Value *BRHS,
4311 bool &IsSwappedOps) {
4313 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4314 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4315 return IsMatchingOps || IsSwappedOps;
4318 /// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4319 /// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4320 /// BRHS" is false. Otherwise, return None if we can't infer anything.
4321 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
4324 CmpInst::Predicate BPred,
4327 bool IsSwappedOps) {
4328 // Canonicalize the operands so they're matching.
4330 std::swap(BLHS, BRHS);
4331 BPred = ICmpInst::getSwappedPredicate(BPred);
4333 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
4335 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
4341 /// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4342 /// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4343 /// C2" is false. Otherwise, return None if we can't infer anything.
4344 static Optional<bool>
4345 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4346 const ConstantInt *C1,
4347 CmpInst::Predicate BPred,
4348 const Value *BLHS, const ConstantInt *C2) {
4349 assert(ALHS == BLHS && "LHS operands must match.");
4350 ConstantRange DomCR =
4351 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4353 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4354 ConstantRange Intersection = DomCR.intersectWith(CR);
4355 ConstantRange Difference = DomCR.difference(CR);
4356 if (Intersection.isEmptySet())
4358 if (Difference.isEmptySet())
4363 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
4364 const DataLayout &DL, bool InvertAPred,
4365 unsigned Depth, AssumptionCache *AC,
4366 const Instruction *CxtI,
4367 const DominatorTree *DT) {
4368 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example.
4369 if (LHS->getType() != RHS->getType())
4372 Type *OpTy = LHS->getType();
4373 assert(OpTy->getScalarType()->isIntegerTy(1));
4375 // LHS ==> RHS by definition
4376 if (!InvertAPred && LHS == RHS)
4379 if (OpTy->isVectorTy())
4380 // TODO: extending the code below to handle vectors
4382 assert(OpTy->isIntegerTy(1) && "implied by above");
4384 ICmpInst::Predicate APred, BPred;
4388 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
4389 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
4393 APred = CmpInst::getInversePredicate(APred);
4395 // Can we infer anything when the two compares have matching operands?
4397 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4398 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4399 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
4401 // No amount of additional analysis will infer the second condition, so
4406 // Can we infer anything when the LHS operands match and the RHS operands are
4407 // constants (not necessarily matching)?
4408 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4409 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4410 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4411 cast<ConstantInt>(BRHS)))
4413 // No amount of additional analysis will infer the second condition, so
4419 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,