LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1322/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1323/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1324/// target's VLEN range. Callers must ensure the target is RISC-V.
1325static bool isReadVLENB(const IntrinsicInst &II) {
1326 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1327 if (!MAV)
1328 return false;
1329 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1330 if (!MD || MD->getNumOperands() != 1)
1331 return false;
1332 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1333 return RegName && RegName->getString() == "vlenb";
1334}
1335
1336/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1337/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1338/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1339/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1340/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1341/// attribute, when present, pins the subtarget's VLEN in units of
1342/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1343/// RVVBytesPerBlock.
1345 unsigned Width) {
1346 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1347 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1348
1349 const Function *F = II.getFunction();
1350 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1351 ConstantRange VScale = getVScaleRange(F, Width);
1352 Range = Range.intersectWith(
1354 }
1355 return Range;
1356}
1357
1359 Value *Arm, bool Invert,
1360 const SimplifyQuery &Q, unsigned Depth) {
1361 // If we have a constant arm, we are done.
1362 if (Known.isConstant())
1363 return;
1364
1365 // See what condition implies about the bits of the select arm.
1366 KnownBits CondRes(Known.getBitWidth());
1367 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1368 // If we don't get any information from the condition, no reason to
1369 // proceed.
1370 if (CondRes.isUnknown())
1371 return;
1372
1373 // We can have conflict if the condition is dead. I.e if we have
1374 // (x | 64) < 32 ? (x | 64) : y
1375 // we will have conflict at bit 6 from the condition/the `or`.
1376 // In that case just return. Its not particularly important
1377 // what we do, as this select is going to be simplified soon.
1378 CondRes = CondRes.unionWith(Known);
1379 if (CondRes.hasConflict())
1380 return;
1381
1382 // Finally make sure the information we found is valid. This is relatively
1383 // expensive so it's left for the very end.
1384 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1385 return;
1386
1387 // Finally, we know we get information from the condition and its valid,
1388 // so return it.
1389 Known = std::move(CondRes);
1390}
1391
1392// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1393// Returns the input and lower/upper bounds.
1394static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1395 const APInt *&CLow, const APInt *&CHigh) {
1397 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1398 "Input should be a Select!");
1399
1400 const Value *LHS = nullptr, *RHS = nullptr;
1402 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1403 return false;
1404
1405 if (!match(RHS, m_APInt(CLow)))
1406 return false;
1407
1408 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1410 if (getInverseMinMaxFlavor(SPF) != SPF2)
1411 return false;
1412
1413 if (!match(RHS2, m_APInt(CHigh)))
1414 return false;
1415
1416 if (SPF == SPF_SMIN)
1417 std::swap(CLow, CHigh);
1418
1419 In = LHS2;
1420 return CLow->sle(*CHigh);
1421}
1422
1424 const APInt *&CLow,
1425 const APInt *&CHigh) {
1426 assert((II->getIntrinsicID() == Intrinsic::smin ||
1427 II->getIntrinsicID() == Intrinsic::smax) &&
1428 "Must be smin/smax");
1429
1430 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1431 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1432 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1433 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1434 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1435 return false;
1436
1437 if (II->getIntrinsicID() == Intrinsic::smin)
1438 std::swap(CLow, CHigh);
1439 return CLow->sle(*CHigh);
1440}
1441
1443 KnownBits &Known) {
1444 const APInt *CLow, *CHigh;
1445 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1446 Known = Known.unionWith(
1447 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1448}
1449
1451 const APInt &DemandedElts,
1453 const SimplifyQuery &Q,
1454 unsigned Depth) {
1455 unsigned BitWidth = Known.getBitWidth();
1456
1457 KnownBits Known2(BitWidth);
1458 switch (I->getOpcode()) {
1459 default: break;
1460 case Instruction::Load:
1461 if (MDNode *MD =
1462 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1464 break;
1465 case Instruction::And:
1466 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1467 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1468
1469 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1470 break;
1471 case Instruction::Or:
1472 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1473 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1474
1475 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1476 break;
1477 case Instruction::Xor:
1478 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1479 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1480
1481 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1482 break;
1483 case Instruction::Mul: {
1486 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1487 DemandedElts, Known, Known2, Q, Depth);
1488 break;
1489 }
1490 case Instruction::UDiv: {
1491 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1492 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1493 Known =
1495 break;
1496 }
1497 case Instruction::SDiv: {
1498 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1499 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1500 Known =
1502 break;
1503 }
1504 case Instruction::Select: {
1505 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1506 KnownBits Res(Known.getBitWidth());
1507 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1508 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1509 return Res;
1510 };
1511 // Only known if known in both the LHS and RHS.
1512 Known =
1513 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1514 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1515 break;
1516 }
1517 case Instruction::FPTrunc:
1518 case Instruction::FPExt:
1519 case Instruction::FPToUI:
1520 case Instruction::FPToSI:
1521 case Instruction::SIToFP:
1522 case Instruction::UIToFP:
1523 break; // Can't work with floating point.
1524 case Instruction::PtrToInt:
1525 case Instruction::PtrToAddr:
1526 case Instruction::IntToPtr:
1527 // Fall through and handle them the same as zext/trunc.
1528 [[fallthrough]];
1529 case Instruction::ZExt:
1530 case Instruction::Trunc: {
1531 Type *SrcTy = I->getOperand(0)->getType();
1532
1533 unsigned SrcBitWidth;
1534 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1535 // which fall through here.
1536 Type *ScalarTy = SrcTy->getScalarType();
1537 SrcBitWidth = ScalarTy->isPointerTy() ?
1538 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1539 Q.DL.getTypeSizeInBits(ScalarTy);
1540
1541 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1542 Known = Known.anyextOrTrunc(SrcBitWidth);
1543 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1544 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1545 Inst && Inst->hasNonNeg() && !Known.isNegative())
1546 Known.makeNonNegative();
1547 Known = Known.zextOrTrunc(BitWidth);
1548 break;
1549 }
1550 case Instruction::BitCast: {
1551 Type *SrcTy = I->getOperand(0)->getType();
1552 if (SrcTy->isIntOrPtrTy() &&
1553 // TODO: For now, not handling conversions like:
1554 // (bitcast i64 %x to <2 x i32>)
1555 !I->getType()->isVectorTy()) {
1556 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1557 break;
1558 }
1559
1560 const Value *V;
1561 // Handle bitcast from floating point to integer.
1562 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1563 V->getType()->isFPOrFPVectorTy()) {
1564 Type *FPType = V->getType()->getScalarType();
1565 KnownFPClass Result =
1566 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1567
1568 Known = Result.toKnownBits(FPType->getFltSemantics());
1569
1570 break;
1571 }
1572
1573 // Handle cast from vector integer type to scalar or vector integer.
1574 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1575 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1576 !I->getType()->isIntOrIntVectorTy() ||
1577 isa<ScalableVectorType>(I->getType()))
1578 break;
1579
1580 unsigned NumElts = DemandedElts.getBitWidth();
1581 bool IsLE = Q.DL.isLittleEndian();
1582 // Look through a cast from narrow vector elements to wider type.
1583 // Examples: v4i32 -> v2i64, v3i8 -> v24
1584 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1585 if (BitWidth % SubBitWidth == 0) {
1586 // Known bits are automatically intersected across demanded elements of a
1587 // vector. So for example, if a bit is computed as known zero, it must be
1588 // zero across all demanded elements of the vector.
1589 //
1590 // For this bitcast, each demanded element of the output is sub-divided
1591 // across a set of smaller vector elements in the source vector. To get
1592 // the known bits for an entire element of the output, compute the known
1593 // bits for each sub-element sequentially. This is done by shifting the
1594 // one-set-bit demanded elements parameter across the sub-elements for
1595 // consecutive calls to computeKnownBits. We are using the demanded
1596 // elements parameter as a mask operator.
1597 //
1598 // The known bits of each sub-element are then inserted into place
1599 // (dependent on endian) to form the full result of known bits.
1600 unsigned SubScale = BitWidth / SubBitWidth;
1601 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1602 for (unsigned i = 0; i != NumElts; ++i) {
1603 if (DemandedElts[i])
1604 SubDemandedElts.setBit(i * SubScale);
1605 }
1606
1607 KnownBits KnownSrc(SubBitWidth);
1608 for (unsigned i = 0; i != SubScale; ++i) {
1609 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1610 Depth + 1);
1611 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1612 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1613 }
1614 }
1615 // Look through a cast from wider vector elements to narrow type.
1616 // Examples: v2i64 -> v4i32
1617 if (SubBitWidth % BitWidth == 0) {
1618 unsigned SubScale = SubBitWidth / BitWidth;
1619 KnownBits KnownSrc(SubBitWidth);
1620 APInt SubDemandedElts =
1621 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1622 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1623 Depth + 1);
1624
1625 Known.setAllConflict();
1626 for (unsigned i = 0; i != NumElts; ++i) {
1627 if (DemandedElts[i]) {
1628 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1629 unsigned Offset = (Shifts % SubScale) * BitWidth;
1630 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1631 if (Known.isUnknown())
1632 break;
1633 }
1634 }
1635 }
1636 break;
1637 }
1638 case Instruction::SExt: {
1639 // Compute the bits in the result that are not present in the input.
1640 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1641
1642 Known = Known.trunc(SrcBitWidth);
1643 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1644 // If the sign bit of the input is known set or clear, then we know the
1645 // top bits of the result.
1646 Known = Known.sext(BitWidth);
1647 break;
1648 }
1649 case Instruction::Shl: {
1652 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1653 bool ShAmtNonZero) {
1654 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1655 };
1656 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1657 KF);
1658 // Trailing zeros of a right-shifted constant never decrease.
1659 const APInt *C;
1660 if (match(I->getOperand(0), m_APInt(C)))
1661 Known.Zero.setLowBits(C->countr_zero());
1662
1663 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1664 // lands at bit Y, when BitWidth is a power of 2.
1665 const APInt *YC;
1666 Value *X = I->getOperand(0);
1667 if (isPowerOf2_32(BitWidth) &&
1668 match(I->getOperand(1),
1670 m_SpecificInt(BitWidth - 1)))) &&
1671 YC->ult(BitWidth - 1)) {
1672 unsigned Y = YC->getZExtValue();
1673 Known.One.setBit(Y);
1674 Known.Zero.setBitsFrom(Y + 1);
1675 }
1676 break;
1677 }
1678 case Instruction::LShr: {
1679 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1680 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1681 bool ShAmtNonZero) {
1682 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1683 };
1684 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1685 KF);
1686 // Leading zeros of a left-shifted constant never decrease.
1687 const APInt *C;
1688 if (match(I->getOperand(0), m_APInt(C)))
1689 Known.Zero.setHighBits(C->countl_zero());
1690 break;
1691 }
1692 case Instruction::AShr: {
1693 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1694 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1695 bool ShAmtNonZero) {
1696 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1697 };
1698 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1699 KF);
1700 break;
1701 }
1702 case Instruction::Sub: {
1705 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1706 DemandedElts, Known, Known2, Q, Depth);
1707 break;
1708 }
1709 case Instruction::Add: {
1712 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1713 DemandedElts, Known, Known2, Q, Depth);
1714 break;
1715 }
1716 case Instruction::SRem:
1717 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1718 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1719 Known = KnownBits::srem(Known, Known2);
1720 break;
1721
1722 case Instruction::URem:
1723 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1724 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1725 Known = KnownBits::urem(Known, Known2);
1726 break;
1727 case Instruction::Alloca:
1728 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1729 break;
1730 case Instruction::GetElementPtr: {
1731 // Analyze all of the subscripts of this getelementptr instruction
1732 // to determine if we can prove known low zero bits.
1733 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1734 // Accumulate the constant indices in a separate variable
1735 // to minimize the number of calls to computeForAddSub.
1736 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1737 APInt AccConstIndices(IndexWidth, 0);
1738
1739 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1740 if (IndexWidth == BitWidth) {
1741 // Note that inbounds does *not* guarantee nsw for the addition, as only
1742 // the offset is signed, while the base address is unsigned.
1743 Known = KnownBits::add(Known, IndexBits);
1744 } else {
1745 // If the index width is smaller than the pointer width, only add the
1746 // value to the low bits.
1747 assert(IndexWidth < BitWidth &&
1748 "Index width can't be larger than pointer width");
1749 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1750 }
1751 };
1752
1754 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1755 // TrailZ can only become smaller, short-circuit if we hit zero.
1756 if (Known.isUnknown())
1757 break;
1758
1759 Value *Index = I->getOperand(i);
1760
1761 // Handle case when index is zero.
1762 Constant *CIndex = dyn_cast<Constant>(Index);
1763 if (CIndex && CIndex->isNullValue())
1764 continue;
1765
1766 if (StructType *STy = GTI.getStructTypeOrNull()) {
1767 // Handle struct member offset arithmetic.
1768
1769 assert(CIndex &&
1770 "Access to structure field must be known at compile time");
1771
1772 if (CIndex->getType()->isVectorTy())
1773 Index = CIndex->getSplatValue();
1774
1775 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1776 const StructLayout *SL = Q.DL.getStructLayout(STy);
1777 uint64_t Offset = SL->getElementOffset(Idx);
1778 AccConstIndices += Offset;
1779 continue;
1780 }
1781
1782 // Handle array index arithmetic.
1783 Type *IndexedTy = GTI.getIndexedType();
1784 if (!IndexedTy->isSized()) {
1785 Known.resetAll();
1786 break;
1787 }
1788
1789 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1790 uint64_t StrideInBytes = Stride.getKnownMinValue();
1791 if (!Stride.isScalable()) {
1792 // Fast path for constant offset.
1793 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1794 AccConstIndices +=
1795 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1796 continue;
1797 }
1798 }
1799
1800 KnownBits IndexBits =
1801 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1802 KnownBits ScalingFactor(IndexWidth);
1803 // Multiply by current sizeof type.
1804 // &A[i] == A + i * sizeof(*A[i]).
1805 if (Stride.isScalable()) {
1806 // For scalable types the only thing we know about sizeof is
1807 // that this is a multiple of the minimum size.
1808 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1809 } else {
1810 ScalingFactor =
1811 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1812 }
1813 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1814 }
1815 if (!Known.isUnknown() && !AccConstIndices.isZero())
1816 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1817 break;
1818 }
1819 case Instruction::PHI: {
1820 const PHINode *P = cast<PHINode>(I);
1821 BinaryOperator *BO = nullptr;
1822 Value *R = nullptr, *L = nullptr;
1823 if (matchSimpleRecurrence(P, BO, R, L)) {
1824 // Handle the case of a simple two-predecessor recurrence PHI.
1825 // There's a lot more that could theoretically be done here, but
1826 // this is sufficient to catch some interesting cases.
1827 unsigned Opcode = BO->getOpcode();
1828
1829 switch (Opcode) {
1830 // If this is a shift recurrence, we know the bits being shifted in. We
1831 // can combine that with information about the start value of the
1832 // recurrence to conclude facts about the result. If this is a udiv
1833 // recurrence, we know that the result can never exceed either the
1834 // numerator or the start value, whichever is greater.
1835 case Instruction::LShr:
1836 case Instruction::AShr:
1837 case Instruction::Shl:
1838 case Instruction::UDiv:
1839 if (BO->getOperand(0) != I)
1840 break;
1841 [[fallthrough]];
1842
1843 // For a urem recurrence, the result can never exceed the start value. The
1844 // phi could either be the numerator or the denominator.
1845 case Instruction::URem: {
1846 // We have matched a recurrence of the form:
1847 // %iv = [R, %entry], [%iv.next, %backedge]
1848 // %iv.next = shift_op %iv, L
1849
1850 // Recurse with the phi context to avoid concern about whether facts
1851 // inferred hold at original context instruction. TODO: It may be
1852 // correct to use the original context. IF warranted, explore and
1853 // add sufficient tests to cover.
1855 RecQ.CxtI = P;
1856 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1857 switch (Opcode) {
1858 case Instruction::Shl:
1859 // A shl recurrence will only increase the tailing zeros
1860 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1861 break;
1862 case Instruction::LShr:
1863 case Instruction::UDiv:
1864 case Instruction::URem:
1865 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1866 // the start value.
1867 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1868 break;
1869 case Instruction::AShr:
1870 // An ashr recurrence will extend the initial sign bit
1871 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1872 Known.One.setHighBits(Known2.countMinLeadingOnes());
1873 break;
1874 }
1875 break;
1876 }
1877
1878 // Check for operations that have the property that if
1879 // both their operands have low zero bits, the result
1880 // will have low zero bits.
1881 case Instruction::Add:
1882 case Instruction::Sub:
1883 case Instruction::And:
1884 case Instruction::Or:
1885 case Instruction::Mul: {
1886 // Change the context instruction to the "edge" that flows into the
1887 // phi. This is important because that is where the value is actually
1888 // "evaluated" even though it is used later somewhere else. (see also
1889 // D69571).
1891
1892 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1893 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1894 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1895
1896 // Ok, we have a PHI of the form L op= R. Check for low
1897 // zero bits.
1898 RecQ.CxtI = RInst;
1899 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1900
1901 // We need to take the minimum number of known bits
1902 KnownBits Known3(BitWidth);
1903 RecQ.CxtI = LInst;
1904 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1905
1906 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1907 Known3.countMinTrailingZeros()));
1908
1909 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1910 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1911 break;
1912
1913 switch (Opcode) {
1914 // If initial value of recurrence is nonnegative, and we are adding
1915 // a nonnegative number with nsw, the result can only be nonnegative
1916 // or poison value regardless of the number of times we execute the
1917 // add in phi recurrence. If initial value is negative and we are
1918 // adding a negative number with nsw, the result can only be
1919 // negative or poison value. Similar arguments apply to sub and mul.
1920 //
1921 // (add non-negative, non-negative) --> non-negative
1922 // (add negative, negative) --> negative
1923 case Instruction::Add: {
1924 if (Known2.isNonNegative() && Known3.isNonNegative())
1925 Known.makeNonNegative();
1926 else if (Known2.isNegative() && Known3.isNegative())
1927 Known.makeNegative();
1928 break;
1929 }
1930
1931 // (sub nsw non-negative, negative) --> non-negative
1932 // (sub nsw negative, non-negative) --> negative
1933 case Instruction::Sub: {
1934 if (BO->getOperand(0) != I)
1935 break;
1936 if (Known2.isNonNegative() && Known3.isNegative())
1937 Known.makeNonNegative();
1938 else if (Known2.isNegative() && Known3.isNonNegative())
1939 Known.makeNegative();
1940 break;
1941 }
1942
1943 // (mul nsw non-negative, non-negative) --> non-negative
1944 case Instruction::Mul:
1945 if (Known2.isNonNegative() && Known3.isNonNegative())
1946 Known.makeNonNegative();
1947 break;
1948
1949 default:
1950 break;
1951 }
1952 break;
1953 }
1954
1955 default:
1956 break;
1957 }
1958 }
1959
1960 // Unreachable blocks may have zero-operand PHI nodes.
1961 if (P->getNumIncomingValues() == 0)
1962 break;
1963
1964 // Otherwise take the unions of the known bit sets of the operands,
1965 // taking conservative care to avoid excessive recursion.
1966 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1967 // Skip if every incoming value references to ourself.
1968 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1969 break;
1970
1971 Known.setAllConflict();
1972 for (const Use &U : P->operands()) {
1973 Value *IncValue;
1974 const PHINode *CxtPhi;
1975 Instruction *CxtI;
1976 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1977 // Skip direct self references.
1978 if (IncValue == P)
1979 continue;
1980
1981 // Change the context instruction to the "edge" that flows into the
1982 // phi. This is important because that is where the value is actually
1983 // "evaluated" even though it is used later somewhere else. (see also
1984 // D69571).
1986
1987 Known2 = KnownBits(BitWidth);
1988
1989 // Recurse, but cap the recursion to one level, because we don't
1990 // want to waste time spinning around in loops.
1991 // TODO: See if we can base recursion limiter on number of incoming phi
1992 // edges so we don't overly clamp analysis.
1993 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1995
1996 // See if we can further use a conditional branch into the phi
1997 // to help us determine the range of the value.
1998 if (!Known2.isConstant()) {
1999 CmpPredicate Pred;
2000 const APInt *RHSC;
2001 BasicBlock *TrueSucc, *FalseSucc;
2002 // TODO: Use RHS Value and compute range from its known bits.
2003 if (match(RecQ.CxtI,
2004 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2005 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2006 // Check for cases of duplicate successors.
2007 if ((TrueSucc == CxtPhi->getParent()) !=
2008 (FalseSucc == CxtPhi->getParent())) {
2009 // If we're using the false successor, invert the predicate.
2010 if (FalseSucc == CxtPhi->getParent())
2011 Pred = CmpInst::getInversePredicate(Pred);
2012 // Get the knownbits implied by the incoming phi condition.
2013 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2014 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2015 // We can have conflicts here if we are analyzing deadcode (its
2016 // impossible for us reach this BB based the icmp).
2017 if (KnownUnion.hasConflict()) {
2018 // No reason to continue analyzing in a known dead region, so
2019 // just resetAll and break. This will cause us to also exit the
2020 // outer loop.
2021 Known.resetAll();
2022 break;
2023 }
2024 Known2 = KnownUnion;
2025 }
2026 }
2027 }
2028
2029 Known = Known.intersectWith(Known2);
2030 // If all bits have been ruled out, there's no need to check
2031 // more operands.
2032 if (Known.isUnknown())
2033 break;
2034 }
2035 }
2036 break;
2037 }
2038 case Instruction::Call:
2039 case Instruction::Invoke: {
2040 // If range metadata is attached to this call, set known bits from that,
2041 // and then intersect with known bits based on other properties of the
2042 // function.
2043 if (MDNode *MD =
2044 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2046
2047 const auto *CB = cast<CallBase>(I);
2048
2049 if (std::optional<ConstantRange> Range = CB->getRange())
2050 Known = Known.unionWith(Range->toKnownBits());
2051
2052 if (const Value *RV = CB->getReturnedArgOperand()) {
2053 if (RV->getType() == I->getType()) {
2054 computeKnownBits(RV, Known2, Q, Depth + 1);
2055 Known = Known.unionWith(Known2);
2056 // If the function doesn't return properly for all input values
2057 // (e.g. unreachable exits) then there might be conflicts between the
2058 // argument value and the range metadata. Simply discard the known bits
2059 // in case of conflicts.
2060 if (Known.hasConflict())
2061 Known.resetAll();
2062 }
2063 }
2064 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2065 switch (II->getIntrinsicID()) {
2066 default:
2067 break;
2068 case Intrinsic::abs: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2071 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2072 break;
2073 }
2074 case Intrinsic::bitreverse:
2075 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2076 Known = Known.unionWith(Known2.reverseBits());
2077 break;
2078 case Intrinsic::bswap:
2079 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2080 Known = Known.unionWith(Known2.byteSwap());
2081 break;
2082 case Intrinsic::ctlz: {
2083 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2084 // If we have a known 1, its position is our upper bound.
2085 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2086 // If this call is poison for 0 input, the result will be less than 2^n.
2087 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2088 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2089 unsigned LowBits = llvm::bit_width(PossibleLZ);
2090 Known.Zero.setBitsFrom(LowBits);
2091 break;
2092 }
2093 case Intrinsic::cttz: {
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2095 // If we have a known 1, its position is our upper bound.
2096 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2097 // If this call is poison for 0 input, the result will be less than 2^n.
2098 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2099 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2100 unsigned LowBits = llvm::bit_width(PossibleTZ);
2101 Known.Zero.setBitsFrom(LowBits);
2102 break;
2103 }
2104 case Intrinsic::ctpop: {
2105 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2106 // We can bound the space the count needs. Also, bits known to be zero
2107 // can't contribute to the population.
2108 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2109 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2110 Known.Zero.setBitsFrom(LowBits);
2111 // TODO: we could bound KnownOne using the lower bound on the number
2112 // of bits which might be set provided by popcnt KnownOne2.
2113 break;
2114 }
2115 case Intrinsic::fshr:
2116 case Intrinsic::fshl: {
2117 const APInt *SA;
2118 if (!match(I->getOperand(2), m_APInt(SA)))
2119 break;
2120
2121 KnownBits Known3(BitWidth);
2122 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2123 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2124 Known = II->getIntrinsicID() == Intrinsic::fshl
2125 ? KnownBits::fshl(Known2, Known3, *SA)
2126 : KnownBits::fshr(Known2, Known3, *SA);
2127 break;
2128 }
2129 case Intrinsic::clmul:
2130 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2131 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2132 Known = KnownBits::clmul(Known, Known2);
2133 break;
2134 case Intrinsic::pext:
2135 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2136 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2137 Known = KnownBits::pext(Known, Known2);
2138 break;
2139 case Intrinsic::pdep:
2140 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2141 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2142 Known = KnownBits::pdep(Known, Known2);
2143 break;
2144 case Intrinsic::uadd_sat:
2145 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2146 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2147 Known = KnownBits::uadd_sat(Known, Known2);
2148 break;
2149 case Intrinsic::usub_sat:
2150 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2151 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2152 Known = KnownBits::usub_sat(Known, Known2);
2153 break;
2154 case Intrinsic::sadd_sat:
2155 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2156 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2157 Known = KnownBits::sadd_sat(Known, Known2);
2158 break;
2159 case Intrinsic::ssub_sat:
2160 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2161 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2162 Known = KnownBits::ssub_sat(Known, Known2);
2163 break;
2164 // Vec reverse preserves bits from input vec.
2165 case Intrinsic::vector_reverse:
2166 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2167 Depth + 1);
2168 break;
2169 // for min/max/and/or reduce, any bit common to each element in the
2170 // input vec is set in the output.
2171 case Intrinsic::vector_reduce_and:
2172 case Intrinsic::vector_reduce_or:
2173 case Intrinsic::vector_reduce_umax:
2174 case Intrinsic::vector_reduce_umin:
2175 case Intrinsic::vector_reduce_smax:
2176 case Intrinsic::vector_reduce_smin:
2177 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2178 break;
2179 case Intrinsic::vector_reduce_xor: {
2180 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2181 // The zeros common to all vecs are zero in the output.
2182 // If the number of elements is odd, then the common ones remain. If the
2183 // number of elements is even, then the common ones becomes zeros.
2184 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2185 // Even, so the ones become zeros.
2186 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2187 if (EvenCnt)
2188 Known.Zero |= Known.One;
2189 // Maybe even element count so need to clear ones.
2190 if (VecTy->isScalableTy() || EvenCnt)
2191 Known.One.clearAllBits();
2192 break;
2193 }
2194 case Intrinsic::vector_reduce_add: {
2195 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2196 if (!VecTy)
2197 break;
2198 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2199 Known = Known.reduceAdd(VecTy->getNumElements());
2200 break;
2201 }
2202 case Intrinsic::umin:
2203 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2204 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2205 Known = KnownBits::umin(Known, Known2);
2206 break;
2207 case Intrinsic::umax:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::umax(Known, Known2);
2211 break;
2212 case Intrinsic::smin:
2213 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2214 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2215 Known = KnownBits::smin(Known, Known2);
2217 break;
2218 case Intrinsic::smax:
2219 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2220 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2221 Known = KnownBits::smax(Known, Known2);
2223 break;
2224 case Intrinsic::ptrmask: {
2225 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2226
2227 const Value *Mask = I->getOperand(1);
2228 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2229 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2230 // TODO: 1-extend would be more precise.
2231 Known &= Known2.anyextOrTrunc(BitWidth);
2232 break;
2233 }
2234 case Intrinsic::x86_sse2_pmulh_w:
2235 case Intrinsic::x86_avx2_pmulh_w:
2236 case Intrinsic::x86_avx512_pmulh_w_512:
2237 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2238 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2239 Known = KnownBits::mulhs(Known, Known2);
2240 break;
2241 case Intrinsic::x86_sse2_pmulhu_w:
2242 case Intrinsic::x86_avx2_pmulhu_w:
2243 case Intrinsic::x86_avx512_pmulhu_w_512:
2244 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2245 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2246 Known = KnownBits::mulhu(Known, Known2);
2247 break;
2248 case Intrinsic::x86_sse42_crc32_64_64:
2249 Known.Zero.setBitsFrom(32);
2250 break;
2251 case Intrinsic::x86_ssse3_phadd_d_128:
2252 case Intrinsic::x86_ssse3_phadd_w_128:
2253 case Intrinsic::x86_avx2_phadd_d:
2254 case Intrinsic::x86_avx2_phadd_w: {
2256 I, DemandedElts, Q, Depth,
2257 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2258 return KnownBits::add(KnownLHS, KnownRHS);
2259 });
2260 break;
2261 }
2262 case Intrinsic::x86_ssse3_phadd_sw_128:
2263 case Intrinsic::x86_avx2_phadd_sw: {
2265 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2266 break;
2267 }
2268 case Intrinsic::x86_ssse3_phsub_d_128:
2269 case Intrinsic::x86_ssse3_phsub_w_128:
2270 case Intrinsic::x86_avx2_phsub_d:
2271 case Intrinsic::x86_avx2_phsub_w: {
2273 I, DemandedElts, Q, Depth,
2274 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2275 return KnownBits::sub(KnownLHS, KnownRHS);
2276 });
2277 break;
2278 }
2279 case Intrinsic::x86_ssse3_phsub_sw_128:
2280 case Intrinsic::x86_avx2_phsub_sw: {
2282 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2283 break;
2284 }
2285 case Intrinsic::riscv_vsetvli:
2286 case Intrinsic::riscv_vsetvlimax: {
2287 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2288 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2290 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2291 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2292 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2293 uint64_t MaxVLEN =
2294 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2295 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2296
2297 // Result of vsetvli must be not larger than AVL.
2298 if (HasAVL)
2299 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2300 MaxVL = std::min(MaxVL, CI->getZExtValue());
2301
2302 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2303 if (BitWidth > KnownZeroFirstBit)
2304 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2305 break;
2306 }
2307 case Intrinsic::amdgcn_mbcnt_hi:
2308 case Intrinsic::amdgcn_mbcnt_lo: {
2309 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2310 // most 31 + src1.
2311 Known.Zero.setBitsFrom(
2312 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2313 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2314 Known = KnownBits::add(Known, Known2);
2315 break;
2316 }
2317 case Intrinsic::vscale: {
2318 if (!II->getParent() || !II->getFunction())
2319 break;
2320
2321 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2322 break;
2323 }
2324 case Intrinsic::stepvector: {
2325 auto *VecTy = cast<VectorType>(II->getType());
2326 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2327 if (!isUIntN(BitWidth, MinNumElts))
2328 break;
2329
2330 bool Overflow = false;
2331 APInt MaxNumElts(BitWidth, MinNumElts);
2332 if (VecTy->isScalableTy()) {
2333 if (!II->getParent() || !II->getFunction())
2334 break;
2335 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2337 .umul_ov(MaxNumElts, Overflow);
2338 }
2339
2340 // Give up if the lane count could wrap. Stepvector truncates lane
2341 // indices that do not fit in the element type.
2342 if (Overflow)
2343 break;
2344
2345 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2346 break;
2347 }
2348 }
2349 }
2350 break;
2351 }
2352 case Instruction::ShuffleVector: {
2353 if (auto *Splat = getSplatValue(I)) {
2355 break;
2356 }
2357
2358 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2359 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2360 if (!Shuf) {
2361 Known.resetAll();
2362 return;
2363 }
2364 // For undef elements, we don't know anything about the common state of
2365 // the shuffle result.
2366 APInt DemandedLHS, DemandedRHS;
2367 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2368 Known.resetAll();
2369 return;
2370 }
2371 Known.setAllConflict();
2372 if (!!DemandedLHS) {
2373 const Value *LHS = Shuf->getOperand(0);
2374 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2375 // If we don't know any bits, early out.
2376 if (Known.isUnknown())
2377 break;
2378 }
2379 if (!!DemandedRHS) {
2380 const Value *RHS = Shuf->getOperand(1);
2381 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2382 Known = Known.intersectWith(Known2);
2383 }
2384 break;
2385 }
2386 case Instruction::InsertElement: {
2387 if (isa<ScalableVectorType>(I->getType())) {
2388 Known.resetAll();
2389 return;
2390 }
2391 const Value *Vec = I->getOperand(0);
2392 const Value *Elt = I->getOperand(1);
2393 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2394 unsigned NumElts = DemandedElts.getBitWidth();
2395 APInt DemandedVecElts = DemandedElts;
2396 bool NeedsElt = true;
2397 // If we know the index we are inserting too, clear it from Vec check.
2398 if (CIdx && CIdx->getValue().ult(NumElts)) {
2399 DemandedVecElts.clearBit(CIdx->getZExtValue());
2400 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2401 }
2402
2403 Known.setAllConflict();
2404 if (NeedsElt) {
2405 computeKnownBits(Elt, Known, Q, Depth + 1);
2406 // If we don't know any bits, early out.
2407 if (Known.isUnknown())
2408 break;
2409 }
2410
2411 if (!DemandedVecElts.isZero()) {
2412 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2413 Known = Known.intersectWith(Known2);
2414 }
2415 break;
2416 }
2417 case Instruction::ExtractElement: {
2418 // Look through extract element. If the index is non-constant or
2419 // out-of-range demand all elements, otherwise just the extracted element.
2420 const Value *Vec = I->getOperand(0);
2421 const Value *Idx = I->getOperand(1);
2422 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2423 if (isa<ScalableVectorType>(Vec->getType())) {
2424 // FIXME: there's probably *something* we can do with scalable vectors
2425 Known.resetAll();
2426 break;
2427 }
2428 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2429 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2430 if (CIdx && CIdx->getValue().ult(NumElts))
2431 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2432 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2433 break;
2434 }
2435 case Instruction::ExtractValue:
2436 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2438 if (EVI->getNumIndices() != 1) break;
2439 if (EVI->getIndices()[0] == 0) {
2440 switch (II->getIntrinsicID()) {
2441 default: break;
2442 case Intrinsic::uadd_with_overflow:
2443 case Intrinsic::sadd_with_overflow:
2445 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2446 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2447 break;
2448 case Intrinsic::usub_with_overflow:
2449 case Intrinsic::ssub_with_overflow:
2451 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2452 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2453 break;
2454 case Intrinsic::umul_with_overflow:
2455 case Intrinsic::smul_with_overflow:
2456 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2457 false, DemandedElts, Known, Known2, Q, Depth);
2458 break;
2459 }
2460 }
2461 }
2462 break;
2463 case Instruction::Freeze:
2464 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2465 Depth + 1))
2466 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2467 break;
2468 }
2469}
2470
2471/// Determine which bits of V are known to be either zero or one and return
2472/// them.
2473KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2474 const SimplifyQuery &Q, unsigned Depth) {
2475 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2476 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2477 return Known;
2478}
2479
2480/// Determine which bits of V are known to be either zero or one and return
2481/// them.
2483 unsigned Depth) {
2484 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2486 return Known;
2487}
2488
2489/// Determine which bits of V are known to be either zero or one and return
2490/// them in the Known bit set.
2491///
2492/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2493/// we cannot optimize based on the assumption that it is zero without changing
2494/// it to be an explicit zero. If we don't change it to zero, other code could
2495/// optimized based on the contradictory assumption that it is non-zero.
2496/// Because instcombine aggressively folds operations with undef args anyway,
2497/// this won't lose us code quality.
2498///
2499/// This function is defined on values with integer type, values with pointer
2500/// type, and vectors of integers. In the case
2501/// where V is a vector, known zero, and known one values are the
2502/// same width as the vector element, and the bit is set only if it is true
2503/// for all of the demanded elements in the vector specified by DemandedElts.
2504void computeKnownBits(const Value *V, const APInt &DemandedElts,
2505 KnownBits &Known, const SimplifyQuery &Q,
2506 unsigned Depth) {
2507 if (!DemandedElts) {
2508 // No demanded elts, better to assume we don't know anything.
2509 Known.resetAll();
2510 return;
2511 }
2512
2513 assert(V && "No Value?");
2514 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2515
2516#ifndef NDEBUG
2517 Type *Ty = V->getType();
2518 unsigned BitWidth = Known.getBitWidth();
2519
2520 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2521 "Not integer or pointer type!");
2522
2523 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2524 assert(
2525 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2526 "DemandedElt width should equal the fixed vector number of elements");
2527 } else {
2528 assert(DemandedElts == APInt(1, 1) &&
2529 "DemandedElt width should be 1 for scalars or scalable vectors");
2530 }
2531
2532 Type *ScalarTy = Ty->getScalarType();
2533 if (ScalarTy->isPointerTy()) {
2534 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2535 "V and Known should have same BitWidth");
2536 } else {
2537 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2538 "V and Known should have same BitWidth");
2539 }
2540#endif
2541
2542 const APInt *C;
2543 if (match(V, m_APInt(C))) {
2544 // We know all of the bits for a scalar constant or a splat vector constant!
2546 return;
2547 }
2548 // Null and aggregate-zero are all-zeros.
2550 Known.setAllZero();
2551 return;
2552 }
2553 // Handle a constant vector by taking the intersection of the known bits of
2554 // each element.
2556 assert(!isa<ScalableVectorType>(V->getType()));
2557 // We know that CDV must be a vector of integers. Take the intersection of
2558 // each element.
2559 Known.setAllConflict();
2560 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2561 if (!DemandedElts[i])
2562 continue;
2563 APInt Elt = CDV->getElementAsAPInt(i);
2564 Known.Zero &= ~Elt;
2565 Known.One &= Elt;
2566 }
2567 if (Known.hasConflict())
2568 Known.resetAll();
2569 return;
2570 }
2571
2572 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2573 assert(!isa<ScalableVectorType>(V->getType()));
2574 // We know that CV must be a vector of integers. Take the intersection of
2575 // each element.
2576 Known.setAllConflict();
2577 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2578 if (!DemandedElts[i])
2579 continue;
2580 Constant *Element = CV->getAggregateElement(i);
2581 if (isa<PoisonValue>(Element))
2582 continue;
2583 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2584 if (!ElementCI) {
2585 Known.resetAll();
2586 return;
2587 }
2588 const APInt &Elt = ElementCI->getValue();
2589 Known.Zero &= ~Elt;
2590 Known.One &= Elt;
2591 }
2592 if (Known.hasConflict())
2593 Known.resetAll();
2594 return;
2595 }
2596
2597 // Start out not knowing anything.
2598 Known.resetAll();
2599
2600 // We can't imply anything about undefs.
2601 if (isa<UndefValue>(V))
2602 return;
2603
2604 // There's no point in looking through other users of ConstantData for
2605 // assumptions. Confirm that we've handled them all.
2606 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2607
2608 if (const auto *A = dyn_cast<Argument>(V))
2609 if (std::optional<ConstantRange> Range = A->getRange())
2610 Known = Range->toKnownBits();
2611
2612 // All recursive calls that increase depth must come after this.
2614 return;
2615
2616 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2617 // the bits of its aliasee.
2618 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2619 if (!GA->isInterposable())
2620 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2621 return;
2622 }
2623
2624 if (const Operator *I = dyn_cast<Operator>(V))
2625 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2626 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2627 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2628 Known = CR->toKnownBits();
2629 }
2630
2631 // Aligned pointers have trailing zeros - refine Known.Zero set
2632 if (isa<PointerType>(V->getType())) {
2633 Align Alignment = V->getPointerAlignment(Q.DL);
2634 Known.Zero.setLowBits(Log2(Alignment));
2635 }
2636
2637 // computeKnownBitsFromContext strictly refines Known.
2638 // Therefore, we run them after computeKnownBitsFromOperator.
2639
2640 // Check whether we can determine known bits from context such as assumes.
2642}
2643
2644/// Try to detect a recurrence that the value of the induction variable is
2645/// always a power of two (or zero).
2646static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2647 SimplifyQuery &Q, unsigned Depth) {
2648 BinaryOperator *BO = nullptr;
2649 Value *Start = nullptr, *Step = nullptr;
2650 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2651 return false;
2652
2653 // Initial value must be a power of two.
2654 for (const Use &U : PN->operands()) {
2655 if (U.get() == Start) {
2656 // Initial value comes from a different BB, need to adjust context
2657 // instruction for analysis.
2658 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2659 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2660 return false;
2661 }
2662 }
2663
2664 // Except for Mul, the induction variable must be on the left side of the
2665 // increment expression, otherwise its value can be arbitrary.
2666 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2667 return false;
2668
2669 Q.CxtI = BO->getParent()->getTerminator();
2670 switch (BO->getOpcode()) {
2671 case Instruction::Mul:
2672 // Power of two is closed under multiplication.
2673 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2674 Q.IIQ.hasNoSignedWrap(BO)) &&
2675 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2676 case Instruction::SDiv:
2677 // Start value must not be signmask for signed division, so simply being a
2678 // power of two is not sufficient, and it has to be a constant.
2679 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2680 return false;
2681 [[fallthrough]];
2682 case Instruction::UDiv:
2683 // Divisor must be a power of two.
2684 // If OrZero is false, cannot guarantee induction variable is non-zero after
2685 // division, same for Shr, unless it is exact division.
2686 return (OrZero || Q.IIQ.isExact(BO)) &&
2687 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2688 case Instruction::Shl:
2689 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2690 case Instruction::AShr:
2691 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2692 return false;
2693 [[fallthrough]];
2694 case Instruction::LShr:
2695 return OrZero || Q.IIQ.isExact(BO);
2696 default:
2697 return false;
2698 }
2699}
2700
2701/// Return true if we can infer that \p V is known to be a power of 2 from
2702/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2703static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2704 const Value *Cond,
2705 bool CondIsTrue) {
2706 CmpPredicate Pred;
2707 const APInt *RHSC;
2708 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2709 return false;
2710 if (!CondIsTrue)
2711 Pred = ICmpInst::getInversePredicate(Pred);
2712 // ctpop(V) u< 2
2713 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2714 return true;
2715 // ctpop(V) == 1
2716 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2717}
2718
2719/// Return true if the given value is known to have exactly one
2720/// bit set when defined. For vectors return true if every element is known to
2721/// be a power of two when defined. Supports values with integer or pointer
2722/// types and vectors of integers.
2723bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2724 const SimplifyQuery &Q, unsigned Depth) {
2725 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2726
2727 if (isa<Constant>(V))
2728 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2729
2730 // i1 is by definition a power of 2 or zero.
2731 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2732 return true;
2733
2734 // Try to infer from assumptions.
2735 if (Q.AC && Q.CxtI) {
2736 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2737 if (!AssumeVH)
2738 continue;
2739 CallInst *I = cast<CallInst>(AssumeVH);
2740 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2741 /*CondIsTrue=*/true) &&
2743 return true;
2744 }
2745 }
2746
2747 // Handle dominating conditions.
2748 if (Q.DC && Q.CxtI && Q.DT) {
2749 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2750 Value *Cond = BI->getCondition();
2751
2752 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2754 /*CondIsTrue=*/true) &&
2755 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2756 return true;
2757
2758 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2760 /*CondIsTrue=*/false) &&
2761 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2762 return true;
2763 }
2764 }
2765
2766 auto *I = dyn_cast<Instruction>(V);
2767 if (!I)
2768 return false;
2769
2770 if (Q.CxtI && match(V, m_VScale())) {
2771 const Function *F = Q.CxtI->getFunction();
2772 // The vscale_range indicates vscale is a power-of-two.
2773 return F->hasFnAttribute(Attribute::VScaleRange);
2774 }
2775
2776 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2777 // it is shifted off the end then the result is undefined.
2778 if (match(I, m_Shl(m_One(), m_Value())))
2779 return true;
2780
2781 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2782 // the bottom. If it is shifted off the bottom then the result is undefined.
2783 if (match(I, m_LShr(m_SignMask(), m_Value())))
2784 return true;
2785
2786 // The remaining tests are all recursive, so bail out if we hit the limit.
2788 return false;
2789
2790 switch (I->getOpcode()) {
2791 case Instruction::ZExt:
2792 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2793 case Instruction::Trunc:
2794 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2795 case Instruction::Shl:
2796 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2797 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2798 return false;
2799 case Instruction::LShr:
2800 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2801 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2802 return false;
2803 case Instruction::UDiv:
2805 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2806 return false;
2807 case Instruction::Mul:
2808 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2809 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2810 (OrZero || isKnownNonZero(I, Q, Depth));
2811 case Instruction::And:
2812 // A power of two and'd with anything is a power of two or zero.
2813 if (OrZero &&
2814 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2815 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2816 return true;
2817 // X & (-X) is always a power of two or zero.
2818 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2819 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2820 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2821 return false;
2822 case Instruction::Add: {
2823 // Adding a power-of-two or zero to the same power-of-two or zero yields
2824 // either the original power-of-two, a larger power-of-two or zero.
2826 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2827 Q.IIQ.hasNoSignedWrap(VOBO)) {
2828 if (match(I->getOperand(0),
2829 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2830 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2831 return true;
2832 if (match(I->getOperand(1),
2833 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2834 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2835 return true;
2836
2837 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2838 KnownBits LHSBits(BitWidth);
2839 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2840
2841 KnownBits RHSBits(BitWidth);
2842 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2843 // If i8 V is a power of two or zero:
2844 // ZeroBits: 1 1 1 0 1 1 1 1
2845 // ~ZeroBits: 0 0 0 1 0 0 0 0
2846 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2847 // If OrZero isn't set, we cannot give back a zero result.
2848 // Make sure either the LHS or RHS has a bit set.
2849 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2850 return true;
2851 }
2852
2853 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2854 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2855 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2856 return true;
2857 return false;
2858 }
2859 case Instruction::Select:
2860 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2861 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2862 case Instruction::PHI: {
2863 // A PHI node is power of two if all incoming values are power of two, or if
2864 // it is an induction variable where in each step its value is a power of
2865 // two.
2866 auto *PN = cast<PHINode>(I);
2868
2869 // Check if it is an induction variable and always power of two.
2870 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2871 return true;
2872
2873 // Recursively check all incoming values. Limit recursion to 2 levels, so
2874 // that search complexity is limited to number of operands^2.
2875 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2876 return llvm::all_of(PN->operands(), [&](const Use &U) {
2877 // Value is power of 2 if it is coming from PHI node itself by induction.
2878 if (U.get() == PN)
2879 return true;
2880
2881 // Change the context instruction to the incoming block where it is
2882 // evaluated.
2883 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2884 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2885 });
2886 }
2887 case Instruction::Invoke:
2888 case Instruction::Call: {
2889 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2890 switch (II->getIntrinsicID()) {
2891 case Intrinsic::umax:
2892 case Intrinsic::smax:
2893 case Intrinsic::umin:
2894 case Intrinsic::smin:
2895 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2896 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2897 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2898 // thus dont change pow2/non-pow2 status.
2899 case Intrinsic::bitreverse:
2900 case Intrinsic::bswap:
2901 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2902 case Intrinsic::fshr:
2903 case Intrinsic::fshl:
2904 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2905 if (II->getArgOperand(0) == II->getArgOperand(1))
2906 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2907 break;
2908 case Intrinsic::riscv_vsetvlimax:
2909 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2910 // for any valid vtype, so it is a power of two regardless of OrZero.
2911 return true;
2912 case Intrinsic::read_register:
2913 case Intrinsic::read_volatile_register: {
2914 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2915 // of two, so it is a power of two regardless of OrZero.
2916 const Module *M = II->getModule();
2917 if (!M || !M->getTargetTriple().isRISCV())
2918 break;
2919 return isReadVLENB(*II);
2920 }
2921 default:
2922 break;
2923 }
2924 }
2925 return false;
2926 }
2927 default:
2928 return false;
2929 }
2930}
2931
2932/// Test whether a GEP's result is known to be non-null.
2933///
2934/// Uses properties inherent in a GEP to try to determine whether it is known
2935/// to be non-null.
2936///
2937/// Currently this routine does not support vector GEPs.
2938static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2939 unsigned Depth) {
2940 const Function *F = nullptr;
2941 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2942 F = I->getFunction();
2943
2944 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2945 // may be null iff the base pointer is null and the offset is zero.
2946 if (!GEP->hasNoUnsignedWrap() &&
2947 !(GEP->isInBounds() &&
2948 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2949 return false;
2950
2951 // FIXME: Support vector-GEPs.
2952 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2953
2954 // If the base pointer is non-null, we cannot walk to a null address with an
2955 // inbounds GEP in address space zero.
2956 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2957 return true;
2958
2959 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2960 // If so, then the GEP cannot produce a null pointer, as doing so would
2961 // inherently violate the inbounds contract within address space zero.
2963 GTI != GTE; ++GTI) {
2964 // Struct types are easy -- they must always be indexed by a constant.
2965 if (StructType *STy = GTI.getStructTypeOrNull()) {
2966 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2967 unsigned ElementIdx = OpC->getZExtValue();
2968 const StructLayout *SL = Q.DL.getStructLayout(STy);
2969 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2970 if (ElementOffset > 0)
2971 return true;
2972 continue;
2973 }
2974
2975 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2976 if (GTI.getSequentialElementStride(Q.DL).isZero())
2977 continue;
2978
2979 // Fast path the constant operand case both for efficiency and so we don't
2980 // increment Depth when just zipping down an all-constant GEP.
2981 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2982 if (!OpC->isZero())
2983 return true;
2984 continue;
2985 }
2986
2987 // We post-increment Depth here because while isKnownNonZero increments it
2988 // as well, when we pop back up that increment won't persist. We don't want
2989 // to recurse 10k times just because we have 10k GEP operands. We don't
2990 // bail completely out because we want to handle constant GEPs regardless
2991 // of depth.
2993 continue;
2994
2995 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2996 return true;
2997 }
2998
2999 return false;
3000}
3001
3003 const Instruction *CtxI,
3004 const DominatorTree *DT) {
3005 assert(!isa<Constant>(V) && "Called for constant?");
3006
3007 if (!CtxI || !DT)
3008 return false;
3009
3010 unsigned NumUsesExplored = 0;
3011 for (auto &U : V->uses()) {
3012 // Avoid massive lists
3013 if (NumUsesExplored >= DomConditionsMaxUses)
3014 break;
3015 NumUsesExplored++;
3016
3017 const Instruction *UI = cast<Instruction>(U.getUser());
3018 // If the value is used as an argument to a call or invoke, then argument
3019 // attributes may provide an answer about null-ness.
3020 if (V->getType()->isPointerTy()) {
3021 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3022 if (CB->isArgOperand(&U) &&
3023 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3024 /*AllowUndefOrPoison=*/false) &&
3025 DT->dominates(CB, CtxI))
3026 return true;
3027 }
3028 }
3029
3030 // If the value is used as a load/store, then the pointer must be non null.
3031 if (V == getLoadStorePointerOperand(UI)) {
3034 DT->dominates(UI, CtxI))
3035 return true;
3036 }
3037
3038 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3039 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3040 isValidAssumeForContext(UI, CtxI, DT))
3041 return true;
3042
3043 // Consider only compare instructions uniquely controlling a branch
3044 Value *RHS;
3045 CmpPredicate Pred;
3046 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3047 continue;
3048
3049 bool NonNullIfTrue;
3050 if (cmpExcludesZero(Pred, RHS))
3051 NonNullIfTrue = true;
3053 NonNullIfTrue = false;
3054 else
3055 continue;
3056
3059 for (const auto *CmpU : UI->users()) {
3060 assert(WorkList.empty() && "Should be!");
3061 if (Visited.insert(CmpU).second)
3062 WorkList.push_back(CmpU);
3063
3064 while (!WorkList.empty()) {
3065 auto *Curr = WorkList.pop_back_val();
3066
3067 // If a user is an AND, add all its users to the work list. We only
3068 // propagate "pred != null" condition through AND because it is only
3069 // correct to assume that all conditions of AND are met in true branch.
3070 // TODO: Support similar logic of OR and EQ predicate?
3071 if (NonNullIfTrue)
3072 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3073 for (const auto *CurrU : Curr->users())
3074 if (Visited.insert(CurrU).second)
3075 WorkList.push_back(CurrU);
3076 continue;
3077 }
3078
3079 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3080 BasicBlock *NonNullSuccessor =
3081 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3082 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3083 if (DT->dominates(Edge, CtxI->getParent()))
3084 return true;
3085 } else if (NonNullIfTrue && isGuard(Curr) &&
3086 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3087 return true;
3088 }
3089 }
3090 }
3091 }
3092
3093 return false;
3094}
3095
3096/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3097/// ensure that the value it's attached to is never Value? 'RangeType' is
3098/// is the type of the value described by the range.
3099static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3100 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3101 assert(NumRanges >= 1);
3102 for (unsigned i = 0; i < NumRanges; ++i) {
3104 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3106 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3107 ConstantRange Range(Lower->getValue(), Upper->getValue());
3108 if (Range.contains(Value))
3109 return false;
3110 }
3111 return true;
3112}
3113
3114/// Try to detect a recurrence that monotonically increases/decreases from a
3115/// non-zero starting value. These are common as induction variables.
3116static bool isNonZeroRecurrence(const PHINode *PN) {
3117 BinaryOperator *BO = nullptr;
3118 Value *Start = nullptr, *Step = nullptr;
3119 const APInt *StartC, *StepC;
3120 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3121 !match(Start, m_APInt(StartC)) || StartC->isZero())
3122 return false;
3123
3124 switch (BO->getOpcode()) {
3125 case Instruction::Add:
3126 // Starting from non-zero and stepping away from zero can never wrap back
3127 // to zero.
3128 return BO->hasNoUnsignedWrap() ||
3129 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3130 StartC->isNegative() == StepC->isNegative());
3131 case Instruction::Mul:
3132 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3133 match(Step, m_APInt(StepC)) && !StepC->isZero();
3134 case Instruction::Shl:
3135 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3136 case Instruction::AShr:
3137 case Instruction::LShr:
3138 return BO->isExact();
3139 default:
3140 return false;
3141 }
3142}
3143
3144static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3146 m_Specific(Op1), m_Zero()))) ||
3148 m_Specific(Op0), m_Zero())));
3149}
3150
3151static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3152 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3153 bool NUW, unsigned Depth) {
3154 // (X + (X != 0)) is non zero
3155 if (matchOpWithOpEqZero(X, Y))
3156 return true;
3157
3158 if (NUW)
3159 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3160 isKnownNonZero(X, DemandedElts, Q, Depth);
3161
3162 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3163 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3164
3165 // If X and Y are both non-negative (as signed values) then their sum is not
3166 // zero unless both X and Y are zero.
3167 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3168 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3169 isKnownNonZero(X, DemandedElts, Q, Depth))
3170 return true;
3171
3172 // If X and Y are both negative (as signed values) then their sum is not
3173 // zero unless both X and Y equal INT_MIN.
3174 if (XKnown.isNegative() && YKnown.isNegative()) {
3176 // The sign bit of X is set. If some other bit is set then X is not equal
3177 // to INT_MIN.
3178 if (XKnown.One.intersects(Mask))
3179 return true;
3180 // The sign bit of Y is set. If some other bit is set then Y is not equal
3181 // to INT_MIN.
3182 if (YKnown.One.intersects(Mask))
3183 return true;
3184 }
3185
3186 // The sum of a non-negative number and a power of two is not zero.
3187 if (XKnown.isNonNegative() &&
3188 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3189 return true;
3190 if (YKnown.isNonNegative() &&
3191 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3192 return true;
3193
3194 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3195}
3196
3197static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3198 unsigned BitWidth, Value *X, Value *Y,
3199 unsigned Depth) {
3200 // (X - (X != 0)) is non zero
3201 // ((X != 0) - X) is non zero
3202 if (matchOpWithOpEqZero(X, Y))
3203 return true;
3204
3205 // TODO: Move this case into isKnownNonEqual().
3206 if (auto *C = dyn_cast<Constant>(X))
3207 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3208 return true;
3209
3210 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3211}
3212
3213static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3214 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3215 bool NUW, unsigned Depth) {
3216 // If X and Y are non-zero then so is X * Y as long as the multiplication
3217 // does not overflow.
3218 if (NSW || NUW)
3219 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3220 isKnownNonZero(Y, DemandedElts, Q, Depth);
3221
3222 // If either X or Y is odd, then if the other is non-zero the result can't
3223 // be zero.
3224 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3225 if (XKnown.One[0])
3226 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3227
3228 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3229 if (YKnown.One[0])
3230 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3231
3232 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3233 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3234 // the lowest known One of X and Y. If they are non-zero, the result
3235 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3236 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3237 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3238 BitWidth;
3239}
3240
3241static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3242 const SimplifyQuery &Q, const KnownBits &KnownVal,
3243 unsigned Depth) {
3244 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3245 switch (I->getOpcode()) {
3246 case Instruction::Shl:
3247 return Lhs.shl(Rhs);
3248 case Instruction::LShr:
3249 return Lhs.lshr(Rhs);
3250 case Instruction::AShr:
3251 return Lhs.ashr(Rhs);
3252 default:
3253 llvm_unreachable("Unknown Shift Opcode");
3254 }
3255 };
3256
3257 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3258 switch (I->getOpcode()) {
3259 case Instruction::Shl:
3260 return Lhs.lshr(Rhs);
3261 case Instruction::LShr:
3262 case Instruction::AShr:
3263 return Lhs.shl(Rhs);
3264 default:
3265 llvm_unreachable("Unknown Shift Opcode");
3266 }
3267 };
3268
3269 if (KnownVal.isUnknown())
3270 return false;
3271
3272 KnownBits KnownCnt =
3273 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3274 APInt MaxShift = KnownCnt.getMaxValue();
3275 unsigned NumBits = KnownVal.getBitWidth();
3276 if (MaxShift.uge(NumBits))
3277 return false;
3278
3279 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3280 return true;
3281
3282 // If all of the bits shifted out are known to be zero, and Val is known
3283 // non-zero then at least one non-zero bit must remain.
3284 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3285 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3286 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3287 return true;
3288
3289 return false;
3290}
3291
3293 const APInt &DemandedElts,
3294 const SimplifyQuery &Q, unsigned Depth) {
3295 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3296 switch (I->getOpcode()) {
3297 case Instruction::Alloca:
3298 // Alloca never returns null, malloc might.
3299 return I->getType()->getPointerAddressSpace() == 0;
3300 case Instruction::GetElementPtr:
3301 if (I->getType()->isPointerTy())
3303 break;
3304 case Instruction::BitCast: {
3305 // We need to be a bit careful here. We can only peek through the bitcast
3306 // if the scalar size of elements in the operand are smaller than and a
3307 // multiple of the size they are casting too. Take three cases:
3308 //
3309 // 1) Unsafe:
3310 // bitcast <2 x i16> %NonZero to <4 x i8>
3311 //
3312 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3313 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3314 // guranteed (imagine just sign bit set in the 2 i16 elements).
3315 //
3316 // 2) Unsafe:
3317 // bitcast <4 x i3> %NonZero to <3 x i4>
3318 //
3319 // Even though the scalar size of the src (`i3`) is smaller than the
3320 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3321 // its possible for the `3 x i4` elements to be zero because there are
3322 // some elements in the destination that don't contain any full src
3323 // element.
3324 //
3325 // 3) Safe:
3326 // bitcast <4 x i8> %NonZero to <2 x i16>
3327 //
3328 // This is always safe as non-zero in the 4 i8 elements implies
3329 // non-zero in the combination of any two adjacent ones. Since i8 is a
3330 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3331 // This all implies the 2 i16 elements are non-zero.
3332 Type *FromTy = I->getOperand(0)->getType();
3333 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3334 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3335 return isKnownNonZero(I->getOperand(0), Q, Depth);
3336 } break;
3337 case Instruction::IntToPtr:
3338 // Note that we have to take special care to avoid looking through
3339 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3340 // as casts that can alter the value, e.g., AddrSpaceCasts.
3341 if (!isa<ScalableVectorType>(I->getType()) &&
3342 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3343 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3344 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3345 break;
3346 case Instruction::PtrToAddr:
3347 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3348 // so we can directly forward.
3349 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3350 case Instruction::PtrToInt:
3351 // For inttoptr, make sure the result size is >= the address size. If the
3352 // address is non-zero, any larger value is also non-zero.
3353 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3354 I->getType()->getScalarSizeInBits())
3355 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3356 break;
3357 case Instruction::Trunc:
3358 // nuw/nsw trunc preserves zero/non-zero status of input.
3359 if (auto *TI = dyn_cast<TruncInst>(I))
3360 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3361 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3362 break;
3363
3364 // Iff x - y != 0, then x ^ y != 0
3365 // Therefore we can do the same exact checks
3366 case Instruction::Xor:
3367 case Instruction::Sub:
3368 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3369 I->getOperand(1), Depth);
3370 case Instruction::Or:
3371 // (X | (X != 0)) is non zero
3372 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3373 return true;
3374 // X | Y != 0 if X != Y.
3375 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3376 Depth))
3377 return true;
3378 // X | Y != 0 if X != 0 or Y != 0.
3379 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3380 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3381 case Instruction::SExt:
3382 case Instruction::ZExt:
3383 // ext X != 0 if X != 0.
3384 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3385
3386 case Instruction::Shl: {
3387 // shl nsw/nuw can't remove any non-zero bits.
3389 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3390 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3391
3392 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3393 // if the lowest bit is shifted off the end.
3395 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3396 if (Known.One[0])
3397 return true;
3398
3399 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3400 }
3401 case Instruction::LShr:
3402 case Instruction::AShr: {
3403 // shr exact can only shift out zero bits.
3405 if (BO->isExact())
3406 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3407
3408 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3409 // defined if the sign bit is shifted off the end.
3411 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3412 if (Known.isNegative())
3413 return true;
3414
3415 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3416 // position >= C, because the sum >= max(A, B).
3417 Value *A, *B;
3418 const APInt *C;
3419 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3420 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3421 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3422 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3423 if (!KnownA.One.lshr(*C).isZero())
3424 return true;
3425 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3426 if (!KnownB.One.lshr(*C).isZero())
3427 return true;
3428 }
3429
3430 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3431 }
3432 case Instruction::UDiv:
3433 case Instruction::SDiv: {
3434 // X / Y
3435 // div exact can only produce a zero if the dividend is zero.
3436 if (cast<PossiblyExactOperator>(I)->isExact())
3437 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3438
3439 KnownBits XKnown =
3440 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3441 // If X is fully unknown we won't be able to figure anything out so don't
3442 // both computing knownbits for Y.
3443 if (XKnown.isUnknown())
3444 return false;
3445
3446 KnownBits YKnown =
3447 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3448 if (I->getOpcode() == Instruction::SDiv) {
3449 // For signed division need to compare abs value of the operands.
3450 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3451 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3452 }
3453 // If X u>= Y then div is non zero (0/0 is UB).
3454 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3455 // If X is total unknown or X u< Y we won't be able to prove non-zero
3456 // with compute known bits so just return early.
3457 return XUgeY && *XUgeY;
3458 }
3459 case Instruction::Add: {
3460 // X + Y.
3461
3462 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3463 // non-zero.
3465 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3466 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3467 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3468 }
3469 case Instruction::Mul: {
3471 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3472 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3473 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3474 }
3475 case Instruction::Select: {
3476 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3477
3478 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3479 // then see if the select condition implies the arm is non-zero. For example
3480 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3481 // dominated by `X != 0`.
3482 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3483 Value *Op;
3484 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3485 // Op is trivially non-zero.
3486 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3487 return true;
3488
3489 // The condition of the select dominates the true/false arm. Check if the
3490 // condition implies that a given arm is non-zero.
3491 Value *X;
3492 CmpPredicate Pred;
3493 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3494 return false;
3495
3496 if (!IsTrueArm)
3497 Pred = ICmpInst::getInversePredicate(Pred);
3498
3499 return cmpExcludesZero(Pred, X);
3500 };
3501
3502 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3503 SelectArmIsNonZero(/* IsTrueArm */ false))
3504 return true;
3505 break;
3506 }
3507 case Instruction::PHI: {
3508 auto *PN = cast<PHINode>(I);
3510 return true;
3511
3512 // Check if all incoming values are non-zero using recursion.
3514 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3515 return llvm::all_of(PN->operands(), [&](const Use &U) {
3516 if (U.get() == PN)
3517 return true;
3518 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3519 // Check if the branch on the phi excludes zero.
3520 CmpPredicate Pred;
3521 Value *X;
3522 BasicBlock *TrueSucc, *FalseSucc;
3523 if (match(RecQ.CxtI,
3524 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3525 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3526 // Check for cases of duplicate successors.
3527 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3528 // If we're using the false successor, invert the predicate.
3529 if (FalseSucc == PN->getParent())
3530 Pred = CmpInst::getInversePredicate(Pred);
3531 if (cmpExcludesZero(Pred, X))
3532 return true;
3533 }
3534 }
3535 // Finally recurse on the edge and check it directly.
3536 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3537 });
3538 }
3539 case Instruction::InsertElement: {
3540 if (isa<ScalableVectorType>(I->getType()))
3541 break;
3542
3543 const Value *Vec = I->getOperand(0);
3544 const Value *Elt = I->getOperand(1);
3545 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3546
3547 unsigned NumElts = DemandedElts.getBitWidth();
3548 APInt DemandedVecElts = DemandedElts;
3549 bool SkipElt = false;
3550 // If we know the index we are inserting too, clear it from Vec check.
3551 if (CIdx && CIdx->getValue().ult(NumElts)) {
3552 DemandedVecElts.clearBit(CIdx->getZExtValue());
3553 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3554 }
3555
3556 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3557 // are non-zero.
3558 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3559 (DemandedVecElts.isZero() ||
3560 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3561 }
3562 case Instruction::ExtractElement:
3563 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3564 const Value *Vec = EEI->getVectorOperand();
3565 const Value *Idx = EEI->getIndexOperand();
3566 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3567 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3568 unsigned NumElts = VecTy->getNumElements();
3569 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3570 if (CIdx && CIdx->getValue().ult(NumElts))
3571 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3572 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3573 }
3574 }
3575 break;
3576 case Instruction::ShuffleVector: {
3577 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3578 if (!Shuf)
3579 break;
3580 APInt DemandedLHS, DemandedRHS;
3581 // For undef elements, we don't know anything about the common state of
3582 // the shuffle result.
3583 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3584 break;
3585 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3586 return (DemandedRHS.isZero() ||
3587 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3588 (DemandedLHS.isZero() ||
3589 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3590 }
3591 case Instruction::Freeze:
3592 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3593 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3594 Depth);
3595 case Instruction::Load: {
3596 auto *LI = cast<LoadInst>(I);
3597 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3598 // is never null.
3599 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3600 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3601 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3602 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3603 return true;
3604 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3606 }
3607
3608 // No need to fall through to computeKnownBits as range metadata is already
3609 // handled in isKnownNonZero.
3610 return false;
3611 }
3612 case Instruction::ExtractValue: {
3613 const WithOverflowInst *WO;
3615 switch (WO->getBinaryOp()) {
3616 default:
3617 break;
3618 case Instruction::Add:
3619 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3620 WO->getArgOperand(1),
3621 /*NSW=*/false,
3622 /*NUW=*/false, Depth);
3623 case Instruction::Sub:
3624 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3625 WO->getArgOperand(1), Depth);
3626 case Instruction::Mul:
3627 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3628 WO->getArgOperand(1),
3629 /*NSW=*/false, /*NUW=*/false, Depth);
3630 break;
3631 }
3632 }
3633 break;
3634 }
3635 case Instruction::Call:
3636 case Instruction::Invoke: {
3637 const auto *Call = cast<CallBase>(I);
3638 if (I->getType()->isPointerTy()) {
3639 if (Call->isReturnNonNull())
3640 return true;
3641 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3642 Call, /*MustPreserveOffset=*/true))
3643 return isKnownNonZero(RP, Q, Depth);
3644 } else {
3645 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3647 if (std::optional<ConstantRange> Range = Call->getRange()) {
3648 const APInt ZeroValue(Range->getBitWidth(), 0);
3649 if (!Range->contains(ZeroValue))
3650 return true;
3651 }
3652 if (const Value *RV = Call->getReturnedArgOperand())
3653 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3654 return true;
3655 }
3656
3657 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3658 switch (II->getIntrinsicID()) {
3659 case Intrinsic::sshl_sat:
3660 case Intrinsic::ushl_sat:
3661 case Intrinsic::abs:
3662 case Intrinsic::bitreverse:
3663 case Intrinsic::bswap:
3664 case Intrinsic::ctpop:
3665 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3666 // NB: We don't do usub_sat here as in any case we can prove its
3667 // non-zero, we will fold it to `sub nuw` in InstCombine.
3668 case Intrinsic::ssub_sat:
3669 // For most types, if x != y then ssub.sat x, y != 0. But
3670 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3671 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3672 if (BitWidth == 1)
3673 return false;
3674 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3675 II->getArgOperand(1), Depth);
3676 case Intrinsic::sadd_sat:
3677 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3678 II->getArgOperand(1),
3679 /*NSW=*/true, /* NUW=*/false, Depth);
3680 // Vec reverse preserves zero/non-zero status from input vec.
3681 case Intrinsic::vector_reverse:
3682 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3683 Q, Depth);
3684 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3685 case Intrinsic::vector_reduce_or:
3686 case Intrinsic::vector_reduce_umax:
3687 case Intrinsic::vector_reduce_umin:
3688 case Intrinsic::vector_reduce_smax:
3689 case Intrinsic::vector_reduce_smin:
3690 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3691 case Intrinsic::umax:
3692 case Intrinsic::uadd_sat:
3693 // umax(X, (X != 0)) is non zero
3694 // X +usat (X != 0) is non zero
3695 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3696 return true;
3697
3698 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3699 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3700 case Intrinsic::smax: {
3701 // If either arg is strictly positive the result is non-zero. Otherwise
3702 // the result is non-zero if both ops are non-zero.
3703 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3704 const KnownBits &OpKnown) {
3705 if (!OpNonZero.has_value())
3706 OpNonZero = OpKnown.isNonZero() ||
3707 isKnownNonZero(Op, DemandedElts, Q, Depth);
3708 return *OpNonZero;
3709 };
3710 // Avoid re-computing isKnownNonZero.
3711 std::optional<bool> Op0NonZero, Op1NonZero;
3712 KnownBits Op1Known =
3713 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3714 if (Op1Known.isNonNegative() &&
3715 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3716 return true;
3717 KnownBits Op0Known =
3718 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3719 if (Op0Known.isNonNegative() &&
3720 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3721 return true;
3722 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3723 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3724 }
3725 case Intrinsic::smin: {
3726 // If either arg is negative the result is non-zero. Otherwise
3727 // the result is non-zero if both ops are non-zero.
3728 KnownBits Op1Known =
3729 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3730 if (Op1Known.isNegative())
3731 return true;
3732 KnownBits Op0Known =
3733 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3734 if (Op0Known.isNegative())
3735 return true;
3736
3737 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3738 return true;
3739 }
3740 [[fallthrough]];
3741 case Intrinsic::umin:
3742 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3743 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3744 case Intrinsic::cttz:
3745 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3746 .Zero[0];
3747 case Intrinsic::ctlz:
3748 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3749 .isNonNegative();
3750 case Intrinsic::fshr:
3751 case Intrinsic::fshl:
3752 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3753 if (II->getArgOperand(0) == II->getArgOperand(1))
3754 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3755 break;
3756 case Intrinsic::vscale:
3757 return true;
3758 case Intrinsic::experimental_get_vector_length:
3759 return isKnownNonZero(I->getOperand(0), Q, Depth);
3760 default:
3761 break;
3762 }
3763 break;
3764 }
3765
3766 return false;
3767 }
3768 }
3769
3771 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3772 return Known.One != 0;
3773}
3774
3775/// Return true if the given value is known to be non-zero when defined. For
3776/// vectors, return true if every demanded element is known to be non-zero when
3777/// defined. For pointers, if the context instruction and dominator tree are
3778/// specified, perform context-sensitive analysis and return true if the
3779/// pointer couldn't possibly be null at the specified instruction.
3780/// Supports values with integer or pointer type and vectors of integers.
3781bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3782 const SimplifyQuery &Q, unsigned Depth) {
3783 Type *Ty = V->getType();
3784
3785#ifndef NDEBUG
3786 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3787
3788 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3789 assert(
3790 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3791 "DemandedElt width should equal the fixed vector number of elements");
3792 } else {
3793 assert(DemandedElts == APInt(1, 1) &&
3794 "DemandedElt width should be 1 for scalars");
3795 }
3796#endif
3797
3798 if (auto *C = dyn_cast<Constant>(V)) {
3799 if (C->isNullValue())
3800 return false;
3801 if (isa<ConstantInt>(C))
3802 // Must be non-zero due to null test above.
3803 return true;
3804
3805 // For constant vectors, check that all elements are poison or known
3806 // non-zero to determine that the whole vector is known non-zero.
3807 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3808 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3809 if (!DemandedElts[i])
3810 continue;
3811 Constant *Elt = C->getAggregateElement(i);
3812 if (!Elt || Elt->isNullValue())
3813 return false;
3814 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3815 return false;
3816 }
3817 return true;
3818 }
3819
3820 // Constant ptrauth can be null, iff the base pointer can be.
3821 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3822 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3823
3824 // A global variable in address space 0 is non null unless extern weak
3825 // or an absolute symbol reference. Other address spaces may have null as a
3826 // valid address for a global, so we can't assume anything.
3827 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3828 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3829 GV->getType()->getAddressSpace() == 0)
3830 return true;
3831 }
3832
3833 // For constant expressions, fall through to the Operator code below.
3834 if (!isa<ConstantExpr>(V))
3835 return false;
3836 }
3837
3838 if (const auto *A = dyn_cast<Argument>(V))
3839 if (std::optional<ConstantRange> Range = A->getRange()) {
3840 const APInt ZeroValue(Range->getBitWidth(), 0);
3841 if (!Range->contains(ZeroValue))
3842 return true;
3843 }
3844
3845 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3846 return true;
3847
3848 // Some of the tests below are recursive, so bail out if we hit the limit.
3850 return false;
3851
3852 // Check for pointer simplifications.
3853
3854 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3855 // A byval, inalloca may not be null in a non-default addres space. A
3856 // nonnull argument is assumed never 0.
3857 if (const Argument *A = dyn_cast<Argument>(V)) {
3858 if (((A->hasPassPointeeByValueCopyAttr() &&
3859 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3860 A->hasNonNullAttr()))
3861 return true;
3862 }
3863 }
3864
3865 if (const auto *I = dyn_cast<Operator>(V))
3866 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3867 return true;
3868
3869 if (!isa<Constant>(V) &&
3871 return true;
3872
3873 if (const Value *Stripped = stripNullTest(V))
3874 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3875
3876 return false;
3877}
3878
3880 unsigned Depth) {
3881 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3882 APInt DemandedElts =
3883 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3884 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3885}
3886
3887/// If the pair of operators are the same invertible function, return the
3888/// the operands of the function corresponding to each input. Otherwise,
3889/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3890/// every input value to exactly one output value. This is equivalent to
3891/// saying that Op1 and Op2 are equal exactly when the specified pair of
3892/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3893static std::optional<std::pair<Value*, Value*>>
3895 const Operator *Op2) {
3896 if (Op1->getOpcode() != Op2->getOpcode())
3897 return std::nullopt;
3898
3899 auto getOperands = [&](unsigned OpNum) -> auto {
3900 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3901 };
3902
3903 switch (Op1->getOpcode()) {
3904 default:
3905 break;
3906 case Instruction::Or:
3907 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3908 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3909 break;
3910 [[fallthrough]];
3911 case Instruction::Xor:
3912 case Instruction::Add: {
3913 Value *Other;
3914 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3915 return std::make_pair(Op1->getOperand(1), Other);
3916 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3917 return std::make_pair(Op1->getOperand(0), Other);
3918 break;
3919 }
3920 case Instruction::Sub:
3921 if (Op1->getOperand(0) == Op2->getOperand(0))
3922 return getOperands(1);
3923 if (Op1->getOperand(1) == Op2->getOperand(1))
3924 return getOperands(0);
3925 break;
3926 case Instruction::Mul: {
3927 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3928 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3929 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3930 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3931 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3932 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3933 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3934 break;
3935
3936 // Assume operand order has been canonicalized
3937 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3938 isa<ConstantInt>(Op1->getOperand(1)) &&
3939 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3940 return getOperands(0);
3941 break;
3942 }
3943 case Instruction::Shl: {
3944 // Same as multiplies, with the difference that we don't need to check
3945 // for a non-zero multiply. Shifts always multiply by non-zero.
3946 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3947 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3948 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3949 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3950 break;
3951
3952 if (Op1->getOperand(1) == Op2->getOperand(1))
3953 return getOperands(0);
3954 break;
3955 }
3956 case Instruction::AShr:
3957 case Instruction::LShr: {
3958 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3959 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3960 if (!PEO1->isExact() || !PEO2->isExact())
3961 break;
3962
3963 if (Op1->getOperand(1) == Op2->getOperand(1))
3964 return getOperands(0);
3965 break;
3966 }
3967 case Instruction::SExt:
3968 case Instruction::ZExt:
3969 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3970 return getOperands(0);
3971 break;
3972 case Instruction::PHI: {
3973 const PHINode *PN1 = cast<PHINode>(Op1);
3974 const PHINode *PN2 = cast<PHINode>(Op2);
3975
3976 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3977 // are a single invertible function of the start values? Note that repeated
3978 // application of an invertible function is also invertible
3979 BinaryOperator *BO1 = nullptr;
3980 Value *Start1 = nullptr, *Step1 = nullptr;
3981 BinaryOperator *BO2 = nullptr;
3982 Value *Start2 = nullptr, *Step2 = nullptr;
3983 if (PN1->getParent() != PN2->getParent() ||
3984 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3985 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3986 break;
3987
3989 cast<Operator>(BO2));
3990 if (!Values)
3991 break;
3992
3993 // We have to be careful of mutually defined recurrences here. Ex:
3994 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3995 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3996 // The invertibility of these is complicated, and not worth reasoning
3997 // about (yet?).
3998 if (Values->first != PN1 || Values->second != PN2)
3999 break;
4000
4001 return std::make_pair(Start1, Start2);
4002 }
4003 }
4004 return std::nullopt;
4005}
4006
4007/// Return true if V1 == (binop V2, X), where X is known non-zero.
4008/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4009/// implies V2 != V1.
4010static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4011 const APInt &DemandedElts,
4012 const SimplifyQuery &Q, unsigned Depth) {
4014 if (!BO)
4015 return false;
4016 switch (BO->getOpcode()) {
4017 default:
4018 break;
4019 case Instruction::Or:
4020 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4021 break;
4022 [[fallthrough]];
4023 case Instruction::Xor:
4024 case Instruction::Add:
4025 Value *Op = nullptr;
4026 if (V2 == BO->getOperand(0))
4027 Op = BO->getOperand(1);
4028 else if (V2 == BO->getOperand(1))
4029 Op = BO->getOperand(0);
4030 else
4031 return false;
4032 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4033 }
4034 return false;
4035}
4036
4037/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4038/// the multiplication is nuw or nsw.
4039static bool isNonEqualMul(const Value *V1, const Value *V2,
4040 const APInt &DemandedElts, const SimplifyQuery &Q,
4041 unsigned Depth) {
4042 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4043 const APInt *C;
4044 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4045 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4046 !C->isZero() && !C->isOne() &&
4047 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4048 }
4049 return false;
4050}
4051
4052/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4053/// the shift is nuw or nsw.
4054static bool isNonEqualShl(const Value *V1, const Value *V2,
4055 const APInt &DemandedElts, const SimplifyQuery &Q,
4056 unsigned Depth) {
4057 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4058 const APInt *C;
4059 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4060 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4061 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4062 }
4063 return false;
4064}
4065
4066static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4067 const APInt &DemandedElts, const SimplifyQuery &Q,
4068 unsigned Depth) {
4069 // Check two PHIs are in same block.
4070 if (PN1->getParent() != PN2->getParent())
4071 return false;
4072
4074 bool UsedFullRecursion = false;
4075 for (const BasicBlock *IncomBB : PN1->blocks()) {
4076 if (!VisitedBBs.insert(IncomBB).second)
4077 continue; // Don't reprocess blocks that we have dealt with already.
4078 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4079 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4080 const APInt *C1, *C2;
4081 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4082 continue;
4083
4084 // Only one pair of phi operands is allowed for full recursion.
4085 if (UsedFullRecursion)
4086 return false;
4087
4089 RecQ.CxtI = IncomBB->getTerminator();
4090 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4091 return false;
4092 UsedFullRecursion = true;
4093 }
4094 return true;
4095}
4096
4097static bool isNonEqualSelect(const Value *V1, const Value *V2,
4098 const APInt &DemandedElts, const SimplifyQuery &Q,
4099 unsigned Depth) {
4100 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4101 if (!SI1)
4102 return false;
4103
4104 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4105 const Value *Cond1 = SI1->getCondition();
4106 const Value *Cond2 = SI2->getCondition();
4107 if (Cond1 == Cond2)
4108 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4109 DemandedElts, Q, Depth + 1) &&
4110 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4111 DemandedElts, Q, Depth + 1);
4112 }
4113 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4114 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4115}
4116
4117// Check to see if A is both a GEP and is the incoming value for a PHI in the
4118// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4119// one of them being the recursive GEP A and the other a ptr at same base and at
4120// the same/higher offset than B we are only incrementing the pointer further in
4121// loop if offset of recursive GEP is greater than 0.
4123 const SimplifyQuery &Q) {
4124 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4125 return false;
4126
4127 auto *GEPA = dyn_cast<GEPOperator>(A);
4128 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4129 return false;
4130
4131 // Handle 2 incoming PHI values with one being a recursive GEP.
4132 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4133 if (!PN || PN->getNumIncomingValues() != 2)
4134 return false;
4135
4136 // Search for the recursive GEP as an incoming operand, and record that as
4137 // Step.
4138 Value *Start = nullptr;
4139 Value *Step = const_cast<Value *>(A);
4140 if (PN->getIncomingValue(0) == Step)
4141 Start = PN->getIncomingValue(1);
4142 else if (PN->getIncomingValue(1) == Step)
4143 Start = PN->getIncomingValue(0);
4144 else
4145 return false;
4146
4147 // Other incoming node base should match the B base.
4148 // StartOffset >= OffsetB && StepOffset > 0?
4149 // StartOffset <= OffsetB && StepOffset < 0?
4150 // Is non-equal if above are true.
4151 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4152 // optimisation to inbounds GEPs only.
4153 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4154 APInt StartOffset(IndexWidth, 0);
4155 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4156 APInt StepOffset(IndexWidth, 0);
4157 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4158
4159 // Check if Base Pointer of Step matches the PHI.
4160 if (Step != PN)
4161 return false;
4162 APInt OffsetB(IndexWidth, 0);
4163 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4164 return Start == B &&
4165 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4166 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4167}
4168
4169static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4170 const SimplifyQuery &Q, unsigned Depth) {
4171 if (!Q.CxtI)
4172 return false;
4173
4174 // Try to infer NonEqual based on information from dominating conditions.
4175 if (Q.DC && Q.DT) {
4176 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4177 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4178 Value *Cond = BI->getCondition();
4179 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4180 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4182 /*LHSIsTrue=*/true, Depth)
4183 .value_or(false))
4184 return true;
4185
4186 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4187 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4189 /*LHSIsTrue=*/false, Depth)
4190 .value_or(false))
4191 return true;
4192 }
4193
4194 return false;
4195 };
4196
4197 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4198 IsKnownNonEqualFromDominatingCondition(V2))
4199 return true;
4200 }
4201
4202 if (!Q.AC)
4203 return false;
4204
4205 // Try to infer NonEqual based on information from assumptions.
4206 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4207 if (!AssumeVH)
4208 continue;
4209 CallInst *I = cast<CallInst>(AssumeVH);
4210
4211 assert(I->getFunction() == Q.CxtI->getFunction() &&
4212 "Got assumption for the wrong function!");
4213 assert(I->getIntrinsicID() == Intrinsic::assume &&
4214 "must be an assume intrinsic");
4215
4216 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4217 /*LHSIsTrue=*/true, Depth)
4218 .value_or(false) &&
4220 return true;
4221 }
4222
4223 return false;
4224}
4225
4226static bool isNonEqualURem(const Value *X, const Value *Rem,
4227 const SimplifyQuery &Q) {
4228 const Value *Y;
4229 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4230 return false;
4231
4232 // For a defined urem, X != X urem Y exactly when X u>= Y.
4233 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4235 return true;
4236
4237 std::optional<bool> Implied =
4239 return Implied && *Implied;
4240}
4241
4242/// Return true if it is known that V1 != V2.
4243static bool isKnownNonEqual(const Value *V1, const Value *V2,
4244 const APInt &DemandedElts, const SimplifyQuery &Q,
4245 unsigned Depth) {
4246 if (V1 == V2)
4247 return false;
4248 if (V1->getType() != V2->getType())
4249 // We can't look through casts yet.
4250 return false;
4251
4253 return false;
4254
4255 // See if we can recurse through (exactly one of) our operands. This
4256 // requires our operation be 1-to-1 and map every input value to exactly
4257 // one output value. Such an operation is invertible.
4258 auto *O1 = dyn_cast<Operator>(V1);
4259 auto *O2 = dyn_cast<Operator>(V2);
4260 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4261 if (auto Values = getInvertibleOperands(O1, O2))
4262 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4263 Depth + 1);
4264
4265 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4266 const PHINode *PN2 = cast<PHINode>(V2);
4267 // FIXME: This is missing a generalization to handle the case where one is
4268 // a PHI and another one isn't.
4269 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4270 return true;
4271 };
4272 }
4273
4274 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4275 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4276 return true;
4277
4278 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4279 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4280 return true;
4281
4282 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4283 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4284 return true;
4285
4286 if (V1->getType()->isIntOrIntVectorTy()) {
4287 // Are any known bits in V1 contradictory to known bits in V2? If V1
4288 // has a known zero where V2 has a known one, they must not be equal.
4289 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4290 if (!Known1.isUnknown()) {
4291 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4292 if (Known1.Zero.intersects(Known2.One) ||
4293 Known2.Zero.intersects(Known1.One))
4294 return true;
4295 }
4296 }
4297
4298 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4299 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4300 return true;
4301
4304 return true;
4305
4306 Value *A, *B;
4307 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4308 // Check PtrToInt type matches the pointer size.
4309 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4311 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4312
4313 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4314 return true;
4315
4316 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4317 return true;
4318
4319 return false;
4320}
4321
4322/// For vector constants, loop over the elements and find the constant with the
4323/// minimum number of sign bits. Return 0 if the value is not a vector constant
4324/// or if any element was not analyzed; otherwise, return the count for the
4325/// element with the minimum number of sign bits.
4327 const APInt &DemandedElts,
4328 unsigned TyBits) {
4329 const auto *CV = dyn_cast<Constant>(V);
4330 if (!CV || !isa<FixedVectorType>(CV->getType()))
4331 return 0;
4332
4333 unsigned MinSignBits = TyBits;
4334 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4335 for (unsigned i = 0; i != NumElts; ++i) {
4336 if (!DemandedElts[i])
4337 continue;
4338 // If we find a non-ConstantInt, bail out.
4339 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4340 if (!Elt)
4341 return 0;
4342
4343 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4344 }
4345
4346 return MinSignBits;
4347}
4348
4349static unsigned ComputeNumSignBitsImpl(const Value *V,
4350 const APInt &DemandedElts,
4351 const SimplifyQuery &Q, unsigned Depth);
4352
4353static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4354 const SimplifyQuery &Q, unsigned Depth) {
4355 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4356 assert(Result > 0 && "At least one sign bit needs to be present!");
4357 return Result;
4358}
4359
4360/// Return the number of times the sign bit of the register is replicated into
4361/// the other bits. We know that at least 1 bit is always equal to the sign bit
4362/// (itself), but other cases can give us information. For example, immediately
4363/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4364/// other, so we return 3. For vectors, return the number of sign bits for the
4365/// vector element with the minimum number of known sign bits of the demanded
4366/// elements in the vector specified by DemandedElts.
4367static unsigned ComputeNumSignBitsImpl(const Value *V,
4368 const APInt &DemandedElts,
4369 const SimplifyQuery &Q, unsigned Depth) {
4370 Type *Ty = V->getType();
4371#ifndef NDEBUG
4372 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4373
4374 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4375 assert(
4376 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4377 "DemandedElt width should equal the fixed vector number of elements");
4378 } else {
4379 assert(DemandedElts == APInt(1, 1) &&
4380 "DemandedElt width should be 1 for scalars");
4381 }
4382#endif
4383
4384 // We return the minimum number of sign bits that are guaranteed to be present
4385 // in V, so for undef we have to conservatively return 1. We don't have the
4386 // same behavior for poison though -- that's a FIXME today.
4387
4388 Type *ScalarTy = Ty->getScalarType();
4389 unsigned TyBits = ScalarTy->isPointerTy() ?
4390 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4391 Q.DL.getTypeSizeInBits(ScalarTy);
4392
4393 unsigned Tmp, Tmp2;
4394 unsigned FirstAnswer = 1;
4395
4396 // Note that ConstantInt is handled by the general computeKnownBits case
4397 // below.
4398
4400 return 1;
4401
4402 if (auto *U = dyn_cast<Operator>(V)) {
4403 switch (Operator::getOpcode(V)) {
4404 default: break;
4405 case Instruction::BitCast: {
4406 Value *Src = U->getOperand(0);
4407 Type *SrcTy = Src->getType();
4408
4409 // Skip if the source type is not an integer or integer vector type
4410 // This ensures we only process integer-like types
4411 if (!SrcTy->isIntOrIntVectorTy())
4412 break;
4413
4414 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4415
4416 // Bitcast 'large element' scalar/vector to 'small element' vector.
4417 if ((SrcBits % TyBits) != 0)
4418 break;
4419
4420 // Only proceed if the destination type is a fixed-size vector
4421 if (isa<FixedVectorType>(Ty)) {
4422 // Fast case - sign splat can be simply split across the small elements.
4423 // This works for both vector and scalar sources
4424 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4425 if (Tmp == SrcBits)
4426 return TyBits;
4427 }
4428 break;
4429 }
4430 case Instruction::SExt:
4431 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4432 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4433 Tmp;
4434
4435 case Instruction::SDiv: {
4436 const APInt *Denominator;
4437 // sdiv X, C -> adds log(C) sign bits.
4438 if (match(U->getOperand(1), m_APInt(Denominator))) {
4439
4440 // Ignore non-positive denominator.
4441 if (!Denominator->isStrictlyPositive())
4442 break;
4443
4444 // Calculate the incoming numerator bits.
4445 unsigned NumBits =
4446 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4447
4448 // Add floor(log(C)) bits to the numerator bits.
4449 return std::min(TyBits, NumBits + Denominator->logBase2());
4450 }
4451 break;
4452 }
4453
4454 case Instruction::SRem: {
4455 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4456
4457 const APInt *Denominator;
4458 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4459 // positive constant. This let us put a lower bound on the number of sign
4460 // bits.
4461 if (match(U->getOperand(1), m_APInt(Denominator))) {
4462
4463 // Ignore non-positive denominator.
4464 if (Denominator->isStrictlyPositive()) {
4465 // Calculate the leading sign bit constraints by examining the
4466 // denominator. Given that the denominator is positive, there are two
4467 // cases:
4468 //
4469 // 1. The numerator is positive. The result range is [0,C) and
4470 // [0,C) u< (1 << ceilLogBase2(C)).
4471 //
4472 // 2. The numerator is negative. Then the result range is (-C,0] and
4473 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4474 //
4475 // Thus a lower bound on the number of sign bits is `TyBits -
4476 // ceilLogBase2(C)`.
4477
4478 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4479 Tmp = std::max(Tmp, ResBits);
4480 }
4481 }
4482 return Tmp;
4483 }
4484
4485 case Instruction::AShr: {
4486 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4487 // ashr X, C -> adds C sign bits. Vectors too.
4488 const APInt *ShAmt;
4489 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4490 if (ShAmt->uge(TyBits))
4491 break; // Bad shift.
4492 unsigned ShAmtLimited = ShAmt->getZExtValue();
4493 Tmp += ShAmtLimited;
4494 if (Tmp > TyBits) Tmp = TyBits;
4495 }
4496 return Tmp;
4497 }
4498 case Instruction::Shl: {
4499 const APInt *ShAmt;
4500 Value *X = nullptr;
4501 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4502 // shl destroys sign bits.
4503 if (ShAmt->uge(TyBits))
4504 break; // Bad shift.
4505 // We can look through a zext (more or less treating it as a sext) if
4506 // all extended bits are shifted out.
4507 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4508 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4509 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4510 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4511 } else
4512 Tmp =
4513 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4514 if (ShAmt->uge(Tmp))
4515 break; // Shifted all sign bits out.
4516 Tmp2 = ShAmt->getZExtValue();
4517 return Tmp - Tmp2;
4518 }
4519 break;
4520 }
4521 case Instruction::And:
4522 case Instruction::Or:
4523 case Instruction::Xor: // NOT is handled here.
4524 // Logical binary ops preserve the number of sign bits at the worst.
4525 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4526 if (Tmp != 1) {
4527 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4528 FirstAnswer = std::min(Tmp, Tmp2);
4529 // We computed what we know about the sign bits as our first
4530 // answer. Now proceed to the generic code that uses
4531 // computeKnownBits, and pick whichever answer is better.
4532 }
4533 break;
4534
4535 case Instruction::Select: {
4536 // If we have a clamp pattern, we know that the number of sign bits will
4537 // be the minimum of the clamp min/max range.
4538 const Value *X;
4539 const APInt *CLow, *CHigh;
4540 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4541 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4542
4543 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4544 if (Tmp == 1)
4545 break;
4546 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4547 return std::min(Tmp, Tmp2);
4548 }
4549
4550 case Instruction::Add:
4551 // Add can have at most one carry bit. Thus we know that the output
4552 // is, at worst, one more bit than the inputs.
4553 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4554 if (Tmp == 1) break;
4555
4556 // Special case decrementing a value (ADD X, -1):
4557 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4558 if (CRHS->isAllOnesValue()) {
4559 KnownBits Known(TyBits);
4560 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4561
4562 // If the input is known to be 0 or 1, the output is 0/-1, which is
4563 // all sign bits set.
4564 if ((Known.Zero | 1).isAllOnes())
4565 return TyBits;
4566
4567 // If we are subtracting one from a positive number, there is no carry
4568 // out of the result.
4569 if (Known.isNonNegative())
4570 return Tmp;
4571 }
4572
4573 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4574 if (Tmp2 == 1)
4575 break;
4576 return std::min(Tmp, Tmp2) - 1;
4577
4578 case Instruction::Sub:
4579 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4580 if (Tmp2 == 1)
4581 break;
4582
4583 // Handle NEG.
4584 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4585 if (CLHS->isNullValue()) {
4586 KnownBits Known(TyBits);
4587 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4588 // If the input is known to be 0 or 1, the output is 0/-1, which is
4589 // all sign bits set.
4590 if ((Known.Zero | 1).isAllOnes())
4591 return TyBits;
4592
4593 // If the input is known to be positive (the sign bit is known clear),
4594 // the output of the NEG has the same number of sign bits as the
4595 // input.
4596 if (Known.isNonNegative())
4597 return Tmp2;
4598
4599 // Otherwise, we treat this like a SUB.
4600 }
4601
4602 // Sub can have at most one carry bit. Thus we know that the output
4603 // is, at worst, one more bit than the inputs.
4604 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4605 if (Tmp == 1)
4606 break;
4607 return std::min(Tmp, Tmp2) - 1;
4608
4609 case Instruction::Mul: {
4610 // The output of the Mul can be at most twice the valid bits in the
4611 // inputs.
4612 unsigned SignBitsOp0 =
4613 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4614 if (SignBitsOp0 == 1)
4615 break;
4616 unsigned SignBitsOp1 =
4617 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4618 if (SignBitsOp1 == 1)
4619 break;
4620 unsigned OutValidBits =
4621 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4622 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4623 }
4624
4625 case Instruction::PHI: {
4626 const PHINode *PN = cast<PHINode>(U);
4627 unsigned NumIncomingValues = PN->getNumIncomingValues();
4628 // Don't analyze large in-degree PHIs.
4629 if (NumIncomingValues > 4) break;
4630 // Unreachable blocks may have zero-operand PHI nodes.
4631 if (NumIncomingValues == 0) break;
4632
4633 // Take the minimum of all incoming values. This can't infinitely loop
4634 // because of our depth threshold.
4636 Tmp = TyBits;
4637 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4638 if (Tmp == 1) return Tmp;
4639 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4640 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4641 DemandedElts, RecQ, Depth + 1));
4642 }
4643 return Tmp;
4644 }
4645
4646 case Instruction::Trunc: {
4647 // If the input contained enough sign bits that some remain after the
4648 // truncation, then we can make use of that. Otherwise we don't know
4649 // anything.
4650 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4651 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4652 if (Tmp > (OperandTyBits - TyBits))
4653 return Tmp - (OperandTyBits - TyBits);
4654
4655 return 1;
4656 }
4657
4658 case Instruction::ExtractElement:
4659 // Look through extract element. At the moment we keep this simple and
4660 // skip tracking the specific element. But at least we might find
4661 // information valid for all elements of the vector (for example if vector
4662 // is sign extended, shifted, etc).
4663 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4664
4665 case Instruction::ShuffleVector: {
4666 // Collect the minimum number of sign bits that are shared by every vector
4667 // element referenced by the shuffle.
4668 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4669 if (!Shuf) {
4670 // FIXME: Add support for shufflevector constant expressions.
4671 return 1;
4672 }
4673 APInt DemandedLHS, DemandedRHS;
4674 // For undef elements, we don't know anything about the common state of
4675 // the shuffle result.
4676 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4677 return 1;
4678 Tmp = std::numeric_limits<unsigned>::max();
4679 if (!!DemandedLHS) {
4680 const Value *LHS = Shuf->getOperand(0);
4681 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4682 }
4683 // If we don't know anything, early out and try computeKnownBits
4684 // fall-back.
4685 if (Tmp == 1)
4686 break;
4687 if (!!DemandedRHS) {
4688 const Value *RHS = Shuf->getOperand(1);
4689 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4690 Tmp = std::min(Tmp, Tmp2);
4691 }
4692 // If we don't know anything, early out and try computeKnownBits
4693 // fall-back.
4694 if (Tmp == 1)
4695 break;
4696 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4697 return Tmp;
4698 }
4699 case Instruction::Call: {
4700 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4701 switch (II->getIntrinsicID()) {
4702 default:
4703 break;
4704 case Intrinsic::abs:
4705 Tmp =
4706 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4707 if (Tmp == 1)
4708 break;
4709
4710 // Absolute value reduces number of sign bits by at most 1.
4711 return Tmp - 1;
4712 case Intrinsic::smin:
4713 case Intrinsic::smax: {
4714 const APInt *CLow, *CHigh;
4715 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4716 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4717 }
4718 }
4719 }
4720 }
4721 }
4722 }
4723
4724 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4725 // use this information.
4726
4727 // If we can examine all elements of a vector constant successfully, we're
4728 // done (we can't do any better than that). If not, keep trying.
4729 if (unsigned VecSignBits =
4730 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4731 return VecSignBits;
4732
4733 KnownBits Known(TyBits);
4734 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4735
4736 // If we know that the sign bit is either zero or one, determine the number of
4737 // identical bits in the top of the input value.
4738 return std::max(FirstAnswer, Known.countMinSignBits());
4739}
4740
4742 const TargetLibraryInfo *TLI) {
4743 const Function *F = CB.getCalledFunction();
4744 if (!F)
4746
4747 if (F->isIntrinsic())
4748 return F->getIntrinsicID();
4749
4750 // We are going to infer semantics of a library function based on mapping it
4751 // to an LLVM intrinsic. Check that the library function is available from
4752 // this callbase and in this environment.
4753 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4755
4756 LibFunc Func = TLI->getLibFunc(CB);
4757 if (Func == NotLibFunc)
4759
4760 switch (Func) {
4761 default:
4762 break;
4763 case LibFunc_sin:
4764 case LibFunc_sinf:
4765 case LibFunc_sinl:
4766 return Intrinsic::sin;
4767 case LibFunc_cos:
4768 case LibFunc_cosf:
4769 case LibFunc_cosl:
4770 return Intrinsic::cos;
4771 case LibFunc_tan:
4772 case LibFunc_tanf:
4773 case LibFunc_tanl:
4774 return Intrinsic::tan;
4775 case LibFunc_asin:
4776 case LibFunc_asinf:
4777 case LibFunc_asinl:
4778 return Intrinsic::asin;
4779 case LibFunc_acos:
4780 case LibFunc_acosf:
4781 case LibFunc_acosl:
4782 return Intrinsic::acos;
4783 case LibFunc_atan:
4784 case LibFunc_atanf:
4785 case LibFunc_atanl:
4786 return Intrinsic::atan;
4787 case LibFunc_atan2:
4788 case LibFunc_atan2f:
4789 case LibFunc_atan2l:
4790 return Intrinsic::atan2;
4791 case LibFunc_sinh:
4792 case LibFunc_sinhf:
4793 case LibFunc_sinhl:
4794 return Intrinsic::sinh;
4795 case LibFunc_cosh:
4796 case LibFunc_coshf:
4797 case LibFunc_coshl:
4798 return Intrinsic::cosh;
4799 case LibFunc_tanh:
4800 case LibFunc_tanhf:
4801 case LibFunc_tanhl:
4802 return Intrinsic::tanh;
4803 case LibFunc_exp:
4804 case LibFunc_expf:
4805 case LibFunc_expl:
4806 return Intrinsic::exp;
4807 case LibFunc_exp2:
4808 case LibFunc_exp2f:
4809 case LibFunc_exp2l:
4810 return Intrinsic::exp2;
4811 case LibFunc_exp10:
4812 case LibFunc_exp10f:
4813 case LibFunc_exp10l:
4814 return Intrinsic::exp10;
4815 case LibFunc_log:
4816 case LibFunc_logf:
4817 case LibFunc_logl:
4818 return Intrinsic::log;
4819 case LibFunc_log10:
4820 case LibFunc_log10f:
4821 case LibFunc_log10l:
4822 return Intrinsic::log10;
4823 case LibFunc_log2:
4824 case LibFunc_log2f:
4825 case LibFunc_log2l:
4826 return Intrinsic::log2;
4827 case LibFunc_fabs:
4828 case LibFunc_fabsf:
4829 case LibFunc_fabsl:
4830 return Intrinsic::fabs;
4831 case LibFunc_fmin:
4832 case LibFunc_fminf:
4833 case LibFunc_fminl:
4834 return Intrinsic::minnum;
4835 case LibFunc_fmax:
4836 case LibFunc_fmaxf:
4837 case LibFunc_fmaxl:
4838 return Intrinsic::maxnum;
4839 case LibFunc_copysign:
4840 case LibFunc_copysignf:
4841 case LibFunc_copysignl:
4842 return Intrinsic::copysign;
4843 case LibFunc_floor:
4844 case LibFunc_floorf:
4845 case LibFunc_floorl:
4846 return Intrinsic::floor;
4847 case LibFunc_ceil:
4848 case LibFunc_ceilf:
4849 case LibFunc_ceill:
4850 return Intrinsic::ceil;
4851 case LibFunc_trunc:
4852 case LibFunc_truncf:
4853 case LibFunc_truncl:
4854 return Intrinsic::trunc;
4855 case LibFunc_rint:
4856 case LibFunc_rintf:
4857 case LibFunc_rintl:
4858 return Intrinsic::rint;
4859 case LibFunc_nearbyint:
4860 case LibFunc_nearbyintf:
4861 case LibFunc_nearbyintl:
4862 return Intrinsic::nearbyint;
4863 case LibFunc_round:
4864 case LibFunc_roundf:
4865 case LibFunc_roundl:
4866 return Intrinsic::round;
4867 case LibFunc_roundeven:
4868 case LibFunc_roundevenf:
4869 case LibFunc_roundevenl:
4870 return Intrinsic::roundeven;
4871 case LibFunc_pow:
4872 case LibFunc_powf:
4873 case LibFunc_powl:
4874 return Intrinsic::pow;
4875 case LibFunc_sqrt:
4876 case LibFunc_sqrtf:
4877 case LibFunc_sqrtl:
4878 return Intrinsic::sqrt;
4879 }
4880
4882}
4883
4884/// Given an exploded icmp instruction, return true if the comparison only
4885/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4886/// the result of the comparison is true when the input value is signed.
4888 bool &TrueIfSigned) {
4889 switch (Pred) {
4890 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4891 TrueIfSigned = true;
4892 return RHS.isZero();
4893 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4894 TrueIfSigned = true;
4895 return RHS.isAllOnes();
4896 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4897 TrueIfSigned = false;
4898 return RHS.isAllOnes();
4899 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4900 TrueIfSigned = false;
4901 return RHS.isZero();
4902 case ICmpInst::ICMP_UGT:
4903 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4904 TrueIfSigned = true;
4905 return RHS.isMaxSignedValue();
4906 case ICmpInst::ICMP_UGE:
4907 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4908 TrueIfSigned = true;
4909 return RHS.isMinSignedValue();
4910 case ICmpInst::ICMP_ULT:
4911 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4912 TrueIfSigned = false;
4913 return RHS.isMinSignedValue();
4914 case ICmpInst::ICMP_ULE:
4915 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4916 TrueIfSigned = false;
4917 return RHS.isMaxSignedValue();
4918 default:
4919 return false;
4920 }
4921}
4922
4924 bool CondIsTrue,
4925 const Instruction *CxtI,
4926 KnownFPClass &KnownFromContext,
4927 unsigned Depth = 0) {
4928 Value *A, *B;
4930 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4931 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4932 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4933 Depth + 1);
4934 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4935 Depth + 1);
4936 return;
4937 }
4939 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4940 Depth + 1);
4941 return;
4942 }
4943 CmpPredicate Pred;
4944 Value *LHS;
4945 uint64_t ClassVal = 0;
4946 const APFloat *CRHS;
4947 const APInt *RHS;
4948 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4949 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4950 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4951 LHS != V);
4952 if (CmpVal == V)
4953 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4955 m_Specific(V), m_ConstantInt(ClassVal)))) {
4956 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4957 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4958 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4959 m_APInt(RHS)))) {
4960 bool TrueIfSigned;
4961 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4962 return;
4963 if (TrueIfSigned == CondIsTrue)
4964 KnownFromContext.signBitMustBeOne();
4965 else
4966 KnownFromContext.signBitMustBeZero();
4967 }
4968}
4969
4970/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4971/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4972/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4973/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4974/// exponent range is [-149, -2], but the 0 edge case is above this range).
4975static std::tuple<int, int, int>
4977 if (!Q.CxtI || !Q.DC || !Q.DT)
4979
4980 // Intersect the bounds implied by every dominating condition, keeping the
4981 // tightest maximum. A value may participate in multiple compares
4982 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4983 int MaxExp = APFloat::IEK_Inf;
4984 int MaxExpNonZero = APFloat::IEK_Inf;
4985
4986 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4987 CmpPredicate Pred;
4988 const APFloat *LimitC;
4989 if (!match(BI->getCondition(),
4990 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4991 continue;
4992
4993 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4994 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4995 continue;
4996
4997 // If fabs(x) <= K, implies the exponent min exp range.
4998 // if fabs(x) >= K, swap the successor
4999 bool IsLessEqual =
5000 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5001 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5002 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5003
5004 bool KnownStrictlyLess =
5005 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5006 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5007
5008 BasicBlockEdge Edge1(BI->getParent(),
5009 BI->getSuccessor(IsLessEqual ? 0 : 1));
5010 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
5011 // frexp returns an exponent one greater than ilogb.
5012 int Exp = ilogb(*LimitC) + 1;
5013
5014 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5015 // exponent drops by one when K is exact power of two.
5016 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5017 --Exp;
5018
5019 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5020 // may exclude.
5021
5022 // TODO: Figure out lower bound to detect no-underflow.
5023 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5024 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5025 }
5026 }
5027
5028 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5029}
5030
5032 const SimplifyQuery &Q) {
5033 KnownFPClass KnownFromContext;
5034
5035 if (Q.CC && Q.CC->AffectedValues.contains(V))
5037 KnownFromContext);
5038
5039 if (!Q.CxtI)
5040 return KnownFromContext;
5041
5042 if (Q.DC && Q.DT) {
5043 // Handle dominating conditions.
5044 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5045 Value *Cond = BI->getCondition();
5046
5047 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5048 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5049 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5050 KnownFromContext);
5051
5052 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5053 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5054 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5055 KnownFromContext);
5056 }
5057 }
5058
5059 if (!Q.AC)
5060 return KnownFromContext;
5061
5062 // Try to restrict the floating-point classes based on information from
5063 // assumptions.
5064 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5065 if (!AssumeVH)
5066 continue;
5067 CallInst *I = cast<CallInst>(AssumeVH);
5068
5069 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5070 "Got assumption for the wrong function!");
5071 assert(I->getIntrinsicID() == Intrinsic::assume &&
5072 "must be an assume intrinsic");
5073
5074 if (!isValidAssumeForContext(I, Q))
5075 continue;
5076
5077 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5078 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5079 }
5080
5081 return KnownFromContext;
5082}
5083
5085 Value *Arm, bool Invert,
5086 const SimplifyQuery &SQ,
5087 unsigned Depth) {
5088
5089 KnownFPClass KnownSrc;
5091 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5092 Depth + 1);
5093 KnownSrc = KnownSrc.unionWith(Known);
5094 if (KnownSrc.isUnknown())
5095 return;
5096
5097 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5098 Known = KnownSrc;
5099}
5100
5101void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5102 FPClassTest InterestedClasses, KnownFPClass &Known,
5103 const SimplifyQuery &Q, unsigned Depth);
5104
5106 FPClassTest InterestedClasses,
5107 const SimplifyQuery &Q, unsigned Depth) {
5108 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5109 APInt DemandedElts =
5110 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5111 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5112}
5113
5115 const APInt &DemandedElts,
5116 FPClassTest InterestedClasses,
5118 const SimplifyQuery &Q,
5119 unsigned Depth) {
5120 if ((InterestedClasses &
5122 return;
5123
5124 KnownFPClass KnownSrc;
5125 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5126 KnownSrc, Q, Depth + 1);
5127 Known = KnownFPClass::fptrunc(KnownSrc);
5128}
5129
5131 switch (IID) {
5132 case Intrinsic::minimum:
5134 case Intrinsic::maximum:
5136 case Intrinsic::minimumnum:
5138 case Intrinsic::maximumnum:
5140 case Intrinsic::minnum:
5142 case Intrinsic::maxnum:
5144 default:
5145 llvm_unreachable("not a floating-point min-max intrinsic");
5146 }
5147}
5148
5149/// \return true if this is a floating point value that is known to have a
5150/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5151static bool isAbsoluteValueULEOne(const Value *V) {
5152 // TODO: Handle frexp
5153 // TODO: Other rounding intrinsics?
5154 // TODO: Try computeKnownExponentRangeFromContext
5155
5156 // fabs(x - floor(x)) <= 1
5157 const Value *SubFloorX;
5158 if (match(V, m_FSub(m_Value(SubFloorX),
5160 return true;
5161
5164}
5165
5166void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5167 FPClassTest InterestedClasses, KnownFPClass &Known,
5168 const SimplifyQuery &Q, unsigned Depth) {
5169 assert(Known.isUnknown() && "should not be called with known information");
5170
5171 if (!DemandedElts) {
5172 // No demanded elts, better to assume we don't know anything.
5173 Known.resetAll();
5174 return;
5175 }
5176
5177 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5178
5179 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5180 Known = KnownFPClass(CFP->getValueAPF());
5181 return;
5182 }
5183
5185 Known.KnownFPClasses = fcPosZero;
5186 Known.setSignBit(false);
5187 return;
5188 }
5189
5190 if (isa<PoisonValue>(V)) {
5191 Known.KnownFPClasses = fcNone;
5192 Known.setSignBit(false);
5193 return;
5194 }
5195
5196 // Try to handle fixed width vector constants
5197 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5198 const Constant *CV = dyn_cast<Constant>(V);
5199 if (VFVTy && CV) {
5200 Known.KnownFPClasses = fcNone;
5201 bool SignBitAllZero = true;
5202 bool SignBitAllOne = true;
5203
5204 // For vectors, verify that each element is not NaN.
5205 unsigned NumElts = VFVTy->getNumElements();
5206 for (unsigned i = 0; i != NumElts; ++i) {
5207 if (!DemandedElts[i])
5208 continue;
5209
5210 Constant *Elt = CV->getAggregateElement(i);
5211 if (!Elt) {
5212 Known = KnownFPClass();
5213 return;
5214 }
5215 if (isa<PoisonValue>(Elt))
5216 continue;
5217 auto *CElt = dyn_cast<ConstantFP>(Elt);
5218 if (!CElt) {
5219 Known = KnownFPClass();
5220 return;
5221 }
5222
5223 const APFloat &C = CElt->getValueAPF();
5224 Known.KnownFPClasses |= C.classify();
5225 if (C.isNegative())
5226 SignBitAllZero = false;
5227 else
5228 SignBitAllOne = false;
5229 }
5230 if (SignBitAllOne != SignBitAllZero)
5231 Known.setSignBit(SignBitAllOne);
5232 return;
5233 }
5234
5235 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5236 Known.KnownFPClasses = fcNone;
5237 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5238 Known |= CDS->getElementAsAPFloat(I).classify();
5239 return;
5240 }
5241
5242 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5243 // TODO: Handle complex aggregates
5244 Known.KnownFPClasses = fcNone;
5245 for (const Use &Op : CA->operands()) {
5246 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5247 if (!CFP) {
5248 Known = KnownFPClass();
5249 return;
5250 }
5251
5252 Known |= CFP->getValueAPF().classify();
5253 }
5254
5255 return;
5256 }
5257
5258 FPClassTest KnownNotFromFlags = fcNone;
5259 if (const auto *CB = dyn_cast<CallBase>(V))
5260 KnownNotFromFlags |= CB->getRetNoFPClass();
5261 else if (const auto *Arg = dyn_cast<Argument>(V))
5262 KnownNotFromFlags |= Arg->getNoFPClass();
5263
5264 const Operator *Op = dyn_cast<Operator>(V);
5266 if (FPOp->hasNoNaNs())
5267 KnownNotFromFlags |= fcNan;
5268 if (FPOp->hasNoInfs())
5269 KnownNotFromFlags |= fcInf;
5270 }
5271
5272 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5273 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5274
5275 // We no longer need to find out about these bits from inputs if we can
5276 // assume this from flags/attributes.
5277 InterestedClasses &= ~KnownNotFromFlags;
5278
5279 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5280 Known.knownNot(KnownNotFromFlags);
5281 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5282 if (*AssumedClasses.getSignBit())
5283 Known.signBitMustBeOne();
5284 else
5285 Known.signBitMustBeZero();
5286 }
5287 });
5288
5289 if (!Op)
5290 return;
5291
5292 // All recursive calls that increase depth must come after this.
5294 return;
5295
5296 const unsigned Opc = Op->getOpcode();
5297 switch (Opc) {
5298 case Instruction::FNeg: {
5299 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5300 Known, Q, Depth + 1);
5301 Known.fneg();
5302 break;
5303 }
5304 case Instruction::Select: {
5305 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5306 KnownFPClass Res;
5307 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5308 Depth + 1);
5309 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5310 Depth);
5311 return Res;
5312 };
5313 // Only known if known in both the LHS and RHS.
5314 Known =
5315 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5316 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5317 break;
5318 }
5319 case Instruction::Load: {
5320 const MDNode *NoFPClass =
5321 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5322 if (!NoFPClass)
5323 break;
5324
5325 ConstantInt *MaskVal =
5327 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5328 break;
5329 }
5330 case Instruction::Call: {
5331 const CallInst *II = cast<CallInst>(Op);
5332 const Intrinsic::ID IID = II->getIntrinsicID();
5333 switch (IID) {
5334 case Intrinsic::fabs: {
5335 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5336 // If we only care about the sign bit we don't need to inspect the
5337 // operand.
5338 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5339 InterestedClasses, Known, Q, Depth + 1);
5340 }
5341
5342 Known.fabs();
5343 break;
5344 }
5345 case Intrinsic::copysign: {
5346 KnownFPClass KnownSign;
5347
5348 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5349 Known, Q, Depth + 1);
5350 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5351 KnownSign, Q, Depth + 1);
5352 Known.copysign(KnownSign);
5353 break;
5354 }
5355 case Intrinsic::fma:
5356 case Intrinsic::fmuladd: {
5357 if ((InterestedClasses & fcNegative) == fcNone)
5358 break;
5359
5360 // FIXME: This should check isGuaranteedNotToBeUndef
5361 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5362 KnownFPClass KnownSrc, KnownAddend;
5363 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5364 InterestedClasses, KnownAddend, Q, Depth + 1);
5365 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5366 InterestedClasses, KnownSrc, Q, Depth + 1);
5367
5368 const Function *F = II->getFunction();
5369 const fltSemantics &FltSem =
5370 II->getType()->getScalarType()->getFltSemantics();
5372 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5373
5374 if (KnownNotFromFlags & fcNan) {
5375 KnownSrc.knownNot(fcNan);
5376 KnownAddend.knownNot(fcNan);
5377 }
5378
5379 if (KnownNotFromFlags & fcInf) {
5380 KnownSrc.knownNot(fcInf);
5381 KnownAddend.knownNot(fcInf);
5382 }
5383
5384 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5385 break;
5386 }
5387
5388 KnownFPClass KnownSrc[3];
5389 for (int I = 0; I != 3; ++I) {
5390 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5391 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5392 if (KnownSrc[I].isUnknown())
5393 return;
5394
5395 if (KnownNotFromFlags & fcNan)
5396 KnownSrc[I].knownNot(fcNan);
5397 if (KnownNotFromFlags & fcInf)
5398 KnownSrc[I].knownNot(fcInf);
5399 }
5400
5401 const Function *F = II->getFunction();
5402 const fltSemantics &FltSem =
5403 II->getType()->getScalarType()->getFltSemantics();
5405 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5406 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5407 break;
5408 }
5409 case Intrinsic::sqrt:
5410 case Intrinsic::experimental_constrained_sqrt: {
5411 KnownFPClass KnownSrc;
5412 FPClassTest InterestedSrcs = InterestedClasses;
5413 if (InterestedClasses & fcNan)
5414 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5415
5416 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5417 KnownSrc, Q, Depth + 1);
5418
5420
5421 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5422 if (!HasNSZ) {
5423 const Function *F = II->getFunction();
5424 const fltSemantics &FltSem =
5425 II->getType()->getScalarType()->getFltSemantics();
5426 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5427 }
5428
5429 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5430 if (HasNSZ)
5431 Known.knownNot(fcNegZero);
5432
5433 break;
5434 }
5435 case Intrinsic::sin: {
5436 KnownFPClass KnownSrc;
5437 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5438 KnownSrc, Q, Depth + 1);
5439 Known = KnownFPClass::sin(KnownSrc);
5440 break;
5441 }
5442 case Intrinsic::cos: {
5443 KnownFPClass KnownSrc;
5444 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5445 KnownSrc, Q, Depth + 1);
5446 Known = KnownFPClass::cos(KnownSrc);
5447 break;
5448 }
5449 case Intrinsic::tan: {
5450 KnownFPClass KnownSrc;
5451 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5452 KnownSrc, Q, Depth + 1);
5453 Known = KnownFPClass::tan(KnownSrc);
5454 break;
5455 }
5456 case Intrinsic::sinh: {
5457 KnownFPClass KnownSrc;
5458 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5459 KnownSrc, Q, Depth + 1);
5460 Known = KnownFPClass::sinh(KnownSrc);
5461 break;
5462 }
5463 case Intrinsic::cosh: {
5464 KnownFPClass KnownSrc;
5465 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5466 KnownSrc, Q, Depth + 1);
5467 Known = KnownFPClass::cosh(KnownSrc);
5468 break;
5469 }
5470 case Intrinsic::tanh: {
5471 KnownFPClass KnownSrc;
5472 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5473 KnownSrc, Q, Depth + 1);
5474 Known = KnownFPClass::tanh(KnownSrc);
5475 break;
5476 }
5477 case Intrinsic::asin: {
5478 KnownFPClass KnownSrc;
5479 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5480 KnownSrc, Q, Depth + 1);
5481 Known = KnownFPClass::asin(KnownSrc);
5482 break;
5483 }
5484 case Intrinsic::acos: {
5485 KnownFPClass KnownSrc;
5486 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5487 KnownSrc, Q, Depth + 1);
5488 Known = KnownFPClass::acos(KnownSrc);
5489 break;
5490 }
5491 case Intrinsic::atan: {
5492 KnownFPClass KnownSrc;
5493 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5494 KnownSrc, Q, Depth + 1);
5495 Known = KnownFPClass::atan(KnownSrc);
5496 break;
5497 }
5498 case Intrinsic::atan2: {
5499 FPClassTest InterestedY = InterestedClasses;
5500 FPClassTest InterestedX = InterestedClasses;
5501
5502 // We can rule out zero and subnormal if x cannot have a positive value.
5503 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5504 InterestedX |= fcPositive | fcNegSubnormal;
5505
5506 KnownFPClass KnownY, KnownX;
5507 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5508 KnownY, Q, Depth + 1);
5509 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5510 KnownX, Q, Depth + 1);
5511
5512 const Function *F = II->getFunction();
5514 F ? F->getDenormalMode(
5515 II->getType()->getScalarType()->getFltSemantics())
5517 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5518 break;
5519 }
5520 case Intrinsic::maxnum:
5521 case Intrinsic::minnum:
5522 case Intrinsic::minimum:
5523 case Intrinsic::maximum:
5524 case Intrinsic::minimumnum:
5525 case Intrinsic::maximumnum: {
5526 KnownFPClass KnownLHS, KnownRHS;
5527 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5528 KnownLHS, Q, Depth + 1);
5529 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5530 KnownRHS, Q, Depth + 1);
5531
5532 const Function *F = II->getFunction();
5533
5535 F ? F->getDenormalMode(
5536 II->getType()->getScalarType()->getFltSemantics())
5538
5539 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5540 Mode);
5541 break;
5542 }
5543 case Intrinsic::canonicalize: {
5544 KnownFPClass KnownSrc;
5545 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5546 KnownSrc, Q, Depth + 1);
5547
5548 const Function *F = II->getFunction();
5549 DenormalMode DenormMode =
5550 F ? F->getDenormalMode(
5551 II->getType()->getScalarType()->getFltSemantics())
5553 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5554 break;
5555 }
5556 case Intrinsic::vector_reduce_fmax:
5557 case Intrinsic::vector_reduce_fmin:
5558 case Intrinsic::vector_reduce_fmaximum:
5559 case Intrinsic::vector_reduce_fminimum:
5560 case Intrinsic::vector_reduce_fmaximumnum:
5561 case Intrinsic::vector_reduce_fminimumnum: {
5562 // reduce min/max will choose an element from one of the vector elements,
5563 // so we can infer and class information that is common to all elements.
5564 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5565 InterestedClasses, Q, Depth + 1);
5566 // Can only propagate sign if output is never NaN.
5567 if (!Known.isKnownNeverNaN())
5568 Known.setSignBit(std::nullopt);
5569 break;
5570 }
5571 // reverse preserves all characteristics of the input vec's element.
5572 case Intrinsic::vector_reverse:
5574 II->getArgOperand(0), DemandedElts.reverseBits(),
5575 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5576 break;
5577 case Intrinsic::trunc:
5578 case Intrinsic::floor:
5579 case Intrinsic::ceil:
5580 case Intrinsic::rint:
5581 case Intrinsic::nearbyint:
5582 case Intrinsic::round:
5583 case Intrinsic::roundeven: {
5584 KnownFPClass KnownSrc;
5585 FPClassTest InterestedSrcs = InterestedClasses;
5586 if (InterestedSrcs & fcPosFinite)
5587 InterestedSrcs |= fcPosFinite;
5588 if (InterestedSrcs & fcNegFinite)
5589 InterestedSrcs |= fcNegFinite;
5590 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5591 KnownSrc, Q, Depth + 1);
5592
5594 KnownSrc, IID == Intrinsic::trunc,
5595 V->getType()->getScalarType()->isMultiUnitFPType());
5596 break;
5597 }
5598 case Intrinsic::exp:
5599 case Intrinsic::exp2:
5600 case Intrinsic::exp10:
5601 case Intrinsic::amdgcn_exp2: {
5602 KnownFPClass KnownSrc;
5603 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5604 KnownSrc, Q, Depth + 1);
5605
5606 Known = KnownFPClass::exp(KnownSrc);
5607
5608 Type *EltTy = II->getType()->getScalarType();
5609 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5610 Known.knownNot(fcSubnormal);
5611
5612 break;
5613 }
5614 case Intrinsic::fptrunc_round: {
5615 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5616 Q, Depth);
5617 break;
5618 }
5619 case Intrinsic::log:
5620 case Intrinsic::log10:
5621 case Intrinsic::log2:
5622 case Intrinsic::experimental_constrained_log:
5623 case Intrinsic::experimental_constrained_log10:
5624 case Intrinsic::experimental_constrained_log2:
5625 case Intrinsic::amdgcn_log: {
5626 Type *EltTy = II->getType()->getScalarType();
5627
5628 // log(+inf) -> +inf
5629 // log([+-]0.0) -> -inf
5630 // log(-inf) -> nan
5631 // log(-x) -> nan
5632 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5633 FPClassTest InterestedSrcs = InterestedClasses;
5634 if ((InterestedClasses & fcNegInf) != fcNone)
5635 InterestedSrcs |= fcZero | fcSubnormal;
5636 if ((InterestedClasses & fcNan) != fcNone)
5637 InterestedSrcs |= fcNan | fcNegative;
5638
5639 KnownFPClass KnownSrc;
5640 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5641 KnownSrc, Q, Depth + 1);
5642
5643 const Function *F = II->getFunction();
5644 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5646 Known = KnownFPClass::log(KnownSrc, Mode);
5647 }
5648
5649 break;
5650 }
5651 case Intrinsic::pow: {
5652 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5653 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5654 if (!WantNaN && !WantNegative)
5655 break;
5656
5657 FPClassTest InterestedLHS = fcNone;
5658 FPClassTest InterestedRHS = fcNone;
5659 if (WantNaN) {
5660 // pow may return NaN if one of the arguments is NaN. NaN may also be
5661 // produced from a negative, non-zero finite base and a non-integer
5662 // exponent.
5663 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5664 InterestedRHS |= fcNan;
5665 }
5666 if (WantNegative) {
5667 // A negative value is returned when a negative base is raised to an odd
5668 // integer power. Only normal values can be odd integers.
5669 InterestedLHS |= fcNegative;
5670 InterestedRHS |= fcNormal;
5671 }
5672
5673 KnownFPClass KnownLHS;
5674 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5675 KnownLHS, Q, Depth + 1);
5676
5677 // If the LHS is unknown, then querying the RHS is only useful for rare
5678 // edge cases.
5679 if (KnownLHS.isUnknown())
5680 break;
5681
5682 KnownFPClass KnownRHS;
5683 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5684 KnownRHS, Q, Depth + 1);
5685 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5686 break;
5687 }
5688 case Intrinsic::powi: {
5689 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5690 break;
5691
5692 // The exponent is always a scalar, even when raising a vector to a power.
5693 const Value *Exp = II->getArgOperand(1);
5694 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5695 KnownBits ExponentKnownBits(BitWidth);
5696 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5697
5698 FPClassTest InterestedSrcs = fcNone;
5699 if (InterestedClasses & fcNan)
5700 InterestedSrcs |= fcNan;
5701 if (!ExponentKnownBits.isZero()) {
5702 if (InterestedClasses & fcInf)
5703 InterestedSrcs |= fcFinite | fcInf;
5704 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5705 InterestedSrcs |= fcNegative;
5706 }
5707
5708 KnownFPClass KnownSrc;
5709 if (InterestedSrcs != fcNone)
5710 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5711 KnownSrc, Q, Depth + 1);
5712
5713 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5714 break;
5715 }
5716 case Intrinsic::ldexp: {
5717 KnownFPClass KnownSrc;
5718 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5719 KnownSrc, Q, Depth + 1);
5720 // Can refine inf/zero handling based on the exponent operand.
5721 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5722
5723 const Value *ExpArg = II->getArgOperand(1);
5724 ConstantRange ExpKnownRange =
5725 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5726 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5727 : ConstantRange::getFull(
5728 ExpArg->getType()->getScalarSizeInBits());
5729
5730 const fltSemantics &Flt =
5731 II->getType()->getScalarType()->getFltSemantics();
5732
5733 const Function *F = II->getFunction();
5735 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5736
5737 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5738 ExpKnownRange.getSignedMax(), Flt, Mode);
5739 break;
5740 }
5741 case Intrinsic::arithmetic_fence: {
5742 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5743 Known, Q, Depth + 1);
5744 break;
5745 }
5746 case Intrinsic::experimental_constrained_sitofp:
5747 case Intrinsic::experimental_constrained_uitofp:
5748 // Cannot produce nan
5749 Known.knownNot(fcNan);
5750
5751 // sitofp and uitofp turn into +0.0 for zero.
5752 Known.knownNot(fcNegZero);
5753
5754 // Integers cannot be subnormal
5755 Known.knownNot(fcSubnormal);
5756
5757 if (IID == Intrinsic::experimental_constrained_uitofp)
5758 Known.signBitMustBeZero();
5759
5760 // TODO: Copy inf handling from instructions
5761 break;
5762
5763 case Intrinsic::amdgcn_fract: {
5764 Known.knownNot(fcInf);
5765
5766 if (InterestedClasses & fcNan) {
5767 KnownFPClass KnownSrc;
5768 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5769 InterestedClasses, KnownSrc, Q, Depth + 1);
5770
5771 if (KnownSrc.isKnownNeverInfOrNaN())
5772 Known.knownNot(fcNan);
5773 else if (KnownSrc.isKnownNever(fcSNan))
5774 Known.knownNot(fcSNan);
5775 }
5776
5777 break;
5778 }
5779 case Intrinsic::amdgcn_rcp: {
5780 KnownFPClass KnownSrc;
5781 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5782 KnownSrc, Q, Depth + 1);
5783
5784 Known.propagateNonNaN(KnownSrc);
5785
5786 Type *EltTy = II->getType()->getScalarType();
5787
5788 // f32 denormal always flushed.
5789 if (EltTy->isFloatTy()) {
5790 Known.knownNot(fcSubnormal);
5791 KnownSrc.knownNot(fcSubnormal);
5792 }
5793
5794 if (KnownSrc.isKnownNever(fcNegative))
5795 Known.knownNot(fcNegative);
5796 if (KnownSrc.isKnownNever(fcPositive))
5797 Known.knownNot(fcPositive);
5798
5799 if (const Function *F = II->getFunction()) {
5800 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5801 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5802 Known.knownNot(fcPosInf);
5803 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5804 Known.knownNot(fcNegInf);
5805 }
5806
5807 break;
5808 }
5809 case Intrinsic::amdgcn_rsq: {
5810 KnownFPClass KnownSrc;
5811 // The only negative value that can be returned is -inf for -0 inputs.
5813
5814 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5815 KnownSrc, Q, Depth + 1);
5816
5817 // Negative -> nan
5818 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5819 Known.knownNot(fcNan);
5820 else if (KnownSrc.isKnownNever(fcSNan))
5821 Known.knownNot(fcSNan);
5822
5823 // +inf -> +0
5824 if (KnownSrc.isKnownNeverPosInfinity())
5825 Known.knownNot(fcPosZero);
5826
5827 Type *EltTy = II->getType()->getScalarType();
5828
5829 // f32 denormal always flushed.
5830 if (EltTy->isFloatTy())
5831 Known.knownNot(fcPosSubnormal);
5832
5833 if (const Function *F = II->getFunction()) {
5834 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5835
5836 // -0 -> -inf
5837 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5838 Known.knownNot(fcNegInf);
5839
5840 // +0 -> +inf
5841 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5842 Known.knownNot(fcPosInf);
5843 }
5844
5845 break;
5846 }
5847 case Intrinsic::amdgcn_trig_preop: {
5848 // Always returns a value [0, 1)
5849 Known.knownNot(fcNan | fcInf | fcNegative);
5850 break;
5851 }
5852 case Intrinsic::convert_from_arbitrary_fp: {
5853 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5854 StringRef FormatStr = cast<MDString>(MD)->getString();
5855
5856 const fltSemantics *SrcSemantics =
5858 if (!SrcSemantics)
5859 break;
5860
5861 const fltSemantics DstSemantics =
5862 II->getType()->getScalarType()->getFltSemantics();
5863
5864 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5865 Known.knownNot(fcNan);
5866
5867 // fcInf can only be cleared if the source format has no Inf encoding
5868 // and the dst max exp can accommodate src max exp.
5869 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5870 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5871 APFloat::semanticsMaxExponent(DstSemantics))
5872 Known.knownNot(fcInf);
5873
5874 // Check and clear all neg flags for formats that do not have signed
5875 // representation.
5876 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5877 Known.knownNot(fcNegative);
5878
5879 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5880 // zero.
5881 if (!APFloat::semanticsHasZero(*SrcSemantics))
5882 Known.knownNot(fcZero);
5883 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5884 Known.knownNot(fcNegZero);
5885
5886 // If src lands normally in dest, the result can never be subnormal.
5887 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5888 Known.knownNot(fcSubnormal);
5889 break;
5890 }
5891 default:
5892 break;
5893 }
5894
5895 break;
5896 }
5897 case Instruction::FAdd:
5898 case Instruction::FSub: {
5899 KnownFPClass KnownLHS, KnownRHS;
5900 bool WantNegative =
5901 Op->getOpcode() == Instruction::FAdd &&
5902 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5903 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5904 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5905
5906 if (!WantNaN && !WantNegative && !WantNegZero)
5907 break;
5908
5909 FPClassTest InterestedSrcs = InterestedClasses;
5910 if (WantNegative)
5911 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5912 if (InterestedClasses & fcNan)
5913 InterestedSrcs |= fcInf;
5914 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5915 KnownRHS, Q, Depth + 1);
5916
5917 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5918 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5919 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5920 Depth + 1);
5921 if (Self)
5922 KnownLHS = KnownRHS;
5923
5924 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5925 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5926 WantNegZero || Opc == Instruction::FSub) {
5927
5928 // FIXME: Context function should always be passed in separately
5929 const Function *F = cast<Instruction>(Op)->getFunction();
5930 const fltSemantics &FltSem =
5931 Op->getType()->getScalarType()->getFltSemantics();
5933 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5934
5935 if (Self && Opc == Instruction::FAdd) {
5936 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5937 } else {
5938 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5939 // there's no point.
5940
5941 if (!Self) {
5942 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5943 KnownLHS, Q, Depth + 1);
5944 }
5945
5946 Known = Opc == Instruction::FAdd
5947 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5948 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5949 }
5950 }
5951
5952 break;
5953 }
5954 case Instruction::FMul: {
5955 const Function *F = cast<Instruction>(Op)->getFunction();
5957 F ? F->getDenormalMode(
5958 Op->getType()->getScalarType()->getFltSemantics())
5960
5961 Value *LHS = Op->getOperand(0);
5962 Value *RHS = Op->getOperand(1);
5963 // X * X is always non-negative or a NaN.
5964 // FIXME: Should check isGuaranteedNotToBeUndef
5965 if (LHS == RHS) {
5966 KnownFPClass KnownSrc;
5967 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5968 Depth + 1);
5969 Known = KnownFPClass::square(KnownSrc, Mode);
5970 break;
5971 }
5972
5973 KnownFPClass KnownLHS, KnownRHS;
5974
5975 const APFloat *CRHS;
5976 if (match(RHS, m_APFloat(CRHS))) {
5977 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5978 Depth + 1);
5979 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5980 } else {
5981 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5982 Depth + 1);
5983 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5984 // additional not-nan if the addend is known-not negative infinity if the
5985 // multiply is known-not infinity.
5986
5987 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5988 Depth + 1);
5989 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5990 }
5991
5992 /// Propgate no-infs if the other source is known smaller than one, such
5993 /// that this cannot introduce overflow.
5994 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5995 Known.knownNot(fcInf);
5996 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5997 Known.knownNot(fcInf);
5998
5999 break;
6000 }
6001 case Instruction::FDiv: {
6002 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6003
6004 const Function *F = cast<Instruction>(Op)->getFunction();
6005 const fltSemantics &FltSem =
6006 Op->getType()->getScalarType()->getFltSemantics();
6008 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6009
6010 if (Op->getOperand(0) == Op->getOperand(1) &&
6011 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6012 // X / X is always exactly 1.0 or a NaN.
6013 Known.KnownFPClasses = fcNan | fcPosNormal;
6014
6015 if (!WantNan)
6016 break;
6017
6018 KnownFPClass KnownSrc;
6019 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6020 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6021 Depth + 1);
6022
6023 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6024 break;
6025 }
6026
6027 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6028 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6029 if (!WantNan && !WantNegative && !WantPositive)
6030 break;
6031
6032 KnownFPClass KnownLHS, KnownRHS;
6033 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6034 Q, Depth + 1);
6035
6036 bool KnowSomethingUseful =
6037 KnownRHS.isKnownNeverNaN() ||
6040
6041 if (KnowSomethingUseful)
6042 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6043 Q, Depth + 1);
6044
6045 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6046 break;
6047 }
6048 case Instruction::FRem: {
6049 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6050
6051 Known.knownNot(fcInf);
6052
6053 const Function *F = cast<Instruction>(Op)->getFunction();
6055 F ? F->getDenormalMode(
6056 Op->getType()->getScalarType()->getFltSemantics())
6058
6059 if (Op->getOperand(0) == Op->getOperand(1) &&
6060 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6061 // X % X is always exactly [+-]0.0 or a NaN.
6062 Known.KnownFPClasses = fcNan | fcZero;
6063
6064 if (!WantNan)
6065 break;
6066
6067 KnownFPClass KnownSrc;
6068 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6069 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6070 Depth + 1);
6071
6072 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6073 break;
6074 }
6075
6076 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6077 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6078 if (!WantNan && !WantNegative && !WantPositive)
6079 break;
6080
6081 KnownFPClass KnownLHS, KnownRHS;
6082 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6083 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6084 Depth + 1);
6085
6086 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6087 KnownRHS.isKnownNever(fcNegative) ||
6088 KnownRHS.isKnownNever(fcPositive);
6089
6090 if (KnowSomethingUseful || WantPositive)
6091 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6092 Q, Depth + 1);
6093
6094 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6095
6096 break;
6097 }
6098 case Instruction::FPExt: {
6099 KnownFPClass KnownSrc;
6100 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6101 KnownSrc, Q, Depth + 1);
6102
6103 const fltSemantics &DstTy =
6104 Op->getType()->getScalarType()->getFltSemantics();
6105 const fltSemantics &SrcTy =
6106 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6107
6108 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6109 break;
6110 }
6111 case Instruction::FPTrunc: {
6112 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6113 Depth);
6114 break;
6115 }
6116 case Instruction::SIToFP:
6117 case Instruction::UIToFP: {
6118 // Cannot produce nan
6119 Known.knownNot(fcNan);
6120
6121 // Integers cannot be subnormal
6122 Known.knownNot(fcSubnormal);
6123
6124 // sitofp and uitofp turn into +0.0 for zero.
6125 Known.knownNot(fcNegZero);
6126
6127 // UIToFP is always non-negative regardless of known bits.
6128 if (Op->getOpcode() == Instruction::UIToFP)
6129 Known.signBitMustBeZero();
6130
6131 // Only compute known bits if we can learn something useful from them.
6132 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6133 break;
6134
6135 KnownBits IntKnown =
6136 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6137
6138 // If the integer is non-zero, the result cannot be +0.0
6139 if (IntKnown.isNonZero())
6140 Known.knownNot(fcPosZero);
6141
6142 if (Op->getOpcode() == Instruction::SIToFP) {
6143 // If the signed integer is known non-negative, the result is
6144 // non-negative. If the signed integer is known negative, the result is
6145 // negative.
6146 if (IntKnown.isNonNegative()) {
6147 Known.signBitMustBeZero();
6148 } else if (IntKnown.isNegative()) {
6149 Known.signBitMustBeOne();
6150 }
6151 }
6152
6153 // Guard kept for ilogb()
6154 if (InterestedClasses & fcInf) {
6155 // Get width of largest magnitude integer known.
6156 // This still works for a signed minimum value because the largest FP
6157 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6158 int IntSize = IntKnown.getBitWidth();
6159 if (Op->getOpcode() == Instruction::UIToFP)
6160 IntSize -= IntKnown.countMinLeadingZeros();
6161 else if (Op->getOpcode() == Instruction::SIToFP)
6162 IntSize -= IntKnown.countMinSignBits();
6163
6164 // If the exponent of the largest finite FP value can hold the largest
6165 // integer, the result of the cast must be finite.
6166 Type *FPTy = Op->getType()->getScalarType();
6167 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6168 Known.knownNot(fcInf);
6169 }
6170
6171 break;
6172 }
6173 case Instruction::ExtractElement: {
6174 // Look through extract element. If the index is non-constant or
6175 // out-of-range demand all elements, otherwise just the extracted element.
6176 const Value *Vec = Op->getOperand(0);
6177
6178 APInt DemandedVecElts;
6179 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6180 unsigned NumElts = VecTy->getNumElements();
6181 DemandedVecElts = APInt::getAllOnes(NumElts);
6182 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6183 if (CIdx && CIdx->getValue().ult(NumElts))
6184 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6185 } else {
6186 DemandedVecElts = APInt(1, 1);
6187 }
6188
6189 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6190 Q, Depth + 1);
6191 }
6192 case Instruction::InsertElement: {
6193 if (isa<ScalableVectorType>(Op->getType()))
6194 return;
6195
6196 const Value *Vec = Op->getOperand(0);
6197 const Value *Elt = Op->getOperand(1);
6198 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6199 unsigned NumElts = DemandedElts.getBitWidth();
6200 APInt DemandedVecElts = DemandedElts;
6201 bool NeedsElt = true;
6202 // If we know the index we are inserting to, clear it from Vec check.
6203 if (CIdx && CIdx->getValue().ult(NumElts)) {
6204 DemandedVecElts.clearBit(CIdx->getZExtValue());
6205 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6206 }
6207
6208 // Do we demand the inserted element?
6209 if (NeedsElt) {
6210 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6211 // If we don't know any bits, early out.
6212 if (Known.isUnknown())
6213 break;
6214 } else {
6215 Known.KnownFPClasses = fcNone;
6216 }
6217
6218 // Do we need anymore elements from Vec?
6219 if (!DemandedVecElts.isZero()) {
6220 KnownFPClass Known2;
6221 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6222 Depth + 1);
6223 Known |= Known2;
6224 }
6225
6226 break;
6227 }
6228 case Instruction::ShuffleVector: {
6229 // Handle vector splat idiom
6230 if (Value *Splat = getSplatValue(V)) {
6231 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6232 break;
6233 }
6234
6235 // For undef elements, we don't know anything about the common state of
6236 // the shuffle result.
6237 APInt DemandedLHS, DemandedRHS;
6238 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6239 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6240 return;
6241
6242 if (!!DemandedLHS) {
6243 const Value *LHS = Shuf->getOperand(0);
6244 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6245 Depth + 1);
6246
6247 // If we don't know any bits, early out.
6248 if (Known.isUnknown())
6249 break;
6250 } else {
6251 Known.KnownFPClasses = fcNone;
6252 }
6253
6254 if (!!DemandedRHS) {
6255 KnownFPClass Known2;
6256 const Value *RHS = Shuf->getOperand(1);
6257 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6258 Depth + 1);
6259 Known |= Known2;
6260 }
6261
6262 break;
6263 }
6264 case Instruction::ExtractValue: {
6265 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6266 ArrayRef<unsigned> Indices = Extract->getIndices();
6267 const Value *Src = Extract->getAggregateOperand();
6268 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6269 Indices[0] == 0) {
6270 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6271 switch (II->getIntrinsicID()) {
6272 case Intrinsic::frexp: {
6273 Known.knownNot(fcSubnormal);
6274
6275 KnownFPClass KnownSrc;
6276 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6277 InterestedClasses, KnownSrc, Q, Depth + 1);
6278
6279 const Function *F = cast<Instruction>(Op)->getFunction();
6280 const fltSemantics &FltSem =
6281 Op->getType()->getScalarType()->getFltSemantics();
6282
6284 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6285 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6286 return;
6287 }
6288 default:
6289 break;
6290 }
6291 }
6292 }
6293
6294 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6295 Depth + 1);
6296 break;
6297 }
6298 case Instruction::PHI: {
6299 const PHINode *P = cast<PHINode>(Op);
6300 // Unreachable blocks may have zero-operand PHI nodes.
6301 if (P->getNumIncomingValues() == 0)
6302 break;
6303
6304 // Otherwise take the unions of the known bit sets of the operands,
6305 // taking conservative care to avoid excessive recursion.
6306 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6307
6308 if (Depth < PhiRecursionLimit) {
6309 // Skip if every incoming value references to ourself.
6310 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6311 break;
6312
6313 bool First = true;
6314
6315 for (const Use &U : P->operands()) {
6316 Value *IncValue;
6317 Instruction *CxtI;
6318 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6319 // Skip direct self references.
6320 if (IncValue == P)
6321 continue;
6322
6323 KnownFPClass KnownSrc;
6324 // Recurse, but cap the recursion to two levels, because we don't want
6325 // to waste time spinning around in loops. We need at least depth 2 to
6326 // detect known sign bits.
6327 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6329 PhiRecursionLimit);
6330
6331 if (First) {
6332 Known = KnownSrc;
6333 First = false;
6334 } else {
6335 Known |= KnownSrc;
6336 }
6337
6338 if (Known.KnownFPClasses == fcAllFlags)
6339 break;
6340 }
6341 }
6342
6343 // Look for the case of a for loop which has a positive
6344 // initial value and is incremented by a squared value.
6345 // This will propagate sign information out of such loops.
6346 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6347 break;
6348 for (unsigned I = 0; I < 2; I++) {
6349 Value *RecurValue = P->getIncomingValue(1 - I);
6351 if (!II)
6352 continue;
6353 Value *R, *L, *Init;
6354 PHINode *PN;
6356 PN == P) {
6357 switch (II->getIntrinsicID()) {
6358 case Intrinsic::fma:
6359 case Intrinsic::fmuladd: {
6360 KnownFPClass KnownStart;
6361 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6362 Q, Depth + 1);
6363 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6364 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6366 break;
6367 }
6368 }
6369 }
6370 }
6371 break;
6372 }
6373 case Instruction::BitCast: {
6374 const Value *Src;
6375 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6376 !Src->getType()->isIntOrIntVectorTy())
6377 break;
6378
6379 const Type *Ty = Op->getType();
6380
6381 Value *CastLHS, *CastRHS;
6382
6383 // Match bitcast(umax(bitcast(a), bitcast(b)))
6384 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6385 m_BitCast(m_Value(CastRHS)))) &&
6386 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6387 KnownFPClass KnownLHS, KnownRHS;
6388 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6389 Depth + 1);
6390 if (!KnownRHS.isUnknown()) {
6391 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6392 Q, Depth + 1);
6393 Known = KnownLHS | KnownRHS;
6394 }
6395
6396 return;
6397 }
6398
6399 const Type *EltTy = Ty->getScalarType();
6400 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6401 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6402
6404 break;
6405 }
6406 default:
6407 break;
6408 }
6409}
6410
6412 const APInt &DemandedElts,
6413 FPClassTest InterestedClasses,
6414 const SimplifyQuery &SQ,
6415 unsigned Depth) {
6416 KnownFPClass KnownClasses;
6417 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6418 Depth);
6419 return KnownClasses;
6420}
6421
6423 FPClassTest InterestedClasses,
6424 const SimplifyQuery &SQ,
6425 unsigned Depth) {
6427 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6428 return Known;
6429}
6430
6432 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6433 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6434 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6435 return computeKnownFPClass(V, InterestedClasses,
6436 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6437 Depth);
6438}
6439
6441llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6442 FastMathFlags FMF, FPClassTest InterestedClasses,
6443 const SimplifyQuery &SQ, unsigned Depth) {
6444 if (FMF.noNaNs())
6445 InterestedClasses &= ~fcNan;
6446 if (FMF.noInfs())
6447 InterestedClasses &= ~fcInf;
6448
6449 KnownFPClass Result =
6450 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6451
6452 if (FMF.noNaNs())
6453 Result.KnownFPClasses &= ~fcNan;
6454 if (FMF.noInfs())
6455 Result.KnownFPClasses &= ~fcInf;
6456 return Result;
6457}
6458
6460 FPClassTest InterestedClasses,
6461 const SimplifyQuery &SQ,
6462 unsigned Depth) {
6463 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6464 APInt DemandedElts =
6465 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6466 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6467 Depth);
6468}
6469
6471 unsigned Depth) {
6473 return Known.isKnownNeverNegZero();
6474}
6475
6477 unsigned Depth) {
6480 return Known.cannotBeOrderedLessThanZero();
6481}
6482
6484 unsigned Depth) {
6486 return Known.isKnownNeverInfinity();
6487}
6488
6489/// Return true if the floating-point value can never contain a NaN or infinity.
6491 unsigned Depth) {
6493 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6494}
6495
6496/// Return true if the floating-point scalar value is not a NaN or if the
6497/// floating-point vector value has no NaN elements. Return false if a value
6498/// could ever be NaN.
6500 unsigned Depth) {
6502 return Known.isKnownNeverNaN();
6503}
6504
6505/// Return false if we can prove that the specified FP value's sign bit is 0.
6506/// Return true if we can prove that the specified FP value's sign bit is 1.
6507/// Otherwise return std::nullopt.
6508std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6509 const SimplifyQuery &SQ,
6510 unsigned Depth) {
6512 return Known.getSignBit();
6513}
6514
6516 auto *User = cast<Instruction>(U.getUser());
6517 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6518 if (FPOp->hasNoSignedZeros())
6519 return true;
6520 }
6521
6522 switch (User->getOpcode()) {
6523 case Instruction::FPToSI:
6524 case Instruction::FPToUI:
6525 return true;
6526 case Instruction::FCmp:
6527 // fcmp treats both positive and negative zero as equal.
6528 return true;
6529 case Instruction::Call:
6530 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6531 switch (II->getIntrinsicID()) {
6532 case Intrinsic::fabs:
6533 return true;
6534 case Intrinsic::copysign:
6535 return U.getOperandNo() == 0;
6536 case Intrinsic::is_fpclass: {
6537 auto Test =
6538 static_cast<FPClassTest>(
6539 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6542 }
6543 default:
6544 return false;
6545 }
6546 }
6547 return false;
6548 default:
6549 return false;
6550 }
6551}
6552
6554 auto *User = cast<Instruction>(U.getUser());
6555 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6556 if (FPOp->hasNoNaNs())
6557 return true;
6558 }
6559
6560 switch (User->getOpcode()) {
6561 case Instruction::FPToSI:
6562 case Instruction::FPToUI:
6563 return true;
6564 // Proper FP math operations ignore the sign bit of NaN.
6565 case Instruction::FAdd:
6566 case Instruction::FSub:
6567 case Instruction::FMul:
6568 case Instruction::FDiv:
6569 case Instruction::FRem:
6570 case Instruction::FPTrunc:
6571 case Instruction::FPExt:
6572 case Instruction::FCmp:
6573 return true;
6574 // Bitwise FP operations should preserve the sign bit of NaN.
6575 case Instruction::FNeg:
6576 case Instruction::Select:
6577 case Instruction::PHI:
6578 return false;
6579 case Instruction::Ret:
6580 return User->getFunction()->getAttributes().getRetNoFPClass() &
6582 case Instruction::Call:
6583 case Instruction::Invoke: {
6584 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6585 switch (II->getIntrinsicID()) {
6586 case Intrinsic::fabs:
6587 return true;
6588 case Intrinsic::copysign:
6589 return U.getOperandNo() == 0;
6590 // Other proper FP math intrinsics ignore the sign bit of NaN.
6591 case Intrinsic::maxnum:
6592 case Intrinsic::minnum:
6593 case Intrinsic::maximum:
6594 case Intrinsic::minimum:
6595 case Intrinsic::maximumnum:
6596 case Intrinsic::minimumnum:
6597 case Intrinsic::canonicalize:
6598 case Intrinsic::fma:
6599 case Intrinsic::fmuladd:
6600 case Intrinsic::sqrt:
6601 case Intrinsic::pow:
6602 case Intrinsic::powi:
6603 case Intrinsic::fptoui_sat:
6604 case Intrinsic::fptosi_sat:
6605 case Intrinsic::is_fpclass:
6606 return true;
6607 default:
6608 return false;
6609 }
6610 }
6611
6612 FPClassTest NoFPClass =
6613 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6614 return NoFPClass & FPClassTest::fcNan;
6615 }
6616 default:
6617 return false;
6618 }
6619}
6620
6622 FastMathFlags FMF) {
6623 if (isa<PoisonValue>(V))
6624 return true;
6625 if (isa<UndefValue>(V))
6626 return false;
6627
6628 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6629 return true;
6630
6632 if (!I)
6633 return false;
6634
6635 switch (I->getOpcode()) {
6636 case Instruction::SIToFP:
6637 case Instruction::UIToFP:
6638 // TODO: Could check nofpclass(inf) on incoming argument
6639 if (FMF.noInfs())
6640 return true;
6641
6642 // Need to check int size cannot produce infinity, which computeKnownFPClass
6643 // knows how to do already.
6644 return isKnownNeverInfinity(I, SQ);
6645 case Instruction::Call: {
6646 const CallInst *CI = cast<CallInst>(I);
6647 switch (CI->getIntrinsicID()) {
6648 case Intrinsic::trunc:
6649 case Intrinsic::floor:
6650 case Intrinsic::ceil:
6651 case Intrinsic::rint:
6652 case Intrinsic::nearbyint:
6653 case Intrinsic::round:
6654 case Intrinsic::roundeven:
6655 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6656 default:
6657 break;
6658 }
6659
6660 break;
6661 }
6662 default:
6663 break;
6664 }
6665
6666 return false;
6667}
6668
6670
6671 // All byte-wide stores are splatable, even of arbitrary variables.
6672 if (V->getType()->isIntegerTy(8))
6673 return V;
6674
6675 LLVMContext &Ctx = V->getContext();
6676
6677 // Undef don't care.
6678 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6679 if (isa<UndefValue>(V))
6680 return UndefInt8;
6681
6682 // Return poison for zero-sized type.
6683 if (DL.getTypeStoreSize(V->getType()).isZero())
6684 return PoisonValue::get(Type::getInt8Ty(Ctx));
6685
6687 if (!C) {
6688 // Conceptually, we could handle things like:
6689 // %a = zext i8 %X to i16
6690 // %b = shl i16 %a, 8
6691 // %c = or i16 %a, %b
6692 // but until there is an example that actually needs this, it doesn't seem
6693 // worth worrying about.
6694 return nullptr;
6695 }
6696
6697 // Handle 'null' ConstantArrayZero etc.
6698 if (C->isNullValue())
6700
6701 // Constant floating-point values can be handled as integer values if the
6702 // corresponding integer value is "byteable". An important case is 0.0.
6703 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6704 Type *ScalarTy = CFP->getType()->getScalarType();
6705 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6706 return isBytewiseValue(
6707 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6708
6709 // Don't handle long double formats, which have strange constraints.
6710 return nullptr;
6711 }
6712
6713 // We can handle constant integers that are multiple of 8 bits.
6714 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6715 if (CI->getBitWidth() % 8 == 0) {
6716 if (!CI->getValue().isSplat(8))
6717 return nullptr;
6718 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6719 }
6720 }
6721
6722 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6723 if (CE->getOpcode() == Instruction::IntToPtr) {
6724 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6725 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6727 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6728 return isBytewiseValue(Op, DL);
6729 }
6730 }
6731 }
6732
6733 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6734 if (LHS == RHS)
6735 return LHS;
6736 if (!LHS || !RHS)
6737 return nullptr;
6738 if (LHS == UndefInt8)
6739 return RHS;
6740 if (RHS == UndefInt8)
6741 return LHS;
6742 return nullptr;
6743 };
6744
6746 Value *Val = UndefInt8;
6747 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6748 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6749 return nullptr;
6750 return Val;
6751 }
6752
6754 Value *Val = UndefInt8;
6755 for (Value *Op : C->operands())
6756 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6757 return nullptr;
6758 return Val;
6759 }
6760
6761 // Don't try to handle the handful of other constants.
6762 return nullptr;
6763}
6764
6765// This is the recursive version of BuildSubAggregate. It takes a few different
6766// arguments. Idxs is the index within the nested struct From that we are
6767// looking at now (which is of type IndexedType). IdxSkip is the number of
6768// indices from Idxs that should be left out when inserting into the resulting
6769// struct. To is the result struct built so far, new insertvalue instructions
6770// build on that.
6771static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6773 unsigned IdxSkip,
6774 BasicBlock::iterator InsertBefore) {
6775 StructType *STy = dyn_cast<StructType>(IndexedType);
6776 if (STy) {
6777 // Save the original To argument so we can modify it
6778 Value *OrigTo = To;
6779 // General case, the type indexed by Idxs is a struct
6780 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6781 // Process each struct element recursively
6782 Idxs.push_back(i);
6783 Value *PrevTo = To;
6784 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6785 InsertBefore);
6786 Idxs.pop_back();
6787 if (!To) {
6788 // Couldn't find any inserted value for this index? Cleanup
6789 while (PrevTo != OrigTo) {
6791 PrevTo = Del->getAggregateOperand();
6792 Del->eraseFromParent();
6793 }
6794 // Stop processing elements
6795 break;
6796 }
6797 }
6798 // If we successfully found a value for each of our subaggregates
6799 if (To)
6800 return To;
6801 }
6802 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6803 // the struct's elements had a value that was inserted directly. In the latter
6804 // case, perhaps we can't determine each of the subelements individually, but
6805 // we might be able to find the complete struct somewhere.
6806
6807 // Find the value that is at that particular spot
6808 Value *V = FindInsertedValue(From, Idxs);
6809
6810 if (!V)
6811 return nullptr;
6812
6813 // Insert the value in the new (sub) aggregate
6814 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6815 InsertBefore);
6816}
6817
6818// This helper takes a nested struct and extracts a part of it (which is again a
6819// struct) into a new value. For example, given the struct:
6820// { a, { b, { c, d }, e } }
6821// and the indices "1, 1" this returns
6822// { c, d }.
6823//
6824// It does this by inserting an insertvalue for each element in the resulting
6825// struct, as opposed to just inserting a single struct. This will only work if
6826// each of the elements of the substruct are known (ie, inserted into From by an
6827// insertvalue instruction somewhere).
6828//
6829// All inserted insertvalue instructions are inserted before InsertBefore
6831 BasicBlock::iterator InsertBefore) {
6832 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6833 idx_range);
6834 Value *To = PoisonValue::get(IndexedType);
6835 SmallVector<unsigned, 10> Idxs(idx_range);
6836 unsigned IdxSkip = Idxs.size();
6837
6838 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6839}
6840
6841/// Given an aggregate and a sequence of indices, see if the scalar value
6842/// indexed is already around as a register, for example if it was inserted
6843/// directly into the aggregate.
6844///
6845/// If InsertBefore is not null, this function will duplicate (modified)
6846/// insertvalues when a part of a nested struct is extracted.
6847Value *
6849 std::optional<BasicBlock::iterator> InsertBefore) {
6850 // Nothing to index? Just return V then (this is useful at the end of our
6851 // recursion).
6852 if (idx_range.empty())
6853 return V;
6854 // We have indices, so V should have an indexable type.
6855 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6856 "Not looking at a struct or array?");
6857 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6858 "Invalid indices for type?");
6859
6860 if (Constant *C = dyn_cast<Constant>(V)) {
6861 C = C->getAggregateElement(idx_range[0]);
6862 if (!C) return nullptr;
6863 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6864 }
6865
6867 // Loop the indices for the insertvalue instruction in parallel with the
6868 // requested indices
6869 const unsigned *req_idx = idx_range.begin();
6870 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6871 i != e; ++i, ++req_idx) {
6872 if (req_idx == idx_range.end()) {
6873 // We can't handle this without inserting insertvalues
6874 if (!InsertBefore)
6875 return nullptr;
6876
6877 // The requested index identifies a part of a nested aggregate. Handle
6878 // this specially. For example,
6879 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6880 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6881 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6882 // This can be changed into
6883 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6884 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6885 // which allows the unused 0,0 element from the nested struct to be
6886 // removed.
6887 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6888 *InsertBefore);
6889 }
6890
6891 // This insert value inserts something else than what we are looking for.
6892 // See if the (aggregate) value inserted into has the value we are
6893 // looking for, then.
6894 if (*req_idx != *i)
6895 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6896 InsertBefore);
6897 }
6898 // If we end up here, the indices of the insertvalue match with those
6899 // requested (though possibly only partially). Now we recursively look at
6900 // the inserted value, passing any remaining indices.
6901 return FindInsertedValue(I->getInsertedValueOperand(),
6902 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6903 }
6904
6906 // If we're extracting a value from an aggregate that was extracted from
6907 // something else, we can extract from that something else directly instead.
6908 // However, we will need to chain I's indices with the requested indices.
6909
6910 // Calculate the number of indices required
6911 unsigned size = I->getNumIndices() + idx_range.size();
6912 // Allocate some space to put the new indices in
6914 Idxs.reserve(size);
6915 // Add indices from the extract value instruction
6916 Idxs.append(I->idx_begin(), I->idx_end());
6917
6918 // Add requested indices
6919 Idxs.append(idx_range.begin(), idx_range.end());
6920
6921 assert(Idxs.size() == size
6922 && "Number of indices added not correct?");
6923
6924 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6925 }
6926 // Otherwise, we don't know (such as, extracting from a function return value
6927 // or load instruction)
6928 return nullptr;
6929}
6930
6931// If V refers to an initialized global constant, set Slice either to
6932// its initializer if the size of its elements equals ElementSize, or,
6933// for ElementSize == 8, to its representation as an array of unsiged
6934// char. Return true on success.
6935// Offset is in the unit "nr of ElementSize sized elements".
6938 unsigned ElementSize, uint64_t Offset) {
6939 assert(V && "V should not be null.");
6940 assert((ElementSize % 8) == 0 &&
6941 "ElementSize expected to be a multiple of the size of a byte.");
6942 unsigned ElementSizeInBytes = ElementSize / 8;
6943
6944 // Drill down into the pointer expression V, ignoring any intervening
6945 // casts, and determine the identity of the object it references along
6946 // with the cumulative byte offset into it.
6947 const GlobalVariable *GV =
6949 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6950 // Fail if V is not based on constant global object.
6951 return false;
6952
6953 const DataLayout &DL = GV->getDataLayout();
6954 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6955
6956 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6957 /*AllowNonInbounds*/ true))
6958 // Fail if a constant offset could not be determined.
6959 return false;
6960
6961 uint64_t StartIdx = Off.getLimitedValue();
6962 if (StartIdx == UINT64_MAX)
6963 // Fail if the constant offset is excessive.
6964 return false;
6965
6966 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6967 // elements. Simply bail out if that isn't possible.
6968 if ((StartIdx % ElementSizeInBytes) != 0)
6969 return false;
6970
6971 Offset += StartIdx / ElementSizeInBytes;
6972 ConstantDataArray *Array = nullptr;
6973 ArrayType *ArrayTy = nullptr;
6974
6975 if (GV->getInitializer()->isNullValue()) {
6976 Type *GVTy = GV->getValueType();
6977 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6978 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6979
6980 Slice.Array = nullptr;
6981 Slice.Offset = 0;
6982 // Return an empty Slice for undersized constants to let callers
6983 // transform even undefined library calls into simpler, well-defined
6984 // expressions. This is preferable to making the calls although it
6985 // prevents sanitizers from detecting such calls.
6986 Slice.Length = Length < Offset ? 0 : Length - Offset;
6987 return true;
6988 }
6989
6990 auto *Init = const_cast<Constant *>(GV->getInitializer());
6991 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6992 Type *InitElTy = ArrayInit->getElementType();
6993 if (InitElTy->isIntegerTy(ElementSize)) {
6994 // If Init is an initializer for an array of the expected type
6995 // and size, use it as is.
6996 Array = ArrayInit;
6997 ArrayTy = ArrayInit->getType();
6998 }
6999 }
7000
7001 if (!Array) {
7002 if (ElementSize != 8)
7003 // TODO: Handle conversions to larger integral types.
7004 return false;
7005
7006 // Otherwise extract the portion of the initializer starting
7007 // at Offset as an array of bytes, and reset Offset.
7009 if (!Init)
7010 return false;
7011
7012 Offset = 0;
7014 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7015 }
7016
7017 uint64_t NumElts = ArrayTy->getArrayNumElements();
7018 if (Offset > NumElts)
7019 return false;
7020
7021 Slice.Array = Array;
7022 Slice.Offset = Offset;
7023 Slice.Length = NumElts - Offset;
7024 return true;
7025}
7026
7027/// Extract bytes from the initializer of the constant array V, which need
7028/// not be a nul-terminated string. On success, store the bytes in Str and
7029/// return true. When TrimAtNul is set, Str will contain only the bytes up
7030/// to but not including the first nul. Return false on failure.
7032 bool TrimAtNul) {
7034 if (!getConstantDataArrayInfo(V, Slice, 8))
7035 return false;
7036
7037 if (Slice.Array == nullptr) {
7038 if (TrimAtNul) {
7039 // Return a nul-terminated string even for an empty Slice. This is
7040 // safe because all existing SimplifyLibcalls callers require string
7041 // arguments and the behavior of the functions they fold is undefined
7042 // otherwise. Folding the calls this way is preferable to making
7043 // the undefined library calls, even though it prevents sanitizers
7044 // from reporting such calls.
7045 Str = StringRef();
7046 return true;
7047 }
7048 if (Slice.Length == 1) {
7049 Str = StringRef("", 1);
7050 return true;
7051 }
7052 // We cannot instantiate a StringRef as we do not have an appropriate string
7053 // of 0s at hand.
7054 return false;
7055 }
7056
7057 // Start out with the entire array in the StringRef.
7058 Str = Slice.Array->getAsString();
7059 // Skip over 'offset' bytes.
7060 Str = Str.substr(Slice.Offset);
7061
7062 if (TrimAtNul) {
7063 // Trim off the \0 and anything after it. If the array is not nul
7064 // terminated, we just return the whole end of string. The client may know
7065 // some other way that the string is length-bound.
7066 Str = Str.substr(0, Str.find('\0'));
7067 }
7068 return true;
7069}
7070
7071// These next two are very similar to the above, but also look through PHI
7072// nodes.
7073// TODO: See if we can integrate these two together.
7074
7075/// If we can compute the length of the string pointed to by
7076/// the specified pointer, return 'len+1'. If we can't, return 0.
7079 unsigned CharSize) {
7080 // Look through noop bitcast instructions.
7081 V = V->stripPointerCasts();
7082
7083 // If this is a PHI node, there are two cases: either we have already seen it
7084 // or we haven't.
7085 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7086 if (!PHIs.insert(PN).second)
7087 return ~0ULL; // already in the set.
7088
7089 // If it was new, see if all the input strings are the same length.
7090 uint64_t LenSoFar = ~0ULL;
7091 for (Value *IncValue : PN->incoming_values()) {
7092 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7093 if (Len == 0) return 0; // Unknown length -> unknown.
7094
7095 if (Len == ~0ULL) continue;
7096
7097 if (Len != LenSoFar && LenSoFar != ~0ULL)
7098 return 0; // Disagree -> unknown.
7099 LenSoFar = Len;
7100 }
7101
7102 // Success, all agree.
7103 return LenSoFar;
7104 }
7105
7106 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7107 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7108 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7109 if (Len1 == 0) return 0;
7110 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7111 if (Len2 == 0) return 0;
7112 if (Len1 == ~0ULL) return Len2;
7113 if (Len2 == ~0ULL) return Len1;
7114 if (Len1 != Len2) return 0;
7115 return Len1;
7116 }
7117
7118 // Otherwise, see if we can read the string.
7120 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7121 return 0;
7122
7123 if (Slice.Array == nullptr)
7124 // Zeroinitializer (including an empty one).
7125 return 1;
7126
7127 // Search for the first nul character. Return a conservative result even
7128 // when there is no nul. This is safe since otherwise the string function
7129 // being folded such as strlen is undefined, and can be preferable to
7130 // making the undefined library call.
7131 unsigned NullIndex = 0;
7132 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7133 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7134 break;
7135 }
7136
7137 return NullIndex + 1;
7138}
7139
7140/// If we can compute the length of the string pointed to by
7141/// the specified pointer, return 'len+1'. If we can't, return 0.
7142uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7143 if (!V->getType()->isPointerTy())
7144 return 0;
7145
7147 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7148 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7149 // an empty string as a length.
7150 return Len == ~0ULL ? 1 : Len;
7151}
7152
7153const Value *
7155 bool MustPreserveOffset) {
7156 assert(Call &&
7157 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7158 if (const Value *RV = Call->getReturnedArgOperand())
7159 return RV;
7160 // This can be used only as a aliasing property.
7162 Call, MustPreserveOffset))
7163 return Call->getArgOperand(0);
7164 return nullptr;
7165}
7166
7168 const CallBase *Call, bool MustPreserveOffset) {
7169 switch (Call->getIntrinsicID()) {
7170 case Intrinsic::launder_invariant_group:
7171 case Intrinsic::strip_invariant_group:
7172 case Intrinsic::aarch64_irg:
7173 case Intrinsic::aarch64_tagp:
7174 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7175 // input pointer (and thus preserves the byte offset, which is the property
7176 // the MustPreserveOffset flag selects). However, it will not necessarily
7177 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7178 // descriptor", which has "all loads return 0, all stores are dropped"
7179 // semantics. Given the context of this intrinsic list, no one should be
7180 // relying on such a strict bit-exact null mapping (and, at time of
7181 // writing, they are not), but we document this fact out of an abundance
7182 // of caution.
7183 case Intrinsic::amdgcn_make_buffer_rsrc:
7184 return true;
7185 case Intrinsic::ptrmask:
7186 return !MustPreserveOffset;
7187 case Intrinsic::threadlocal_address:
7188 // The underlying variable changes with thread ID. The Thread ID may change
7189 // at coroutine suspend points.
7190 return !Call->getParent()->getParent()->isPresplitCoroutine();
7191 default:
7192 return false;
7193 }
7194}
7195
7196/// \p PN defines a loop-variant pointer to an object. Check if the
7197/// previous iteration of the loop was referring to the same object as \p PN.
7199 const LoopInfo *LI) {
7200 // Find the loop-defined value.
7201 Loop *L = LI->getLoopFor(PN->getParent());
7202 if (PN->getNumIncomingValues() != 2)
7203 return true;
7204
7205 // Find the value from previous iteration.
7206 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7207 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7208 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7209 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7210 return true;
7211
7212 // If a new pointer is loaded in the loop, the pointer references a different
7213 // object in every iteration. E.g.:
7214 // for (i)
7215 // int *p = a[i];
7216 // ...
7217 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7218 if (!L->isLoopInvariant(Load->getPointerOperand()))
7219 return false;
7220 return true;
7221}
7222
7223const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7224 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7225 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7226 const Value *PtrOp = GEP->getPointerOperand();
7227 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7228 return V;
7229 V = PtrOp;
7230 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7231 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7232 Value *NewV = cast<Operator>(V)->getOperand(0);
7233 if (!NewV->getType()->isPointerTy())
7234 return V;
7235 V = NewV;
7236 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7237 if (GA->isInterposable())
7238 return V;
7239 V = GA->getAliasee();
7240 } else {
7241 if (auto *PHI = dyn_cast<PHINode>(V)) {
7242 // Look through single-arg phi nodes created by LCSSA.
7243 if (PHI->getNumIncomingValues() == 1) {
7244 V = PHI->getIncomingValue(0);
7245 continue;
7246 }
7247 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7248 // CaptureTracking can know about special capturing properties of some
7249 // intrinsics like launder.invariant.group, that can't be expressed with
7250 // the attributes, but have properties like returning aliasing pointer.
7251 // Because some analysis may assume that nocaptured pointer is not
7252 // returned from some special intrinsic (because function would have to
7253 // be marked with returns attribute), it is crucial to use this function
7254 // because it should be in sync with CaptureTracking. Not using it may
7255 // cause weird miscompilations where 2 aliasing pointers are assumed to
7256 // noalias.
7258 Call, /*MustPreserveOffset=*/false)) {
7259 V = RP;
7260 continue;
7261 }
7262 }
7263
7264 return V;
7265 }
7266 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7267 }
7268 return V;
7269}
7270
7273 const LoopInfo *LI, unsigned MaxLookup) {
7276 Worklist.push_back(V);
7277 do {
7278 const Value *P = Worklist.pop_back_val();
7279 P = getUnderlyingObject(P, MaxLookup);
7280
7281 if (!Visited.insert(P).second)
7282 continue;
7283
7284 if (auto *SI = dyn_cast<SelectInst>(P)) {
7285 Worklist.push_back(SI->getTrueValue());
7286 Worklist.push_back(SI->getFalseValue());
7287 continue;
7288 }
7289
7290 if (auto *PN = dyn_cast<PHINode>(P)) {
7291 // If this PHI changes the underlying object in every iteration of the
7292 // loop, don't look through it. Consider:
7293 // int **A;
7294 // for (i) {
7295 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7296 // Curr = A[i];
7297 // *Prev, *Curr;
7298 //
7299 // Prev is tracking Curr one iteration behind so they refer to different
7300 // underlying objects.
7301 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7303 append_range(Worklist, PN->incoming_values());
7304 else
7305 Objects.push_back(P);
7306 continue;
7307 }
7308
7309 Objects.push_back(P);
7310 } while (!Worklist.empty());
7311}
7312
7314 const unsigned MaxVisited = 8;
7315
7318 Worklist.push_back(V);
7319 const Value *Object = nullptr;
7320 // Used as fallback if we can't find a common underlying object through
7321 // recursion.
7322 bool First = true;
7323 const Value *FirstObject = getUnderlyingObject(V);
7324 do {
7325 const Value *P = Worklist.pop_back_val();
7326 P = First ? FirstObject : getUnderlyingObject(P);
7327 First = false;
7328
7329 if (!Visited.insert(P).second)
7330 continue;
7331
7332 if (Visited.size() == MaxVisited)
7333 return FirstObject;
7334
7335 if (auto *SI = dyn_cast<SelectInst>(P)) {
7336 Worklist.push_back(SI->getTrueValue());
7337 Worklist.push_back(SI->getFalseValue());
7338 continue;
7339 }
7340
7341 if (auto *PN = dyn_cast<PHINode>(P)) {
7342 append_range(Worklist, PN->incoming_values());
7343 continue;
7344 }
7345
7346 if (!Object)
7347 Object = P;
7348 else if (Object != P)
7349 return FirstObject;
7350 } while (!Worklist.empty());
7351
7352 return Object ? Object : FirstObject;
7353}
7354
7355/// This is the function that does the work of looking through basic
7356/// ptrtoint+arithmetic+inttoptr sequences.
7357static const Value *getUnderlyingObjectFromInt(const Value *V) {
7358 do {
7359 if (const Operator *U = dyn_cast<Operator>(V)) {
7360 // If we find a ptrtoint, we can transfer control back to the
7361 // regular getUnderlyingObjectFromInt.
7362 if (U->getOpcode() == Instruction::PtrToInt)
7363 return U->getOperand(0);
7364 // If we find an add of a constant, a multiplied value, or a phi, it's
7365 // likely that the other operand will lead us to the base
7366 // object. We don't have to worry about the case where the
7367 // object address is somehow being computed by the multiply,
7368 // because our callers only care when the result is an
7369 // identifiable object.
7370 if (U->getOpcode() != Instruction::Add ||
7371 (!isa<ConstantInt>(U->getOperand(1)) &&
7372 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7373 !isa<PHINode>(U->getOperand(1))))
7374 return V;
7375 V = U->getOperand(0);
7376 } else {
7377 return V;
7378 }
7379 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7380 } while (true);
7381}
7382
7383/// This is a wrapper around getUnderlyingObjects and adds support for basic
7384/// ptrtoint+arithmetic+inttoptr sequences.
7385/// It returns false if unidentified object is found in getUnderlyingObjects.
7387 SmallVectorImpl<Value *> &Objects) {
7389 SmallVector<const Value *, 4> Working(1, V);
7390 do {
7391 V = Working.pop_back_val();
7392
7394 getUnderlyingObjects(V, Objs);
7395
7396 for (const Value *V : Objs) {
7397 if (!Visited.insert(V).second)
7398 continue;
7399 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7400 const Value *O =
7401 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7402 if (O->getType()->isPointerTy()) {
7403 Working.push_back(O);
7404 continue;
7405 }
7406 }
7407 // If getUnderlyingObjects fails to find an identifiable object,
7408 // getUnderlyingObjectsForCodeGen also fails for safety.
7409 if (!isIdentifiedObject(V)) {
7410 Objects.clear();
7411 return false;
7412 }
7413 Objects.push_back(const_cast<Value *>(V));
7414 }
7415 } while (!Working.empty());
7416 return true;
7417}
7418
7420 AllocaInst *Result = nullptr;
7422 SmallVector<Value *, 4> Worklist;
7423
7424 auto AddWork = [&](Value *V) {
7425 if (Visited.insert(V).second)
7426 Worklist.push_back(V);
7427 };
7428
7429 AddWork(V);
7430 do {
7431 V = Worklist.pop_back_val();
7432 assert(Visited.count(V));
7433
7434 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7435 if (Result && Result != AI)
7436 return nullptr;
7437 Result = AI;
7438 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7439 AddWork(CI->getOperand(0));
7440 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7441 for (Value *IncValue : PN->incoming_values())
7442 AddWork(IncValue);
7443 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7444 AddWork(SI->getTrueValue());
7445 AddWork(SI->getFalseValue());
7447 if (OffsetZero && !GEP->hasAllZeroIndices())
7448 return nullptr;
7449 AddWork(GEP->getPointerOperand());
7450 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7451 Value *Returned = CB->getReturnedArgOperand();
7452 if (Returned)
7453 AddWork(Returned);
7454 else
7455 return nullptr;
7456 } else {
7457 return nullptr;
7458 }
7459 } while (!Worklist.empty());
7460
7461 return Result;
7462}
7463
7465 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7466 for (const User *U : V->users()) {
7468 if (!II)
7469 return false;
7470
7471 if (AllowLifetime && II->isLifetimeStartOrEnd())
7472 continue;
7473
7474 if (AllowDroppable && II->isDroppable())
7475 continue;
7476
7477 return false;
7478 }
7479 return true;
7480}
7481
7484 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7485}
7488 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7489}
7490
7492 if (auto *II = dyn_cast<IntrinsicInst>(I))
7493 return isTriviallyVectorizable(II->getIntrinsicID());
7494 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7495 return (!Shuffle || Shuffle->isSelect()) &&
7497}
7498
7500 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7501 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7502 bool IgnoreUBImplyingAttrs) {
7503 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7504 AC, DT, TLI, UseVariableInfo,
7505 IgnoreUBImplyingAttrs);
7506}
7507
7509 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7510 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7511 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7512#ifndef NDEBUG
7513 if (Inst->getOpcode() != Opcode) {
7514 // Check that the operands are actually compatible with the Opcode override.
7515 auto hasEqualReturnAndLeadingOperandTypes =
7516 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7517 if (Inst->getNumOperands() < NumLeadingOperands)
7518 return false;
7519 const Type *ExpectedType = Inst->getType();
7520 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7521 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7522 return false;
7523 return true;
7524 };
7526 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7527 assert(!Instruction::isUnaryOp(Opcode) ||
7528 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7529 }
7530#endif
7531
7532 switch (Opcode) {
7533 default:
7534 return true;
7535 case Instruction::UDiv:
7536 case Instruction::URem: {
7537 // x / y is undefined if y == 0.
7538 const APInt *V;
7539 if (match(Inst->getOperand(1), m_APInt(V)))
7540 return *V != 0;
7541 return false;
7542 }
7543 case Instruction::SDiv:
7544 case Instruction::SRem: {
7545 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7546 const APInt *Numerator, *Denominator;
7547 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7548 return false;
7549 // We cannot hoist this division if the denominator is 0.
7550 if (*Denominator == 0)
7551 return false;
7552 // It's safe to hoist if the denominator is not 0 or -1.
7553 if (!Denominator->isAllOnes())
7554 return true;
7555 // At this point we know that the denominator is -1. It is safe to hoist as
7556 // long we know that the numerator is not INT_MIN.
7557 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7558 return !Numerator->isMinSignedValue();
7559 // The numerator *might* be MinSignedValue.
7560 return false;
7561 }
7562 case Instruction::Load: {
7563 if (!UseVariableInfo)
7564 return false;
7565
7566 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7567 if (!LI)
7568 return false;
7569 if (mustSuppressSpeculation(*LI))
7570 return false;
7571 const DataLayout &DL = LI->getDataLayout();
7573 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7574 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7575 }
7576 case Instruction::Call: {
7577 auto *CI = dyn_cast<const CallInst>(Inst);
7578 if (!CI)
7579 return false;
7580 const Function *Callee = CI->getCalledFunction();
7581
7582 // The called function could have undefined behavior or side-effects, even
7583 // if marked readnone nounwind.
7584 if (!Callee || !Callee->isSpeculatable())
7585 return false;
7586 // Since the operands may be changed after hoisting, undefined behavior may
7587 // be triggered by some UB-implying attributes.
7588 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7589 }
7590 case Instruction::VAArg:
7591 case Instruction::Alloca:
7592 case Instruction::Invoke:
7593 case Instruction::CallBr:
7594 case Instruction::PHI:
7595 case Instruction::Store:
7596 case Instruction::Ret:
7597 case Instruction::UncondBr:
7598 case Instruction::CondBr:
7599 case Instruction::IndirectBr:
7600 case Instruction::Switch:
7601 case Instruction::Unreachable:
7602 case Instruction::Fence:
7603 case Instruction::AtomicRMW:
7604 case Instruction::AtomicCmpXchg:
7605 case Instruction::LandingPad:
7606 case Instruction::Resume:
7607 case Instruction::CatchSwitch:
7608 case Instruction::CatchPad:
7609 case Instruction::CatchRet:
7610 case Instruction::CleanupPad:
7611 case Instruction::CleanupRet:
7612 return false; // Misc instructions which have effects
7613 }
7614}
7615
7617 if (I.mayReadOrWriteMemory())
7618 // Memory dependency possible
7619 return true;
7621 // Can't move above a maythrow call or infinite loop. Or if an
7622 // inalloca alloca, above a stacksave call.
7623 return true;
7625 // 1) Can't reorder two inf-loop calls, even if readonly
7626 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7627 // safe to speculative execute. (Inverse of above)
7628 return true;
7629 return false;
7630}
7631
7632/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7646
7647/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7650 bool ForSigned,
7651 const SimplifyQuery &SQ) {
7652 ConstantRange CR1 =
7653 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7654 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7657 return CR1.intersectWith(CR2, RangeType);
7658}
7659
7661 const Value *RHS,
7662 const SimplifyQuery &SQ,
7663 bool IsNSW) {
7664 ConstantRange LHSRange =
7665 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7666 ConstantRange RHSRange =
7667 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7668
7669 // mul nsw of two non-negative numbers is also nuw.
7670 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7672
7673 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7674}
7675
7677 const Value *RHS,
7678 const SimplifyQuery &SQ) {
7679 // Multiplying n * m significant bits yields a result of n + m significant
7680 // bits. If the total number of significant bits does not exceed the
7681 // result bit width (minus 1), there is no overflow.
7682 // This means if we have enough leading sign bits in the operands
7683 // we can guarantee that the result does not overflow.
7684 // Ref: "Hacker's Delight" by Henry Warren
7685 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7686
7687 // Note that underestimating the number of sign bits gives a more
7688 // conservative answer.
7689 unsigned SignBits =
7690 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7691
7692 // First handle the easy case: if we have enough sign bits there's
7693 // definitely no overflow.
7694 if (SignBits > BitWidth + 1)
7696
7697 // There are two ambiguous cases where there can be no overflow:
7698 // SignBits == BitWidth + 1 and
7699 // SignBits == BitWidth
7700 // The second case is difficult to check, therefore we only handle the
7701 // first case.
7702 if (SignBits == BitWidth + 1) {
7703 // It overflows only when both arguments are negative and the true
7704 // product is exactly the minimum negative number.
7705 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7706 // For simplicity we just check if at least one side is not negative.
7707 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7708 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7709 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7711 }
7713}
7714
7717 const WithCache<const Value *> &RHS,
7718 const SimplifyQuery &SQ) {
7719 ConstantRange LHSRange =
7720 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7721 ConstantRange RHSRange =
7722 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7723 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7724}
7725
7726static OverflowResult
7729 const AddOperator *Add, const SimplifyQuery &SQ) {
7730 if (Add && Add->hasNoSignedWrap()) {
7732 }
7733
7734 // If LHS and RHS each have at least two sign bits, the addition will look
7735 // like
7736 //
7737 // XX..... +
7738 // YY.....
7739 //
7740 // If the carry into the most significant position is 0, X and Y can't both
7741 // be 1 and therefore the carry out of the addition is also 0.
7742 //
7743 // If the carry into the most significant position is 1, X and Y can't both
7744 // be 0 and therefore the carry out of the addition is also 1.
7745 //
7746 // Since the carry into the most significant position is always equal to
7747 // the carry out of the addition, there is no signed overflow.
7748 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7750
7751 ConstantRange LHSRange =
7752 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7753 ConstantRange RHSRange =
7754 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7755 OverflowResult OR =
7756 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7758 return OR;
7759
7760 // The remaining code needs Add to be available. Early returns if not so.
7761 if (!Add)
7763
7764 // If the sign of Add is the same as at least one of the operands, this add
7765 // CANNOT overflow. If this can be determined from the known bits of the
7766 // operands the above signedAddMayOverflow() check will have already done so.
7767 // The only other way to improve on the known bits is from an assumption, so
7768 // call computeKnownBitsFromContext() directly.
7769 bool LHSOrRHSKnownNonNegative =
7770 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7771 bool LHSOrRHSKnownNegative =
7772 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7773 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7774 KnownBits AddKnown(LHSRange.getBitWidth());
7775 computeKnownBitsFromContext(Add, AddKnown, SQ);
7776 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7777 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7779 }
7780
7782}
7783
7785 const Value *RHS,
7786 const SimplifyQuery &SQ) {
7787 // X - (X % ?)
7788 // The remainder of a value can't have greater magnitude than itself,
7789 // so the subtraction can't overflow.
7790
7791 // X - (X -nuw ?)
7792 // In the minimal case, this would simplify to "?", so there's no subtract
7793 // at all. But if this analysis is used to peek through casts, for example,
7794 // then determining no-overflow may allow other transforms.
7795
7796 // TODO: There are other patterns like this.
7797 // See simplifyICmpWithBinOpOnLHS() for candidates.
7798 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7799 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7800 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7802
7803 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7804 SQ.DL)) {
7805 if (*C)
7808 }
7809
7810 ConstantRange LHSRange =
7811 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7812 ConstantRange RHSRange =
7813 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7814 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7815}
7816
7818 const Value *RHS,
7819 const SimplifyQuery &SQ) {
7820 // X - (X % ?)
7821 // The remainder of a value can't have greater magnitude than itself,
7822 // so the subtraction can't overflow.
7823
7824 // X - (X -nsw ?)
7825 // In the minimal case, this would simplify to "?", so there's no subtract
7826 // at all. But if this analysis is used to peek through casts, for example,
7827 // then determining no-overflow may allow other transforms.
7828 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7829 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7830 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7832
7833 // If LHS and RHS each have at least two sign bits, the subtraction
7834 // cannot overflow.
7835 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7837
7838 ConstantRange LHSRange =
7839 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7840 ConstantRange RHSRange =
7841 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7842 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7843}
7844
7846 const DominatorTree &DT) {
7847 SmallVector<const CondBrInst *, 2> GuardingBranches;
7849
7850 for (const User *U : WO->users()) {
7851 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7852 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7853
7854 if (EVI->getIndices()[0] == 0)
7855 Results.push_back(EVI);
7856 else {
7857 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7858
7859 for (const auto *U : EVI->users())
7860 if (const auto *B = dyn_cast<CondBrInst>(U))
7861 GuardingBranches.push_back(B);
7862 }
7863 } else {
7864 // We are using the aggregate directly in a way we don't want to analyze
7865 // here (storing it to a global, say).
7866 return false;
7867 }
7868 }
7869
7870 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7871 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7872
7873 // Check if all users of the add are provably no-wrap.
7874 for (const auto *Result : Results) {
7875 // If the extractvalue itself is not executed on overflow, the we don't
7876 // need to check each use separately, since domination is transitive.
7877 if (DT.dominates(NoWrapEdge, Result->getParent()))
7878 continue;
7879
7880 for (const auto &RU : Result->uses())
7881 if (!DT.dominates(NoWrapEdge, RU))
7882 return false;
7883 }
7884
7885 return true;
7886 };
7887
7888 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7889}
7890
7891/// Shifts return poison if shiftwidth is larger than the bitwidth.
7892static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7893 auto *C = dyn_cast<Constant>(ShiftAmount);
7894 if (!C)
7895 return false;
7896
7897 // Shifts return poison if shiftwidth is larger than the bitwidth.
7899 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7900 unsigned NumElts = FVTy->getNumElements();
7901 for (unsigned i = 0; i < NumElts; ++i)
7902 ShiftAmounts.push_back(C->getAggregateElement(i));
7903 } else if (isa<ScalableVectorType>(C->getType()))
7904 return false; // Can't tell, just return false to be safe
7905 else
7906 ShiftAmounts.push_back(C);
7907
7908 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7909 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7910 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7911 });
7912
7913 return Safe;
7914}
7915
7917 bool ConsiderFlagsAndMetadata) {
7918
7919 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7920 Op->hasPoisonGeneratingAnnotations())
7921 return true;
7922
7923 unsigned Opcode = Op->getOpcode();
7924
7925 // Check whether opcode is a poison/undef-generating operation
7926 switch (Opcode) {
7927 case Instruction::Shl:
7928 case Instruction::AShr:
7929 case Instruction::LShr:
7930 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7931 case Instruction::FPToSI:
7932 case Instruction::FPToUI:
7933 // fptosi/ui yields poison if the resulting value does not fit in the
7934 // destination type.
7935 return true;
7936 case Instruction::Call:
7937 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7938 switch (II->getIntrinsicID()) {
7939 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7940 case Intrinsic::ctlz:
7941 case Intrinsic::cttz:
7942 case Intrinsic::abs:
7943 // We're not considering flags so it is safe to just return false.
7944 return false;
7945 case Intrinsic::sshl_sat:
7946 case Intrinsic::ushl_sat:
7947 if (!includesPoison(Kind) ||
7948 shiftAmountKnownInRange(II->getArgOperand(1)))
7949 return false;
7950 break;
7951 }
7952 }
7953 [[fallthrough]];
7954 case Instruction::CallBr:
7955 case Instruction::Invoke: {
7956 const auto *CB = cast<CallBase>(Op);
7957 return !CB->hasRetAttr(Attribute::NoUndef) &&
7958 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7959 }
7960 case Instruction::InsertElement:
7961 case Instruction::ExtractElement: {
7962 // If index exceeds the length of the vector, it returns poison
7963 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7964 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7965 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7966 if (includesPoison(Kind))
7967 return !Idx ||
7968 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7969 return false;
7970 }
7971 case Instruction::ShuffleVector: {
7973 ? cast<ConstantExpr>(Op)->getShuffleMask()
7974 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7975 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7976 }
7977 case Instruction::FNeg:
7978 case Instruction::PHI:
7979 case Instruction::Select:
7980 case Instruction::ExtractValue:
7981 case Instruction::InsertValue:
7982 case Instruction::Freeze:
7983 case Instruction::ICmp:
7984 case Instruction::FCmp:
7985 case Instruction::GetElementPtr:
7986 return false;
7987 case Instruction::AddrSpaceCast:
7988 return true;
7989 default: {
7990 const auto *CE = dyn_cast<ConstantExpr>(Op);
7991 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7992 return false;
7993 else if (Instruction::isBinaryOp(Opcode))
7994 return false;
7995 // Be conservative and return true.
7996 return true;
7997 }
7998 }
7999}
8000
8002 bool ConsiderFlagsAndMetadata) {
8003 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8004 ConsiderFlagsAndMetadata);
8005}
8006
8007bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8008 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8009 ConsiderFlagsAndMetadata);
8010}
8011
8012static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8013 unsigned Depth) {
8014 if (ValAssumedPoison == V)
8015 return true;
8016
8017 const unsigned MaxDepth = 2;
8018 if (Depth >= MaxDepth)
8019 return false;
8020
8021 if (const auto *I = dyn_cast<Instruction>(V)) {
8022 if (any_of(I->operands(), [=](const Use &Op) {
8023 return propagatesPoison(Op) &&
8024 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8025 }))
8026 return true;
8027
8028 // V = extractvalue V0, idx
8029 // V2 = extractvalue V0, idx2
8030 // V0's elements are all poison or not. (e.g., add_with_overflow)
8031 const WithOverflowInst *II;
8033 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8034 llvm::is_contained(II->args(), ValAssumedPoison)))
8035 return true;
8036 }
8037 return false;
8038}
8039
8040static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8041 unsigned Depth) {
8042 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8043 return true;
8044
8045 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8046 return true;
8047
8048 const unsigned MaxDepth = 2;
8049 if (Depth >= MaxDepth)
8050 return false;
8051
8052 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8053 if (I && !canCreatePoison(cast<Operator>(I))) {
8054 return all_of(I->operands(), [=](const Value *Op) {
8055 return impliesPoison(Op, V, Depth + 1);
8056 });
8057 }
8058 return false;
8059}
8060
8061bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8062 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8063}
8064
8065static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8066
8068 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8069 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8071 return false;
8072
8073 if (isa<MetadataAsValue>(V))
8074 return false;
8075
8076 if (const auto *A = dyn_cast<Argument>(V)) {
8077 if (A->hasAttribute(Attribute::NoUndef) ||
8078 A->hasAttribute(Attribute::Dereferenceable) ||
8079 A->hasAttribute(Attribute::DereferenceableOrNull))
8080 return true;
8081 }
8082
8083 if (auto *C = dyn_cast<Constant>(V)) {
8084 if (isa<PoisonValue>(C))
8085 return !includesPoison(Kind);
8086
8087 if (isa<UndefValue>(C))
8088 return !includesUndef(Kind);
8089
8092 return true;
8093
8094 if (C->getType()->isVectorTy()) {
8095 if (isa<ConstantExpr>(C)) {
8096 // Scalable vectors can use a ConstantExpr to build a splat.
8097 if (Constant *SplatC = C->getSplatValue())
8098 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8099 return true;
8100 } else {
8101 if (includesUndef(Kind) && C->containsUndefElement())
8102 return false;
8103 if (includesPoison(Kind) && C->containsPoisonElement())
8104 return false;
8105 return !C->containsConstantExpression();
8106 }
8107 }
8108 }
8109
8110 // Strip cast operations from a pointer value.
8111 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8112 // inbounds with zero offset. To guarantee that the result isn't poison, the
8113 // stripped pointer is checked as it has to be pointing into an allocated
8114 // object or be null `null` to ensure `inbounds` getelement pointers with a
8115 // zero offset could not produce poison.
8116 // It can strip off addrspacecast that do not change bit representation as
8117 // well. We believe that such addrspacecast is equivalent to no-op.
8118 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8119 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8120 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8121 return true;
8122
8123 auto OpCheck = [&](const Value *V) {
8124 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8125 };
8126
8127 if (auto *Opr = dyn_cast<Operator>(V)) {
8128 // If the value is a freeze instruction, then it can never
8129 // be undef or poison.
8130 if (isa<FreezeInst>(V))
8131 return true;
8132
8133 if (const auto *CB = dyn_cast<CallBase>(V)) {
8134 if (CB->hasRetAttr(Attribute::NoUndef) ||
8135 CB->hasRetAttr(Attribute::Dereferenceable) ||
8136 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8137 return true;
8138 }
8139
8140 if (!::canCreateUndefOrPoison(Opr, Kind,
8141 /*ConsiderFlagsAndMetadata=*/true)) {
8142 if (const auto *PN = dyn_cast<PHINode>(V)) {
8143 unsigned Num = PN->getNumIncomingValues();
8144 bool IsWellDefined = true;
8145 for (unsigned i = 0; i < Num; ++i) {
8146 if (PN == PN->getIncomingValue(i))
8147 continue;
8148 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8149 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8150 DT, Depth + 1, Kind)) {
8151 IsWellDefined = false;
8152 break;
8153 }
8154 }
8155 if (IsWellDefined)
8156 return true;
8157 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8158 : nullptr) {
8159 // For splats we only need to check the value being splatted.
8160 if (OpCheck(Splat))
8161 return true;
8162 } else if (all_of(Opr->operands(), OpCheck))
8163 return true;
8164 }
8165 }
8166
8167 if (auto *I = dyn_cast<LoadInst>(V))
8168 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8169 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8170 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8171 return true;
8172
8174 return true;
8175
8176 // CxtI may be null or a cloned instruction.
8177 if (!CtxI || !CtxI->getParent() || !DT)
8178 return false;
8179
8180 auto *DNode = DT->getNode(CtxI->getParent());
8181 if (!DNode)
8182 // Unreachable block
8183 return false;
8184
8185 // If V is used as a branch condition before reaching CtxI, V cannot be
8186 // undef or poison.
8187 // br V, BB1, BB2
8188 // BB1:
8189 // CtxI ; V cannot be undef or poison here
8190 auto *Dominator = DNode->getIDom();
8191 // This check is purely for compile time reasons: we can skip the IDom walk
8192 // if what we are checking for includes undef and the value is not an integer.
8193 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8194 while (Dominator) {
8195 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8196
8197 Value *Cond = nullptr;
8198 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8199 Cond = BI->getCondition();
8200 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8201 Cond = SI->getCondition();
8202 }
8203
8204 if (Cond) {
8205 if (Cond == V)
8206 return true;
8207 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8208 // For poison, we can analyze further
8209 auto *Opr = cast<Operator>(Cond);
8210 if (any_of(Opr->operands(), [V](const Use &U) {
8211 return V == U && propagatesPoison(U);
8212 }))
8213 return true;
8214 }
8215 }
8216
8217 Dominator = Dominator->getIDom();
8218 }
8219
8220 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8221 return true;
8222
8223 return false;
8224}
8225
8227 const Instruction *CtxI,
8228 const DominatorTree *DT,
8229 unsigned Depth) {
8230 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8232}
8233
8235 const Instruction *CtxI,
8236 const DominatorTree *DT, unsigned Depth) {
8237 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8239}
8240
8242 const Instruction *CtxI,
8243 const DominatorTree *DT, unsigned Depth) {
8244 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8246}
8247
8248/// Return true if undefined behavior would provably be executed on the path to
8249/// OnPathTo if Root produced a posion result. Note that this doesn't say
8250/// anything about whether OnPathTo is actually executed or whether Root is
8251/// actually poison. This can be used to assess whether a new use of Root can
8252/// be added at a location which is control equivalent with OnPathTo (such as
8253/// immediately before it) without introducing UB which didn't previously
8254/// exist. Note that a false result conveys no information.
8256 Instruction *OnPathTo,
8257 DominatorTree *DT) {
8258 // Basic approach is to assume Root is poison, propagate poison forward
8259 // through all users we can easily track, and then check whether any of those
8260 // users are provable UB and must execute before out exiting block might
8261 // exit.
8262
8263 // The set of all recursive users we've visited (which are assumed to all be
8264 // poison because of said visit)
8267 Worklist.push_back(Root);
8268 while (!Worklist.empty()) {
8269 const Instruction *I = Worklist.pop_back_val();
8270
8271 // If we know this must trigger UB on a path leading our target.
8272 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8273 return true;
8274
8275 // If we can't analyze propagation through this instruction, just skip it
8276 // and transitive users. Safe as false is a conservative result.
8277 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8278 return KnownPoison.contains(U) && propagatesPoison(U);
8279 }))
8280 continue;
8281
8282 if (KnownPoison.insert(I).second)
8283 for (const User *User : I->users())
8284 Worklist.push_back(cast<Instruction>(User));
8285 }
8286
8287 // Might be non-UB, or might have a path we couldn't prove must execute on
8288 // way to exiting bb.
8289 return false;
8290}
8291
8293 const SimplifyQuery &SQ) {
8294 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8295 Add, SQ);
8296}
8297
8300 const WithCache<const Value *> &RHS,
8301 const SimplifyQuery &SQ) {
8302 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8303}
8304
8306 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8307 // of time because it's possible for another thread to interfere with it for an
8308 // arbitrary length of time, but programs aren't allowed to rely on that.
8309
8310 // If there is no successor, then execution can't transfer to it.
8311 if (isa<ReturnInst>(I))
8312 return false;
8314 return false;
8315
8316 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8317 // Instruction::willReturn.
8318 //
8319 // FIXME: Move this check into Instruction::willReturn.
8320 if (isa<CatchPadInst>(I)) {
8321 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8322 default:
8323 // A catchpad may invoke exception object constructors and such, which
8324 // in some languages can be arbitrary code, so be conservative by default.
8325 return false;
8327 // For CoreCLR, it just involves a type test.
8328 return true;
8329 }
8330 }
8331
8332 // An instruction that returns without throwing must transfer control flow
8333 // to a successor.
8334 return !I->mayThrow() && I->willReturn();
8335}
8336
8338 // TODO: This is slightly conservative for invoke instruction since exiting
8339 // via an exception *is* normal control for them.
8340 for (const Instruction &I : *BB)
8342 return false;
8343 return true;
8344}
8345
8352
8355 assert(ScanLimit && "scan limit must be non-zero");
8356 for (const Instruction &I : Range) {
8357 if (--ScanLimit == 0)
8358 return false;
8360 return false;
8361 }
8362 return true;
8363}
8364
8366 const Loop *L) {
8367 // The loop header is guaranteed to be executed for every iteration.
8368 //
8369 // FIXME: Relax this constraint to cover all basic blocks that are
8370 // guaranteed to be executed at every iteration.
8371 if (I->getParent() != L->getHeader()) return false;
8372
8373 for (const Instruction &LI : *L->getHeader()) {
8374 if (&LI == I) return true;
8375 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8376 }
8377 llvm_unreachable("Instruction not contained in its own parent basic block.");
8378}
8379
8381 switch (IID) {
8382 // TODO: Add more intrinsics.
8383 case Intrinsic::sadd_with_overflow:
8384 case Intrinsic::ssub_with_overflow:
8385 case Intrinsic::smul_with_overflow:
8386 case Intrinsic::uadd_with_overflow:
8387 case Intrinsic::usub_with_overflow:
8388 case Intrinsic::umul_with_overflow:
8389 // If an input is a vector containing a poison element, the
8390 // two output vectors (calculated results, overflow bits)'
8391 // corresponding lanes are poison.
8392 return true;
8393 case Intrinsic::ctpop:
8394 case Intrinsic::ctlz:
8395 case Intrinsic::cttz:
8396 case Intrinsic::abs:
8397 case Intrinsic::smax:
8398 case Intrinsic::smin:
8399 case Intrinsic::umax:
8400 case Intrinsic::umin:
8401 case Intrinsic::scmp:
8402 case Intrinsic::is_fpclass:
8403 case Intrinsic::ptrmask:
8404 case Intrinsic::ucmp:
8405 case Intrinsic::bitreverse:
8406 case Intrinsic::bswap:
8407 case Intrinsic::sadd_sat:
8408 case Intrinsic::ssub_sat:
8409 case Intrinsic::sshl_sat:
8410 case Intrinsic::uadd_sat:
8411 case Intrinsic::usub_sat:
8412 case Intrinsic::ushl_sat:
8413 case Intrinsic::smul_fix:
8414 case Intrinsic::smul_fix_sat:
8415 case Intrinsic::umul_fix:
8416 case Intrinsic::umul_fix_sat:
8417 case Intrinsic::pow:
8418 case Intrinsic::powi:
8419 case Intrinsic::sin:
8420 case Intrinsic::sinh:
8421 case Intrinsic::cos:
8422 case Intrinsic::cosh:
8423 case Intrinsic::sincos:
8424 case Intrinsic::sincospi:
8425 case Intrinsic::tan:
8426 case Intrinsic::tanh:
8427 case Intrinsic::asin:
8428 case Intrinsic::acos:
8429 case Intrinsic::atan:
8430 case Intrinsic::atan2:
8431 case Intrinsic::canonicalize:
8432 case Intrinsic::sqrt:
8433 case Intrinsic::exp:
8434 case Intrinsic::exp2:
8435 case Intrinsic::exp10:
8436 case Intrinsic::log:
8437 case Intrinsic::log2:
8438 case Intrinsic::log10:
8439 case Intrinsic::modf:
8440 case Intrinsic::floor:
8441 case Intrinsic::ceil:
8442 case Intrinsic::trunc:
8443 case Intrinsic::rint:
8444 case Intrinsic::nearbyint:
8445 case Intrinsic::round:
8446 case Intrinsic::roundeven:
8447 case Intrinsic::lrint:
8448 case Intrinsic::llrint:
8449 case Intrinsic::fshl:
8450 case Intrinsic::fshr:
8451 case Intrinsic::frexp:
8452 case Intrinsic::get_active_lane_mask:
8453 return true;
8454 default:
8455 return false;
8456 }
8457}
8458
8459bool llvm::propagatesPoison(const Use &PoisonOp) {
8460 const Operator *I = cast<Operator>(PoisonOp.getUser());
8461 switch (I->getOpcode()) {
8462 case Instruction::Freeze:
8463 case Instruction::PHI:
8464 case Instruction::Invoke:
8465 return false;
8466 case Instruction::Select:
8467 return PoisonOp.getOperandNo() == 0;
8468 case Instruction::Call:
8469 if (auto *II = dyn_cast<IntrinsicInst>(I))
8470 return intrinsicPropagatesPoison(II->getIntrinsicID());
8471 return false;
8472 case Instruction::ICmp:
8473 case Instruction::FCmp:
8474 case Instruction::GetElementPtr:
8475 return true;
8476 default:
8478 return true;
8479
8480 // Be conservative and return false.
8481 return false;
8482 }
8483}
8484
8485/// Enumerates all operands of \p I that are guaranteed to not be undef or
8486/// poison. If the callback \p Handle returns true, stop processing and return
8487/// true. Otherwise, return false.
8488template <typename CallableT>
8490 const CallableT &Handle) {
8491 switch (I->getOpcode()) {
8492 case Instruction::Store:
8493 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8494 return true;
8495 break;
8496
8497 case Instruction::Load:
8498 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8499 return true;
8500 break;
8501
8502 // Since dereferenceable attribute imply noundef, atomic operations
8503 // also implicitly have noundef pointers too
8504 case Instruction::AtomicCmpXchg:
8506 return true;
8507 break;
8508
8509 case Instruction::AtomicRMW:
8510 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8511 return true;
8512 break;
8513
8514 case Instruction::Call:
8515 case Instruction::Invoke: {
8516 const CallBase *CB = cast<CallBase>(I);
8517 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8518 return true;
8519 for (unsigned i = 0; i < CB->arg_size(); ++i)
8520 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8521 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8522 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8523 Handle(CB->getArgOperand(i)))
8524 return true;
8525 break;
8526 }
8527 case Instruction::Ret:
8528 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8529 Handle(I->getOperand(0)))
8530 return true;
8531 break;
8532 case Instruction::Switch:
8533 if (Handle(cast<SwitchInst>(I)->getCondition()))
8534 return true;
8535 break;
8536 case Instruction::CondBr:
8537 if (Handle(cast<CondBrInst>(I)->getCondition()))
8538 return true;
8539 break;
8540 default:
8541 break;
8542 }
8543
8544 return false;
8545}
8546
8547/// Enumerates all operands of \p I that are guaranteed to not be poison.
8548template <typename CallableT>
8550 const CallableT &Handle) {
8551 if (handleGuaranteedWellDefinedOps(I, Handle))
8552 return true;
8553 switch (I->getOpcode()) {
8554 // Divisors of these operations are allowed to be partially undef.
8555 case Instruction::UDiv:
8556 case Instruction::SDiv:
8557 case Instruction::URem:
8558 case Instruction::SRem:
8559 return Handle(I->getOperand(1));
8560 default:
8561 return false;
8562 }
8563}
8564
8566 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8568 I, [&](const Value *V) { return KnownPoison.count(V); });
8569}
8570
8572 bool PoisonOnly) {
8573 // We currently only look for uses of values within the same basic
8574 // block, as that makes it easier to guarantee that the uses will be
8575 // executed given that Inst is executed.
8576 //
8577 // FIXME: Expand this to consider uses beyond the same basic block. To do
8578 // this, look out for the distinction between post-dominance and strong
8579 // post-dominance.
8580 const BasicBlock *BB = nullptr;
8582 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8583 BB = Inst->getParent();
8584 Begin = Inst->getIterator();
8585 Begin++;
8586 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8587 if (Arg->getParent()->isDeclaration())
8588 return false;
8589 BB = &Arg->getParent()->getEntryBlock();
8590 Begin = BB->begin();
8591 } else {
8592 return false;
8593 }
8594
8595 // Limit number of instructions we look at, to avoid scanning through large
8596 // blocks. The current limit is chosen arbitrarily.
8597 unsigned ScanLimit = 32;
8598 BasicBlock::const_iterator End = BB->end();
8599
8600 if (!PoisonOnly) {
8601 // Since undef does not propagate eagerly, be conservative & just check
8602 // whether a value is directly passed to an instruction that must take
8603 // well-defined operands.
8604
8605 for (const auto &I : make_range(Begin, End)) {
8606 if (--ScanLimit == 0)
8607 break;
8608
8609 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8610 return WellDefinedOp == V;
8611 }))
8612 return true;
8613
8615 break;
8616 }
8617 return false;
8618 }
8619
8620 // Set of instructions that we have proved will yield poison if Inst
8621 // does.
8622 SmallPtrSet<const Value *, 16> YieldsPoison;
8624
8625 YieldsPoison.insert(V);
8626 Visited.insert(BB);
8627
8628 while (true) {
8629 for (const auto &I : make_range(Begin, End)) {
8630 if (--ScanLimit == 0)
8631 return false;
8632 if (mustTriggerUB(&I, YieldsPoison))
8633 return true;
8635 return false;
8636
8637 // If an operand is poison and propagates it, mark I as yielding poison.
8638 for (const Use &Op : I.operands()) {
8639 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8640 YieldsPoison.insert(&I);
8641 break;
8642 }
8643 }
8644
8645 // Special handling for select, which returns poison if its operand 0 is
8646 // poison (handled in the loop above) *or* if both its true/false operands
8647 // are poison (handled here).
8648 if (I.getOpcode() == Instruction::Select &&
8649 YieldsPoison.count(I.getOperand(1)) &&
8650 YieldsPoison.count(I.getOperand(2))) {
8651 YieldsPoison.insert(&I);
8652 }
8653 }
8654
8655 BB = BB->getSingleSuccessor();
8656 if (!BB || !Visited.insert(BB).second)
8657 break;
8658
8659 Begin = BB->getFirstNonPHIIt();
8660 End = BB->end();
8661 }
8662 return false;
8663}
8664
8666 return ::programUndefinedIfUndefOrPoison(Inst, false);
8667}
8668
8670 return ::programUndefinedIfUndefOrPoison(Inst, true);
8671}
8672
8673static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8674 if (FMF.noNaNs())
8675 return true;
8676
8677 if (auto *C = dyn_cast<ConstantFP>(V))
8678 return !C->isNaN();
8679
8680 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8681 if (!C->getElementType()->isFloatingPointTy())
8682 return false;
8683 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8684 if (C->getElementAsAPFloat(I).isNaN())
8685 return false;
8686 }
8687 return true;
8688 }
8689
8691 return true;
8692
8693 return false;
8694}
8695
8696static bool isKnownNonZero(const Value *V) {
8697 if (auto *C = dyn_cast<ConstantFP>(V))
8698 return !C->isZero();
8699
8700 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8701 if (!C->getElementType()->isFloatingPointTy())
8702 return false;
8703 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8704 if (C->getElementAsAPFloat(I).isZero())
8705 return false;
8706 }
8707 return true;
8708 }
8709
8710 return false;
8711}
8712
8713/// Match clamp pattern for float types without care about NaNs or signed zeros.
8714/// Given non-min/max outer cmp/select from the clamp pattern this
8715/// function recognizes if it can be substitued by a "canonical" min/max
8716/// pattern.
8718 Value *CmpLHS, Value *CmpRHS,
8719 Value *TrueVal, Value *FalseVal,
8720 Value *&LHS, Value *&RHS) {
8721 // Try to match
8722 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8723 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8724 // and return description of the outer Max/Min.
8725
8726 // First, check if select has inverse order:
8727 if (CmpRHS == FalseVal) {
8728 std::swap(TrueVal, FalseVal);
8729 Pred = CmpInst::getInversePredicate(Pred);
8730 }
8731
8732 // Assume success now. If there's no match, callers should not use these anyway.
8733 LHS = TrueVal;
8734 RHS = FalseVal;
8735
8736 const APFloat *FC1;
8737 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8738 return {SPF_UNKNOWN, SPNB_NA, false};
8739
8740 const APFloat *FC2;
8741 switch (Pred) {
8742 case CmpInst::FCMP_OLT:
8743 case CmpInst::FCMP_OLE:
8744 case CmpInst::FCMP_ULT:
8745 case CmpInst::FCMP_ULE:
8746 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8747 *FC1 < *FC2)
8748 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8749 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8750 *FC1 < *FC2)
8751 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8752 break;
8753 case CmpInst::FCMP_OGT:
8754 case CmpInst::FCMP_OGE:
8755 case CmpInst::FCMP_UGT:
8756 case CmpInst::FCMP_UGE:
8757 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8758 *FC1 > *FC2)
8759 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8760 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8761 *FC1 > *FC2)
8762 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8763 break;
8764 default:
8765 break;
8766 }
8767
8768 return {SPF_UNKNOWN, SPNB_NA, false};
8769}
8770
8771/// Recognize variations of:
8772/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8774 Value *CmpLHS, Value *CmpRHS,
8775 Value *TrueVal, Value *FalseVal) {
8776 // Swap the select operands and predicate to match the patterns below.
8777 if (CmpRHS != TrueVal) {
8778 Pred = ICmpInst::getSwappedPredicate(Pred);
8779 std::swap(TrueVal, FalseVal);
8780 }
8781 const APInt *C1;
8782 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8783 const APInt *C2;
8784 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8785 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8786 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8787 return {SPF_SMAX, SPNB_NA, false};
8788
8789 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8790 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8791 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8792 return {SPF_SMIN, SPNB_NA, false};
8793
8794 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8795 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8796 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8797 return {SPF_UMAX, SPNB_NA, false};
8798
8799 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8800 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8801 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8802 return {SPF_UMIN, SPNB_NA, false};
8803 }
8804 return {SPF_UNKNOWN, SPNB_NA, false};
8805}
8806
8807/// Recognize variations of:
8808/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8810 Value *CmpLHS, Value *CmpRHS,
8811 Value *TVal, Value *FVal,
8812 unsigned Depth) {
8813 // TODO: Allow FP min/max with nnan/nsz.
8814 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8815
8816 Value *A = nullptr, *B = nullptr;
8817 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8818 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8819 return {SPF_UNKNOWN, SPNB_NA, false};
8820
8821 Value *C = nullptr, *D = nullptr;
8822 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8823 if (L.Flavor != R.Flavor)
8824 return {SPF_UNKNOWN, SPNB_NA, false};
8825
8826 // We have something like: x Pred y ? min(a, b) : min(c, d).
8827 // Try to match the compare to the min/max operations of the select operands.
8828 // First, make sure we have the right compare predicate.
8829 switch (L.Flavor) {
8830 case SPF_SMIN:
8831 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8832 Pred = ICmpInst::getSwappedPredicate(Pred);
8833 std::swap(CmpLHS, CmpRHS);
8834 }
8835 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8836 break;
8837 return {SPF_UNKNOWN, SPNB_NA, false};
8838 case SPF_SMAX:
8839 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8840 Pred = ICmpInst::getSwappedPredicate(Pred);
8841 std::swap(CmpLHS, CmpRHS);
8842 }
8843 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8844 break;
8845 return {SPF_UNKNOWN, SPNB_NA, false};
8846 case SPF_UMIN:
8847 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8848 Pred = ICmpInst::getSwappedPredicate(Pred);
8849 std::swap(CmpLHS, CmpRHS);
8850 }
8851 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8852 break;
8853 return {SPF_UNKNOWN, SPNB_NA, false};
8854 case SPF_UMAX:
8855 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8856 Pred = ICmpInst::getSwappedPredicate(Pred);
8857 std::swap(CmpLHS, CmpRHS);
8858 }
8859 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8860 break;
8861 return {SPF_UNKNOWN, SPNB_NA, false};
8862 default:
8863 return {SPF_UNKNOWN, SPNB_NA, false};
8864 }
8865
8866 // If there is a common operand in the already matched min/max and the other
8867 // min/max operands match the compare operands (either directly or inverted),
8868 // then this is min/max of the same flavor.
8869
8870 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8871 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8872 if (D == B) {
8873 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8874 match(A, m_Not(m_Specific(CmpRHS)))))
8875 return {L.Flavor, SPNB_NA, false};
8876 }
8877 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8878 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8879 if (C == B) {
8880 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8881 match(A, m_Not(m_Specific(CmpRHS)))))
8882 return {L.Flavor, SPNB_NA, false};
8883 }
8884 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8885 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8886 if (D == A) {
8887 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8888 match(B, m_Not(m_Specific(CmpRHS)))))
8889 return {L.Flavor, SPNB_NA, false};
8890 }
8891 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8892 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8893 if (C == A) {
8894 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8895 match(B, m_Not(m_Specific(CmpRHS)))))
8896 return {L.Flavor, SPNB_NA, false};
8897 }
8898
8899 return {SPF_UNKNOWN, SPNB_NA, false};
8900}
8901
8902/// If the input value is the result of a 'not' op, constant integer, or vector
8903/// splat of a constant integer, return the bitwise-not source value.
8904/// TODO: This could be extended to handle non-splat vector integer constants.
8905static