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/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/ScopeExit.h"
23#include "llvm/ADT/StringRef.h"
33#include "llvm/Analysis/Loads.h"
38#include "llvm/IR/Argument.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/Constant.h"
45#include "llvm/IR/Constants.h"
48#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
52#include "llvm/IR/GlobalAlias.h"
53#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/InstrTypes.h"
56#include "llvm/IR/Instruction.h"
59#include "llvm/IR/Intrinsics.h"
60#include "llvm/IR/IntrinsicsAArch64.h"
61#include "llvm/IR/IntrinsicsAMDGPU.h"
62#include "llvm/IR/IntrinsicsRISCV.h"
63#include "llvm/IR/IntrinsicsX86.h"
64#include "llvm/IR/LLVMContext.h"
65#include "llvm/IR/Metadata.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/Operator.h"
69#include "llvm/IR/Type.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
81#include <algorithm>
82#include <cassert>
83#include <cstdint>
84#include <optional>
85#include <utility>
86
87using namespace llvm;
88using namespace llvm::PatternMatch;
89
90// Controls the number of uses of the value searched for possible
91// dominating comparisons.
92static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
93 cl::Hidden, cl::init(20));
94
95/// Maximum number of instructions to check between assume and context
96/// instruction.
97static constexpr unsigned MaxInstrsToCheckForFree = 32;
98
99/// Returns the bitwidth of the given scalar or pointer type. For vector types,
100/// returns the element type's bitwidth.
101static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
102 if (unsigned BitWidth = Ty->getScalarSizeInBits())
103 return BitWidth;
104
105 return DL.getPointerTypeSizeInBits(Ty);
106}
107
108// Given the provided Value and, potentially, a context instruction, return
109// the preferred context instruction (if any).
110static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
111 // If we've been provided with a context instruction, then use that (provided
112 // it has been inserted).
113 if (CxtI && CxtI->getParent())
114 return CxtI;
115
116 // If the value is really an already-inserted instruction, then use that.
117 CxtI = dyn_cast<Instruction>(V);
118 if (CxtI && CxtI->getParent())
119 return CxtI;
120
121 return nullptr;
122}
123
125 const APInt &DemandedElts,
126 APInt &DemandedLHS, APInt &DemandedRHS) {
127 if (isa<ScalableVectorType>(Shuf->getType())) {
128 assert(DemandedElts == APInt(1,1));
129 DemandedLHS = DemandedRHS = DemandedElts;
130 return true;
131 }
132
133 int NumElts =
134 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
135 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
136 DemandedElts, DemandedLHS, DemandedRHS);
137}
138
139static void computeKnownBits(const Value *V, const APInt &DemandedElts,
140 KnownBits &Known, const SimplifyQuery &Q,
141 unsigned Depth);
142
144 const SimplifyQuery &Q, unsigned Depth) {
145 // Since the number of lanes in a scalable vector is unknown at compile time,
146 // we track one bit which is implicitly broadcast to all lanes. This means
147 // that all lanes in a scalable vector are considered demanded.
148 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
149 APInt DemandedElts =
150 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
151 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
152}
153
155 const DataLayout &DL, AssumptionCache *AC,
156 const Instruction *CxtI, const DominatorTree *DT,
157 bool UseInstrInfo, unsigned Depth) {
159 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
160 Depth);
161}
162
164 AssumptionCache *AC, const Instruction *CxtI,
165 const DominatorTree *DT, bool UseInstrInfo,
166 unsigned Depth) {
167 return computeKnownBits(
168 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
169}
170
171KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
172 const DataLayout &DL, AssumptionCache *AC,
173 const Instruction *CxtI,
174 const DominatorTree *DT, bool UseInstrInfo,
175 unsigned Depth) {
176 return computeKnownBits(
177 V, DemandedElts,
178 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
179}
180
183 const SimplifyQuery &SQ) {
184 // Look for an inverted mask: (X & ~M) op (Y & M).
185 {
186 Value *M;
187 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
189 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
192 }
193
194 // X op (Y & ~X)
196 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
199
200 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
201 // for constant Y.
202 Value *Y;
203 if (match(RHS,
205 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
206 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
207 return IsNoUndef ? NoCommonBitsSetResult::Known
209 }
210
211 // Peek through extends to find a 'not' of the other side:
212 // (ext Y) op ext(~Y)
213 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
215 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
218
219 // Look for: (A & B) op ~(A | B)
220 {
221 Value *A, *B;
222 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
224 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
225 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
226 return IsNoUndef ? NoCommonBitsSetResult::Known
228 }
229 }
230
231 // Look for: (X << V) op (Y >> (BitWidth - V))
232 // or (X >> V) op (Y << (BitWidth - V))
233 {
234 const Value *V;
235 const APInt *R;
236 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
237 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
238 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
239 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
240 R->uge(LHS->getType()->getScalarSizeInBits()))
242 }
243
245}
246
249 const WithCache<const Value *> &RHSCache,
250 const SimplifyQuery &SQ) {
251 const Value *LHS = LHSCache.getValue();
252 const Value *RHS = RHSCache.getValue();
253
254 assert(LHS->getType() == RHS->getType() &&
255 "LHS and RHS should have the same type");
256 assert(LHS->getType()->isIntOrIntVectorTy() &&
257 "LHS and RHS should be integers");
258
260 if (Result == NoCommonBitsSetResult::Known)
262
263 NoCommonBitsSetResult CommuteResult =
265 if (CommuteResult == NoCommonBitsSetResult::Known)
267
269 RHSCache.getKnownBits(SQ)))
271
275
277}
278
280 const WithCache<const Value *> &RHSCache,
281 const SimplifyQuery &SQ) {
282 NoCommonBitsSetResult Result =
283 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
284 return Result == NoCommonBitsSetResult::Known;
285}
286
288 return !I->user_empty() &&
289 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
290}
291
293 return !I->user_empty() && all_of(I->users(), [](const User *U) {
294 CmpPredicate P;
295 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
296 });
297}
298
300 bool OrZero, AssumptionCache *AC,
301 const Instruction *CxtI,
302 const DominatorTree *DT, bool UseInstrInfo,
303 unsigned Depth) {
304 return ::isKnownToBeAPowerOfTwo(
305 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
306 Depth);
307}
308
309static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
310 const SimplifyQuery &Q, unsigned Depth);
311
313 unsigned Depth) {
314 return computeKnownBits(V, SQ, Depth).isNonNegative();
315}
316
318 unsigned Depth) {
319 if (auto *CI = dyn_cast<ConstantInt>(V))
320 return CI->getValue().isStrictlyPositive();
321
322 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
323 // this updated.
325 return Known.isNonNegative() &&
326 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
327}
328
330 unsigned Depth) {
331 return computeKnownBits(V, SQ, Depth).isNegative();
332}
333
334static bool isKnownNonEqual(const Value *V1, const Value *V2,
335 const APInt &DemandedElts, const SimplifyQuery &Q,
336 unsigned Depth);
337
338bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
339 const SimplifyQuery &Q, unsigned Depth) {
340 // We don't support looking through casts.
341 if (V1 == V2 || V1->getType() != V2->getType())
342 return false;
343 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
344 APInt DemandedElts =
345 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
346 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
347}
348
349bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
350 const SimplifyQuery &SQ, unsigned Depth) {
351 KnownBits Known(Mask.getBitWidth());
353 return Mask.isSubsetOf(Known.Zero);
354}
355
356static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
357 const SimplifyQuery &Q, unsigned Depth);
358
359static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
360 unsigned Depth = 0) {
361 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
362 APInt DemandedElts =
363 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
364 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
365}
366
367unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
368 AssumptionCache *AC, const Instruction *CxtI,
369 const DominatorTree *DT, bool UseInstrInfo,
370 unsigned Depth) {
371 return ::ComputeNumSignBits(
372 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
373}
374
376 AssumptionCache *AC,
377 const Instruction *CxtI,
378 const DominatorTree *DT,
379 unsigned Depth) {
380 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
381 return V->getType()->getScalarSizeInBits() - SignBits + 1;
382}
383
384/// Try to detect the lerp pattern: a * (b - c) + c * d
385/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
386///
387/// In that particular case, we can use the following chain of reasoning:
388///
389/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
390///
391/// Since that is true for arbitrary a, b, c and d within our constraints, we
392/// can conclude that:
393///
394/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
395///
396/// Considering that any result of the lerp would be less or equal to U, it
397/// would have at least the number of leading 0s as in U.
398///
399/// While being quite a specific situation, it is fairly common in computer
400/// graphics in the shape of alpha blending.
401///
402/// Modifies given KnownOut in-place with the inferred information.
403static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
404 const APInt &DemandedElts,
405 KnownBits &KnownOut,
406 const SimplifyQuery &Q,
407 unsigned Depth) {
408
409 Type *Ty = Op0->getType();
410 const unsigned BitWidth = Ty->getScalarSizeInBits();
411
412 // Only handle scalar types for now
413 if (Ty->isVectorTy())
414 return;
415
416 // Try to match: a * (b - c) + c * d.
417 // When a == 1 => A == nullptr, the same applies to d/D as well.
418 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
419 const Instruction *SubBC = nullptr;
420
421 const auto MatchSubBC = [&]() {
422 // (b - c) can have two forms that interest us:
423 //
424 // 1. sub nuw %b, %c
425 // 2. xor %c, %b
426 //
427 // For the first case, nuw flag guarantees our requirement b >= c.
428 //
429 // The second case might happen when the analysis can infer that b is a mask
430 // for c and we can transform sub operation into xor (that is usually true
431 // for constant b's). Even though xor is symmetrical, canonicalization
432 // ensures that the constant will be the RHS. We have additional checks
433 // later on to ensure that this xor operation is equivalent to subtraction.
435 m_Xor(m_Value(C), m_Value(B))));
436 };
437
438 const auto MatchASubBC = [&]() {
439 // Cases:
440 // - a * (b - c)
441 // - (b - c) * a
442 // - (b - c) <- a implicitly equals 1
443 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
444 };
445
446 const auto MatchCD = [&]() {
447 // Cases:
448 // - d * c
449 // - c * d
450 // - c <- d implicitly equals 1
452 };
453
454 const auto Match = [&](const Value *LHS, const Value *RHS) {
455 // We do use m_Specific(C) in MatchCD, so we have to make sure that
456 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
457 // has to evaluate first and return true.
458 //
459 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
460 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
461 };
462
463 if (!Match(Op0, Op1) && !Match(Op1, Op0))
464 return;
465
466 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
467 // For some of the values we use the convention of leaving
468 // it nullptr to signify an implicit constant 1.
469 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
471 };
472
473 // Check that all operands are non-negative
474 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
475 if (!KnownA.isNonNegative())
476 return;
477
478 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
479 if (!KnownD.isNonNegative())
480 return;
481
482 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
483 if (!KnownB.isNonNegative())
484 return;
485
486 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
487 if (!KnownC.isNonNegative())
488 return;
489
490 // If we matched subtraction as xor, we need to actually check that xor
491 // is semantically equivalent to subtraction.
492 //
493 // For that to be true, b has to be a mask for c or that b's known
494 // ones cover all known and possible ones of c.
495 if (SubBC->getOpcode() == Instruction::Xor &&
496 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
497 return;
498
499 const APInt MaxA = KnownA.getMaxValue();
500 const APInt MaxD = KnownD.getMaxValue();
501 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
502 const APInt MaxB = KnownB.getMaxValue();
503
504 // We can't infer leading zeros info if the upper-bound estimate wraps.
505 bool Overflow;
506 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
507
508 if (Overflow)
509 return;
510
511 // If we know that x <= y and both are positive than x has at least the same
512 // number of leading zeros as y.
513 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
514 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
515}
516
517static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
518 bool NSW, bool NUW,
519 const APInt &DemandedElts,
520 KnownBits &KnownOut, KnownBits &Known2,
521 const SimplifyQuery &Q, unsigned Depth) {
522 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
523
524 // If one operand is unknown and we have no nowrap information,
525 // the result will be unknown independently of the second operand.
526 if (KnownOut.isUnknown() && !NSW && !NUW)
527 return;
528
529 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
530 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
531
532 if (!Add && NSW && !KnownOut.isNonNegative() &&
534 .value_or(false) ||
535 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
536 KnownOut.makeNonNegative();
537
538 if (Add)
539 // Try to match lerp pattern and combine results
540 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
541}
542
543static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
544 bool NUW, const APInt &DemandedElts,
545 KnownBits &Known, KnownBits &Known2,
546 const SimplifyQuery &Q, unsigned Depth) {
547 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
548 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
549
550 bool isKnownNegative = false;
551 bool isKnownNonNegative = false;
552 // If the multiplication is known not to overflow, compute the sign bit.
553 if (NSW) {
554 if (Op0 == Op1) {
555 // The product of a number with itself is non-negative.
556 isKnownNonNegative = true;
557 } else {
558 bool isKnownNonNegativeOp1 = Known.isNonNegative();
559 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
560 bool isKnownNegativeOp1 = Known.isNegative();
561 bool isKnownNegativeOp0 = Known2.isNegative();
562 // The product of two numbers with the same sign is non-negative.
563 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
564 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
565 if (!isKnownNonNegative && NUW) {
566 // mul nuw nsw with a factor > 1 is non-negative.
567 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
568 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
569 KnownBits::sgt(Known2, One).value_or(false);
570 }
571
572 // The product of a negative number and a non-negative number is either
573 // negative or zero.
576 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
577 Known2.isNonZero()) ||
578 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
579 }
580 }
581
582 bool SelfMultiply = Op0 == Op1;
583 if (SelfMultiply)
584 SelfMultiply &=
585 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
586 Known = KnownBits::mul(Known, Known2, SelfMultiply);
587
588 if (SelfMultiply) {
589 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
590 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
591 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
592
593 if (OutValidBits < TyBits) {
594 APInt KnownZeroMask =
595 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
596 Known.Zero |= KnownZeroMask;
597 }
598 }
599
600 // Only make use of no-wrap flags if we failed to compute the sign bit
601 // directly. This matters if the multiplication always overflows, in
602 // which case we prefer to follow the result of the direct computation,
603 // though as the program is invoking undefined behaviour we can choose
604 // whatever we like here.
605 if (isKnownNonNegative && !Known.isNegative())
606 Known.makeNonNegative();
607 else if (isKnownNegative && !Known.isNonNegative())
608 Known.makeNegative();
609}
610
612 KnownBits &Known) {
613 unsigned BitWidth = Known.getBitWidth();
614 unsigned NumRanges = Ranges.getNumOperands() / 2;
615 assert(NumRanges >= 1);
616
617 Known.setAllConflict();
618
619 for (unsigned i = 0; i < NumRanges; ++i) {
621 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
624 ConstantRange Range(Lower->getValue(), Upper->getValue());
625 // BitWidth must equal the Ranges BitWidth for the correct number of high
626 // bits to be set.
627 assert(BitWidth == Range.getBitWidth() &&
628 "Known bit width must match range bit width!");
629
630 // The first CommonPrefixBits of all values in Range are equal.
631 unsigned CommonPrefixBits =
632 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
633 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
634 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
635 Known.One &= UnsignedMax & Mask;
636 Known.Zero &= ~UnsignedMax & Mask;
637 }
638}
639
640static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
641 // The instruction defining an assumption's condition itself is always
642 // considered ephemeral to that assumption (even if it has other
643 // non-ephemeral users). See r246696's test case for an example.
644 if (is_contained(I->operands(), E))
645 return true;
646
647 const auto *EI = dyn_cast<Instruction>(E);
648 if (!EI)
649 return false;
650
651 if (EI == I)
652 return true;
653
656 Visited.insert(EI);
657 WorkList.push_back(EI);
658 bool ReachesI = false;
659 while (!WorkList.empty()) {
660 const Instruction *V = WorkList.pop_back_val();
661 for (const User *U : V->users()) {
662 const auto *UI = cast<Instruction>(U);
663 if (UI == I) {
664 ReachesI = true;
665 continue;
666 }
667 if (UI->mayHaveSideEffects() || UI->isTerminator())
668 return false;
669 if (Visited.insert(UI).second)
670 WorkList.push_back(UI);
671 }
672 }
673 return ReachesI;
674}
675
676// Is this an intrinsic that cannot be speculated but also cannot trap?
678 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
679 return CI->isAssumeLikeIntrinsic();
680
681 return false;
682}
683
685 const Instruction *CxtI,
686 const DominatorTree *DT,
687 bool AllowEphemerals) {
688 // There are two restrictions on the use of an assume:
689 // 1. The assume must dominate the context (or the control flow must
690 // reach the assume whenever it reaches the context).
691 // 2. The context must not be in the assume's set of ephemeral values
692 // (otherwise we will use the assume to prove that the condition
693 // feeding the assume is trivially true, thus causing the removal of
694 // the assume).
695
696 if (Inv->getParent() == CxtI->getParent()) {
697 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
698 // in the BB.
699 if (Inv->comesBefore(CxtI))
700 return true;
701
702 // Don't let an assume affect itself - this would cause the problems
703 // `isEphemeralValueOf` is trying to prevent, and it would also make
704 // the loop below go out of bounds.
705 if (!AllowEphemerals && Inv == CxtI)
706 return false;
707
708 // The context comes first, but they're both in the same block.
709 // Make sure there is nothing in between that might interrupt
710 // the control flow, not even CxtI itself.
711 // We limit the scan distance between the assume and its context instruction
712 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
713 // it can be adjusted if needed (could be turned into a cl::opt).
714 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
716 return false;
717
718 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
719 }
720
721 // Inv and CxtI are in different blocks.
722 if (DT) {
723 if (DT->dominates(Inv, CxtI))
724 return true;
725 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
726 Inv->getParent()->isEntryBlock()) {
727 // We don't have a DT, but this trivially dominates.
728 return true;
729 }
730
731 return false;
732}
733
735 const Instruction *CtxI) {
736 // Helper to check if there are any calls in the range that may free memory.
737 unsigned NumChecked = 0;
738 auto hasNoFreeInRange = [&NumChecked](auto Range) {
739 for (const Instruction &I : Range) {
740 if (NumChecked++ > MaxInstrsToCheckForFree)
741 return false;
742
743 if (auto *CB = dyn_cast<CallBase>(&I)) {
744 if (!CB->hasFnAttr(Attribute::NoFree))
745 return false;
746 } else if (I.maySynchronize())
747 return false;
748 }
749 return true;
750 };
751
752 const BasicBlock *CtxBB = CtxI->getParent();
753 const BasicBlock *AssumeBB = Assume->getParent();
754 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
755 if (CtxBB == AssumeBB) {
756 // Same block case: check that Assume comes before CtxI.
757 if (Assume != CtxI && !Assume->comesBefore(CtxI))
758 return false;
759 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
760 }
761
762 // Handle chain of single-predecessor blocks.
763 const BasicBlock *CurBB = CtxBB;
764 while (true) {
765 if (CurBB == AssumeBB)
766 return hasNoFreeInRange(
767 make_range(Assume->getIterator(), AssumeBB->end()));
768
769 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
770 if (!PredBB)
771 return false;
772
773 if (!hasNoFreeInRange(make_range(CurBB->begin(),
774 CurBB == CtxBB ? CtxIter : CurBB->end())))
775 return false;
776 CurBB = PredBB;
777 }
778}
779
780// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
781// we still have enough information about `RHS` to conclude non-zero. For
782// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
783// so the extra compile time may not be worth it, but possibly a second API
784// should be created for use outside of loops.
785static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
786 // v u> y implies v != 0.
787 if (Pred == ICmpInst::ICMP_UGT)
788 return true;
789
790 // Special-case v != 0 to also handle v != null.
791 if (Pred == ICmpInst::ICMP_NE)
792 return match(RHS, m_Zero());
793
794 // All other predicates - rely on generic ConstantRange handling.
795 const APInt *C;
796 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
797 if (match(RHS, m_APInt(C))) {
799 return !TrueValues.contains(Zero);
800 }
801
803 if (VC == nullptr)
804 return false;
805
806 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
807 ++ElemIdx) {
809 Pred, VC->getElementAsAPInt(ElemIdx));
810 if (TrueValues.contains(Zero))
811 return false;
812 }
813 return true;
814}
815
816static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
817 Value *&ValOut, Instruction *&CtxIOut,
818 const PHINode **PhiOut = nullptr) {
819 ValOut = U->get();
820 if (ValOut == PHI)
821 return;
822 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
823 if (PhiOut)
824 *PhiOut = PHI;
825 Value *V;
826 // If the Use is a select of this phi, compute analysis on other arm to break
827 // recursion.
828 // TODO: Min/Max
829 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
830 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
831 ValOut = V;
832
833 // Same for select, if this phi is 2-operand phi, compute analysis on other
834 // incoming value to break recursion.
835 // TODO: We could handle any number of incoming edges as long as we only have
836 // two unique values.
837 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
838 IncPhi && IncPhi->getNumIncomingValues() == 2) {
839 for (int Idx = 0; Idx < 2; ++Idx) {
840 if (IncPhi->getIncomingValue(Idx) == PHI) {
841 ValOut = IncPhi->getIncomingValue(1 - Idx);
842 if (PhiOut)
843 *PhiOut = IncPhi;
844 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
845 break;
846 }
847 }
848 }
849}
850
851static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
852 // Use of assumptions is context-sensitive. If we don't have a context, we
853 // cannot use them!
854 if (!Q.AC || !Q.CxtI)
855 return false;
856
857 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
858 if (!Elem.Assume)
859 continue;
860
861 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
862 assert(I->getFunction() == Q.CxtI->getFunction() &&
863 "Got assumption for the wrong function!");
864
865 if (Elem.Index != AssumptionCache::ExprResultIdx) {
867 I->getOperandBundleAt(Elem.Index)) &&
869 return true;
870 continue;
871 }
872
873 // Warning: This loop can end up being somewhat performance sensitive.
874 // We're running this loop for once for each value queried resulting in a
875 // runtime of ~O(#assumes * #values).
876
877 Value *RHS;
878 CmpPredicate Pred;
879 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
880 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
881 continue;
882
884 return true;
885 }
886
887 return false;
888}
889
892 const SimplifyQuery &Q) {
893 if (RHS->getType()->isPointerTy()) {
894 // Handle comparison of pointer to null explicitly, as it will not be
895 // covered by the m_APInt() logic below.
896 if (LHS == V && match(RHS, m_Zero())) {
897 switch (Pred) {
899 Known.setAllZero();
900 break;
903 Known.makeNonNegative();
904 break;
906 Known.makeNegative();
907 break;
908 default:
909 break;
910 }
911 }
912 return;
913 }
914
915 unsigned BitWidth = Known.getBitWidth();
916 auto m_V =
918
919 Value *Y;
920 const APInt *Mask, *C;
921 if (!match(RHS, m_APInt(C)))
922 return;
923
924 uint64_t ShAmt;
925 switch (Pred) {
927 // assume(V = C)
928 if (match(LHS, m_V)) {
929 Known = Known.unionWith(KnownBits::makeConstant(*C));
930 // assume(V & Mask = C)
931 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
932 // For one bits in Mask, we can propagate bits from C to V.
933 Known.One |= *C;
934 if (match(Y, m_APInt(Mask)))
935 Known.Zero |= ~*C & *Mask;
936 // assume(V | Mask = C)
937 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
938 // For zero bits in Mask, we can propagate bits from C to V.
939 Known.Zero |= ~*C;
940 if (match(Y, m_APInt(Mask)))
941 Known.One |= *C & ~*Mask;
942 // assume(V << ShAmt = C)
943 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
944 ShAmt < BitWidth) {
945 // For those bits in C that are known, we can propagate them to known
946 // bits in V shifted to the right by ShAmt.
948 RHSKnown >>= ShAmt;
949 Known = Known.unionWith(RHSKnown);
950 // assume(V >> ShAmt = C)
951 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
952 ShAmt < BitWidth) {
953 // For those bits in RHS that are known, we can propagate them to known
954 // bits in V shifted to the right by C.
956 RHSKnown <<= ShAmt;
957 Known = Known.unionWith(RHSKnown);
958 }
959 break;
960 case ICmpInst::ICMP_NE: {
961 // assume (V & B != 0) where B is a power of 2
962 const APInt *BPow2;
963 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
964 Known.One |= *BPow2;
965 break;
966 }
967 default: {
968 const APInt *Offset = nullptr;
969 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
971 if (Offset)
972 LHSRange = LHSRange.sub(*Offset);
973 Known = Known.unionWith(LHSRange.toKnownBits());
974 }
975 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
976 // X & Y u> C -> X u> C && Y u> C
977 // X nuw- Y u> C -> X u> C
978 if (match(LHS, m_c_And(m_V, m_Value())) ||
979 match(LHS, m_NUWSub(m_V, m_Value())))
980 Known.One.setHighBits(
981 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
982 }
983 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
984 // X | Y u< C -> X u< C && Y u< C
985 // X nuw+ Y u< C -> X u< C && Y u< C
986 if (match(LHS, m_c_Or(m_V, m_Value())) ||
987 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
988 Known.Zero.setHighBits(
989 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
990 }
991 }
992 } break;
993 }
994}
995
996static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
998 const SimplifyQuery &SQ, bool Invert) {
1000 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1001 Value *LHS = Cmp->getOperand(0);
1002 Value *RHS = Cmp->getOperand(1);
1003
1004 // Handle icmp pred (trunc V), C
1005 if (match(LHS, m_Trunc(m_Specific(V)))) {
1006 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1007 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1009 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1010 else
1011 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1012 return;
1013 }
1014
1015 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1016}
1017
1019 KnownBits &Known, const SimplifyQuery &SQ,
1020 bool Invert, unsigned Depth) {
1021 Value *A, *B;
1024 KnownBits Known2(Known.getBitWidth());
1025 KnownBits Known3(Known.getBitWidth());
1026 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1027 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1028 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1030 Known2 = Known2.unionWith(Known3);
1031 else
1032 Known2 = Known2.intersectWith(Known3);
1033 Known = Known.unionWith(Known2);
1034 return;
1035 }
1036
1037 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1038 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1039 return;
1040 }
1041
1042 if (match(Cond, m_Trunc(m_Specific(V)))) {
1043 KnownBits DstKnown(1);
1044 if (Invert) {
1045 DstKnown.setAllZero();
1046 } else {
1047 DstKnown.setAllOnes();
1048 }
1050 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1051 return;
1052 }
1053 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1054 return;
1055 }
1056
1058 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1059}
1060
1062 const SimplifyQuery &Q, unsigned Depth) {
1063 // Handle injected condition.
1064 if (Q.CC && Q.CC->AffectedValues.contains(V))
1066
1067 if (!Q.CxtI)
1068 return;
1069
1070 if (Q.DC && Q.DT) {
1071 // Handle dominating conditions.
1072 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1073 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1074 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1075 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1076 /*Invert*/ false, Depth);
1077
1078 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1079 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1080 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1081 /*Invert*/ true, Depth);
1082 }
1083
1084 if (Known.hasConflict())
1085 Known.resetAll();
1086 }
1087
1088 if (!Q.AC)
1089 return;
1090
1091 unsigned BitWidth = Known.getBitWidth();
1092
1093 // Note that the patterns below need to be kept in sync with the code
1094 // in AssumptionCache::updateAffectedValues.
1095
1096 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1097 if (!Elem.Assume)
1098 continue;
1099
1100 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1101 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1102 "Got assumption for the wrong function!");
1103
1104 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1105 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1106 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1107 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1108 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1110 Known.Zero |= (*Alignment - 1) & ~*Offset;
1111 Known.One |= (*Alignment - 1) & *Offset;
1112 }
1113 }
1114 continue;
1115 }
1116
1117 // Warning: This loop can end up being somewhat performance sensitive.
1118 // We're running this loop for once for each value queried resulting in a
1119 // runtime of ~O(#assumes * #values).
1120
1121 Value *Arg = I->getArgOperand(0);
1122
1123 if (Arg == V && isValidAssumeForContext(I, Q)) {
1124 assert(BitWidth == 1 && "assume operand is not i1?");
1125 (void)BitWidth;
1126 Known.setAllOnes();
1127 return;
1128 }
1129 if (match(Arg, m_Not(m_Specific(V))) &&
1131 assert(BitWidth == 1 && "assume operand is not i1?");
1132 (void)BitWidth;
1133 Known.setAllZero();
1134 return;
1135 }
1136 auto *Trunc = dyn_cast<TruncInst>(Arg);
1137 if (Trunc && Trunc->getOperand(0) == V &&
1139 if (Trunc->hasNoUnsignedWrap()) {
1141 return;
1142 }
1143 Known.One.setBit(0);
1144 return;
1145 }
1146
1147 // The remaining tests are all recursive, so bail out if we hit the limit.
1149 continue;
1150
1151 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1152 if (!Cmp)
1153 continue;
1154
1155 if (!isValidAssumeForContext(I, Q))
1156 continue;
1157
1158 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1159 }
1160
1161 // Conflicting assumption: Undefined behavior will occur on this execution
1162 // path.
1163 if (Known.hasConflict())
1164 Known.resetAll();
1165}
1166
1167/// Compute known bits from a shift operator, including those with a
1168/// non-constant shift amount. Known is the output of this function. Known2 is a
1169/// pre-allocated temporary with the same bit width as Known and on return
1170/// contains the known bit of the shift value source. KF is an
1171/// operator-specific function that, given the known-bits and a shift amount,
1172/// compute the implied known-bits of the shift operator's result respectively
1173/// for that shift amount. The results from calling KF are conservatively
1174/// combined for all permitted shift amounts.
1176 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1177 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1178 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1179 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1180 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1181 // To limit compile-time impact, only query isKnownNonZero() if we know at
1182 // least something about the shift amount.
1183 bool ShAmtNonZero =
1184 Known.isNonZero() ||
1185 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1186 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1187 Known = KF(Known2, Known, ShAmtNonZero);
1188}
1189
1190static KnownBits
1191getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1192 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1193 const SimplifyQuery &Q, unsigned Depth) {
1194 unsigned BitWidth = KnownLHS.getBitWidth();
1195 KnownBits KnownOut(BitWidth);
1196 bool IsAnd = false;
1197 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1198 Value *X = nullptr, *Y = nullptr;
1199
1200 switch (I->getOpcode()) {
1201 case Instruction::And:
1202 KnownOut = KnownLHS & KnownRHS;
1203 IsAnd = true;
1204 // and(x, -x) is common idioms that will clear all but lowest set
1205 // bit. If we have a single known bit in x, we can clear all bits
1206 // above it.
1207 // TODO: instcombine often reassociates independent `and` which can hide
1208 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1209 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1210 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1211 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1212 KnownOut = KnownLHS.blsi();
1213 else
1214 KnownOut = KnownRHS.blsi();
1215 }
1216 break;
1217 case Instruction::Or:
1218 KnownOut = KnownLHS | KnownRHS;
1219 break;
1220 case Instruction::Xor:
1221 KnownOut = KnownLHS ^ KnownRHS;
1222 // xor(x, x-1) is common idioms that will clear all but lowest set
1223 // bit. If we have a single known bit in x, we can clear all bits
1224 // above it.
1225 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1226 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1227 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1228 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1229 if (HasKnownOne &&
1231 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1232 KnownOut = XBits.blsmsk();
1233 }
1234 break;
1235 default:
1236 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1237 }
1238
1239 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1240 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1241 // here we handle the more general case of adding any odd number by
1242 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1243 // TODO: This could be generalized to clearing any bit set in y where the
1244 // following bit is known to be unset in y.
1245 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1249 KnownBits KnownY(BitWidth);
1250 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1251 if (KnownY.countMinTrailingOnes() > 0) {
1252 if (IsAnd)
1253 KnownOut.Zero.setBit(0);
1254 else
1255 KnownOut.One.setBit(0);
1256 }
1257 }
1258 return KnownOut;
1259}
1260
1262 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1263 unsigned Depth,
1264 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1265 KnownBitsFunc) {
1266 APInt DemandedEltsLHS, DemandedEltsRHS;
1268 DemandedElts, DemandedEltsLHS,
1269 DemandedEltsRHS);
1270
1271 const auto ComputeForSingleOpFunc =
1272 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1273 return KnownBitsFunc(
1274 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1275 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1276 };
1277
1278 if (DemandedEltsRHS.isZero())
1279 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1280 if (DemandedEltsLHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1282
1283 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1284 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1285}
1286
1287// Public so this can be used in `SimplifyDemandedUseBits`.
1289 const KnownBits &KnownLHS,
1290 const KnownBits &KnownRHS,
1291 const SimplifyQuery &SQ,
1292 unsigned Depth) {
1293 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1294 APInt DemandedElts =
1295 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1296
1297 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1298 Depth);
1299}
1300
1302 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1303 // Without vscale_range, we only know that vscale is non-zero.
1304 if (!Attr.isValid())
1306
1307 unsigned AttrMin = Attr.getVScaleRangeMin();
1308 // Minimum is larger than vscale width, result is always poison.
1309 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1310 return ConstantRange::getEmpty(BitWidth);
1311
1312 APInt Min(BitWidth, AttrMin);
1313 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1314 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1316
1317 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1318}
1319
1321 Value *Arm, bool Invert,
1322 const SimplifyQuery &Q, unsigned Depth) {
1323 // If we have a constant arm, we are done.
1324 if (Known.isConstant())
1325 return;
1326
1327 // See what condition implies about the bits of the select arm.
1328 KnownBits CondRes(Known.getBitWidth());
1329 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1330 // If we don't get any information from the condition, no reason to
1331 // proceed.
1332 if (CondRes.isUnknown())
1333 return;
1334
1335 // We can have conflict if the condition is dead. I.e if we have
1336 // (x | 64) < 32 ? (x | 64) : y
1337 // we will have conflict at bit 6 from the condition/the `or`.
1338 // In that case just return. Its not particularly important
1339 // what we do, as this select is going to be simplified soon.
1340 CondRes = CondRes.unionWith(Known);
1341 if (CondRes.hasConflict())
1342 return;
1343
1344 // Finally make sure the information we found is valid. This is relatively
1345 // expensive so it's left for the very end.
1346 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1347 return;
1348
1349 // Finally, we know we get information from the condition and its valid,
1350 // so return it.
1351 Known = std::move(CondRes);
1352}
1353
1354// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1355// Returns the input and lower/upper bounds.
1356static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1357 const APInt *&CLow, const APInt *&CHigh) {
1359 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1360 "Input should be a Select!");
1361
1362 const Value *LHS = nullptr, *RHS = nullptr;
1364 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1365 return false;
1366
1367 if (!match(RHS, m_APInt(CLow)))
1368 return false;
1369
1370 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1372 if (getInverseMinMaxFlavor(SPF) != SPF2)
1373 return false;
1374
1375 if (!match(RHS2, m_APInt(CHigh)))
1376 return false;
1377
1378 if (SPF == SPF_SMIN)
1379 std::swap(CLow, CHigh);
1380
1381 In = LHS2;
1382 return CLow->sle(*CHigh);
1383}
1384
1386 const APInt *&CLow,
1387 const APInt *&CHigh) {
1388 assert((II->getIntrinsicID() == Intrinsic::smin ||
1389 II->getIntrinsicID() == Intrinsic::smax) &&
1390 "Must be smin/smax");
1391
1392 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1393 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1394 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1395 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1396 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1397 return false;
1398
1399 if (II->getIntrinsicID() == Intrinsic::smin)
1400 std::swap(CLow, CHigh);
1401 return CLow->sle(*CHigh);
1402}
1403
1405 KnownBits &Known) {
1406 const APInt *CLow, *CHigh;
1407 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1408 Known = Known.unionWith(
1409 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1410}
1411
1413 const APInt &DemandedElts,
1415 const SimplifyQuery &Q,
1416 unsigned Depth) {
1417 unsigned BitWidth = Known.getBitWidth();
1418
1419 KnownBits Known2(BitWidth);
1420 switch (I->getOpcode()) {
1421 default: break;
1422 case Instruction::Load:
1423 if (MDNode *MD =
1424 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1426 break;
1427 case Instruction::And:
1428 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1429 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1430
1431 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1432 break;
1433 case Instruction::Or:
1434 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1435 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1436
1437 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1438 break;
1439 case Instruction::Xor:
1440 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1441 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1442
1443 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1444 break;
1445 case Instruction::Mul: {
1448 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1449 DemandedElts, Known, Known2, Q, Depth);
1450 break;
1451 }
1452 case Instruction::UDiv: {
1453 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1454 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1455 Known =
1457 break;
1458 }
1459 case Instruction::SDiv: {
1460 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1461 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1462 Known =
1464 break;
1465 }
1466 case Instruction::Select: {
1467 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1468 KnownBits Res(Known.getBitWidth());
1469 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1470 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1471 return Res;
1472 };
1473 // Only known if known in both the LHS and RHS.
1474 Known =
1475 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1476 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1477 break;
1478 }
1479 case Instruction::FPTrunc:
1480 case Instruction::FPExt:
1481 case Instruction::FPToUI:
1482 case Instruction::FPToSI:
1483 case Instruction::SIToFP:
1484 case Instruction::UIToFP:
1485 break; // Can't work with floating point.
1486 case Instruction::PtrToInt:
1487 case Instruction::PtrToAddr:
1488 case Instruction::IntToPtr:
1489 // Fall through and handle them the same as zext/trunc.
1490 [[fallthrough]];
1491 case Instruction::ZExt:
1492 case Instruction::Trunc: {
1493 Type *SrcTy = I->getOperand(0)->getType();
1494
1495 unsigned SrcBitWidth;
1496 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1497 // which fall through here.
1498 Type *ScalarTy = SrcTy->getScalarType();
1499 SrcBitWidth = ScalarTy->isPointerTy() ?
1500 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1501 Q.DL.getTypeSizeInBits(ScalarTy);
1502
1503 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1504 Known = Known.anyextOrTrunc(SrcBitWidth);
1505 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1506 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1507 Inst && Inst->hasNonNeg() && !Known.isNegative())
1508 Known.makeNonNegative();
1509 Known = Known.zextOrTrunc(BitWidth);
1510 break;
1511 }
1512 case Instruction::BitCast: {
1513 Type *SrcTy = I->getOperand(0)->getType();
1514 if (SrcTy->isIntOrPtrTy() &&
1515 // TODO: For now, not handling conversions like:
1516 // (bitcast i64 %x to <2 x i32>)
1517 !I->getType()->isVectorTy()) {
1518 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1519 break;
1520 }
1521
1522 const Value *V;
1523 // Handle bitcast from floating point to integer.
1524 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1525 V->getType()->isFPOrFPVectorTy()) {
1526 Type *FPType = V->getType()->getScalarType();
1527 KnownFPClass Result =
1528 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1529 FPClassTest FPClasses = Result.KnownFPClasses;
1530
1531 // TODO: Treat it as zero/poison if the use of I is unreachable.
1532 if (FPClasses == fcNone)
1533 break;
1534
1535 if (Result.isKnownNever(fcNormal | fcSubnormal | fcNan)) {
1536 Known.setAllConflict();
1537
1538 if (FPClasses & fcInf)
1539 Known = Known.intersectWith(KnownBits::makeConstant(
1540 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt()));
1541
1542 if (FPClasses & fcZero)
1543 Known = Known.intersectWith(KnownBits::makeConstant(
1544 APInt::getZero(FPType->getScalarSizeInBits())));
1545
1546 Known.Zero.clearSignBit();
1547 Known.One.clearSignBit();
1548 }
1549
1550 if (Result.SignBit) {
1551 if (*Result.SignBit)
1552 Known.makeNegative();
1553 else
1554 Known.makeNonNegative();
1555 }
1556
1557 break;
1558 }
1559
1560 // Handle cast from vector integer type to scalar or vector integer.
1561 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1562 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1563 !I->getType()->isIntOrIntVectorTy() ||
1564 isa<ScalableVectorType>(I->getType()))
1565 break;
1566
1567 unsigned NumElts = DemandedElts.getBitWidth();
1568 bool IsLE = Q.DL.isLittleEndian();
1569 // Look through a cast from narrow vector elements to wider type.
1570 // Examples: v4i32 -> v2i64, v3i8 -> v24
1571 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1572 if (BitWidth % SubBitWidth == 0) {
1573 // Known bits are automatically intersected across demanded elements of a
1574 // vector. So for example, if a bit is computed as known zero, it must be
1575 // zero across all demanded elements of the vector.
1576 //
1577 // For this bitcast, each demanded element of the output is sub-divided
1578 // across a set of smaller vector elements in the source vector. To get
1579 // the known bits for an entire element of the output, compute the known
1580 // bits for each sub-element sequentially. This is done by shifting the
1581 // one-set-bit demanded elements parameter across the sub-elements for
1582 // consecutive calls to computeKnownBits. We are using the demanded
1583 // elements parameter as a mask operator.
1584 //
1585 // The known bits of each sub-element are then inserted into place
1586 // (dependent on endian) to form the full result of known bits.
1587 unsigned SubScale = BitWidth / SubBitWidth;
1588 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1589 for (unsigned i = 0; i != NumElts; ++i) {
1590 if (DemandedElts[i])
1591 SubDemandedElts.setBit(i * SubScale);
1592 }
1593
1594 KnownBits KnownSrc(SubBitWidth);
1595 for (unsigned i = 0; i != SubScale; ++i) {
1596 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1597 Depth + 1);
1598 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1599 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1600 }
1601 }
1602 // Look through a cast from wider vector elements to narrow type.
1603 // Examples: v2i64 -> v4i32
1604 if (SubBitWidth % BitWidth == 0) {
1605 unsigned SubScale = SubBitWidth / BitWidth;
1606 KnownBits KnownSrc(SubBitWidth);
1607 APInt SubDemandedElts =
1608 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1609 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1610 Depth + 1);
1611
1612 Known.setAllConflict();
1613 for (unsigned i = 0; i != NumElts; ++i) {
1614 if (DemandedElts[i]) {
1615 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1616 unsigned Offset = (Shifts % SubScale) * BitWidth;
1617 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1618 if (Known.isUnknown())
1619 break;
1620 }
1621 }
1622 }
1623 break;
1624 }
1625 case Instruction::SExt: {
1626 // Compute the bits in the result that are not present in the input.
1627 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1628
1629 Known = Known.trunc(SrcBitWidth);
1630 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1631 // If the sign bit of the input is known set or clear, then we know the
1632 // top bits of the result.
1633 Known = Known.sext(BitWidth);
1634 break;
1635 }
1636 case Instruction::Shl: {
1639 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1640 bool ShAmtNonZero) {
1641 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1642 };
1643 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1644 KF);
1645 // Trailing zeros of a right-shifted constant never decrease.
1646 const APInt *C;
1647 if (match(I->getOperand(0), m_APInt(C)))
1648 Known.Zero.setLowBits(C->countr_zero());
1649
1650 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1651 // lands at bit Y, when BitWidth is a power of 2.
1652 const APInt *YC;
1653 Value *X = I->getOperand(0);
1654 if (isPowerOf2_32(BitWidth) &&
1655 match(I->getOperand(1),
1657 m_SpecificInt(BitWidth - 1)))) &&
1658 YC->ult(BitWidth - 1)) {
1659 unsigned Y = YC->getZExtValue();
1660 Known.One.setBit(Y);
1661 Known.Zero.setBitsFrom(Y + 1);
1662 }
1663 break;
1664 }
1665 case Instruction::LShr: {
1666 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1667 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1668 bool ShAmtNonZero) {
1669 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1670 };
1671 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1672 KF);
1673 // Leading zeros of a left-shifted constant never decrease.
1674 const APInt *C;
1675 if (match(I->getOperand(0), m_APInt(C)))
1676 Known.Zero.setHighBits(C->countl_zero());
1677 break;
1678 }
1679 case Instruction::AShr: {
1680 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1681 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1682 bool ShAmtNonZero) {
1683 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1684 };
1685 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1686 KF);
1687 break;
1688 }
1689 case Instruction::Sub: {
1692 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1693 DemandedElts, Known, Known2, Q, Depth);
1694 break;
1695 }
1696 case Instruction::Add: {
1699 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1700 DemandedElts, Known, Known2, Q, Depth);
1701 break;
1702 }
1703 case Instruction::SRem:
1704 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1705 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1706 Known = KnownBits::srem(Known, Known2);
1707 break;
1708
1709 case Instruction::URem:
1710 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1711 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1712 Known = KnownBits::urem(Known, Known2);
1713 break;
1714 case Instruction::Alloca:
1715 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1716 break;
1717 case Instruction::GetElementPtr: {
1718 // Analyze all of the subscripts of this getelementptr instruction
1719 // to determine if we can prove known low zero bits.
1720 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1721 // Accumulate the constant indices in a separate variable
1722 // to minimize the number of calls to computeForAddSub.
1723 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1724 APInt AccConstIndices(IndexWidth, 0);
1725
1726 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1727 if (IndexWidth == BitWidth) {
1728 // Note that inbounds does *not* guarantee nsw for the addition, as only
1729 // the offset is signed, while the base address is unsigned.
1730 Known = KnownBits::add(Known, IndexBits);
1731 } else {
1732 // If the index width is smaller than the pointer width, only add the
1733 // value to the low bits.
1734 assert(IndexWidth < BitWidth &&
1735 "Index width can't be larger than pointer width");
1736 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1737 }
1738 };
1739
1741 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1742 // TrailZ can only become smaller, short-circuit if we hit zero.
1743 if (Known.isUnknown())
1744 break;
1745
1746 Value *Index = I->getOperand(i);
1747
1748 // Handle case when index is zero.
1749 Constant *CIndex = dyn_cast<Constant>(Index);
1750 if (CIndex && CIndex->isNullValue())
1751 continue;
1752
1753 if (StructType *STy = GTI.getStructTypeOrNull()) {
1754 // Handle struct member offset arithmetic.
1755
1756 assert(CIndex &&
1757 "Access to structure field must be known at compile time");
1758
1759 if (CIndex->getType()->isVectorTy())
1760 Index = CIndex->getSplatValue();
1761
1762 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1763 const StructLayout *SL = Q.DL.getStructLayout(STy);
1764 uint64_t Offset = SL->getElementOffset(Idx);
1765 AccConstIndices += Offset;
1766 continue;
1767 }
1768
1769 // Handle array index arithmetic.
1770 Type *IndexedTy = GTI.getIndexedType();
1771 if (!IndexedTy->isSized()) {
1772 Known.resetAll();
1773 break;
1774 }
1775
1776 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1777 uint64_t StrideInBytes = Stride.getKnownMinValue();
1778 if (!Stride.isScalable()) {
1779 // Fast path for constant offset.
1780 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1781 AccConstIndices +=
1782 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1783 continue;
1784 }
1785 }
1786
1787 KnownBits IndexBits =
1788 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1789 KnownBits ScalingFactor(IndexWidth);
1790 // Multiply by current sizeof type.
1791 // &A[i] == A + i * sizeof(*A[i]).
1792 if (Stride.isScalable()) {
1793 // For scalable types the only thing we know about sizeof is
1794 // that this is a multiple of the minimum size.
1795 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1796 } else {
1797 ScalingFactor =
1798 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1799 }
1800 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1801 }
1802 if (!Known.isUnknown() && !AccConstIndices.isZero())
1803 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1804 break;
1805 }
1806 case Instruction::PHI: {
1807 const PHINode *P = cast<PHINode>(I);
1808 BinaryOperator *BO = nullptr;
1809 Value *R = nullptr, *L = nullptr;
1810 if (matchSimpleRecurrence(P, BO, R, L)) {
1811 // Handle the case of a simple two-predecessor recurrence PHI.
1812 // There's a lot more that could theoretically be done here, but
1813 // this is sufficient to catch some interesting cases.
1814 unsigned Opcode = BO->getOpcode();
1815
1816 switch (Opcode) {
1817 // If this is a shift recurrence, we know the bits being shifted in. We
1818 // can combine that with information about the start value of the
1819 // recurrence to conclude facts about the result. If this is a udiv
1820 // recurrence, we know that the result can never exceed either the
1821 // numerator or the start value, whichever is greater.
1822 case Instruction::LShr:
1823 case Instruction::AShr:
1824 case Instruction::Shl:
1825 case Instruction::UDiv:
1826 if (BO->getOperand(0) != I)
1827 break;
1828 [[fallthrough]];
1829
1830 // For a urem recurrence, the result can never exceed the start value. The
1831 // phi could either be the numerator or the denominator.
1832 case Instruction::URem: {
1833 // We have matched a recurrence of the form:
1834 // %iv = [R, %entry], [%iv.next, %backedge]
1835 // %iv.next = shift_op %iv, L
1836
1837 // Recurse with the phi context to avoid concern about whether facts
1838 // inferred hold at original context instruction. TODO: It may be
1839 // correct to use the original context. IF warranted, explore and
1840 // add sufficient tests to cover.
1842 RecQ.CxtI = P;
1843 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1844 switch (Opcode) {
1845 case Instruction::Shl:
1846 // A shl recurrence will only increase the tailing zeros
1847 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1848 break;
1849 case Instruction::LShr:
1850 case Instruction::UDiv:
1851 case Instruction::URem:
1852 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1853 // the start value.
1854 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1855 break;
1856 case Instruction::AShr:
1857 // An ashr recurrence will extend the initial sign bit
1858 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1859 Known.One.setHighBits(Known2.countMinLeadingOnes());
1860 break;
1861 }
1862 break;
1863 }
1864
1865 // Check for operations that have the property that if
1866 // both their operands have low zero bits, the result
1867 // will have low zero bits.
1868 case Instruction::Add:
1869 case Instruction::Sub:
1870 case Instruction::And:
1871 case Instruction::Or:
1872 case Instruction::Mul: {
1873 // Change the context instruction to the "edge" that flows into the
1874 // phi. This is important because that is where the value is actually
1875 // "evaluated" even though it is used later somewhere else. (see also
1876 // D69571).
1878
1879 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1880 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1881 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1882
1883 // Ok, we have a PHI of the form L op= R. Check for low
1884 // zero bits.
1885 RecQ.CxtI = RInst;
1886 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1887
1888 // We need to take the minimum number of known bits
1889 KnownBits Known3(BitWidth);
1890 RecQ.CxtI = LInst;
1891 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1892
1893 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1894 Known3.countMinTrailingZeros()));
1895
1896 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1897 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1898 break;
1899
1900 switch (Opcode) {
1901 // If initial value of recurrence is nonnegative, and we are adding
1902 // a nonnegative number with nsw, the result can only be nonnegative
1903 // or poison value regardless of the number of times we execute the
1904 // add in phi recurrence. If initial value is negative and we are
1905 // adding a negative number with nsw, the result can only be
1906 // negative or poison value. Similar arguments apply to sub and mul.
1907 //
1908 // (add non-negative, non-negative) --> non-negative
1909 // (add negative, negative) --> negative
1910 case Instruction::Add: {
1911 if (Known2.isNonNegative() && Known3.isNonNegative())
1912 Known.makeNonNegative();
1913 else if (Known2.isNegative() && Known3.isNegative())
1914 Known.makeNegative();
1915 break;
1916 }
1917
1918 // (sub nsw non-negative, negative) --> non-negative
1919 // (sub nsw negative, non-negative) --> negative
1920 case Instruction::Sub: {
1921 if (BO->getOperand(0) != I)
1922 break;
1923 if (Known2.isNonNegative() && Known3.isNegative())
1924 Known.makeNonNegative();
1925 else if (Known2.isNegative() && Known3.isNonNegative())
1926 Known.makeNegative();
1927 break;
1928 }
1929
1930 // (mul nsw non-negative, non-negative) --> non-negative
1931 case Instruction::Mul:
1932 if (Known2.isNonNegative() && Known3.isNonNegative())
1933 Known.makeNonNegative();
1934 break;
1935
1936 default:
1937 break;
1938 }
1939 break;
1940 }
1941
1942 default:
1943 break;
1944 }
1945 }
1946
1947 // Unreachable blocks may have zero-operand PHI nodes.
1948 if (P->getNumIncomingValues() == 0)
1949 break;
1950
1951 // Otherwise take the unions of the known bit sets of the operands,
1952 // taking conservative care to avoid excessive recursion.
1953 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1954 // Skip if every incoming value references to ourself.
1955 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1956 break;
1957
1958 Known.setAllConflict();
1959 for (const Use &U : P->operands()) {
1960 Value *IncValue;
1961 const PHINode *CxtPhi;
1962 Instruction *CxtI;
1963 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1964 // Skip direct self references.
1965 if (IncValue == P)
1966 continue;
1967
1968 // Change the context instruction to the "edge" that flows into the
1969 // phi. This is important because that is where the value is actually
1970 // "evaluated" even though it is used later somewhere else. (see also
1971 // D69571).
1973
1974 Known2 = KnownBits(BitWidth);
1975
1976 // Recurse, but cap the recursion to one level, because we don't
1977 // want to waste time spinning around in loops.
1978 // TODO: See if we can base recursion limiter on number of incoming phi
1979 // edges so we don't overly clamp analysis.
1980 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1982
1983 // See if we can further use a conditional branch into the phi
1984 // to help us determine the range of the value.
1985 if (!Known2.isConstant()) {
1986 CmpPredicate Pred;
1987 const APInt *RHSC;
1988 BasicBlock *TrueSucc, *FalseSucc;
1989 // TODO: Use RHS Value and compute range from its known bits.
1990 if (match(RecQ.CxtI,
1991 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1992 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1993 // Check for cases of duplicate successors.
1994 if ((TrueSucc == CxtPhi->getParent()) !=
1995 (FalseSucc == CxtPhi->getParent())) {
1996 // If we're using the false successor, invert the predicate.
1997 if (FalseSucc == CxtPhi->getParent())
1998 Pred = CmpInst::getInversePredicate(Pred);
1999 // Get the knownbits implied by the incoming phi condition.
2000 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2001 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2002 // We can have conflicts here if we are analyzing deadcode (its
2003 // impossible for us reach this BB based the icmp).
2004 if (KnownUnion.hasConflict()) {
2005 // No reason to continue analyzing in a known dead region, so
2006 // just resetAll and break. This will cause us to also exit the
2007 // outer loop.
2008 Known.resetAll();
2009 break;
2010 }
2011 Known2 = KnownUnion;
2012 }
2013 }
2014 }
2015
2016 Known = Known.intersectWith(Known2);
2017 // If all bits have been ruled out, there's no need to check
2018 // more operands.
2019 if (Known.isUnknown())
2020 break;
2021 }
2022 }
2023 break;
2024 }
2025 case Instruction::Call:
2026 case Instruction::Invoke: {
2027 // If range metadata is attached to this call, set known bits from that,
2028 // and then intersect with known bits based on other properties of the
2029 // function.
2030 if (MDNode *MD =
2031 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2033
2034 const auto *CB = cast<CallBase>(I);
2035
2036 if (std::optional<ConstantRange> Range = CB->getRange())
2037 Known = Known.unionWith(Range->toKnownBits());
2038
2039 if (const Value *RV = CB->getReturnedArgOperand()) {
2040 if (RV->getType() == I->getType()) {
2041 computeKnownBits(RV, Known2, Q, Depth + 1);
2042 Known = Known.unionWith(Known2);
2043 // If the function doesn't return properly for all input values
2044 // (e.g. unreachable exits) then there might be conflicts between the
2045 // argument value and the range metadata. Simply discard the known bits
2046 // in case of conflicts.
2047 if (Known.hasConflict())
2048 Known.resetAll();
2049 }
2050 }
2051 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2052 switch (II->getIntrinsicID()) {
2053 default:
2054 break;
2055 case Intrinsic::abs: {
2056 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2057 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2058 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2059 break;
2060 }
2061 case Intrinsic::bitreverse:
2062 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2063 Known = Known.unionWith(Known2.reverseBits());
2064 break;
2065 case Intrinsic::bswap:
2066 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2067 Known = Known.unionWith(Known2.byteSwap());
2068 break;
2069 case Intrinsic::ctlz: {
2070 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2071 // If we have a known 1, its position is our upper bound.
2072 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2073 // If this call is poison for 0 input, the result will be less than 2^n.
2074 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2075 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2076 unsigned LowBits = llvm::bit_width(PossibleLZ);
2077 Known.Zero.setBitsFrom(LowBits);
2078 break;
2079 }
2080 case Intrinsic::cttz: {
2081 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2082 // If we have a known 1, its position is our upper bound.
2083 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2084 // If this call is poison for 0 input, the result will be less than 2^n.
2085 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2086 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2087 unsigned LowBits = llvm::bit_width(PossibleTZ);
2088 Known.Zero.setBitsFrom(LowBits);
2089 break;
2090 }
2091 case Intrinsic::ctpop: {
2092 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2093 // We can bound the space the count needs. Also, bits known to be zero
2094 // can't contribute to the population.
2095 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2096 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2097 Known.Zero.setBitsFrom(LowBits);
2098 // TODO: we could bound KnownOne using the lower bound on the number
2099 // of bits which might be set provided by popcnt KnownOne2.
2100 break;
2101 }
2102 case Intrinsic::fshr:
2103 case Intrinsic::fshl: {
2104 const APInt *SA;
2105 if (!match(I->getOperand(2), m_APInt(SA)))
2106 break;
2107
2108 KnownBits Known3(BitWidth);
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2111 Known = II->getIntrinsicID() == Intrinsic::fshl
2112 ? KnownBits::fshl(Known2, Known3, *SA)
2113 : KnownBits::fshr(Known2, Known3, *SA);
2114 break;
2115 }
2116 case Intrinsic::clmul:
2117 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2118 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2119 Known = KnownBits::clmul(Known, Known2);
2120 break;
2121 case Intrinsic::pext:
2122 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2123 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2124 Known = KnownBits::pext(Known, Known2);
2125 break;
2126 case Intrinsic::pdep:
2127 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2128 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2129 Known = KnownBits::pdep(Known, Known2);
2130 break;
2131 case Intrinsic::uadd_sat:
2132 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2133 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2134 Known = KnownBits::uadd_sat(Known, Known2);
2135 break;
2136 case Intrinsic::usub_sat:
2137 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2138 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2139 Known = KnownBits::usub_sat(Known, Known2);
2140 break;
2141 case Intrinsic::sadd_sat:
2142 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2143 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2144 Known = KnownBits::sadd_sat(Known, Known2);
2145 break;
2146 case Intrinsic::ssub_sat:
2147 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2148 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2149 Known = KnownBits::ssub_sat(Known, Known2);
2150 break;
2151 // Vec reverse preserves bits from input vec.
2152 case Intrinsic::vector_reverse:
2153 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2154 Depth + 1);
2155 break;
2156 // for min/max/and/or reduce, any bit common to each element in the
2157 // input vec is set in the output.
2158 case Intrinsic::vector_reduce_and:
2159 case Intrinsic::vector_reduce_or:
2160 case Intrinsic::vector_reduce_umax:
2161 case Intrinsic::vector_reduce_umin:
2162 case Intrinsic::vector_reduce_smax:
2163 case Intrinsic::vector_reduce_smin:
2164 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2165 break;
2166 case Intrinsic::vector_reduce_xor: {
2167 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2168 // The zeros common to all vecs are zero in the output.
2169 // If the number of elements is odd, then the common ones remain. If the
2170 // number of elements is even, then the common ones becomes zeros.
2171 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2172 // Even, so the ones become zeros.
2173 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2174 if (EvenCnt)
2175 Known.Zero |= Known.One;
2176 // Maybe even element count so need to clear ones.
2177 if (VecTy->isScalableTy() || EvenCnt)
2178 Known.One.clearAllBits();
2179 break;
2180 }
2181 case Intrinsic::vector_reduce_add: {
2182 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2183 if (!VecTy)
2184 break;
2185 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2186 Known = Known.reduceAdd(VecTy->getNumElements());
2187 break;
2188 }
2189 case Intrinsic::umin:
2190 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2191 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2192 Known = KnownBits::umin(Known, Known2);
2193 break;
2194 case Intrinsic::umax:
2195 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2196 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2197 Known = KnownBits::umax(Known, Known2);
2198 break;
2199 case Intrinsic::smin:
2200 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2201 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2202 Known = KnownBits::smin(Known, Known2);
2204 break;
2205 case Intrinsic::smax:
2206 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2207 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2208 Known = KnownBits::smax(Known, Known2);
2210 break;
2211 case Intrinsic::ptrmask: {
2212 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2213
2214 const Value *Mask = I->getOperand(1);
2215 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2216 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2217 // TODO: 1-extend would be more precise.
2218 Known &= Known2.anyextOrTrunc(BitWidth);
2219 break;
2220 }
2221 case Intrinsic::x86_sse2_pmulh_w:
2222 case Intrinsic::x86_avx2_pmulh_w:
2223 case Intrinsic::x86_avx512_pmulh_w_512:
2224 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2225 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2226 Known = KnownBits::mulhs(Known, Known2);
2227 break;
2228 case Intrinsic::x86_sse2_pmulhu_w:
2229 case Intrinsic::x86_avx2_pmulhu_w:
2230 case Intrinsic::x86_avx512_pmulhu_w_512:
2231 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2232 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2233 Known = KnownBits::mulhu(Known, Known2);
2234 break;
2235 case Intrinsic::x86_sse42_crc32_64_64:
2236 Known.Zero.setBitsFrom(32);
2237 break;
2238 case Intrinsic::x86_ssse3_phadd_d_128:
2239 case Intrinsic::x86_ssse3_phadd_w_128:
2240 case Intrinsic::x86_avx2_phadd_d:
2241 case Intrinsic::x86_avx2_phadd_w: {
2243 I, DemandedElts, Q, Depth,
2244 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2245 return KnownBits::add(KnownLHS, KnownRHS);
2246 });
2247 break;
2248 }
2249 case Intrinsic::x86_ssse3_phadd_sw_128:
2250 case Intrinsic::x86_avx2_phadd_sw: {
2252 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2253 break;
2254 }
2255 case Intrinsic::x86_ssse3_phsub_d_128:
2256 case Intrinsic::x86_ssse3_phsub_w_128:
2257 case Intrinsic::x86_avx2_phsub_d:
2258 case Intrinsic::x86_avx2_phsub_w: {
2260 I, DemandedElts, Q, Depth,
2261 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2262 return KnownBits::sub(KnownLHS, KnownRHS);
2263 });
2264 break;
2265 }
2266 case Intrinsic::x86_ssse3_phsub_sw_128:
2267 case Intrinsic::x86_avx2_phsub_sw: {
2269 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2270 break;
2271 }
2272 case Intrinsic::riscv_vsetvli:
2273 case Intrinsic::riscv_vsetvlimax: {
2274 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2275 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2277 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2278 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2279 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2280 uint64_t MaxVLEN =
2281 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2282 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2283
2284 // Result of vsetvli must be not larger than AVL.
2285 if (HasAVL)
2286 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2287 MaxVL = std::min(MaxVL, CI->getZExtValue());
2288
2289 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2290 if (BitWidth > KnownZeroFirstBit)
2291 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2292 break;
2293 }
2294 case Intrinsic::amdgcn_mbcnt_hi:
2295 case Intrinsic::amdgcn_mbcnt_lo: {
2296 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2297 // most 31 + src1.
2298 Known.Zero.setBitsFrom(
2299 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2300 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2301 Known = KnownBits::add(Known, Known2);
2302 break;
2303 }
2304 case Intrinsic::vscale: {
2305 if (!II->getParent() || !II->getFunction())
2306 break;
2307
2308 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2309 break;
2310 }
2311 }
2312 }
2313 break;
2314 }
2315 case Instruction::ShuffleVector: {
2316 if (auto *Splat = getSplatValue(I)) {
2318 break;
2319 }
2320
2321 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2322 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2323 if (!Shuf) {
2324 Known.resetAll();
2325 return;
2326 }
2327 // For undef elements, we don't know anything about the common state of
2328 // the shuffle result.
2329 APInt DemandedLHS, DemandedRHS;
2330 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2331 Known.resetAll();
2332 return;
2333 }
2334 Known.setAllConflict();
2335 if (!!DemandedLHS) {
2336 const Value *LHS = Shuf->getOperand(0);
2337 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2338 // If we don't know any bits, early out.
2339 if (Known.isUnknown())
2340 break;
2341 }
2342 if (!!DemandedRHS) {
2343 const Value *RHS = Shuf->getOperand(1);
2344 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2345 Known = Known.intersectWith(Known2);
2346 }
2347 break;
2348 }
2349 case Instruction::InsertElement: {
2350 if (isa<ScalableVectorType>(I->getType())) {
2351 Known.resetAll();
2352 return;
2353 }
2354 const Value *Vec = I->getOperand(0);
2355 const Value *Elt = I->getOperand(1);
2356 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2357 unsigned NumElts = DemandedElts.getBitWidth();
2358 APInt DemandedVecElts = DemandedElts;
2359 bool NeedsElt = true;
2360 // If we know the index we are inserting too, clear it from Vec check.
2361 if (CIdx && CIdx->getValue().ult(NumElts)) {
2362 DemandedVecElts.clearBit(CIdx->getZExtValue());
2363 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2364 }
2365
2366 Known.setAllConflict();
2367 if (NeedsElt) {
2368 computeKnownBits(Elt, Known, Q, Depth + 1);
2369 // If we don't know any bits, early out.
2370 if (Known.isUnknown())
2371 break;
2372 }
2373
2374 if (!DemandedVecElts.isZero()) {
2375 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2376 Known = Known.intersectWith(Known2);
2377 }
2378 break;
2379 }
2380 case Instruction::ExtractElement: {
2381 // Look through extract element. If the index is non-constant or
2382 // out-of-range demand all elements, otherwise just the extracted element.
2383 const Value *Vec = I->getOperand(0);
2384 const Value *Idx = I->getOperand(1);
2385 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2386 if (isa<ScalableVectorType>(Vec->getType())) {
2387 // FIXME: there's probably *something* we can do with scalable vectors
2388 Known.resetAll();
2389 break;
2390 }
2391 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2392 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2393 if (CIdx && CIdx->getValue().ult(NumElts))
2394 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2395 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2396 break;
2397 }
2398 case Instruction::ExtractValue:
2399 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2401 if (EVI->getNumIndices() != 1) break;
2402 if (EVI->getIndices()[0] == 0) {
2403 switch (II->getIntrinsicID()) {
2404 default: break;
2405 case Intrinsic::uadd_with_overflow:
2406 case Intrinsic::sadd_with_overflow:
2408 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2409 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2410 break;
2411 case Intrinsic::usub_with_overflow:
2412 case Intrinsic::ssub_with_overflow:
2414 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2415 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2416 break;
2417 case Intrinsic::umul_with_overflow:
2418 case Intrinsic::smul_with_overflow:
2419 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2420 false, DemandedElts, Known, Known2, Q, Depth);
2421 break;
2422 }
2423 }
2424 }
2425 break;
2426 case Instruction::Freeze:
2427 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2428 Depth + 1))
2429 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2430 break;
2431 }
2432}
2433
2434/// Determine which bits of V are known to be either zero or one and return
2435/// them.
2436KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2437 const SimplifyQuery &Q, unsigned Depth) {
2438 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2439 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2440 return Known;
2441}
2442
2443/// Determine which bits of V are known to be either zero or one and return
2444/// them.
2446 unsigned Depth) {
2447 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2449 return Known;
2450}
2451
2452/// Determine which bits of V are known to be either zero or one and return
2453/// them in the Known bit set.
2454///
2455/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2456/// we cannot optimize based on the assumption that it is zero without changing
2457/// it to be an explicit zero. If we don't change it to zero, other code could
2458/// optimized based on the contradictory assumption that it is non-zero.
2459/// Because instcombine aggressively folds operations with undef args anyway,
2460/// this won't lose us code quality.
2461///
2462/// This function is defined on values with integer type, values with pointer
2463/// type, and vectors of integers. In the case
2464/// where V is a vector, known zero, and known one values are the
2465/// same width as the vector element, and the bit is set only if it is true
2466/// for all of the demanded elements in the vector specified by DemandedElts.
2467void computeKnownBits(const Value *V, const APInt &DemandedElts,
2468 KnownBits &Known, const SimplifyQuery &Q,
2469 unsigned Depth) {
2470 if (!DemandedElts) {
2471 // No demanded elts, better to assume we don't know anything.
2472 Known.resetAll();
2473 return;
2474 }
2475
2476 assert(V && "No Value?");
2477 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2478
2479#ifndef NDEBUG
2480 Type *Ty = V->getType();
2481 unsigned BitWidth = Known.getBitWidth();
2482
2483 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2484 "Not integer or pointer type!");
2485
2486 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2487 assert(
2488 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2489 "DemandedElt width should equal the fixed vector number of elements");
2490 } else {
2491 assert(DemandedElts == APInt(1, 1) &&
2492 "DemandedElt width should be 1 for scalars or scalable vectors");
2493 }
2494
2495 Type *ScalarTy = Ty->getScalarType();
2496 if (ScalarTy->isPointerTy()) {
2497 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2498 "V and Known should have same BitWidth");
2499 } else {
2500 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2501 "V and Known should have same BitWidth");
2502 }
2503#endif
2504
2505 const APInt *C;
2506 if (match(V, m_APInt(C))) {
2507 // We know all of the bits for a scalar constant or a splat vector constant!
2509 return;
2510 }
2511 // Null and aggregate-zero are all-zeros.
2513 Known.setAllZero();
2514 return;
2515 }
2516 // Handle a constant vector by taking the intersection of the known bits of
2517 // each element.
2519 assert(!isa<ScalableVectorType>(V->getType()));
2520 // We know that CDV must be a vector of integers. Take the intersection of
2521 // each element.
2522 Known.setAllConflict();
2523 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2524 if (!DemandedElts[i])
2525 continue;
2526 APInt Elt = CDV->getElementAsAPInt(i);
2527 Known.Zero &= ~Elt;
2528 Known.One &= Elt;
2529 }
2530 if (Known.hasConflict())
2531 Known.resetAll();
2532 return;
2533 }
2534
2535 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2536 assert(!isa<ScalableVectorType>(V->getType()));
2537 // We know that CV must be a vector of integers. Take the intersection of
2538 // each element.
2539 Known.setAllConflict();
2540 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2541 if (!DemandedElts[i])
2542 continue;
2543 Constant *Element = CV->getAggregateElement(i);
2544 if (isa<PoisonValue>(Element))
2545 continue;
2546 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2547 if (!ElementCI) {
2548 Known.resetAll();
2549 return;
2550 }
2551 const APInt &Elt = ElementCI->getValue();
2552 Known.Zero &= ~Elt;
2553 Known.One &= Elt;
2554 }
2555 if (Known.hasConflict())
2556 Known.resetAll();
2557 return;
2558 }
2559
2560 // Start out not knowing anything.
2561 Known.resetAll();
2562
2563 // We can't imply anything about undefs.
2564 if (isa<UndefValue>(V))
2565 return;
2566
2567 // There's no point in looking through other users of ConstantData for
2568 // assumptions. Confirm that we've handled them all.
2569 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2570
2571 if (const auto *A = dyn_cast<Argument>(V))
2572 if (std::optional<ConstantRange> Range = A->getRange())
2573 Known = Range->toKnownBits();
2574
2575 // All recursive calls that increase depth must come after this.
2577 return;
2578
2579 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2580 // the bits of its aliasee.
2581 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2582 if (!GA->isInterposable())
2583 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2584 return;
2585 }
2586
2587 if (const Operator *I = dyn_cast<Operator>(V))
2588 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2589 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2590 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2591 Known = CR->toKnownBits();
2592 }
2593
2594 // Aligned pointers have trailing zeros - refine Known.Zero set
2595 if (isa<PointerType>(V->getType())) {
2596 Align Alignment = V->getPointerAlignment(Q.DL);
2597 Known.Zero.setLowBits(Log2(Alignment));
2598 }
2599
2600 // computeKnownBitsFromContext strictly refines Known.
2601 // Therefore, we run them after computeKnownBitsFromOperator.
2602
2603 // Check whether we can determine known bits from context such as assumes.
2605}
2606
2607/// Try to detect a recurrence that the value of the induction variable is
2608/// always a power of two (or zero).
2609static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2610 SimplifyQuery &Q, unsigned Depth) {
2611 BinaryOperator *BO = nullptr;
2612 Value *Start = nullptr, *Step = nullptr;
2613 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2614 return false;
2615
2616 // Initial value must be a power of two.
2617 for (const Use &U : PN->operands()) {
2618 if (U.get() == Start) {
2619 // Initial value comes from a different BB, need to adjust context
2620 // instruction for analysis.
2621 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2622 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2623 return false;
2624 }
2625 }
2626
2627 // Except for Mul, the induction variable must be on the left side of the
2628 // increment expression, otherwise its value can be arbitrary.
2629 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2630 return false;
2631
2632 Q.CxtI = BO->getParent()->getTerminator();
2633 switch (BO->getOpcode()) {
2634 case Instruction::Mul:
2635 // Power of two is closed under multiplication.
2636 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2637 Q.IIQ.hasNoSignedWrap(BO)) &&
2638 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2639 case Instruction::SDiv:
2640 // Start value must not be signmask for signed division, so simply being a
2641 // power of two is not sufficient, and it has to be a constant.
2642 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2643 return false;
2644 [[fallthrough]];
2645 case Instruction::UDiv:
2646 // Divisor must be a power of two.
2647 // If OrZero is false, cannot guarantee induction variable is non-zero after
2648 // division, same for Shr, unless it is exact division.
2649 return (OrZero || Q.IIQ.isExact(BO)) &&
2650 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2651 case Instruction::Shl:
2652 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2653 case Instruction::AShr:
2654 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2655 return false;
2656 [[fallthrough]];
2657 case Instruction::LShr:
2658 return OrZero || Q.IIQ.isExact(BO);
2659 default:
2660 return false;
2661 }
2662}
2663
2664/// Return true if we can infer that \p V is known to be a power of 2 from
2665/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2666static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2667 const Value *Cond,
2668 bool CondIsTrue) {
2669 CmpPredicate Pred;
2670 const APInt *RHSC;
2671 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2672 return false;
2673 if (!CondIsTrue)
2674 Pred = ICmpInst::getInversePredicate(Pred);
2675 // ctpop(V) u< 2
2676 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2677 return true;
2678 // ctpop(V) == 1
2679 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2680}
2681
2682/// Return true if the given value is known to have exactly one
2683/// bit set when defined. For vectors return true if every element is known to
2684/// be a power of two when defined. Supports values with integer or pointer
2685/// types and vectors of integers.
2686bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2687 const SimplifyQuery &Q, unsigned Depth) {
2688 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2689
2690 if (isa<Constant>(V))
2691 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2692
2693 // i1 is by definition a power of 2 or zero.
2694 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2695 return true;
2696
2697 // Try to infer from assumptions.
2698 if (Q.AC && Q.CxtI) {
2699 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2700 if (!AssumeVH)
2701 continue;
2702 CallInst *I = cast<CallInst>(AssumeVH);
2703 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2704 /*CondIsTrue=*/true) &&
2706 return true;
2707 }
2708 }
2709
2710 // Handle dominating conditions.
2711 if (Q.DC && Q.CxtI && Q.DT) {
2712 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2713 Value *Cond = BI->getCondition();
2714
2715 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2717 /*CondIsTrue=*/true) &&
2718 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2719 return true;
2720
2721 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2723 /*CondIsTrue=*/false) &&
2724 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2725 return true;
2726 }
2727 }
2728
2729 auto *I = dyn_cast<Instruction>(V);
2730 if (!I)
2731 return false;
2732
2733 if (Q.CxtI && match(V, m_VScale())) {
2734 const Function *F = Q.CxtI->getFunction();
2735 // The vscale_range indicates vscale is a power-of-two.
2736 return F->hasFnAttribute(Attribute::VScaleRange);
2737 }
2738
2739 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2740 // it is shifted off the end then the result is undefined.
2741 if (match(I, m_Shl(m_One(), m_Value())))
2742 return true;
2743
2744 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2745 // the bottom. If it is shifted off the bottom then the result is undefined.
2746 if (match(I, m_LShr(m_SignMask(), m_Value())))
2747 return true;
2748
2749 // The remaining tests are all recursive, so bail out if we hit the limit.
2751 return false;
2752
2753 switch (I->getOpcode()) {
2754 case Instruction::ZExt:
2755 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2756 case Instruction::Trunc:
2757 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2758 case Instruction::Shl:
2759 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2760 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2761 return false;
2762 case Instruction::LShr:
2763 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2764 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2765 return false;
2766 case Instruction::UDiv:
2768 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2769 return false;
2770 case Instruction::Mul:
2771 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2772 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2773 (OrZero || isKnownNonZero(I, Q, Depth));
2774 case Instruction::And:
2775 // A power of two and'd with anything is a power of two or zero.
2776 if (OrZero &&
2777 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2778 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2779 return true;
2780 // X & (-X) is always a power of two or zero.
2781 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2782 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2783 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2784 return false;
2785 case Instruction::Add: {
2786 // Adding a power-of-two or zero to the same power-of-two or zero yields
2787 // either the original power-of-two, a larger power-of-two or zero.
2789 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2790 Q.IIQ.hasNoSignedWrap(VOBO)) {
2791 if (match(I->getOperand(0),
2792 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2793 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2794 return true;
2795 if (match(I->getOperand(1),
2796 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2797 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2798 return true;
2799
2800 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2801 KnownBits LHSBits(BitWidth);
2802 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2803
2804 KnownBits RHSBits(BitWidth);
2805 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2806 // If i8 V is a power of two or zero:
2807 // ZeroBits: 1 1 1 0 1 1 1 1
2808 // ~ZeroBits: 0 0 0 1 0 0 0 0
2809 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2810 // If OrZero isn't set, we cannot give back a zero result.
2811 // Make sure either the LHS or RHS has a bit set.
2812 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2813 return true;
2814 }
2815
2816 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2817 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2818 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2819 return true;
2820 return false;
2821 }
2822 case Instruction::Select:
2823 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2824 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2825 case Instruction::PHI: {
2826 // A PHI node is power of two if all incoming values are power of two, or if
2827 // it is an induction variable where in each step its value is a power of
2828 // two.
2829 auto *PN = cast<PHINode>(I);
2831
2832 // Check if it is an induction variable and always power of two.
2833 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2834 return true;
2835
2836 // Recursively check all incoming values. Limit recursion to 2 levels, so
2837 // that search complexity is limited to number of operands^2.
2838 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2839 return llvm::all_of(PN->operands(), [&](const Use &U) {
2840 // Value is power of 2 if it is coming from PHI node itself by induction.
2841 if (U.get() == PN)
2842 return true;
2843
2844 // Change the context instruction to the incoming block where it is
2845 // evaluated.
2846 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2847 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2848 });
2849 }
2850 case Instruction::Invoke:
2851 case Instruction::Call: {
2852 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2853 switch (II->getIntrinsicID()) {
2854 case Intrinsic::umax:
2855 case Intrinsic::smax:
2856 case Intrinsic::umin:
2857 case Intrinsic::smin:
2858 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2859 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2860 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2861 // thus dont change pow2/non-pow2 status.
2862 case Intrinsic::bitreverse:
2863 case Intrinsic::bswap:
2864 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2865 case Intrinsic::fshr:
2866 case Intrinsic::fshl:
2867 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2868 if (II->getArgOperand(0) == II->getArgOperand(1))
2869 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2870 break;
2871 default:
2872 break;
2873 }
2874 }
2875 return false;
2876 }
2877 default:
2878 return false;
2879 }
2880}
2881
2882/// Test whether a GEP's result is known to be non-null.
2883///
2884/// Uses properties inherent in a GEP to try to determine whether it is known
2885/// to be non-null.
2886///
2887/// Currently this routine does not support vector GEPs.
2888static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2889 unsigned Depth) {
2890 const Function *F = nullptr;
2891 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2892 F = I->getFunction();
2893
2894 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2895 // may be null iff the base pointer is null and the offset is zero.
2896 if (!GEP->hasNoUnsignedWrap() &&
2897 !(GEP->isInBounds() &&
2898 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2899 return false;
2900
2901 // FIXME: Support vector-GEPs.
2902 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2903
2904 // If the base pointer is non-null, we cannot walk to a null address with an
2905 // inbounds GEP in address space zero.
2906 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2907 return true;
2908
2909 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2910 // If so, then the GEP cannot produce a null pointer, as doing so would
2911 // inherently violate the inbounds contract within address space zero.
2913 GTI != GTE; ++GTI) {
2914 // Struct types are easy -- they must always be indexed by a constant.
2915 if (StructType *STy = GTI.getStructTypeOrNull()) {
2916 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2917 unsigned ElementIdx = OpC->getZExtValue();
2918 const StructLayout *SL = Q.DL.getStructLayout(STy);
2919 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2920 if (ElementOffset > 0)
2921 return true;
2922 continue;
2923 }
2924
2925 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2926 if (GTI.getSequentialElementStride(Q.DL).isZero())
2927 continue;
2928
2929 // Fast path the constant operand case both for efficiency and so we don't
2930 // increment Depth when just zipping down an all-constant GEP.
2931 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2932 if (!OpC->isZero())
2933 return true;
2934 continue;
2935 }
2936
2937 // We post-increment Depth here because while isKnownNonZero increments it
2938 // as well, when we pop back up that increment won't persist. We don't want
2939 // to recurse 10k times just because we have 10k GEP operands. We don't
2940 // bail completely out because we want to handle constant GEPs regardless
2941 // of depth.
2943 continue;
2944
2945 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2946 return true;
2947 }
2948
2949 return false;
2950}
2951
2953 const Instruction *CtxI,
2954 const DominatorTree *DT) {
2955 assert(!isa<Constant>(V) && "Called for constant?");
2956
2957 if (!CtxI || !DT)
2958 return false;
2959
2960 unsigned NumUsesExplored = 0;
2961 for (auto &U : V->uses()) {
2962 // Avoid massive lists
2963 if (NumUsesExplored >= DomConditionsMaxUses)
2964 break;
2965 NumUsesExplored++;
2966
2967 const Instruction *UI = cast<Instruction>(U.getUser());
2968 // If the value is used as an argument to a call or invoke, then argument
2969 // attributes may provide an answer about null-ness.
2970 if (V->getType()->isPointerTy()) {
2971 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2972 if (CB->isArgOperand(&U) &&
2973 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2974 /*AllowUndefOrPoison=*/false) &&
2975 DT->dominates(CB, CtxI))
2976 return true;
2977 }
2978 }
2979
2980 // If the value is used as a load/store, then the pointer must be non null.
2981 if (V == getLoadStorePointerOperand(UI)) {
2984 DT->dominates(UI, CtxI))
2985 return true;
2986 }
2987
2988 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2989 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2990 isValidAssumeForContext(UI, CtxI, DT))
2991 return true;
2992
2993 // Consider only compare instructions uniquely controlling a branch
2994 Value *RHS;
2995 CmpPredicate Pred;
2996 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2997 continue;
2998
2999 bool NonNullIfTrue;
3000 if (cmpExcludesZero(Pred, RHS))
3001 NonNullIfTrue = true;
3003 NonNullIfTrue = false;
3004 else
3005 continue;
3006
3009 for (const auto *CmpU : UI->users()) {
3010 assert(WorkList.empty() && "Should be!");
3011 if (Visited.insert(CmpU).second)
3012 WorkList.push_back(CmpU);
3013
3014 while (!WorkList.empty()) {
3015 auto *Curr = WorkList.pop_back_val();
3016
3017 // If a user is an AND, add all its users to the work list. We only
3018 // propagate "pred != null" condition through AND because it is only
3019 // correct to assume that all conditions of AND are met in true branch.
3020 // TODO: Support similar logic of OR and EQ predicate?
3021 if (NonNullIfTrue)
3022 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3023 for (const auto *CurrU : Curr->users())
3024 if (Visited.insert(CurrU).second)
3025 WorkList.push_back(CurrU);
3026 continue;
3027 }
3028
3029 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3030 BasicBlock *NonNullSuccessor =
3031 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3032 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3033 if (DT->dominates(Edge, CtxI->getParent()))
3034 return true;
3035 } else if (NonNullIfTrue && isGuard(Curr) &&
3036 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3037 return true;
3038 }
3039 }
3040 }
3041 }
3042
3043 return false;
3044}
3045
3046/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3047/// ensure that the value it's attached to is never Value? 'RangeType' is
3048/// is the type of the value described by the range.
3049static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3050 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3051 assert(NumRanges >= 1);
3052 for (unsigned i = 0; i < NumRanges; ++i) {
3054 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3056 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3057 ConstantRange Range(Lower->getValue(), Upper->getValue());
3058 if (Range.contains(Value))
3059 return false;
3060 }
3061 return true;
3062}
3063
3064/// Try to detect a recurrence that monotonically increases/decreases from a
3065/// non-zero starting value. These are common as induction variables.
3066static bool isNonZeroRecurrence(const PHINode *PN) {
3067 BinaryOperator *BO = nullptr;
3068 Value *Start = nullptr, *Step = nullptr;
3069 const APInt *StartC, *StepC;
3070 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3071 !match(Start, m_APInt(StartC)) || StartC->isZero())
3072 return false;
3073
3074 switch (BO->getOpcode()) {
3075 case Instruction::Add:
3076 // Starting from non-zero and stepping away from zero can never wrap back
3077 // to zero.
3078 return BO->hasNoUnsignedWrap() ||
3079 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3080 StartC->isNegative() == StepC->isNegative());
3081 case Instruction::Mul:
3082 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3083 match(Step, m_APInt(StepC)) && !StepC->isZero();
3084 case Instruction::Shl:
3085 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3086 case Instruction::AShr:
3087 case Instruction::LShr:
3088 return BO->isExact();
3089 default:
3090 return false;
3091 }
3092}
3093
3094static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3096 m_Specific(Op1), m_Zero()))) ||
3098 m_Specific(Op0), m_Zero())));
3099}
3100
3101static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3102 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3103 bool NUW, unsigned Depth) {
3104 // (X + (X != 0)) is non zero
3105 if (matchOpWithOpEqZero(X, Y))
3106 return true;
3107
3108 if (NUW)
3109 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3110 isKnownNonZero(X, DemandedElts, Q, Depth);
3111
3112 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3113 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3114
3115 // If X and Y are both non-negative (as signed values) then their sum is not
3116 // zero unless both X and Y are zero.
3117 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3118 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3119 isKnownNonZero(X, DemandedElts, Q, Depth))
3120 return true;
3121
3122 // If X and Y are both negative (as signed values) then their sum is not
3123 // zero unless both X and Y equal INT_MIN.
3124 if (XKnown.isNegative() && YKnown.isNegative()) {
3126 // The sign bit of X is set. If some other bit is set then X is not equal
3127 // to INT_MIN.
3128 if (XKnown.One.intersects(Mask))
3129 return true;
3130 // The sign bit of Y is set. If some other bit is set then Y is not equal
3131 // to INT_MIN.
3132 if (YKnown.One.intersects(Mask))
3133 return true;
3134 }
3135
3136 // The sum of a non-negative number and a power of two is not zero.
3137 if (XKnown.isNonNegative() &&
3138 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3139 return true;
3140 if (YKnown.isNonNegative() &&
3141 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3142 return true;
3143
3144 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3145}
3146
3147static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3148 unsigned BitWidth, Value *X, Value *Y,
3149 unsigned Depth) {
3150 // (X - (X != 0)) is non zero
3151 // ((X != 0) - X) is non zero
3152 if (matchOpWithOpEqZero(X, Y))
3153 return true;
3154
3155 // TODO: Move this case into isKnownNonEqual().
3156 if (auto *C = dyn_cast<Constant>(X))
3157 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3158 return true;
3159
3160 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3161}
3162
3163static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3164 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3165 bool NUW, unsigned Depth) {
3166 // If X and Y are non-zero then so is X * Y as long as the multiplication
3167 // does not overflow.
3168 if (NSW || NUW)
3169 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3170 isKnownNonZero(Y, DemandedElts, Q, Depth);
3171
3172 // If either X or Y is odd, then if the other is non-zero the result can't
3173 // be zero.
3174 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3175 if (XKnown.One[0])
3176 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3177
3178 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3179 if (YKnown.One[0])
3180 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3181
3182 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3183 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3184 // the lowest known One of X and Y. If they are non-zero, the result
3185 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3186 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3187 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3188 BitWidth;
3189}
3190
3191static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3192 const SimplifyQuery &Q, const KnownBits &KnownVal,
3193 unsigned Depth) {
3194 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3195 switch (I->getOpcode()) {
3196 case Instruction::Shl:
3197 return Lhs.shl(Rhs);
3198 case Instruction::LShr:
3199 return Lhs.lshr(Rhs);
3200 case Instruction::AShr:
3201 return Lhs.ashr(Rhs);
3202 default:
3203 llvm_unreachable("Unknown Shift Opcode");
3204 }
3205 };
3206
3207 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3208 switch (I->getOpcode()) {
3209 case Instruction::Shl:
3210 return Lhs.lshr(Rhs);
3211 case Instruction::LShr:
3212 case Instruction::AShr:
3213 return Lhs.shl(Rhs);
3214 default:
3215 llvm_unreachable("Unknown Shift Opcode");
3216 }
3217 };
3218
3219 if (KnownVal.isUnknown())
3220 return false;
3221
3222 KnownBits KnownCnt =
3223 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3224 APInt MaxShift = KnownCnt.getMaxValue();
3225 unsigned NumBits = KnownVal.getBitWidth();
3226 if (MaxShift.uge(NumBits))
3227 return false;
3228
3229 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3230 return true;
3231
3232 // If all of the bits shifted out are known to be zero, and Val is known
3233 // non-zero then at least one non-zero bit must remain.
3234 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3235 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3236 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3237 return true;
3238
3239 return false;
3240}
3241
3243 const APInt &DemandedElts,
3244 const SimplifyQuery &Q, unsigned Depth) {
3245 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3246 switch (I->getOpcode()) {
3247 case Instruction::Alloca:
3248 // Alloca never returns null, malloc might.
3249 return I->getType()->getPointerAddressSpace() == 0;
3250 case Instruction::GetElementPtr:
3251 if (I->getType()->isPointerTy())
3253 break;
3254 case Instruction::BitCast: {
3255 // We need to be a bit careful here. We can only peek through the bitcast
3256 // if the scalar size of elements in the operand are smaller than and a
3257 // multiple of the size they are casting too. Take three cases:
3258 //
3259 // 1) Unsafe:
3260 // bitcast <2 x i16> %NonZero to <4 x i8>
3261 //
3262 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3263 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3264 // guranteed (imagine just sign bit set in the 2 i16 elements).
3265 //
3266 // 2) Unsafe:
3267 // bitcast <4 x i3> %NonZero to <3 x i4>
3268 //
3269 // Even though the scalar size of the src (`i3`) is smaller than the
3270 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3271 // its possible for the `3 x i4` elements to be zero because there are
3272 // some elements in the destination that don't contain any full src
3273 // element.
3274 //
3275 // 3) Safe:
3276 // bitcast <4 x i8> %NonZero to <2 x i16>
3277 //
3278 // This is always safe as non-zero in the 4 i8 elements implies
3279 // non-zero in the combination of any two adjacent ones. Since i8 is a
3280 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3281 // This all implies the 2 i16 elements are non-zero.
3282 Type *FromTy = I->getOperand(0)->getType();
3283 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3284 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3285 return isKnownNonZero(I->getOperand(0), Q, Depth);
3286 } break;
3287 case Instruction::IntToPtr:
3288 // Note that we have to take special care to avoid looking through
3289 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3290 // as casts that can alter the value, e.g., AddrSpaceCasts.
3291 if (!isa<ScalableVectorType>(I->getType()) &&
3292 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3293 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3294 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3295 break;
3296 case Instruction::PtrToAddr:
3297 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3298 // so we can directly forward.
3299 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3300 case Instruction::PtrToInt:
3301 // For inttoptr, make sure the result size is >= the address size. If the
3302 // address is non-zero, any larger value is also non-zero.
3303 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3304 I->getType()->getScalarSizeInBits())
3305 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3306 break;
3307 case Instruction::Trunc:
3308 // nuw/nsw trunc preserves zero/non-zero status of input.
3309 if (auto *TI = dyn_cast<TruncInst>(I))
3310 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3311 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3312 break;
3313
3314 // Iff x - y != 0, then x ^ y != 0
3315 // Therefore we can do the same exact checks
3316 case Instruction::Xor:
3317 case Instruction::Sub:
3318 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3319 I->getOperand(1), Depth);
3320 case Instruction::Or:
3321 // (X | (X != 0)) is non zero
3322 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3323 return true;
3324 // X | Y != 0 if X != Y.
3325 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3326 Depth))
3327 return true;
3328 // X | Y != 0 if X != 0 or Y != 0.
3329 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3330 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3331 case Instruction::SExt:
3332 case Instruction::ZExt:
3333 // ext X != 0 if X != 0.
3334 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3335
3336 case Instruction::Shl: {
3337 // shl nsw/nuw can't remove any non-zero bits.
3339 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3340 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3341
3342 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3343 // if the lowest bit is shifted off the end.
3345 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3346 if (Known.One[0])
3347 return true;
3348
3349 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3350 }
3351 case Instruction::LShr:
3352 case Instruction::AShr: {
3353 // shr exact can only shift out zero bits.
3355 if (BO->isExact())
3356 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3357
3358 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3359 // defined if the sign bit is shifted off the end.
3361 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3362 if (Known.isNegative())
3363 return true;
3364
3365 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3366 // position >= C, because the sum >= max(A, B).
3367 Value *A, *B;
3368 const APInt *C;
3369 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3370 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3371 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3372 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3373 if (!KnownA.One.lshr(*C).isZero())
3374 return true;
3375 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3376 if (!KnownB.One.lshr(*C).isZero())
3377 return true;
3378 }
3379
3380 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3381 }
3382 case Instruction::UDiv:
3383 case Instruction::SDiv: {
3384 // X / Y
3385 // div exact can only produce a zero if the dividend is zero.
3386 if (cast<PossiblyExactOperator>(I)->isExact())
3387 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3388
3389 KnownBits XKnown =
3390 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3391 // If X is fully unknown we won't be able to figure anything out so don't
3392 // both computing knownbits for Y.
3393 if (XKnown.isUnknown())
3394 return false;
3395
3396 KnownBits YKnown =
3397 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3398 if (I->getOpcode() == Instruction::SDiv) {
3399 // For signed division need to compare abs value of the operands.
3400 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3401 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3402 }
3403 // If X u>= Y then div is non zero (0/0 is UB).
3404 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3405 // If X is total unknown or X u< Y we won't be able to prove non-zero
3406 // with compute known bits so just return early.
3407 return XUgeY && *XUgeY;
3408 }
3409 case Instruction::Add: {
3410 // X + Y.
3411
3412 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3413 // non-zero.
3415 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3416 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3417 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3418 }
3419 case Instruction::Mul: {
3421 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3422 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3423 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3424 }
3425 case Instruction::Select: {
3426 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3427
3428 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3429 // then see if the select condition implies the arm is non-zero. For example
3430 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3431 // dominated by `X != 0`.
3432 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3433 Value *Op;
3434 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3435 // Op is trivially non-zero.
3436 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3437 return true;
3438
3439 // The condition of the select dominates the true/false arm. Check if the
3440 // condition implies that a given arm is non-zero.
3441 Value *X;
3442 CmpPredicate Pred;
3443 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3444 return false;
3445
3446 if (!IsTrueArm)
3447 Pred = ICmpInst::getInversePredicate(Pred);
3448
3449 return cmpExcludesZero(Pred, X);
3450 };
3451
3452 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3453 SelectArmIsNonZero(/* IsTrueArm */ false))
3454 return true;
3455 break;
3456 }
3457 case Instruction::PHI: {
3458 auto *PN = cast<PHINode>(I);
3460 return true;
3461
3462 // Check if all incoming values are non-zero using recursion.
3464 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3465 return llvm::all_of(PN->operands(), [&](const Use &U) {
3466 if (U.get() == PN)
3467 return true;
3468 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3469 // Check if the branch on the phi excludes zero.
3470 CmpPredicate Pred;
3471 Value *X;
3472 BasicBlock *TrueSucc, *FalseSucc;
3473 if (match(RecQ.CxtI,
3474 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3475 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3476 // Check for cases of duplicate successors.
3477 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3478 // If we're using the false successor, invert the predicate.
3479 if (FalseSucc == PN->getParent())
3480 Pred = CmpInst::getInversePredicate(Pred);
3481 if (cmpExcludesZero(Pred, X))
3482 return true;
3483 }
3484 }
3485 // Finally recurse on the edge and check it directly.
3486 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3487 });
3488 }
3489 case Instruction::InsertElement: {
3490 if (isa<ScalableVectorType>(I->getType()))
3491 break;
3492
3493 const Value *Vec = I->getOperand(0);
3494 const Value *Elt = I->getOperand(1);
3495 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3496
3497 unsigned NumElts = DemandedElts.getBitWidth();
3498 APInt DemandedVecElts = DemandedElts;
3499 bool SkipElt = false;
3500 // If we know the index we are inserting too, clear it from Vec check.
3501 if (CIdx && CIdx->getValue().ult(NumElts)) {
3502 DemandedVecElts.clearBit(CIdx->getZExtValue());
3503 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3504 }
3505
3506 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3507 // are non-zero.
3508 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3509 (DemandedVecElts.isZero() ||
3510 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3511 }
3512 case Instruction::ExtractElement:
3513 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3514 const Value *Vec = EEI->getVectorOperand();
3515 const Value *Idx = EEI->getIndexOperand();
3516 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3517 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3518 unsigned NumElts = VecTy->getNumElements();
3519 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3520 if (CIdx && CIdx->getValue().ult(NumElts))
3521 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3522 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3523 }
3524 }
3525 break;
3526 case Instruction::ShuffleVector: {
3527 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3528 if (!Shuf)
3529 break;
3530 APInt DemandedLHS, DemandedRHS;
3531 // For undef elements, we don't know anything about the common state of
3532 // the shuffle result.
3533 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3534 break;
3535 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3536 return (DemandedRHS.isZero() ||
3537 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3538 (DemandedLHS.isZero() ||
3539 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3540 }
3541 case Instruction::Freeze:
3542 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3543 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3544 Depth);
3545 case Instruction::Load: {
3546 auto *LI = cast<LoadInst>(I);
3547 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3548 // is never null.
3549 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3550 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3551 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3552 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3553 return true;
3554 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3556 }
3557
3558 // No need to fall through to computeKnownBits as range metadata is already
3559 // handled in isKnownNonZero.
3560 return false;
3561 }
3562 case Instruction::ExtractValue: {
3563 const WithOverflowInst *WO;
3565 switch (WO->getBinaryOp()) {
3566 default:
3567 break;
3568 case Instruction::Add:
3569 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3570 WO->getArgOperand(1),
3571 /*NSW=*/false,
3572 /*NUW=*/false, Depth);
3573 case Instruction::Sub:
3574 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3575 WO->getArgOperand(1), Depth);
3576 case Instruction::Mul:
3577 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3578 WO->getArgOperand(1),
3579 /*NSW=*/false, /*NUW=*/false, Depth);
3580 break;
3581 }
3582 }
3583 break;
3584 }
3585 case Instruction::Call:
3586 case Instruction::Invoke: {
3587 const auto *Call = cast<CallBase>(I);
3588 if (I->getType()->isPointerTy()) {
3589 if (Call->isReturnNonNull())
3590 return true;
3591 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3592 Call, /*MustPreserveOffset=*/true))
3593 return isKnownNonZero(RP, Q, Depth);
3594 } else {
3595 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3597 if (std::optional<ConstantRange> Range = Call->getRange()) {
3598 const APInt ZeroValue(Range->getBitWidth(), 0);
3599 if (!Range->contains(ZeroValue))
3600 return true;
3601 }
3602 if (const Value *RV = Call->getReturnedArgOperand())
3603 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3604 return true;
3605 }
3606
3607 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3608 switch (II->getIntrinsicID()) {
3609 case Intrinsic::sshl_sat:
3610 case Intrinsic::ushl_sat:
3611 case Intrinsic::abs:
3612 case Intrinsic::bitreverse:
3613 case Intrinsic::bswap:
3614 case Intrinsic::ctpop:
3615 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3616 // NB: We don't do usub_sat here as in any case we can prove its
3617 // non-zero, we will fold it to `sub nuw` in InstCombine.
3618 case Intrinsic::ssub_sat:
3619 // For most types, if x != y then ssub.sat x, y != 0. But
3620 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3621 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3622 if (BitWidth == 1)
3623 return false;
3624 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3625 II->getArgOperand(1), Depth);
3626 case Intrinsic::sadd_sat:
3627 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3628 II->getArgOperand(1),
3629 /*NSW=*/true, /* NUW=*/false, Depth);
3630 // Vec reverse preserves zero/non-zero status from input vec.
3631 case Intrinsic::vector_reverse:
3632 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3633 Q, Depth);
3634 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3635 case Intrinsic::vector_reduce_or:
3636 case Intrinsic::vector_reduce_umax:
3637 case Intrinsic::vector_reduce_umin:
3638 case Intrinsic::vector_reduce_smax:
3639 case Intrinsic::vector_reduce_smin:
3640 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3641 case Intrinsic::umax:
3642 case Intrinsic::uadd_sat:
3643 // umax(X, (X != 0)) is non zero
3644 // X +usat (X != 0) is non zero
3645 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3646 return true;
3647
3648 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3649 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3650 case Intrinsic::smax: {
3651 // If either arg is strictly positive the result is non-zero. Otherwise
3652 // the result is non-zero if both ops are non-zero.
3653 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3654 const KnownBits &OpKnown) {
3655 if (!OpNonZero.has_value())
3656 OpNonZero = OpKnown.isNonZero() ||
3657 isKnownNonZero(Op, DemandedElts, Q, Depth);
3658 return *OpNonZero;
3659 };
3660 // Avoid re-computing isKnownNonZero.
3661 std::optional<bool> Op0NonZero, Op1NonZero;
3662 KnownBits Op1Known =
3663 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3664 if (Op1Known.isNonNegative() &&
3665 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3666 return true;
3667 KnownBits Op0Known =
3668 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3669 if (Op0Known.isNonNegative() &&
3670 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3671 return true;
3672 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3673 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3674 }
3675 case Intrinsic::smin: {
3676 // If either arg is negative the result is non-zero. Otherwise
3677 // the result is non-zero if both ops are non-zero.
3678 KnownBits Op1Known =
3679 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3680 if (Op1Known.isNegative())
3681 return true;
3682 KnownBits Op0Known =
3683 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3684 if (Op0Known.isNegative())
3685 return true;
3686
3687 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3688 return true;
3689 }
3690 [[fallthrough]];
3691 case Intrinsic::umin:
3692 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3693 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3694 case Intrinsic::cttz:
3695 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3696 .Zero[0];
3697 case Intrinsic::ctlz:
3698 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3699 .isNonNegative();
3700 case Intrinsic::fshr:
3701 case Intrinsic::fshl:
3702 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3703 if (II->getArgOperand(0) == II->getArgOperand(1))
3704 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3705 break;
3706 case Intrinsic::vscale:
3707 return true;
3708 case Intrinsic::experimental_get_vector_length:
3709 return isKnownNonZero(I->getOperand(0), Q, Depth);
3710 default:
3711 break;
3712 }
3713 break;
3714 }
3715
3716 return false;
3717 }
3718 }
3719
3721 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3722 return Known.One != 0;
3723}
3724
3725/// Return true if the given value is known to be non-zero when defined. For
3726/// vectors, return true if every demanded element is known to be non-zero when
3727/// defined. For pointers, if the context instruction and dominator tree are
3728/// specified, perform context-sensitive analysis and return true if the
3729/// pointer couldn't possibly be null at the specified instruction.
3730/// Supports values with integer or pointer type and vectors of integers.
3731bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3732 const SimplifyQuery &Q, unsigned Depth) {
3733 Type *Ty = V->getType();
3734
3735#ifndef NDEBUG
3736 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3737
3738 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3739 assert(
3740 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3741 "DemandedElt width should equal the fixed vector number of elements");
3742 } else {
3743 assert(DemandedElts == APInt(1, 1) &&
3744 "DemandedElt width should be 1 for scalars");
3745 }
3746#endif
3747
3748 if (auto *C = dyn_cast<Constant>(V)) {
3749 if (C->isNullValue())
3750 return false;
3751 if (isa<ConstantInt>(C))
3752 // Must be non-zero due to null test above.
3753 return true;
3754
3755 // For constant vectors, check that all elements are poison or known
3756 // non-zero to determine that the whole vector is known non-zero.
3757 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3758 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3759 if (!DemandedElts[i])
3760 continue;
3761 Constant *Elt = C->getAggregateElement(i);
3762 if (!Elt || Elt->isNullValue())
3763 return false;
3764 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3765 return false;
3766 }
3767 return true;
3768 }
3769
3770 // Constant ptrauth can be null, iff the base pointer can be.
3771 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3772 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3773
3774 // A global variable in address space 0 is non null unless extern weak
3775 // or an absolute symbol reference. Other address spaces may have null as a
3776 // valid address for a global, so we can't assume anything.
3777 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3778 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3779 GV->getType()->getAddressSpace() == 0)
3780 return true;
3781 }
3782
3783 // For constant expressions, fall through to the Operator code below.
3784 if (!isa<ConstantExpr>(V))
3785 return false;
3786 }
3787
3788 if (const auto *A = dyn_cast<Argument>(V))
3789 if (std::optional<ConstantRange> Range = A->getRange()) {
3790 const APInt ZeroValue(Range->getBitWidth(), 0);
3791 if (!Range->contains(ZeroValue))
3792 return true;
3793 }
3794
3795 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3796 return true;
3797
3798 // Some of the tests below are recursive, so bail out if we hit the limit.
3800 return false;
3801
3802 // Check for pointer simplifications.
3803
3804 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3805 // A byval, inalloca may not be null in a non-default addres space. A
3806 // nonnull argument is assumed never 0.
3807 if (const Argument *A = dyn_cast<Argument>(V)) {
3808 if (((A->hasPassPointeeByValueCopyAttr() &&
3809 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3810 A->hasNonNullAttr()))
3811 return true;
3812 }
3813 }
3814
3815 if (const auto *I = dyn_cast<Operator>(V))
3816 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3817 return true;
3818
3819 if (!isa<Constant>(V) &&
3821 return true;
3822
3823 if (const Value *Stripped = stripNullTest(V))
3824 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3825
3826 return false;
3827}
3828
3830 unsigned Depth) {
3831 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3832 APInt DemandedElts =
3833 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3834 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3835}
3836
3837/// If the pair of operators are the same invertible function, return the
3838/// the operands of the function corresponding to each input. Otherwise,
3839/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3840/// every input value to exactly one output value. This is equivalent to
3841/// saying that Op1 and Op2 are equal exactly when the specified pair of
3842/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3843static std::optional<std::pair<Value*, Value*>>
3845 const Operator *Op2) {
3846 if (Op1->getOpcode() != Op2->getOpcode())
3847 return std::nullopt;
3848
3849 auto getOperands = [&](unsigned OpNum) -> auto {
3850 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3851 };
3852
3853 switch (Op1->getOpcode()) {
3854 default:
3855 break;
3856 case Instruction::Or:
3857 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3858 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3859 break;
3860 [[fallthrough]];
3861 case Instruction::Xor:
3862 case Instruction::Add: {
3863 Value *Other;
3864 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3865 return std::make_pair(Op1->getOperand(1), Other);
3866 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3867 return std::make_pair(Op1->getOperand(0), Other);
3868 break;
3869 }
3870 case Instruction::Sub:
3871 if (Op1->getOperand(0) == Op2->getOperand(0))
3872 return getOperands(1);
3873 if (Op1->getOperand(1) == Op2->getOperand(1))
3874 return getOperands(0);
3875 break;
3876 case Instruction::Mul: {
3877 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3878 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3879 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3880 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3881 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3882 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3883 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3884 break;
3885
3886 // Assume operand order has been canonicalized
3887 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3888 isa<ConstantInt>(Op1->getOperand(1)) &&
3889 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3890 return getOperands(0);
3891 break;
3892 }
3893 case Instruction::Shl: {
3894 // Same as multiplies, with the difference that we don't need to check
3895 // for a non-zero multiply. Shifts always multiply by non-zero.
3896 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3897 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3898 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3899 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3900 break;
3901
3902 if (Op1->getOperand(1) == Op2->getOperand(1))
3903 return getOperands(0);
3904 break;
3905 }
3906 case Instruction::AShr:
3907 case Instruction::LShr: {
3908 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3909 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3910 if (!PEO1->isExact() || !PEO2->isExact())
3911 break;
3912
3913 if (Op1->getOperand(1) == Op2->getOperand(1))
3914 return getOperands(0);
3915 break;
3916 }
3917 case Instruction::SExt:
3918 case Instruction::ZExt:
3919 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3920 return getOperands(0);
3921 break;
3922 case Instruction::PHI: {
3923 const PHINode *PN1 = cast<PHINode>(Op1);
3924 const PHINode *PN2 = cast<PHINode>(Op2);
3925
3926 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3927 // are a single invertible function of the start values? Note that repeated
3928 // application of an invertible function is also invertible
3929 BinaryOperator *BO1 = nullptr;
3930 Value *Start1 = nullptr, *Step1 = nullptr;
3931 BinaryOperator *BO2 = nullptr;
3932 Value *Start2 = nullptr, *Step2 = nullptr;
3933 if (PN1->getParent() != PN2->getParent() ||
3934 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3935 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3936 break;
3937
3939 cast<Operator>(BO2));
3940 if (!Values)
3941 break;
3942
3943 // We have to be careful of mutually defined recurrences here. Ex:
3944 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3945 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3946 // The invertibility of these is complicated, and not worth reasoning
3947 // about (yet?).
3948 if (Values->first != PN1 || Values->second != PN2)
3949 break;
3950
3951 return std::make_pair(Start1, Start2);
3952 }
3953 }
3954 return std::nullopt;
3955}
3956
3957/// Return true if V1 == (binop V2, X), where X is known non-zero.
3958/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3959/// implies V2 != V1.
3960static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3961 const APInt &DemandedElts,
3962 const SimplifyQuery &Q, unsigned Depth) {
3964 if (!BO)
3965 return false;
3966 switch (BO->getOpcode()) {
3967 default:
3968 break;
3969 case Instruction::Or:
3970 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3971 break;
3972 [[fallthrough]];
3973 case Instruction::Xor:
3974 case Instruction::Add:
3975 Value *Op = nullptr;
3976 if (V2 == BO->getOperand(0))
3977 Op = BO->getOperand(1);
3978 else if (V2 == BO->getOperand(1))
3979 Op = BO->getOperand(0);
3980 else
3981 return false;
3982 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3983 }
3984 return false;
3985}
3986
3987/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3988/// the multiplication is nuw or nsw.
3989static bool isNonEqualMul(const Value *V1, const Value *V2,
3990 const APInt &DemandedElts, const SimplifyQuery &Q,
3991 unsigned Depth) {
3992 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3993 const APInt *C;
3994 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
3995 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3996 !C->isZero() && !C->isOne() &&
3997 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3998 }
3999 return false;
4000}
4001
4002/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4003/// the shift is nuw or nsw.
4004static bool isNonEqualShl(const Value *V1, const Value *V2,
4005 const APInt &DemandedElts, const SimplifyQuery &Q,
4006 unsigned Depth) {
4007 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4008 const APInt *C;
4009 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4010 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4011 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4012 }
4013 return false;
4014}
4015
4016static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4017 const APInt &DemandedElts, const SimplifyQuery &Q,
4018 unsigned Depth) {
4019 // Check two PHIs are in same block.
4020 if (PN1->getParent() != PN2->getParent())
4021 return false;
4022
4024 bool UsedFullRecursion = false;
4025 for (const BasicBlock *IncomBB : PN1->blocks()) {
4026 if (!VisitedBBs.insert(IncomBB).second)
4027 continue; // Don't reprocess blocks that we have dealt with already.
4028 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4029 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4030 const APInt *C1, *C2;
4031 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4032 continue;
4033
4034 // Only one pair of phi operands is allowed for full recursion.
4035 if (UsedFullRecursion)
4036 return false;
4037
4039 RecQ.CxtI = IncomBB->getTerminator();
4040 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4041 return false;
4042 UsedFullRecursion = true;
4043 }
4044 return true;
4045}
4046
4047static bool isNonEqualSelect(const Value *V1, const Value *V2,
4048 const APInt &DemandedElts, const SimplifyQuery &Q,
4049 unsigned Depth) {
4050 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4051 if (!SI1)
4052 return false;
4053
4054 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4055 const Value *Cond1 = SI1->getCondition();
4056 const Value *Cond2 = SI2->getCondition();
4057 if (Cond1 == Cond2)
4058 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4059 DemandedElts, Q, Depth + 1) &&
4060 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4061 DemandedElts, Q, Depth + 1);
4062 }
4063 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4064 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4065}
4066
4067// Check to see if A is both a GEP and is the incoming value for a PHI in the
4068// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4069// one of them being the recursive GEP A and the other a ptr at same base and at
4070// the same/higher offset than B we are only incrementing the pointer further in
4071// loop if offset of recursive GEP is greater than 0.
4073 const SimplifyQuery &Q) {
4074 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4075 return false;
4076
4077 auto *GEPA = dyn_cast<GEPOperator>(A);
4078 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4079 return false;
4080
4081 // Handle 2 incoming PHI values with one being a recursive GEP.
4082 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4083 if (!PN || PN->getNumIncomingValues() != 2)
4084 return false;
4085
4086 // Search for the recursive GEP as an incoming operand, and record that as
4087 // Step.
4088 Value *Start = nullptr;
4089 Value *Step = const_cast<Value *>(A);
4090 if (PN->getIncomingValue(0) == Step)
4091 Start = PN->getIncomingValue(1);
4092 else if (PN->getIncomingValue(1) == Step)
4093 Start = PN->getIncomingValue(0);
4094 else
4095 return false;
4096
4097 // Other incoming node base should match the B base.
4098 // StartOffset >= OffsetB && StepOffset > 0?
4099 // StartOffset <= OffsetB && StepOffset < 0?
4100 // Is non-equal if above are true.
4101 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4102 // optimisation to inbounds GEPs only.
4103 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4104 APInt StartOffset(IndexWidth, 0);
4105 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4106 APInt StepOffset(IndexWidth, 0);
4107 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4108
4109 // Check if Base Pointer of Step matches the PHI.
4110 if (Step != PN)
4111 return false;
4112 APInt OffsetB(IndexWidth, 0);
4113 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4114 return Start == B &&
4115 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4116 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4117}
4118
4119static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4120 const SimplifyQuery &Q, unsigned Depth) {
4121 if (!Q.CxtI)
4122 return false;
4123
4124 // Try to infer NonEqual based on information from dominating conditions.
4125 if (Q.DC && Q.DT) {
4126 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4127 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4128 Value *Cond = BI->getCondition();
4129 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4130 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4132 /*LHSIsTrue=*/true, Depth)
4133 .value_or(false))
4134 return true;
4135
4136 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4137 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4139 /*LHSIsTrue=*/false, Depth)
4140 .value_or(false))
4141 return true;
4142 }
4143
4144 return false;
4145 };
4146
4147 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4148 IsKnownNonEqualFromDominatingCondition(V2))
4149 return true;
4150 }
4151
4152 if (!Q.AC)
4153 return false;
4154
4155 // Try to infer NonEqual based on information from assumptions.
4156 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4157 if (!AssumeVH)
4158 continue;
4159 CallInst *I = cast<CallInst>(AssumeVH);
4160
4161 assert(I->getFunction() == Q.CxtI->getFunction() &&
4162 "Got assumption for the wrong function!");
4163 assert(I->getIntrinsicID() == Intrinsic::assume &&
4164 "must be an assume intrinsic");
4165
4166 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4167 /*LHSIsTrue=*/true, Depth)
4168 .value_or(false) &&
4170 return true;
4171 }
4172
4173 return false;
4174}
4175
4176/// Return true if it is known that V1 != V2.
4177static bool isKnownNonEqual(const Value *V1, const Value *V2,
4178 const APInt &DemandedElts, const SimplifyQuery &Q,
4179 unsigned Depth) {
4180 if (V1 == V2)
4181 return false;
4182 if (V1->getType() != V2->getType())
4183 // We can't look through casts yet.
4184 return false;
4185
4187 return false;
4188
4189 // See if we can recurse through (exactly one of) our operands. This
4190 // requires our operation be 1-to-1 and map every input value to exactly
4191 // one output value. Such an operation is invertible.
4192 auto *O1 = dyn_cast<Operator>(V1);
4193 auto *O2 = dyn_cast<Operator>(V2);
4194 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4195 if (auto Values = getInvertibleOperands(O1, O2))
4196 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4197 Depth + 1);
4198
4199 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4200 const PHINode *PN2 = cast<PHINode>(V2);
4201 // FIXME: This is missing a generalization to handle the case where one is
4202 // a PHI and another one isn't.
4203 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4204 return true;
4205 };
4206 }
4207
4208 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4209 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4210 return true;
4211
4212 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4213 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4214 return true;
4215
4216 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4217 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4218 return true;
4219
4220 if (V1->getType()->isIntOrIntVectorTy()) {
4221 // Are any known bits in V1 contradictory to known bits in V2? If V1
4222 // has a known zero where V2 has a known one, they must not be equal.
4223 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4224 if (!Known1.isUnknown()) {
4225 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4226 if (Known1.Zero.intersects(Known2.One) ||
4227 Known2.Zero.intersects(Known1.One))
4228 return true;
4229 }
4230 }
4231
4232 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4233 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4234 return true;
4235
4238 return true;
4239
4240 Value *A, *B;
4241 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4242 // Check PtrToInt type matches the pointer size.
4243 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4245 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4246
4247 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4248 return true;
4249
4250 return false;
4251}
4252
4253/// For vector constants, loop over the elements and find the constant with the
4254/// minimum number of sign bits. Return 0 if the value is not a vector constant
4255/// or if any element was not analyzed; otherwise, return the count for the
4256/// element with the minimum number of sign bits.
4258 const APInt &DemandedElts,
4259 unsigned TyBits) {
4260 const auto *CV = dyn_cast<Constant>(V);
4261 if (!CV || !isa<FixedVectorType>(CV->getType()))
4262 return 0;
4263
4264 unsigned MinSignBits = TyBits;
4265 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4266 for (unsigned i = 0; i != NumElts; ++i) {
4267 if (!DemandedElts[i])
4268 continue;
4269 // If we find a non-ConstantInt, bail out.
4270 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4271 if (!Elt)
4272 return 0;
4273
4274 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4275 }
4276
4277 return MinSignBits;
4278}
4279
4280static unsigned ComputeNumSignBitsImpl(const Value *V,
4281 const APInt &DemandedElts,
4282 const SimplifyQuery &Q, unsigned Depth);
4283
4284static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4285 const SimplifyQuery &Q, unsigned Depth) {
4286 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4287 assert(Result > 0 && "At least one sign bit needs to be present!");
4288 return Result;
4289}
4290
4291/// Return the number of times the sign bit of the register is replicated into
4292/// the other bits. We know that at least 1 bit is always equal to the sign bit
4293/// (itself), but other cases can give us information. For example, immediately
4294/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4295/// other, so we return 3. For vectors, return the number of sign bits for the
4296/// vector element with the minimum number of known sign bits of the demanded
4297/// elements in the vector specified by DemandedElts.
4298static unsigned ComputeNumSignBitsImpl(const Value *V,
4299 const APInt &DemandedElts,
4300 const SimplifyQuery &Q, unsigned Depth) {
4301 Type *Ty = V->getType();
4302#ifndef NDEBUG
4303 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4304
4305 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4306 assert(
4307 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4308 "DemandedElt width should equal the fixed vector number of elements");
4309 } else {
4310 assert(DemandedElts == APInt(1, 1) &&
4311 "DemandedElt width should be 1 for scalars");
4312 }
4313#endif
4314
4315 // We return the minimum number of sign bits that are guaranteed to be present
4316 // in V, so for undef we have to conservatively return 1. We don't have the
4317 // same behavior for poison though -- that's a FIXME today.
4318
4319 Type *ScalarTy = Ty->getScalarType();
4320 unsigned TyBits = ScalarTy->isPointerTy() ?
4321 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4322 Q.DL.getTypeSizeInBits(ScalarTy);
4323
4324 unsigned Tmp, Tmp2;
4325 unsigned FirstAnswer = 1;
4326
4327 // Note that ConstantInt is handled by the general computeKnownBits case
4328 // below.
4329
4331 return 1;
4332
4333 if (auto *U = dyn_cast<Operator>(V)) {
4334 switch (Operator::getOpcode(V)) {
4335 default: break;
4336 case Instruction::BitCast: {
4337 Value *Src = U->getOperand(0);
4338 Type *SrcTy = Src->getType();
4339
4340 // Skip if the source type is not an integer or integer vector type
4341 // This ensures we only process integer-like types
4342 if (!SrcTy->isIntOrIntVectorTy())
4343 break;
4344
4345 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4346
4347 // Bitcast 'large element' scalar/vector to 'small element' vector.
4348 if ((SrcBits % TyBits) != 0)
4349 break;
4350
4351 // Only proceed if the destination type is a fixed-size vector
4352 if (isa<FixedVectorType>(Ty)) {
4353 // Fast case - sign splat can be simply split across the small elements.
4354 // This works for both vector and scalar sources
4355 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4356 if (Tmp == SrcBits)
4357 return TyBits;
4358 }
4359 break;
4360 }
4361 case Instruction::SExt:
4362 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4363 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4364 Tmp;
4365
4366 case Instruction::SDiv: {
4367 const APInt *Denominator;
4368 // sdiv X, C -> adds log(C) sign bits.
4369 if (match(U->getOperand(1), m_APInt(Denominator))) {
4370
4371 // Ignore non-positive denominator.
4372 if (!Denominator->isStrictlyPositive())
4373 break;
4374
4375 // Calculate the incoming numerator bits.
4376 unsigned NumBits =
4377 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4378
4379 // Add floor(log(C)) bits to the numerator bits.
4380 return std::min(TyBits, NumBits + Denominator->logBase2());
4381 }
4382 break;
4383 }
4384
4385 case Instruction::SRem: {
4386 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4387
4388 const APInt *Denominator;
4389 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4390 // positive constant. This let us put a lower bound on the number of sign
4391 // bits.
4392 if (match(U->getOperand(1), m_APInt(Denominator))) {
4393
4394 // Ignore non-positive denominator.
4395 if (Denominator->isStrictlyPositive()) {
4396 // Calculate the leading sign bit constraints by examining the
4397 // denominator. Given that the denominator is positive, there are two
4398 // cases:
4399 //
4400 // 1. The numerator is positive. The result range is [0,C) and
4401 // [0,C) u< (1 << ceilLogBase2(C)).
4402 //
4403 // 2. The numerator is negative. Then the result range is (-C,0] and
4404 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4405 //
4406 // Thus a lower bound on the number of sign bits is `TyBits -
4407 // ceilLogBase2(C)`.
4408
4409 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4410 Tmp = std::max(Tmp, ResBits);
4411 }
4412 }
4413 return Tmp;
4414 }
4415
4416 case Instruction::AShr: {
4417 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4418 // ashr X, C -> adds C sign bits. Vectors too.
4419 const APInt *ShAmt;
4420 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4421 if (ShAmt->uge(TyBits))
4422 break; // Bad shift.
4423 unsigned ShAmtLimited = ShAmt->getZExtValue();
4424 Tmp += ShAmtLimited;
4425 if (Tmp > TyBits) Tmp = TyBits;
4426 }
4427 return Tmp;
4428 }
4429 case Instruction::Shl: {
4430 const APInt *ShAmt;
4431 Value *X = nullptr;
4432 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4433 // shl destroys sign bits.
4434 if (ShAmt->uge(TyBits))
4435 break; // Bad shift.
4436 // We can look through a zext (more or less treating it as a sext) if
4437 // all extended bits are shifted out.
4438 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4439 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4440 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4441 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4442 } else
4443 Tmp =
4444 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4445 if (ShAmt->uge(Tmp))
4446 break; // Shifted all sign bits out.
4447 Tmp2 = ShAmt->getZExtValue();
4448 return Tmp - Tmp2;
4449 }
4450 break;
4451 }
4452 case Instruction::And:
4453 case Instruction::Or:
4454 case Instruction::Xor: // NOT is handled here.
4455 // Logical binary ops preserve the number of sign bits at the worst.
4456 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4457 if (Tmp != 1) {
4458 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4459 FirstAnswer = std::min(Tmp, Tmp2);
4460 // We computed what we know about the sign bits as our first
4461 // answer. Now proceed to the generic code that uses
4462 // computeKnownBits, and pick whichever answer is better.
4463 }
4464 break;
4465
4466 case Instruction::Select: {
4467 // If we have a clamp pattern, we know that the number of sign bits will
4468 // be the minimum of the clamp min/max range.
4469 const Value *X;
4470 const APInt *CLow, *CHigh;
4471 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4472 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4473
4474 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4475 if (Tmp == 1)
4476 break;
4477 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4478 return std::min(Tmp, Tmp2);
4479 }
4480
4481 case Instruction::Add:
4482 // Add can have at most one carry bit. Thus we know that the output
4483 // is, at worst, one more bit than the inputs.
4484 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4485 if (Tmp == 1) break;
4486
4487 // Special case decrementing a value (ADD X, -1):
4488 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4489 if (CRHS->isAllOnesValue()) {
4490 KnownBits Known(TyBits);
4491 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4492
4493 // If the input is known to be 0 or 1, the output is 0/-1, which is
4494 // all sign bits set.
4495 if ((Known.Zero | 1).isAllOnes())
4496 return TyBits;
4497
4498 // If we are subtracting one from a positive number, there is no carry
4499 // out of the result.
4500 if (Known.isNonNegative())
4501 return Tmp;
4502 }
4503
4504 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4505 if (Tmp2 == 1)
4506 break;
4507 return std::min(Tmp, Tmp2) - 1;
4508
4509 case Instruction::Sub:
4510 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4511 if (Tmp2 == 1)
4512 break;
4513
4514 // Handle NEG.
4515 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4516 if (CLHS->isNullValue()) {
4517 KnownBits Known(TyBits);
4518 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4519 // If the input is known to be 0 or 1, the output is 0/-1, which is
4520 // all sign bits set.
4521 if ((Known.Zero | 1).isAllOnes())
4522 return TyBits;
4523
4524 // If the input is known to be positive (the sign bit is known clear),
4525 // the output of the NEG has the same number of sign bits as the
4526 // input.
4527 if (Known.isNonNegative())
4528 return Tmp2;
4529
4530 // Otherwise, we treat this like a SUB.
4531 }
4532
4533 // Sub can have at most one carry bit. Thus we know that the output
4534 // is, at worst, one more bit than the inputs.
4535 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4536 if (Tmp == 1)
4537 break;
4538 return std::min(Tmp, Tmp2) - 1;
4539
4540 case Instruction::Mul: {
4541 // The output of the Mul can be at most twice the valid bits in the
4542 // inputs.
4543 unsigned SignBitsOp0 =
4544 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4545 if (SignBitsOp0 == 1)
4546 break;
4547 unsigned SignBitsOp1 =
4548 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4549 if (SignBitsOp1 == 1)
4550 break;
4551 unsigned OutValidBits =
4552 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4553 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4554 }
4555
4556 case Instruction::PHI: {
4557 const PHINode *PN = cast<PHINode>(U);
4558 unsigned NumIncomingValues = PN->getNumIncomingValues();
4559 // Don't analyze large in-degree PHIs.
4560 if (NumIncomingValues > 4) break;
4561 // Unreachable blocks may have zero-operand PHI nodes.
4562 if (NumIncomingValues == 0) break;
4563
4564 // Take the minimum of all incoming values. This can't infinitely loop
4565 // because of our depth threshold.
4567 Tmp = TyBits;
4568 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4569 if (Tmp == 1) return Tmp;
4570 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4571 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4572 DemandedElts, RecQ, Depth + 1));
4573 }
4574 return Tmp;
4575 }
4576
4577 case Instruction::Trunc: {
4578 // If the input contained enough sign bits that some remain after the
4579 // truncation, then we can make use of that. Otherwise we don't know
4580 // anything.
4581 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4582 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4583 if (Tmp > (OperandTyBits - TyBits))
4584 return Tmp - (OperandTyBits - TyBits);
4585
4586 return 1;
4587 }
4588
4589 case Instruction::ExtractElement:
4590 // Look through extract element. At the moment we keep this simple and
4591 // skip tracking the specific element. But at least we might find
4592 // information valid for all elements of the vector (for example if vector
4593 // is sign extended, shifted, etc).
4594 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4595
4596 case Instruction::ShuffleVector: {
4597 // Collect the minimum number of sign bits that are shared by every vector
4598 // element referenced by the shuffle.
4599 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4600 if (!Shuf) {
4601 // FIXME: Add support for shufflevector constant expressions.
4602 return 1;
4603 }
4604 APInt DemandedLHS, DemandedRHS;
4605 // For undef elements, we don't know anything about the common state of
4606 // the shuffle result.
4607 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4608 return 1;
4609 Tmp = std::numeric_limits<unsigned>::max();
4610 if (!!DemandedLHS) {
4611 const Value *LHS = Shuf->getOperand(0);
4612 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4613 }
4614 // If we don't know anything, early out and try computeKnownBits
4615 // fall-back.
4616 if (Tmp == 1)
4617 break;
4618 if (!!DemandedRHS) {
4619 const Value *RHS = Shuf->getOperand(1);
4620 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4621 Tmp = std::min(Tmp, Tmp2);
4622 }
4623 // If we don't know anything, early out and try computeKnownBits
4624 // fall-back.
4625 if (Tmp == 1)
4626 break;
4627 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4628 return Tmp;
4629 }
4630 case Instruction::Call: {
4631 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4632 switch (II->getIntrinsicID()) {
4633 default:
4634 break;
4635 case Intrinsic::abs:
4636 Tmp =
4637 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4638 if (Tmp == 1)
4639 break;
4640
4641 // Absolute value reduces number of sign bits by at most 1.
4642 return Tmp - 1;
4643 case Intrinsic::smin:
4644 case Intrinsic::smax: {
4645 const APInt *CLow, *CHigh;
4646 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4647 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4648 }
4649 }
4650 }
4651 }
4652 }
4653 }
4654
4655 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4656 // use this information.
4657
4658 // If we can examine all elements of a vector constant successfully, we're
4659 // done (we can't do any better than that). If not, keep trying.
4660 if (unsigned VecSignBits =
4661 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4662 return VecSignBits;
4663
4664 KnownBits Known(TyBits);
4665 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4666
4667 // If we know that the sign bit is either zero or one, determine the number of
4668 // identical bits in the top of the input value.
4669 return std::max(FirstAnswer, Known.countMinSignBits());
4670}
4671
4673 const TargetLibraryInfo *TLI) {
4674 const Function *F = CB.getCalledFunction();
4675 if (!F)
4677
4678 if (F->isIntrinsic())
4679 return F->getIntrinsicID();
4680
4681 // We are going to infer semantics of a library function based on mapping it
4682 // to an LLVM intrinsic. Check that the library function is available from
4683 // this callbase and in this environment.
4684 LibFunc Func;
4685 if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
4686 !CB.onlyReadsMemory())
4688
4689 switch (Func) {
4690 default:
4691 break;
4692 case LibFunc_sin:
4693 case LibFunc_sinf:
4694 case LibFunc_sinl:
4695 return Intrinsic::sin;
4696 case LibFunc_cos:
4697 case LibFunc_cosf:
4698 case LibFunc_cosl:
4699 return Intrinsic::cos;
4700 case LibFunc_tan:
4701 case LibFunc_tanf:
4702 case LibFunc_tanl:
4703 return Intrinsic::tan;
4704 case LibFunc_asin:
4705 case LibFunc_asinf:
4706 case LibFunc_asinl:
4707 return Intrinsic::asin;
4708 case LibFunc_acos:
4709 case LibFunc_acosf:
4710 case LibFunc_acosl:
4711 return Intrinsic::acos;
4712 case LibFunc_atan:
4713 case LibFunc_atanf:
4714 case LibFunc_atanl:
4715 return Intrinsic::atan;
4716 case LibFunc_atan2:
4717 case LibFunc_atan2f:
4718 case LibFunc_atan2l:
4719 return Intrinsic::atan2;
4720 case LibFunc_sinh:
4721 case LibFunc_sinhf:
4722 case LibFunc_sinhl:
4723 return Intrinsic::sinh;
4724 case LibFunc_cosh:
4725 case LibFunc_coshf:
4726 case LibFunc_coshl:
4727 return Intrinsic::cosh;
4728 case LibFunc_tanh:
4729 case LibFunc_tanhf:
4730 case LibFunc_tanhl:
4731 return Intrinsic::tanh;
4732 case LibFunc_exp:
4733 case LibFunc_expf:
4734 case LibFunc_expl:
4735 return Intrinsic::exp;
4736 case LibFunc_exp2:
4737 case LibFunc_exp2f:
4738 case LibFunc_exp2l:
4739 return Intrinsic::exp2;
4740 case LibFunc_exp10:
4741 case LibFunc_exp10f:
4742 case LibFunc_exp10l:
4743 return Intrinsic::exp10;
4744 case LibFunc_log:
4745 case LibFunc_logf:
4746 case LibFunc_logl:
4747 return Intrinsic::log;
4748 case LibFunc_log10:
4749 case LibFunc_log10f:
4750 case LibFunc_log10l:
4751 return Intrinsic::log10;
4752 case LibFunc_log2:
4753 case LibFunc_log2f:
4754 case LibFunc_log2l:
4755 return Intrinsic::log2;
4756 case LibFunc_fabs:
4757 case LibFunc_fabsf:
4758 case LibFunc_fabsl:
4759 return Intrinsic::fabs;
4760 case LibFunc_fmin:
4761 case LibFunc_fminf:
4762 case LibFunc_fminl:
4763 return Intrinsic::minnum;
4764 case LibFunc_fmax:
4765 case LibFunc_fmaxf:
4766 case LibFunc_fmaxl:
4767 return Intrinsic::maxnum;
4768 case LibFunc_copysign:
4769 case LibFunc_copysignf:
4770 case LibFunc_copysignl:
4771 return Intrinsic::copysign;
4772 case LibFunc_floor:
4773 case LibFunc_floorf:
4774 case LibFunc_floorl:
4775 return Intrinsic::floor;
4776 case LibFunc_ceil:
4777 case LibFunc_ceilf:
4778 case LibFunc_ceill:
4779 return Intrinsic::ceil;
4780 case LibFunc_trunc:
4781 case LibFunc_truncf:
4782 case LibFunc_truncl:
4783 return Intrinsic::trunc;
4784 case LibFunc_rint:
4785 case LibFunc_rintf:
4786 case LibFunc_rintl:
4787 return Intrinsic::rint;
4788 case LibFunc_nearbyint:
4789 case LibFunc_nearbyintf:
4790 case LibFunc_nearbyintl:
4791 return Intrinsic::nearbyint;
4792 case LibFunc_round:
4793 case LibFunc_roundf:
4794 case LibFunc_roundl:
4795 return Intrinsic::round;
4796 case LibFunc_roundeven:
4797 case LibFunc_roundevenf:
4798 case LibFunc_roundevenl:
4799 return Intrinsic::roundeven;
4800 case LibFunc_pow:
4801 case LibFunc_powf:
4802 case LibFunc_powl:
4803 return Intrinsic::pow;
4804 case LibFunc_sqrt:
4805 case LibFunc_sqrtf:
4806 case LibFunc_sqrtl:
4807 return Intrinsic::sqrt;
4808 }
4809
4811}
4812
4813/// Given an exploded icmp instruction, return true if the comparison only
4814/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4815/// the result of the comparison is true when the input value is signed.
4817 bool &TrueIfSigned) {
4818 switch (Pred) {
4819 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4820 TrueIfSigned = true;
4821 return RHS.isZero();
4822 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4823 TrueIfSigned = true;
4824 return RHS.isAllOnes();
4825 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4826 TrueIfSigned = false;
4827 return RHS.isAllOnes();
4828 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4829 TrueIfSigned = false;
4830 return RHS.isZero();
4831 case ICmpInst::ICMP_UGT:
4832 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4833 TrueIfSigned = true;
4834 return RHS.isMaxSignedValue();
4835 case ICmpInst::ICMP_UGE:
4836 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4837 TrueIfSigned = true;
4838 return RHS.isMinSignedValue();
4839 case ICmpInst::ICMP_ULT:
4840 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4841 TrueIfSigned = false;
4842 return RHS.isMinSignedValue();
4843 case ICmpInst::ICMP_ULE:
4844 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4845 TrueIfSigned = false;
4846 return RHS.isMaxSignedValue();
4847 default:
4848 return false;
4849 }
4850}
4851
4853 bool CondIsTrue,
4854 const Instruction *CxtI,
4855 KnownFPClass &KnownFromContext,
4856 unsigned Depth = 0) {
4857 Value *A, *B;
4859 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4860 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4861 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4862 Depth + 1);
4863 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4864 Depth + 1);
4865 return;
4866 }
4868 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4869 Depth + 1);
4870 return;
4871 }
4872 CmpPredicate Pred;
4873 Value *LHS;
4874 uint64_t ClassVal = 0;
4875 const APFloat *CRHS;
4876 const APInt *RHS;
4877 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4878 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4879 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4880 LHS != V);
4881 if (CmpVal == V)
4882 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4884 m_Specific(V), m_ConstantInt(ClassVal)))) {
4885 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4886 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4887 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4888 m_APInt(RHS)))) {
4889 bool TrueIfSigned;
4890 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4891 return;
4892 if (TrueIfSigned == CondIsTrue)
4893 KnownFromContext.signBitMustBeOne();
4894 else
4895 KnownFromContext.signBitMustBeZero();
4896 }
4897}
4898
4899/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4900/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4901/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4902/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4903/// exponent range is [-149, -2], but the 0 edge case is above this range).
4904static std::tuple<int, int, int>
4906 if (!Q.CxtI || !Q.DC || !Q.DT)
4908
4909 // Intersect the bounds implied by every dominating condition, keeping the
4910 // tightest maximum. A value may participate in multiple compares
4911 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4912 int MaxExp = APFloat::IEK_Inf;
4913 int MaxExpNonZero = APFloat::IEK_Inf;
4914
4915 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4916 CmpPredicate Pred;
4917 const APFloat *LimitC;
4918 if (!match(BI->getCondition(),
4919 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4920 continue;
4921
4922 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4923 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4924 continue;
4925
4926 // If fabs(x) <= K, implies the exponent min exp range.
4927 // if fabs(x) >= K, swap the successor
4928 bool IsLessEqual =
4929 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4930 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4931 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4932
4933 bool KnownStrictlyLess =
4934 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4935 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4936
4937 BasicBlockEdge Edge1(BI->getParent(),
4938 BI->getSuccessor(IsLessEqual ? 0 : 1));
4939 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4940 // frexp returns an exponent one greater than ilogb.
4941 int Exp = ilogb(*LimitC) + 1;
4942
4943 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4944 // exponent drops by one when K is exact power of two.
4945 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4946 --Exp;
4947
4948 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4949 // may exclude.
4950
4951 // TODO: Figure out lower bound to detect no-underflow.
4952 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4953 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4954 }
4955 }
4956
4957 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4958}
4959
4961 const SimplifyQuery &Q) {
4962 KnownFPClass KnownFromContext;
4963
4964 if (Q.CC && Q.CC->AffectedValues.contains(V))
4966 KnownFromContext);
4967
4968 if (!Q.CxtI)
4969 return KnownFromContext;
4970
4971 if (Q.DC && Q.DT) {
4972 // Handle dominating conditions.
4973 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4974 Value *Cond = BI->getCondition();
4975
4976 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4977 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
4978 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
4979 KnownFromContext);
4980
4981 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4982 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
4983 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
4984 KnownFromContext);
4985 }
4986 }
4987
4988 if (!Q.AC)
4989 return KnownFromContext;
4990
4991 // Try to restrict the floating-point classes based on information from
4992 // assumptions.
4993 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
4994 if (!AssumeVH)
4995 continue;
4996 CallInst *I = cast<CallInst>(AssumeVH);
4997
4998 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
4999 "Got assumption for the wrong function!");
5000 assert(I->getIntrinsicID() == Intrinsic::assume &&
5001 "must be an assume intrinsic");
5002
5003 if (!isValidAssumeForContext(I, Q))
5004 continue;
5005
5006 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5007 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5008 }
5009
5010 return KnownFromContext;
5011}
5012
5014 Value *Arm, bool Invert,
5015 const SimplifyQuery &SQ,
5016 unsigned Depth) {
5017
5018 KnownFPClass KnownSrc;
5020 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5021 Depth + 1);
5022 KnownSrc = KnownSrc.unionWith(Known);
5023 if (KnownSrc.isUnknown())
5024 return;
5025
5026 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5027 Known = KnownSrc;
5028}
5029
5030void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5031 FPClassTest InterestedClasses, KnownFPClass &Known,
5032 const SimplifyQuery &Q, unsigned Depth);
5033
5035 FPClassTest InterestedClasses,
5036 const SimplifyQuery &Q, unsigned Depth) {
5037 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5038 APInt DemandedElts =
5039 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5040 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5041}
5042
5044 const APInt &DemandedElts,
5045 FPClassTest InterestedClasses,
5047 const SimplifyQuery &Q,
5048 unsigned Depth) {
5049 if ((InterestedClasses &
5051 return;
5052
5053 KnownFPClass KnownSrc;
5054 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5055 KnownSrc, Q, Depth + 1);
5056 Known = KnownFPClass::fptrunc(KnownSrc);
5057}
5058
5060 switch (IID) {
5061 case Intrinsic::minimum:
5063 case Intrinsic::maximum:
5065 case Intrinsic::minimumnum:
5067 case Intrinsic::maximumnum:
5069 case Intrinsic::minnum:
5071 case Intrinsic::maxnum:
5073 default:
5074 llvm_unreachable("not a floating-point min-max intrinsic");
5075 }
5076}
5077
5078/// \return true if this is a floating point value that is known to have a
5079/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5080static bool isAbsoluteValueULEOne(const Value *V) {
5081 // TODO: Handle frexp
5082 // TODO: Other rounding intrinsics?
5083 // TODO: Try computeKnownExponentRangeFromContext
5084
5085 // fabs(x - floor(x)) <= 1
5086 const Value *SubFloorX;
5087 if (match(V, m_FSub(m_Value(SubFloorX),
5089 return true;
5090
5093}
5094
5095void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5096 FPClassTest InterestedClasses, KnownFPClass &Known,
5097 const SimplifyQuery &Q, unsigned Depth) {
5098 assert(Known.isUnknown() && "should not be called with known information");
5099
5100 if (!DemandedElts) {
5101 // No demanded elts, better to assume we don't know anything.
5102 Known.resetAll();
5103 return;
5104 }
5105
5106 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5107
5108 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5109 Known = KnownFPClass(CFP->getValueAPF());
5110 return;
5111 }
5112
5114 Known.KnownFPClasses = fcPosZero;
5115 Known.SignBit = false;
5116 return;
5117 }
5118
5119 if (isa<PoisonValue>(V)) {
5120 Known.KnownFPClasses = fcNone;
5121 Known.SignBit = false;
5122 return;
5123 }
5124
5125 // Try to handle fixed width vector constants
5126 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5127 const Constant *CV = dyn_cast<Constant>(V);
5128 if (VFVTy && CV) {
5129 Known.KnownFPClasses = fcNone;
5130 bool SignBitAllZero = true;
5131 bool SignBitAllOne = true;
5132
5133 // For vectors, verify that each element is not NaN.
5134 unsigned NumElts = VFVTy->getNumElements();
5135 for (unsigned i = 0; i != NumElts; ++i) {
5136 if (!DemandedElts[i])
5137 continue;
5138
5139 Constant *Elt = CV->getAggregateElement(i);
5140 if (!Elt) {
5141 Known = KnownFPClass();
5142 return;
5143 }
5144 if (isa<PoisonValue>(Elt))
5145 continue;
5146 auto *CElt = dyn_cast<ConstantFP>(Elt);
5147 if (!CElt) {
5148 Known = KnownFPClass();
5149 return;
5150 }
5151
5152 const APFloat &C = CElt->getValueAPF();
5153 Known.KnownFPClasses |= C.classify();
5154 if (C.isNegative())
5155 SignBitAllZero = false;
5156 else
5157 SignBitAllOne = false;
5158 }
5159 if (SignBitAllOne != SignBitAllZero)
5160 Known.SignBit = SignBitAllOne;
5161 return;
5162 }
5163
5164 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5165 Known.KnownFPClasses = fcNone;
5166 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5167 Known |= CDS->getElementAsAPFloat(I).classify();
5168 return;
5169 }
5170
5171 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5172 // TODO: Handle complex aggregates
5173 Known.KnownFPClasses = fcNone;
5174 for (const Use &Op : CA->operands()) {
5175 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5176 if (!CFP) {
5177 Known = KnownFPClass();
5178 return;
5179 }
5180
5181 Known |= CFP->getValueAPF().classify();
5182 }
5183
5184 return;
5185 }
5186
5187 FPClassTest KnownNotFromFlags = fcNone;
5188 if (const auto *CB = dyn_cast<CallBase>(V))
5189 KnownNotFromFlags |= CB->getRetNoFPClass();
5190 else if (const auto *Arg = dyn_cast<Argument>(V))
5191 KnownNotFromFlags |= Arg->getNoFPClass();
5192
5193 const Operator *Op = dyn_cast<Operator>(V);
5195 if (FPOp->hasNoNaNs())
5196 KnownNotFromFlags |= fcNan;
5197 if (FPOp->hasNoInfs())
5198 KnownNotFromFlags |= fcInf;
5199 }
5200
5201 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5202 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5203
5204 // We no longer need to find out about these bits from inputs if we can
5205 // assume this from flags/attributes.
5206 InterestedClasses &= ~KnownNotFromFlags;
5207
5208 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5209 Known.knownNot(KnownNotFromFlags);
5210 if (!Known.SignBit && AssumedClasses.SignBit) {
5211 if (*AssumedClasses.SignBit)
5212 Known.signBitMustBeOne();
5213 else
5214 Known.signBitMustBeZero();
5215 }
5216 });
5217
5218 if (!Op)
5219 return;
5220
5221 // All recursive calls that increase depth must come after this.
5223 return;
5224
5225 const unsigned Opc = Op->getOpcode();
5226 switch (Opc) {
5227 case Instruction::FNeg: {
5228 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5229 Known, Q, Depth + 1);
5230 Known.fneg();
5231 break;
5232 }
5233 case Instruction::Select: {
5234 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5235 KnownFPClass Res;
5236 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5237 Depth + 1);
5238 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5239 Depth);
5240 return Res;
5241 };
5242 // Only known if known in both the LHS and RHS.
5243 Known =
5244 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5245 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5246 break;
5247 }
5248 case Instruction::Load: {
5249 const MDNode *NoFPClass =
5250 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5251 if (!NoFPClass)
5252 break;
5253
5254 ConstantInt *MaskVal =
5256 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5257 break;
5258 }
5259 case Instruction::Call: {
5260 const CallInst *II = cast<CallInst>(Op);
5261 const Intrinsic::ID IID = II->getIntrinsicID();
5262 switch (IID) {
5263 case Intrinsic::fabs: {
5264 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5265 // If we only care about the sign bit we don't need to inspect the
5266 // operand.
5267 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5268 InterestedClasses, Known, Q, Depth + 1);
5269 }
5270
5271 Known.fabs();
5272 break;
5273 }
5274 case Intrinsic::copysign: {
5275 KnownFPClass KnownSign;
5276
5277 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5278 Known, Q, Depth + 1);
5279 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5280 KnownSign, Q, Depth + 1);
5281 Known.copysign(KnownSign);
5282 break;
5283 }
5284 case Intrinsic::fma:
5285 case Intrinsic::fmuladd: {
5286 if ((InterestedClasses & fcNegative) == fcNone)
5287 break;
5288
5289 // FIXME: This should check isGuaranteedNotToBeUndef
5290 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5291 KnownFPClass KnownSrc, KnownAddend;
5292 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5293 InterestedClasses, KnownAddend, Q, Depth + 1);
5294 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5295 InterestedClasses, KnownSrc, Q, Depth + 1);
5296
5297 const Function *F = II->getFunction();
5298 const fltSemantics &FltSem =
5299 II->getType()->getScalarType()->getFltSemantics();
5301 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5302
5303 if (KnownNotFromFlags & fcNan) {
5304 KnownSrc.knownNot(fcNan);
5305 KnownAddend.knownNot(fcNan);
5306 }
5307
5308 if (KnownNotFromFlags & fcInf) {
5309 KnownSrc.knownNot(fcInf);
5310 KnownAddend.knownNot(fcInf);
5311 }
5312
5313 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5314 break;
5315 }
5316
5317 KnownFPClass KnownSrc[3];
5318 for (int I = 0; I != 3; ++I) {
5319 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5320 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5321 if (KnownSrc[I].isUnknown())
5322 return;
5323
5324 if (KnownNotFromFlags & fcNan)
5325 KnownSrc[I].knownNot(fcNan);
5326 if (KnownNotFromFlags & fcInf)
5327 KnownSrc[I].knownNot(fcInf);
5328 }
5329
5330 const Function *F = II->getFunction();
5331 const fltSemantics &FltSem =
5332 II->getType()->getScalarType()->getFltSemantics();
5334 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5335 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5336 break;
5337 }
5338 case Intrinsic::sqrt:
5339 case Intrinsic::experimental_constrained_sqrt: {
5340 KnownFPClass KnownSrc;
5341 FPClassTest InterestedSrcs = InterestedClasses;
5342 if (InterestedClasses & fcNan)
5343 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5344
5345 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5346 KnownSrc, Q, Depth + 1);
5347
5349
5350 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5351 if (!HasNSZ) {
5352 const Function *F = II->getFunction();
5353 const fltSemantics &FltSem =
5354 II->getType()->getScalarType()->getFltSemantics();
5355 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5356 }
5357
5358 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5359 if (HasNSZ)
5360 Known.knownNot(fcNegZero);
5361
5362 break;
5363 }
5364 case Intrinsic::sin: {
5365 KnownFPClass KnownSrc;
5366 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5367 KnownSrc, Q, Depth + 1);
5368 Known = KnownFPClass::sin(KnownSrc);
5369 break;
5370 }
5371 case Intrinsic::cos: {
5372 KnownFPClass KnownSrc;
5373 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5374 KnownSrc, Q, Depth + 1);
5375 Known = KnownFPClass::cos(KnownSrc);
5376 break;
5377 }
5378 case Intrinsic::tan: {
5379 KnownFPClass KnownSrc;
5380 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5381 KnownSrc, Q, Depth + 1);
5382 Known = KnownFPClass::tan(KnownSrc);
5383 break;
5384 }
5385 case Intrinsic::sinh: {
5386 KnownFPClass KnownSrc;
5387 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5388 KnownSrc, Q, Depth + 1);
5389 Known = KnownFPClass::sinh(KnownSrc);
5390 break;
5391 }
5392 case Intrinsic::cosh: {
5393 KnownFPClass KnownSrc;
5394 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5395 KnownSrc, Q, Depth + 1);
5396 Known = KnownFPClass::cosh(KnownSrc);
5397 break;
5398 }
5399 case Intrinsic::tanh: {
5400 KnownFPClass KnownSrc;
5401 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5402 KnownSrc, Q, Depth + 1);
5403 Known = KnownFPClass::tanh(KnownSrc);
5404 break;
5405 }
5406 case Intrinsic::asin: {
5407 KnownFPClass KnownSrc;
5408 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5409 KnownSrc, Q, Depth + 1);
5410 Known = KnownFPClass::asin(KnownSrc);
5411 break;
5412 }
5413 case Intrinsic::acos: {
5414 KnownFPClass KnownSrc;
5415 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5416 KnownSrc, Q, Depth + 1);
5417 Known = KnownFPClass::acos(KnownSrc);
5418 break;
5419 }
5420 case Intrinsic::atan: {
5421 KnownFPClass KnownSrc;
5422 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5423 KnownSrc, Q, Depth + 1);
5424 Known = KnownFPClass::atan(KnownSrc);
5425 break;
5426 }
5427 case Intrinsic::atan2: {
5428 KnownFPClass KnownLHS, KnownRHS;
5429 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5430 KnownLHS, Q, Depth + 1);
5431 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5432 KnownRHS, Q, Depth + 1);
5433 Known = KnownFPClass::atan2(KnownLHS, KnownRHS);
5434 break;
5435 }
5436 case Intrinsic::maxnum:
5437 case Intrinsic::minnum:
5438 case Intrinsic::minimum:
5439 case Intrinsic::maximum:
5440 case Intrinsic::minimumnum:
5441 case Intrinsic::maximumnum: {
5442 KnownFPClass KnownLHS, KnownRHS;
5443 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5444 KnownLHS, Q, Depth + 1);
5445 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5446 KnownRHS, Q, Depth + 1);
5447
5448 const Function *F = II->getFunction();
5449
5451 F ? F->getDenormalMode(
5452 II->getType()->getScalarType()->getFltSemantics())
5454
5455 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5456 Mode);
5457 break;
5458 }
5459 case Intrinsic::canonicalize: {
5460 KnownFPClass KnownSrc;
5461 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5462 KnownSrc, Q, Depth + 1);
5463
5464 const Function *F = II->getFunction();
5465 DenormalMode DenormMode =
5466 F ? F->getDenormalMode(
5467 II->getType()->getScalarType()->getFltSemantics())
5469 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5470 break;
5471 }
5472 case Intrinsic::vector_reduce_fmax:
5473 case Intrinsic::vector_reduce_fmin:
5474 case Intrinsic::vector_reduce_fmaximum:
5475 case Intrinsic::vector_reduce_fminimum: {
5476 // reduce min/max will choose an element from one of the vector elements,
5477 // so we can infer and class information that is common to all elements.
5478 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5479 InterestedClasses, Q, Depth + 1);
5480 // Can only propagate sign if output is never NaN.
5481 if (!Known.isKnownNeverNaN())
5482 Known.SignBit.reset();
5483 break;
5484 }
5485 // reverse preserves all characteristics of the input vec's element.
5486 case Intrinsic::vector_reverse:
5488 II->getArgOperand(0), DemandedElts.reverseBits(),
5489 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5490 break;
5491 case Intrinsic::trunc:
5492 case Intrinsic::floor:
5493 case Intrinsic::ceil:
5494 case Intrinsic::rint:
5495 case Intrinsic::nearbyint:
5496 case Intrinsic::round:
5497 case Intrinsic::roundeven: {
5498 KnownFPClass KnownSrc;
5499 FPClassTest InterestedSrcs = InterestedClasses;
5500 if (InterestedSrcs & fcPosFinite)
5501 InterestedSrcs |= fcPosFinite;
5502 if (InterestedSrcs & fcNegFinite)
5503 InterestedSrcs |= fcNegFinite;
5504 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5505 KnownSrc, Q, Depth + 1);
5506
5508 KnownSrc, IID == Intrinsic::trunc,
5509 V->getType()->getScalarType()->isMultiUnitFPType());
5510 break;
5511 }
5512 case Intrinsic::exp:
5513 case Intrinsic::exp2:
5514 case Intrinsic::exp10:
5515 case Intrinsic::amdgcn_exp2: {
5516 KnownFPClass KnownSrc;
5517 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5518 KnownSrc, Q, Depth + 1);
5519
5520 Known = KnownFPClass::exp(KnownSrc);
5521
5522 Type *EltTy = II->getType()->getScalarType();
5523 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5524 Known.knownNot(fcSubnormal);
5525
5526 break;
5527 }
5528 case Intrinsic::fptrunc_round: {
5529 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5530 Q, Depth);
5531 break;
5532 }
5533 case Intrinsic::log:
5534 case Intrinsic::log10:
5535 case Intrinsic::log2:
5536 case Intrinsic::experimental_constrained_log:
5537 case Intrinsic::experimental_constrained_log10:
5538 case Intrinsic::experimental_constrained_log2:
5539 case Intrinsic::amdgcn_log: {
5540 Type *EltTy = II->getType()->getScalarType();
5541
5542 // log(+inf) -> +inf
5543 // log([+-]0.0) -> -inf
5544 // log(-inf) -> nan
5545 // log(-x) -> nan
5546 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5547 FPClassTest InterestedSrcs = InterestedClasses;
5548 if ((InterestedClasses & fcNegInf) != fcNone)
5549 InterestedSrcs |= fcZero | fcSubnormal;
5550 if ((InterestedClasses & fcNan) != fcNone)
5551 InterestedSrcs |= fcNan | fcNegative;
5552
5553 KnownFPClass KnownSrc;
5554 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5555 KnownSrc, Q, Depth + 1);
5556
5557 const Function *F = II->getFunction();
5558 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5560 Known = KnownFPClass::log(KnownSrc, Mode);
5561 }
5562
5563 break;
5564 }
5565 case Intrinsic::powi: {
5566 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5567 break;
5568
5569 const Value *Exp = II->getArgOperand(1);
5570 Type *ExpTy = Exp->getType();
5571 unsigned BitWidth = ExpTy->getScalarType()->getIntegerBitWidth();
5572 KnownBits ExponentKnownBits(BitWidth);
5573 computeKnownBits(Exp, isa<VectorType>(ExpTy) ? DemandedElts : APInt(1, 1),
5574 ExponentKnownBits, Q, Depth + 1);
5575
5576 FPClassTest InterestedSrcs = fcNone;
5577 if (InterestedClasses & fcNan)
5578 InterestedSrcs |= fcNan;
5579 if (!ExponentKnownBits.isZero()) {
5580 if (InterestedClasses & fcInf)
5581 InterestedSrcs |= fcFinite | fcInf;
5582 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5583 InterestedSrcs |= fcNegative;
5584 }
5585
5586 KnownFPClass KnownSrc;
5587 if (InterestedSrcs != fcNone)
5588 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5589 KnownSrc, Q, Depth + 1);
5590
5591 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5592 break;
5593 }
5594 case Intrinsic::ldexp: {
5595 KnownFPClass KnownSrc;
5596 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5597 KnownSrc, Q, Depth + 1);
5598 // Can refine inf/zero handling based on the exponent operand.
5599 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5600
5601 const Value *ExpArg = II->getArgOperand(1);
5602 ConstantRange ExpKnownRange =
5603 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5604 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5605 : ConstantRange::getFull(
5606 ExpArg->getType()->getScalarSizeInBits());
5607
5608 const fltSemantics &Flt =
5609 II->getType()->getScalarType()->getFltSemantics();
5610
5611 const Function *F = II->getFunction();
5613 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5614
5615 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5616 ExpKnownRange.getSignedMax(), Flt, Mode);
5617 break;
5618 }
5619 case Intrinsic::arithmetic_fence: {
5620 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5621 Known, Q, Depth + 1);
5622 break;
5623 }
5624 case Intrinsic::experimental_constrained_sitofp:
5625 case Intrinsic::experimental_constrained_uitofp:
5626 // Cannot produce nan
5627 Known.knownNot(fcNan);
5628
5629 // sitofp and uitofp turn into +0.0 for zero.
5630 Known.knownNot(fcNegZero);
5631
5632 // Integers cannot be subnormal
5633 Known.knownNot(fcSubnormal);
5634
5635 if (IID == Intrinsic::experimental_constrained_uitofp)
5636 Known.signBitMustBeZero();
5637
5638 // TODO: Copy inf handling from instructions
5639 break;
5640
5641 case Intrinsic::amdgcn_fract: {
5642 Known.knownNot(fcInf);
5643
5644 if (InterestedClasses & fcNan) {
5645 KnownFPClass KnownSrc;
5646 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5647 InterestedClasses, KnownSrc, Q, Depth + 1);
5648
5649 if (KnownSrc.isKnownNeverInfOrNaN())
5650 Known.knownNot(fcNan);
5651 else if (KnownSrc.isKnownNever(fcSNan))
5652 Known.knownNot(fcSNan);
5653 }
5654
5655 break;
5656 }
5657 case Intrinsic::amdgcn_rcp: {
5658 KnownFPClass KnownSrc;
5659 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5660 KnownSrc, Q, Depth + 1);
5661
5662 Known.propagateNaN(KnownSrc);
5663
5664 Type *EltTy = II->getType()->getScalarType();
5665
5666 // f32 denormal always flushed.
5667 if (EltTy->isFloatTy()) {
5668 Known.knownNot(fcSubnormal);
5669 KnownSrc.knownNot(fcSubnormal);
5670 }
5671
5672 if (KnownSrc.isKnownNever(fcNegative))
5673 Known.knownNot(fcNegative);
5674 if (KnownSrc.isKnownNever(fcPositive))
5675 Known.knownNot(fcPositive);
5676
5677 if (const Function *F = II->getFunction()) {
5678 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5679 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5680 Known.knownNot(fcPosInf);
5681 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5682 Known.knownNot(fcNegInf);
5683 }
5684
5685 break;
5686 }
5687 case Intrinsic::amdgcn_rsq: {
5688 KnownFPClass KnownSrc;
5689 // The only negative value that can be returned is -inf for -0 inputs.
5691
5692 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5693 KnownSrc, Q, Depth + 1);
5694
5695 // Negative -> nan
5696 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5697 Known.knownNot(fcNan);
5698 else if (KnownSrc.isKnownNever(fcSNan))
5699 Known.knownNot(fcSNan);
5700
5701 // +inf -> +0
5702 if (KnownSrc.isKnownNeverPosInfinity())
5703 Known.knownNot(fcPosZero);
5704
5705 Type *EltTy = II->getType()->getScalarType();
5706
5707 // f32 denormal always flushed.
5708 if (EltTy->isFloatTy())
5709 Known.knownNot(fcPosSubnormal);
5710
5711 if (const Function *F = II->getFunction()) {
5712 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5713
5714 // -0 -> -inf
5715 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5716 Known.knownNot(fcNegInf);
5717
5718 // +0 -> +inf
5719 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5720 Known.knownNot(fcPosInf);
5721 }
5722
5723 break;
5724 }
5725 case Intrinsic::amdgcn_trig_preop: {
5726 // Always returns a value [0, 1)
5727 Known.knownNot(fcNan | fcInf | fcNegative);
5728 break;
5729 }
5730 case Intrinsic::convert_from_arbitrary_fp: {
5731 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5732 StringRef FormatStr = cast<MDString>(MD)->getString();
5733
5734 const fltSemantics *SrcSemantics =
5736 if (!SrcSemantics)
5737 break;
5738
5739 const fltSemantics DstSemantics =
5740 II->getType()->getScalarType()->getFltSemantics();
5741
5742 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5743 Known.knownNot(fcNan);
5744
5745 // fcInf can only be cleared if the source format has no Inf encoding
5746 // and the dst max exp can accommodate src max exp.
5747 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5748 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5749 APFloat::semanticsMaxExponent(DstSemantics))
5750 Known.knownNot(fcInf);
5751
5752 // Check and clear all neg flags for formats that do not have signed
5753 // representation.
5754 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5755 Known.knownNot(fcNegative);
5756
5757 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5758 // zero.
5759 if (!APFloat::semanticsHasZero(*SrcSemantics))
5760 Known.knownNot(fcZero);
5761 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5762 Known.knownNot(fcNegZero);
5763
5764 // If src lands normally in dest, the result can never be subnormal.
5765 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5766 Known.knownNot(fcSubnormal);
5767 break;
5768 }
5769 default:
5770 break;
5771 }
5772
5773 break;
5774 }
5775 case Instruction::FAdd:
5776 case Instruction::FSub: {
5777 KnownFPClass KnownLHS, KnownRHS;
5778 bool WantNegative =
5779 Op->getOpcode() == Instruction::FAdd &&
5780 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5781 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5782 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5783
5784 if (!WantNaN && !WantNegative && !WantNegZero)
5785 break;
5786
5787 FPClassTest InterestedSrcs = InterestedClasses;
5788 if (WantNegative)
5789 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5790 if (InterestedClasses & fcNan)
5791 InterestedSrcs |= fcInf;
5792 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5793 KnownRHS, Q, Depth + 1);
5794
5795 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5796 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5797 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5798 Depth + 1);
5799 if (Self)
5800 KnownLHS = KnownRHS;
5801
5802 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5803 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5804 WantNegZero || Opc == Instruction::FSub) {
5805
5806 // FIXME: Context function should always be passed in separately
5807 const Function *F = cast<Instruction>(Op)->getFunction();
5808 const fltSemantics &FltSem =
5809 Op->getType()->getScalarType()->getFltSemantics();
5811 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5812
5813 if (Self && Opc == Instruction::FAdd) {
5814 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5815 } else {
5816 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5817 // there's no point.
5818
5819 if (!Self) {
5820 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5821 KnownLHS, Q, Depth + 1);
5822 }
5823
5824 Known = Opc == Instruction::FAdd
5825 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5826 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5827 }
5828 }
5829
5830 break;
5831 }
5832 case Instruction::FMul: {
5833 const Function *F = cast<Instruction>(Op)->getFunction();
5835 F ? F->getDenormalMode(
5836 Op->getType()->getScalarType()->getFltSemantics())
5838
5839 Value *LHS = Op->getOperand(0);
5840 Value *RHS = Op->getOperand(1);
5841 // X * X is always non-negative or a NaN.
5842 // FIXME: Should check isGuaranteedNotToBeUndef
5843 if (LHS == RHS) {
5844 KnownFPClass KnownSrc;
5845 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5846 Depth + 1);
5847 Known = KnownFPClass::square(KnownSrc, Mode);
5848 break;
5849 }
5850
5851 KnownFPClass KnownLHS, KnownRHS;
5852
5853 const APFloat *CRHS;
5854 if (match(RHS, m_APFloat(CRHS))) {
5855 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5856 Depth + 1);
5857 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5858 } else {
5859 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5860 Depth + 1);
5861 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5862 // additional not-nan if the addend is known-not negative infinity if the
5863 // multiply is known-not infinity.
5864
5865 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5866 Depth + 1);
5867 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5868 }
5869
5870 /// Propgate no-infs if the other source is known smaller than one, such
5871 /// that this cannot introduce overflow.
5872 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5873 Known.knownNot(fcInf);
5874 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5875 Known.knownNot(fcInf);
5876
5877 break;
5878 }
5879 case Instruction::FDiv:
5880 case Instruction::FRem: {
5881 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5882
5883 if (Op->getOpcode() == Instruction::FRem)
5884 Known.knownNot(fcInf);
5885
5886 if (Op->getOperand(0) == Op->getOperand(1) &&
5887 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5888 if (Op->getOpcode() == Instruction::FDiv) {
5889 // X / X is always exactly 1.0 or a NaN.
5890 Known.KnownFPClasses = fcNan | fcPosNormal;
5891 } else {
5892 // X % X is always exactly [+-]0.0 or a NaN.
5893 Known.KnownFPClasses = fcNan | fcZero;
5894 }
5895
5896 if (!WantNan)
5897 break;
5898
5899 KnownFPClass KnownSrc;
5900 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5901 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5902 Depth + 1);
5903 const Function *F = cast<Instruction>(Op)->getFunction();
5904 const fltSemantics &FltSem =
5905 Op->getType()->getScalarType()->getFltSemantics();
5906
5908 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5909
5910 Known = Op->getOpcode() == Instruction::FDiv
5911 ? KnownFPClass::fdiv_self(KnownSrc, Mode)
5912 : KnownFPClass::frem_self(KnownSrc, Mode);
5913 break;
5914 }
5915
5916 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5917 const bool WantPositive =
5918 Opc == Instruction::FRem && (InterestedClasses & fcPositive) != fcNone;
5919 if (!WantNan && !WantNegative && !WantPositive)
5920 break;
5921
5922 KnownFPClass KnownLHS, KnownRHS;
5923
5924 computeKnownFPClass(Op->getOperand(1), DemandedElts,
5925 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
5926 Depth + 1);
5927
5928 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
5929 KnownRHS.isKnownNever(fcNegative) ||
5930 KnownRHS.isKnownNever(fcPositive);
5931
5932 if (KnowSomethingUseful || WantPositive) {
5933 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5934 Q, Depth + 1);
5935 }
5936
5937 const Function *F = cast<Instruction>(Op)->getFunction();
5938 const fltSemantics &FltSem =
5939 Op->getType()->getScalarType()->getFltSemantics();
5940
5941 if (Op->getOpcode() == Instruction::FDiv) {
5943 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5944 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
5945 } else {
5946 // Inf REM x and x REM 0 produce NaN.
5947 if (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN() &&
5948 KnownLHS.isKnownNeverInfinity() && F &&
5949 KnownRHS.isKnownNeverLogicalZero(F->getDenormalMode(FltSem))) {
5950 Known.knownNot(fcNan);
5951 }
5952
5953 // The sign for frem is the same as the first operand.
5954 if (KnownLHS.cannotBeOrderedLessThanZero())
5956 if (KnownLHS.cannotBeOrderedGreaterThanZero())
5958
5959 // See if we can be more aggressive about the sign of 0.
5960 if (KnownLHS.isKnownNever(fcNegative))
5961 Known.knownNot(fcNegative);
5962 if (KnownLHS.isKnownNever(fcPositive))
5963 Known.knownNot(fcPositive);
5964 }
5965
5966 break;
5967 }
5968 case Instruction::FPExt: {
5969 KnownFPClass KnownSrc;
5970 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5971 KnownSrc, Q, Depth + 1);
5972
5973 const fltSemantics &DstTy =
5974 Op->getType()->getScalarType()->getFltSemantics();
5975 const fltSemantics &SrcTy =
5976 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5977
5978 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
5979 break;
5980 }
5981 case Instruction::FPTrunc: {
5982 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
5983 Depth);
5984 break;
5985 }
5986 case Instruction::SIToFP:
5987 case Instruction::UIToFP: {
5988 // Cannot produce nan
5989 Known.knownNot(fcNan);
5990
5991 // Integers cannot be subnormal
5992 Known.knownNot(fcSubnormal);
5993
5994 // sitofp and uitofp turn into +0.0 for zero.
5995 Known.knownNot(fcNegZero);
5996
5997 // UIToFP is always non-negative regardless of known bits.
5998 if (Op->getOpcode() == Instruction::UIToFP)
5999 Known.signBitMustBeZero();
6000
6001 // Only compute known bits if we can learn something useful from them.
6002 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6003 break;
6004
6005 KnownBits IntKnown =
6006 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6007
6008 // If the integer is non-zero, the result cannot be +0.0
6009 if (IntKnown.isNonZero())
6010 Known.knownNot(fcPosZero);
6011
6012 if (Op->getOpcode() == Instruction::SIToFP) {
6013 // If the signed integer is known non-negative, the result is
6014 // non-negative. If the signed integer is known negative, the result is
6015 // negative.
6016 if (IntKnown.isNonNegative()) {
6017 Known.signBitMustBeZero();
6018 } else if (IntKnown.isNegative()) {
6019 Known.signBitMustBeOne();
6020 }
6021 }
6022
6023 // Guard kept for ilogb()
6024 if (InterestedClasses & fcInf) {
6025 // Get width of largest magnitude integer known.
6026 // This still works for a signed minimum value because the largest FP
6027 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6028 int IntSize = IntKnown.getBitWidth();
6029 if (Op->getOpcode() == Instruction::UIToFP)
6030 IntSize -= IntKnown.countMinLeadingZeros();
6031 else if (Op->getOpcode() == Instruction::SIToFP)
6032 IntSize -= IntKnown.countMinSignBits();
6033
6034 // If the exponent of the largest finite FP value can hold the largest
6035 // integer, the result of the cast must be finite.
6036 Type *FPTy = Op->getType()->getScalarType();
6037 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6038 Known.knownNot(fcInf);
6039 }
6040
6041 break;
6042 }
6043 case Instruction::ExtractElement: {
6044 // Look through extract element. If the index is non-constant or
6045 // out-of-range demand all elements, otherwise just the extracted element.
6046 const Value *Vec = Op->getOperand(0);
6047
6048 APInt DemandedVecElts;
6049 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6050 unsigned NumElts = VecTy->getNumElements();
6051 DemandedVecElts = APInt::getAllOnes(NumElts);
6052 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6053 if (CIdx && CIdx->getValue().ult(NumElts))
6054 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6055 } else {
6056 DemandedVecElts = APInt(1, 1);
6057 }
6058
6059 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6060 Q, Depth + 1);
6061 }
6062 case Instruction::InsertElement: {
6063 if (isa<ScalableVectorType>(Op->getType()))
6064 return;
6065
6066 const Value *Vec = Op->getOperand(0);
6067 const Value *Elt = Op->getOperand(1);
6068 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6069 unsigned NumElts = DemandedElts.getBitWidth();
6070 APInt DemandedVecElts = DemandedElts;
6071 bool NeedsElt = true;
6072 // If we know the index we are inserting to, clear it from Vec check.
6073 if (CIdx && CIdx->getValue().ult(NumElts)) {
6074 DemandedVecElts.clearBit(CIdx->getZExtValue());
6075 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6076 }
6077
6078 // Do we demand the inserted element?
6079 if (NeedsElt) {
6080 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6081 // If we don't know any bits, early out.
6082 if (Known.isUnknown())
6083 break;
6084 } else {
6085 Known.KnownFPClasses = fcNone;
6086 }
6087
6088 // Do we need anymore elements from Vec?
6089 if (!DemandedVecElts.isZero()) {
6090 KnownFPClass Known2;
6091 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6092 Depth + 1);
6093 Known |= Known2;
6094 }
6095
6096 break;
6097 }
6098 case Instruction::ShuffleVector: {
6099 // Handle vector splat idiom
6100 if (Value *Splat = getSplatValue(V)) {
6101 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6102 break;
6103 }
6104
6105 // For undef elements, we don't know anything about the common state of
6106 // the shuffle result.
6107 APInt DemandedLHS, DemandedRHS;
6108 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6109 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6110 return;
6111
6112 if (!!DemandedLHS) {
6113 const Value *LHS = Shuf->getOperand(0);
6114 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6115 Depth + 1);
6116
6117 // If we don't know any bits, early out.
6118 if (Known.isUnknown())
6119 break;
6120 } else {
6121 Known.KnownFPClasses = fcNone;
6122 }
6123
6124 if (!!DemandedRHS) {
6125 KnownFPClass Known2;
6126 const Value *RHS = Shuf->getOperand(1);
6127 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6128 Depth + 1);
6129 Known |= Known2;
6130 }
6131
6132 break;
6133 }
6134 case Instruction::ExtractValue: {
6135 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6136 ArrayRef<unsigned> Indices = Extract->getIndices();
6137 const Value *Src = Extract->getAggregateOperand();
6138 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6139 Indices[0] == 0) {
6140 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6141 switch (II->getIntrinsicID()) {
6142 case Intrinsic::frexp: {
6143 Known.knownNot(fcSubnormal);
6144
6145 KnownFPClass KnownSrc;
6146 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6147 InterestedClasses, KnownSrc, Q, Depth + 1);
6148
6149 const Function *F = cast<Instruction>(Op)->getFunction();
6150 const fltSemantics &FltSem =
6151 Op->getType()->getScalarType()->getFltSemantics();
6152
6154 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6155 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6156 return;
6157 }
6158 default:
6159 break;
6160 }
6161 }
6162 }
6163
6164 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6165 Depth + 1);
6166 break;
6167 }
6168 case Instruction::PHI: {
6169 const PHINode *P = cast<PHINode>(Op);
6170 // Unreachable blocks may have zero-operand PHI nodes.
6171 if (P->getNumIncomingValues() == 0)
6172 break;
6173
6174 // Otherwise take the unions of the known bit sets of the operands,
6175 // taking conservative care to avoid excessive recursion.
6176 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6177
6178 if (Depth < PhiRecursionLimit) {
6179 // Skip if every incoming value references to ourself.
6180 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6181 break;
6182
6183 bool First = true;
6184
6185 for (const Use &U : P->operands()) {
6186 Value *IncValue;
6187 Instruction *CxtI;
6188 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6189 // Skip direct self references.
6190 if (IncValue == P)
6191 continue;
6192
6193 KnownFPClass KnownSrc;
6194 // Recurse, but cap the recursion to two levels, because we don't want
6195 // to waste time spinning around in loops. We need at least depth 2 to
6196 // detect known sign bits.
6197 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6199 PhiRecursionLimit);
6200
6201 if (First) {
6202 Known = KnownSrc;
6203 First = false;
6204 } else {
6205 Known |= KnownSrc;
6206 }
6207
6208 if (Known.KnownFPClasses == fcAllFlags)
6209 break;
6210 }
6211 }
6212
6213 // Look for the case of a for loop which has a positive
6214 // initial value and is incremented by a squared value.
6215 // This will propagate sign information out of such loops.
6216 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6217 break;
6218 for (unsigned I = 0; I < 2; I++) {
6219 Value *RecurValue = P->getIncomingValue(1 - I);
6221 if (!II)
6222 continue;
6223 Value *R, *L, *Init;
6224 PHINode *PN;
6226 PN == P) {
6227 switch (II->getIntrinsicID()) {
6228 case Intrinsic::fma:
6229 case Intrinsic::fmuladd: {
6230 KnownFPClass KnownStart;
6231 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6232 Q, Depth + 1);
6233 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6234 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6236 break;
6237 }
6238 }
6239 }
6240 }
6241 break;
6242 }
6243 case Instruction::BitCast: {
6244 const Value *Src;
6245 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6246 !Src->getType()->isIntOrIntVectorTy())
6247 break;
6248
6249 const Type *Ty = Op->getType();
6250
6251 Value *CastLHS, *CastRHS;
6252
6253 // Match bitcast(umax(bitcast(a), bitcast(b)))
6254 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6255 m_BitCast(m_Value(CastRHS)))) &&
6256 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6257 KnownFPClass KnownLHS, KnownRHS;
6258 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6259 Depth + 1);
6260 if (!KnownRHS.isUnknown()) {
6261 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6262 Q, Depth + 1);
6263 Known = KnownLHS | KnownRHS;
6264 }
6265
6266 return;
6267 }
6268
6269 const Type *EltTy = Ty->getScalarType();
6270 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6271 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6272
6274 break;
6275 }
6276 default:
6277 break;
6278 }
6279}
6280
6282 const APInt &DemandedElts,
6283 FPClassTest InterestedClasses,
6284 const SimplifyQuery &SQ,
6285 unsigned Depth) {
6286 KnownFPClass KnownClasses;
6287 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6288 Depth);
6289 return KnownClasses;
6290}
6291
6293 FPClassTest InterestedClasses,
6294 const SimplifyQuery &SQ,
6295 unsigned Depth) {
6297 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6298 return Known;
6299}
6300
6302 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6303 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6304 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6305 return computeKnownFPClass(V, InterestedClasses,
6306 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6307 Depth);
6308}
6309
6311llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6312 FastMathFlags FMF, FPClassTest InterestedClasses,
6313 const SimplifyQuery &SQ, unsigned Depth) {
6314 if (FMF.noNaNs())
6315 InterestedClasses &= ~fcNan;
6316 if (FMF.noInfs())
6317 InterestedClasses &= ~fcInf;
6318
6319 KnownFPClass Result =
6320 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6321
6322 if (FMF.noNaNs())
6323 Result.KnownFPClasses &= ~fcNan;
6324 if (FMF.noInfs())
6325 Result.KnownFPClasses &= ~fcInf;
6326 return Result;
6327}
6328
6330 FPClassTest InterestedClasses,
6331 const SimplifyQuery &SQ,
6332 unsigned Depth) {
6333 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6334 APInt DemandedElts =
6335 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6336 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6337 Depth);
6338}
6339
6341 unsigned Depth) {
6343 return Known.isKnownNeverNegZero();
6344}
6345
6347 unsigned Depth) {
6350 return Known.cannotBeOrderedLessThanZero();
6351}
6352
6354 unsigned Depth) {
6356 return Known.isKnownNeverInfinity();
6357}
6358
6359/// Return true if the floating-point value can never contain a NaN or infinity.
6361 unsigned Depth) {
6363 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6364}
6365
6366/// Return true if the floating-point scalar value is not a NaN or if the
6367/// floating-point vector value has no NaN elements. Return false if a value
6368/// could ever be NaN.
6370 unsigned Depth) {
6372 return Known.isKnownNeverNaN();
6373}
6374
6375/// Return false if we can prove that the specified FP value's sign bit is 0.
6376/// Return true if we can prove that the specified FP value's sign bit is 1.
6377/// Otherwise return std::nullopt.
6378std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6379 const SimplifyQuery &SQ,
6380 unsigned Depth) {
6382 return Known.SignBit;
6383}
6384
6386 auto *User = cast<Instruction>(U.getUser());
6387 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6388 if (FPOp->hasNoSignedZeros())
6389 return true;
6390 }
6391
6392 switch (User->getOpcode()) {
6393 case Instruction::FPToSI:
6394 case Instruction::FPToUI:
6395 return true;
6396 case Instruction::FCmp:
6397 // fcmp treats both positive and negative zero as equal.
6398 return true;
6399 case Instruction::Call:
6400 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6401 switch (II->getIntrinsicID()) {
6402 case Intrinsic::fabs:
6403 return true;
6404 case Intrinsic::copysign:
6405 return U.getOperandNo() == 0;
6406 case Intrinsic::is_fpclass:
6407 case Intrinsic::vp_is_fpclass: {
6408 auto Test =
6409 static_cast<FPClassTest>(
6410 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6413 }
6414 default:
6415 return false;
6416 }
6417 }
6418 return false;
6419 default:
6420 return false;
6421 }
6422}
6423
6425 auto *User = cast<Instruction>(U.getUser());
6426 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6427 if (FPOp->hasNoNaNs())
6428 return true;
6429 }
6430
6431 switch (User->getOpcode()) {
6432 case Instruction::FPToSI:
6433 case Instruction::FPToUI:
6434 return true;
6435 // Proper FP math operations ignore the sign bit of NaN.
6436 case Instruction::FAdd:
6437 case Instruction::FSub:
6438 case Instruction::FMul:
6439 case Instruction::FDiv:
6440 case Instruction::FRem:
6441 case Instruction::FPTrunc:
6442 case Instruction::FPExt:
6443 case Instruction::FCmp:
6444 return true;
6445 // Bitwise FP operations should preserve the sign bit of NaN.
6446 case Instruction::FNeg:
6447 case Instruction::Select:
6448 case Instruction::PHI:
6449 return false;
6450 case Instruction::Ret:
6451 return User->getFunction()->getAttributes().getRetNoFPClass() &
6453 case Instruction::Call:
6454 case Instruction::Invoke: {
6455 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6456 switch (II->getIntrinsicID()) {
6457 case Intrinsic::fabs:
6458 return true;
6459 case Intrinsic::copysign:
6460 return U.getOperandNo() == 0;
6461 // Other proper FP math intrinsics ignore the sign bit of NaN.
6462 case Intrinsic::maxnum:
6463 case Intrinsic::minnum:
6464 case Intrinsic::maximum:
6465 case Intrinsic::minimum:
6466 case Intrinsic::maximumnum:
6467 case Intrinsic::minimumnum:
6468 case Intrinsic::canonicalize:
6469 case Intrinsic::fma:
6470 case Intrinsic::fmuladd:
6471 case Intrinsic::sqrt:
6472 case Intrinsic::pow:
6473 case Intrinsic::powi:
6474 case Intrinsic::fptoui_sat:
6475 case Intrinsic::fptosi_sat:
6476 case Intrinsic::is_fpclass:
6477 case Intrinsic::vp_is_fpclass:
6478 return true;
6479 default:
6480 return false;
6481 }
6482 }
6483
6484 FPClassTest NoFPClass =
6485 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6486 return NoFPClass & FPClassTest::fcNan;
6487 }
6488 default:
6489 return false;
6490 }
6491}
6492
6494 FastMathFlags FMF) {
6495 if (isa<PoisonValue>(V))
6496 return true;
6497 if (isa<UndefValue>(V))
6498 return false;
6499
6500 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6501 return true;
6502
6504 if (!I)
6505 return false;
6506
6507 switch (I->getOpcode()) {
6508 case Instruction::SIToFP:
6509 case Instruction::UIToFP:
6510 // TODO: Could check nofpclass(inf) on incoming argument
6511 if (FMF.noInfs())
6512 return true;
6513
6514 // Need to check int size cannot produce infinity, which computeKnownFPClass
6515 // knows how to do already.
6516 return isKnownNeverInfinity(I, SQ);
6517 case Instruction::Call: {
6518 const CallInst *CI = cast<CallInst>(I);
6519 switch (CI->getIntrinsicID()) {
6520 case Intrinsic::trunc:
6521 case Intrinsic::floor:
6522 case Intrinsic::ceil:
6523 case Intrinsic::rint:
6524 case Intrinsic::nearbyint:
6525 case Intrinsic::round:
6526 case Intrinsic::roundeven:
6527 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6528 default:
6529 break;
6530 }
6531
6532 break;
6533 }
6534 default:
6535 break;
6536 }
6537
6538 return false;
6539}
6540
6542
6543 // All byte-wide stores are splatable, even of arbitrary variables.
6544 if (V->getType()->isIntegerTy(8))
6545 return V;
6546
6547 LLVMContext &Ctx = V->getContext();
6548
6549 // Undef don't care.
6550 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6551 if (isa<UndefValue>(V))
6552 return UndefInt8;
6553
6554 // Return poison for zero-sized type.
6555 if (DL.getTypeStoreSize(V->getType()).isZero())
6556 return PoisonValue::get(Type::getInt8Ty(Ctx));
6557
6559 if (!C) {
6560 // Conceptually, we could handle things like:
6561 // %a = zext i8 %X to i16
6562 // %b = shl i16 %a, 8
6563 // %c = or i16 %a, %b
6564 // but until there is an example that actually needs this, it doesn't seem
6565 // worth worrying about.
6566 return nullptr;
6567 }
6568
6569 // Handle 'null' ConstantArrayZero etc.
6570 if (C->isNullValue())
6572
6573 // Constant floating-point values can be handled as integer values if the
6574 // corresponding integer value is "byteable". An important case is 0.0.
6575 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6576 Type *ScalarTy = CFP->getType()->getScalarType();
6577 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6578 return isBytewiseValue(
6579 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6580
6581 // Don't handle long double formats, which have strange constraints.
6582 return nullptr;
6583 }
6584
6585 // We can handle constant integers that are multiple of 8 bits.
6586 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6587 if (CI->getBitWidth() % 8 == 0) {
6588 if (!CI->getValue().isSplat(8))
6589 return nullptr;
6590 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6591 }
6592 }
6593
6594 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6595 if (CE->getOpcode() == Instruction::IntToPtr) {
6596 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6597 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6599 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6600 return isBytewiseValue(Op, DL);
6601 }
6602 }
6603 }
6604
6605 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6606 if (LHS == RHS)
6607 return LHS;
6608 if (!LHS || !RHS)
6609 return nullptr;
6610 if (LHS == UndefInt8)
6611 return RHS;
6612 if (RHS == UndefInt8)
6613 return LHS;
6614 return nullptr;
6615 };
6616
6618 Value *Val = UndefInt8;
6619 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6620 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6621 return nullptr;
6622 return Val;
6623 }
6624
6626 Value *Val = UndefInt8;
6627 for (Value *Op : C->operands())
6628 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6629 return nullptr;
6630 return Val;
6631 }
6632
6633 // Don't try to handle the handful of other constants.
6634 return nullptr;
6635}
6636
6637// This is the recursive version of BuildSubAggregate. It takes a few different
6638// arguments. Idxs is the index within the nested struct From that we are
6639// looking at now (which is of type IndexedType). IdxSkip is the number of
6640// indices from Idxs that should be left out when inserting into the resulting
6641// struct. To is the result struct built so far, new insertvalue instructions
6642// build on that.
6643static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6645 unsigned IdxSkip,
6646 BasicBlock::iterator InsertBefore) {
6647 StructType *STy = dyn_cast<StructType>(IndexedType);
6648 if (STy) {
6649 // Save the original To argument so we can modify it
6650 Value *OrigTo = To;
6651 // General case, the type indexed by Idxs is a struct
6652 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6653 // Process each struct element recursively
6654 Idxs.push_back(i);
6655 Value *PrevTo = To;
6656 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6657 InsertBefore);
6658 Idxs.pop_back();
6659 if (!To) {
6660 // Couldn't find any inserted value for this index? Cleanup
6661 while (PrevTo != OrigTo) {
6663 PrevTo = Del->getAggregateOperand();
6664 Del->eraseFromParent();
6665 }
6666 // Stop processing elements
6667 break;
6668 }
6669 }
6670 // If we successfully found a value for each of our subaggregates
6671 if (To)
6672 return To;
6673 }
6674 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6675 // the struct's elements had a value that was inserted directly. In the latter
6676 // case, perhaps we can't determine each of the subelements individually, but
6677 // we might be able to find the complete struct somewhere.
6678
6679 // Find the value that is at that particular spot
6680 Value *V = FindInsertedValue(From, Idxs);
6681
6682 if (!V)
6683 return nullptr;
6684
6685 // Insert the value in the new (sub) aggregate
6686 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6687 InsertBefore);
6688}
6689
6690// This helper takes a nested struct and extracts a part of it (which is again a
6691// struct) into a new value. For example, given the struct:
6692// { a, { b, { c, d }, e } }
6693// and the indices "1, 1" this returns
6694// { c, d }.
6695//
6696// It does this by inserting an insertvalue for each element in the resulting
6697// struct, as opposed to just inserting a single struct. This will only work if
6698// each of the elements of the substruct are known (ie, inserted into From by an
6699// insertvalue instruction somewhere).
6700//
6701// All inserted insertvalue instructions are inserted before InsertBefore
6703 BasicBlock::iterator InsertBefore) {
6704 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6705 idx_range);
6706 Value *To = PoisonValue::get(IndexedType);
6707 SmallVector<unsigned, 10> Idxs(idx_range);
6708 unsigned IdxSkip = Idxs.size();
6709
6710 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6711}
6712
6713/// Given an aggregate and a sequence of indices, see if the scalar value
6714/// indexed is already around as a register, for example if it was inserted
6715/// directly into the aggregate.
6716///
6717/// If InsertBefore is not null, this function will duplicate (modified)
6718/// insertvalues when a part of a nested struct is extracted.
6719Value *
6721 std::optional<BasicBlock::iterator> InsertBefore) {
6722 // Nothing to index? Just return V then (this is useful at the end of our
6723 // recursion).
6724 if (idx_range.empty())
6725 return V;
6726 // We have indices, so V should have an indexable type.
6727 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6728 "Not looking at a struct or array?");
6729 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6730 "Invalid indices for type?");
6731
6732 if (Constant *C = dyn_cast<Constant>(V)) {
6733 C = C->getAggregateElement(idx_range[0]);
6734 if (!C) return nullptr;
6735 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6736 }
6737
6739 // Loop the indices for the insertvalue instruction in parallel with the
6740 // requested indices
6741 const unsigned *req_idx = idx_range.begin();
6742 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6743 i != e; ++i, ++req_idx) {
6744 if (req_idx == idx_range.end()) {
6745 // We can't handle this without inserting insertvalues
6746 if (!InsertBefore)
6747 return nullptr;
6748
6749 // The requested index identifies a part of a nested aggregate. Handle
6750 // this specially. For example,
6751 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6752 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6753 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6754 // This can be changed into
6755 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6756 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6757 // which allows the unused 0,0 element from the nested struct to be
6758 // removed.
6759 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6760 *InsertBefore);
6761 }
6762
6763 // This insert value inserts something else than what we are looking for.
6764 // See if the (aggregate) value inserted into has the value we are
6765 // looking for, then.
6766 if (*req_idx != *i)
6767 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6768 InsertBefore);
6769 }
6770 // If we end up here, the indices of the insertvalue match with those
6771 // requested (though possibly only partially). Now we recursively look at
6772 // the inserted value, passing any remaining indices.
6773 return FindInsertedValue(I->getInsertedValueOperand(),
6774 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6775 }
6776
6778 // If we're extracting a value from an aggregate that was extracted from
6779 // something else, we can extract from that something else directly instead.
6780 // However, we will need to chain I's indices with the requested indices.
6781
6782 // Calculate the number of indices required
6783 unsigned size = I->getNumIndices() + idx_range.size();
6784 // Allocate some space to put the new indices in
6786 Idxs.reserve(size);
6787 // Add indices from the extract value instruction
6788 Idxs.append(I->idx_begin(), I->idx_end());
6789
6790 // Add requested indices
6791 Idxs.append(idx_range.begin(), idx_range.end());
6792
6793 assert(Idxs.size() == size
6794 && "Number of indices added not correct?");
6795
6796 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6797 }
6798 // Otherwise, we don't know (such as, extracting from a function return value
6799 // or load instruction)
6800 return nullptr;
6801}
6802
6803// If V refers to an initialized global constant, set Slice either to
6804// its initializer if the size of its elements equals ElementSize, or,
6805// for ElementSize == 8, to its representation as an array of unsiged
6806// char. Return true on success.
6807// Offset is in the unit "nr of ElementSize sized elements".
6810 unsigned ElementSize, uint64_t Offset) {
6811 assert(V && "V should not be null.");
6812 assert((ElementSize % 8) == 0 &&
6813 "ElementSize expected to be a multiple of the size of a byte.");
6814 unsigned ElementSizeInBytes = ElementSize / 8;
6815
6816 // Drill down into the pointer expression V, ignoring any intervening
6817 // casts, and determine the identity of the object it references along
6818 // with the cumulative byte offset into it.
6819 const GlobalVariable *GV =
6821 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6822 // Fail if V is not based on constant global object.
6823 return false;
6824
6825 const DataLayout &DL = GV->getDataLayout();
6826 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6827
6828 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6829 /*AllowNonInbounds*/ true))
6830 // Fail if a constant offset could not be determined.
6831 return false;
6832
6833 uint64_t StartIdx = Off.getLimitedValue();
6834 if (StartIdx == UINT64_MAX)
6835 // Fail if the constant offset is excessive.
6836 return false;
6837
6838 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6839 // elements. Simply bail out if that isn't possible.
6840 if ((StartIdx % ElementSizeInBytes) != 0)
6841 return false;
6842
6843 Offset += StartIdx / ElementSizeInBytes;
6844 ConstantDataArray *Array = nullptr;
6845 ArrayType *ArrayTy = nullptr;
6846
6847 if (GV->getInitializer()->isNullValue()) {
6848 Type *GVTy = GV->getValueType();
6849 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6850 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6851
6852 Slice.Array = nullptr;
6853 Slice.Offset = 0;
6854 // Return an empty Slice for undersized constants to let callers
6855 // transform even undefined library calls into simpler, well-defined
6856 // expressions. This is preferable to making the calls although it
6857 // prevents sanitizers from detecting such calls.
6858 Slice.Length = Length < Offset ? 0 : Length - Offset;
6859 return true;
6860 }
6861
6862 auto *Init = const_cast<Constant *>(GV->getInitializer());
6863 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6864 Type *InitElTy = ArrayInit->getElementType();
6865 if (InitElTy->isIntegerTy(ElementSize)) {
6866 // If Init is an initializer for an array of the expected type
6867 // and size, use it as is.
6868 Array = ArrayInit;
6869 ArrayTy = ArrayInit->getType();
6870 }
6871 }
6872
6873 if (!Array) {
6874 if (ElementSize != 8)
6875 // TODO: Handle conversions to larger integral types.
6876 return false;
6877
6878 // Otherwise extract the portion of the initializer starting
6879 // at Offset as an array of bytes, and reset Offset.
6881 if (!Init)
6882 return false;
6883
6884 Offset = 0;
6886 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6887 }
6888
6889 uint64_t NumElts = ArrayTy->getArrayNumElements();
6890 if (Offset > NumElts)
6891 return false;
6892
6893 Slice.Array = Array;
6894 Slice.Offset = Offset;
6895 Slice.Length = NumElts - Offset;
6896 return true;
6897}
6898
6899/// Extract bytes from the initializer of the constant array V, which need
6900/// not be a nul-terminated string. On success, store the bytes in Str and
6901/// return true. When TrimAtNul is set, Str will contain only the bytes up
6902/// to but not including the first nul. Return false on failure.
6904 bool TrimAtNul) {
6906 if (!getConstantDataArrayInfo(V, Slice, 8))
6907 return false;
6908
6909 if (Slice.Array == nullptr) {
6910 if (TrimAtNul) {
6911 // Return a nul-terminated string even for an empty Slice. This is
6912 // safe because all existing SimplifyLibcalls callers require string
6913 // arguments and the behavior of the functions they fold is undefined
6914 // otherwise. Folding the calls this way is preferable to making
6915 // the undefined library calls, even though it prevents sanitizers
6916 // from reporting such calls.
6917 Str = StringRef();
6918 return true;
6919 }
6920 if (Slice.Length == 1) {
6921 Str = StringRef("", 1);
6922 return true;
6923 }
6924 // We cannot instantiate a StringRef as we do not have an appropriate string
6925 // of 0s at hand.
6926 return false;
6927 }
6928
6929 // Start out with the entire array in the StringRef.
6930 Str = Slice.Array->getAsString();
6931 // Skip over 'offset' bytes.
6932 Str = Str.substr(Slice.Offset);
6933
6934 if (TrimAtNul) {
6935 // Trim off the \0 and anything after it. If the array is not nul
6936 // terminated, we just return the whole end of string. The client may know
6937 // some other way that the string is length-bound.
6938 Str = Str.substr(0, Str.find('\0'));
6939 }
6940 return true;
6941}
6942
6943// These next two are very similar to the above, but also look through PHI
6944// nodes.
6945// TODO: See if we can integrate these two together.
6946
6947/// If we can compute the length of the string pointed to by
6948/// the specified pointer, return 'len+1'. If we can't, return 0.
6951 unsigned CharSize) {
6952 // Look through noop bitcast instructions.
6953 V = V->stripPointerCasts();
6954
6955 // If this is a PHI node, there are two cases: either we have already seen it
6956 // or we haven't.
6957 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
6958 if (!PHIs.insert(PN).second)
6959 return ~0ULL; // already in the set.
6960
6961 // If it was new, see if all the input strings are the same length.
6962 uint64_t LenSoFar = ~0ULL;
6963 for (Value *IncValue : PN->incoming_values()) {
6964 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
6965 if (Len == 0) return 0; // Unknown length -> unknown.
6966
6967 if (Len == ~0ULL) continue;
6968
6969 if (Len != LenSoFar && LenSoFar != ~0ULL)
6970 return 0; // Disagree -> unknown.
6971 LenSoFar = Len;
6972 }
6973
6974 // Success, all agree.
6975 return LenSoFar;
6976 }
6977
6978 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
6979 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6980 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
6981 if (Len1 == 0) return 0;
6982 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
6983 if (Len2 == 0) return 0;
6984 if (Len1 == ~0ULL) return Len2;
6985 if (Len2 == ~0ULL) return Len1;
6986 if (Len1 != Len2) return 0;
6987 return Len1;
6988 }
6989
6990 // Otherwise, see if we can read the string.
6992 if (!getConstantDataArrayInfo(V, Slice, CharSize))
6993 return 0;
6994
6995 if (Slice.Array == nullptr)
6996 // Zeroinitializer (including an empty one).
6997 return 1;
6998
6999 // Search for the first nul character. Return a conservative result even
7000 // when there is no nul. This is safe since otherwise the string function
7001 // being folded such as strlen is undefined, and can be preferable to
7002 // making the undefined library call.
7003 unsigned NullIndex = 0;
7004 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7005 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7006 break;
7007 }
7008
7009 return NullIndex + 1;
7010}
7011
7012/// If we can compute the length of the string pointed to by
7013/// the specified pointer, return 'len+1'. If we can't, return 0.
7014uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7015 if (!V->getType()->isPointerTy())
7016 return 0;
7017
7019 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7020 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7021 // an empty string as a length.
7022 return Len == ~0ULL ? 1 : Len;
7023}
7024
7025const Value *
7027 bool MustPreserveOffset) {
7028 assert(Call &&
7029 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7030 if (const Value *RV = Call->getReturnedArgOperand())
7031 return RV;
7032 // This can be used only as a aliasing property.
7034 Call, MustPreserveOffset))
7035 return Call->getArgOperand(0);
7036 return nullptr;
7037}
7038
7040 const CallBase *Call, bool MustPreserveOffset) {
7041 switch (Call->getIntrinsicID()) {
7042 case Intrinsic::launder_invariant_group:
7043 case Intrinsic::strip_invariant_group:
7044 case Intrinsic::aarch64_irg:
7045 case Intrinsic::aarch64_tagp:
7046 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7047 // input pointer (and thus preserves the byte offset, which is the property
7048 // the MustPreserveOffset flag selects). However, it will not necessarily
7049 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7050 // descriptor", which has "all loads return 0, all stores are dropped"
7051 // semantics. Given the context of this intrinsic list, no one should be
7052 // relying on such a strict bit-exact null mapping (and, at time of
7053 // writing, they are not), but we document this fact out of an abundance
7054 // of caution.
7055 case Intrinsic::amdgcn_make_buffer_rsrc:
7056 return true;
7057 case Intrinsic::ptrmask:
7058 return !MustPreserveOffset;
7059 case Intrinsic::threadlocal_address:
7060 // The underlying variable changes with thread ID. The Thread ID may change
7061 // at coroutine suspend points.
7062 return !Call->getParent()->getParent()->isPresplitCoroutine();
7063 default:
7064 return false;
7065 }
7066}
7067
7068/// \p PN defines a loop-variant pointer to an object. Check if the
7069/// previous iteration of the loop was referring to the same object as \p PN.
7071 const LoopInfo *LI) {
7072 // Find the loop-defined value.
7073 Loop *L = LI->getLoopFor(PN->getParent());
7074 if (PN->getNumIncomingValues() != 2)
7075 return true;
7076
7077 // Find the value from previous iteration.
7078 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7079 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7080 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7081 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7082 return true;
7083
7084 // If a new pointer is loaded in the loop, the pointer references a different
7085 // object in every iteration. E.g.:
7086 // for (i)
7087 // int *p = a[i];
7088 // ...
7089 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7090 if (!L->isLoopInvariant(Load->getPointerOperand()))
7091 return false;
7092 return true;
7093}
7094
7095const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7096 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7097 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7098 const Value *PtrOp = GEP->getPointerOperand();
7099 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7100 return V;
7101 V = PtrOp;
7102 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7103 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7104 Value *NewV = cast<Operator>(V)->getOperand(0);
7105 if (!NewV->getType()->isPointerTy())
7106 return V;
7107 V = NewV;
7108 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7109 if (GA->isInterposable())
7110 return V;
7111 V = GA->getAliasee();
7112 } else {
7113 if (auto *PHI = dyn_cast<PHINode>(V)) {
7114 // Look through single-arg phi nodes created by LCSSA.
7115 if (PHI->getNumIncomingValues() == 1) {
7116 V = PHI->getIncomingValue(0);
7117 continue;
7118 }
7119 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7120 // CaptureTracking can know about special capturing properties of some
7121 // intrinsics like launder.invariant.group, that can't be expressed with
7122 // the attributes, but have properties like returning aliasing pointer.
7123 // Because some analysis may assume that nocaptured pointer is not
7124 // returned from some special intrinsic (because function would have to
7125 // be marked with returns attribute), it is crucial to use this function
7126 // because it should be in sync with CaptureTracking. Not using it may
7127 // cause weird miscompilations where 2 aliasing pointers are assumed to
7128 // noalias.
7130 Call, /*MustPreserveOffset=*/false)) {
7131 V = RP;
7132 continue;
7133 }
7134 }
7135
7136 return V;
7137 }
7138 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7139 }
7140 return V;
7141}
7142
7145 const LoopInfo *LI, unsigned MaxLookup) {
7148 Worklist.push_back(V);
7149 do {
7150 const Value *P = Worklist.pop_back_val();
7151 P = getUnderlyingObject(P, MaxLookup);
7152
7153 if (!Visited.insert(P).second)
7154 continue;
7155
7156 if (auto *SI = dyn_cast<SelectInst>(P)) {
7157 Worklist.push_back(SI->getTrueValue());
7158 Worklist.push_back(SI->getFalseValue());
7159 continue;
7160 }
7161
7162 if (auto *PN = dyn_cast<PHINode>(P)) {
7163 // If this PHI changes the underlying object in every iteration of the
7164 // loop, don't look through it. Consider:
7165 // int **A;
7166 // for (i) {
7167 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7168 // Curr = A[i];
7169 // *Prev, *Curr;
7170 //
7171 // Prev is tracking Curr one iteration behind so they refer to different
7172 // underlying objects.
7173 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7175 append_range(Worklist, PN->incoming_values());
7176 else
7177 Objects.push_back(P);
7178 continue;
7179 }
7180
7181 Objects.push_back(P);
7182 } while (!Worklist.empty());
7183}
7184
7186 const unsigned MaxVisited = 8;
7187
7190 Worklist.push_back(V);
7191 const Value *Object = nullptr;
7192 // Used as fallback if we can't find a common underlying object through
7193 // recursion.
7194 bool First = true;
7195 const Value *FirstObject = getUnderlyingObject(V);
7196 do {
7197 const Value *P = Worklist.pop_back_val();
7198 P = First ? FirstObject : getUnderlyingObject(P);
7199 First = false;
7200
7201 if (!Visited.insert(P).second)
7202 continue;
7203
7204 if (Visited.size() == MaxVisited)
7205 return FirstObject;
7206
7207 if (auto *SI = dyn_cast<SelectInst>(P)) {
7208 Worklist.push_back(SI->getTrueValue());
7209 Worklist.push_back(SI->getFalseValue());
7210 continue;
7211 }
7212
7213 if (auto *PN = dyn_cast<PHINode>(P)) {
7214 append_range(Worklist, PN->incoming_values());
7215 continue;
7216 }
7217
7218 if (!Object)
7219 Object = P;
7220 else if (Object != P)
7221 return FirstObject;
7222 } while (!Worklist.empty());
7223
7224 return Object ? Object : FirstObject;
7225}
7226
7227/// This is the function that does the work of looking through basic
7228/// ptrtoint+arithmetic+inttoptr sequences.
7229static const Value *getUnderlyingObjectFromInt(const Value *V) {
7230 do {
7231 if (const Operator *U = dyn_cast<Operator>(V)) {
7232 // If we find a ptrtoint, we can transfer control back to the
7233 // regular getUnderlyingObjectFromInt.
7234 if (U->getOpcode() == Instruction::PtrToInt)
7235 return U->getOperand(0);
7236 // If we find an add of a constant, a multiplied value, or a phi, it's
7237 // likely that the other operand will lead us to the base
7238 // object. We don't have to worry about the case where the
7239 // object address is somehow being computed by the multiply,
7240 // because our callers only care when the result is an
7241 // identifiable object.
7242 if (U->getOpcode() != Instruction::Add ||
7243 (!isa<ConstantInt>(U->getOperand(1)) &&
7244 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7245 !isa<PHINode>(U->getOperand(1))))
7246 return V;
7247 V = U->getOperand(0);
7248 } else {
7249 return V;
7250 }
7251 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7252 } while (true);
7253}
7254
7255/// This is a wrapper around getUnderlyingObjects and adds support for basic
7256/// ptrtoint+arithmetic+inttoptr sequences.
7257/// It returns false if unidentified object is found in getUnderlyingObjects.
7259 SmallVectorImpl<Value *> &Objects) {
7261 SmallVector<const Value *, 4> Working(1, V);
7262 do {
7263 V = Working.pop_back_val();
7264
7266 getUnderlyingObjects(V, Objs);
7267
7268 for (const Value *V : Objs) {
7269 if (!Visited.insert(V).second)
7270 continue;
7271 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7272 const Value *O =
7273 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7274 if (O->getType()->isPointerTy()) {
7275 Working.push_back(O);
7276 continue;
7277 }
7278 }
7279 // If getUnderlyingObjects fails to find an identifiable object,
7280 // getUnderlyingObjectsForCodeGen also fails for safety.
7281 if (!isIdentifiedObject(V)) {
7282 Objects.clear();
7283 return false;
7284 }
7285 Objects.push_back(const_cast<Value *>(V));
7286 }
7287 } while (!Working.empty());
7288 return true;
7289}
7290
7292 AllocaInst *Result = nullptr;
7294 SmallVector<Value *, 4> Worklist;
7295
7296 auto AddWork = [&](Value *V) {
7297 if (Visited.insert(V).second)
7298 Worklist.push_back(V);
7299 };
7300
7301 AddWork(V);
7302 do {
7303 V = Worklist.pop_back_val();
7304 assert(Visited.count(V));
7305
7306 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7307 if (Result && Result != AI)
7308 return nullptr;
7309 Result = AI;
7310 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7311 AddWork(CI->getOperand(0));
7312 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7313 for (Value *IncValue : PN->incoming_values())
7314 AddWork(IncValue);
7315 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7316 AddWork(SI->getTrueValue());
7317 AddWork(SI->getFalseValue());
7319 if (OffsetZero && !GEP->hasAllZeroIndices())
7320 return nullptr;
7321 AddWork(GEP->getPointerOperand());
7322 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7323 Value *Returned = CB->getReturnedArgOperand();
7324 if (Returned)
7325 AddWork(Returned);
7326 else
7327 return nullptr;
7328 } else {
7329 return nullptr;
7330 }
7331 } while (!Worklist.empty());
7332
7333 return Result;
7334}
7335
7337 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7338 for (const User *U : V->users()) {
7340 if (!II)
7341 return false;
7342
7343 if (AllowLifetime && II->isLifetimeStartOrEnd())
7344 continue;
7345
7346 if (AllowDroppable && II->isDroppable())
7347 continue;
7348
7349 return false;
7350 }
7351 return true;
7352}
7353
7356 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7357}
7360 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7361}
7362
7364 if (auto *II = dyn_cast<IntrinsicInst>(I))
7365 return isTriviallyVectorizable(II->getIntrinsicID());
7366 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7367 return (!Shuffle || Shuffle->isSelect()) &&
7369}
7370
7372 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7373 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7374 bool IgnoreUBImplyingAttrs) {
7375 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7376 AC, DT, TLI, UseVariableInfo,
7377 IgnoreUBImplyingAttrs);
7378}
7379
7381 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7382 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7383 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7384#ifndef NDEBUG
7385 if (Inst->getOpcode() != Opcode) {
7386 // Check that the operands are actually compatible with the Opcode override.
7387 auto hasEqualReturnAndLeadingOperandTypes =
7388 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7389 if (Inst->getNumOperands() < NumLeadingOperands)
7390 return false;
7391 const Type *ExpectedType = Inst->getType();
7392 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7393 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7394 return false;
7395 return true;
7396 };
7398 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7399 assert(!Instruction::isUnaryOp(Opcode) ||
7400 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7401 }
7402#endif
7403
7404 switch (Opcode) {
7405 default:
7406 return true;
7407 case Instruction::UDiv:
7408 case Instruction::URem: {
7409 // x / y is undefined if y == 0.
7410 const APInt *V;
7411 if (match(Inst->getOperand(1), m_APInt(V)))
7412 return *V != 0;
7413 return false;
7414 }
7415 case Instruction::SDiv:
7416 case Instruction::SRem: {
7417 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7418 const APInt *Numerator, *Denominator;
7419 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7420 return false;
7421 // We cannot hoist this division if the denominator is 0.
7422 if (*Denominator == 0)
7423 return false;
7424 // It's safe to hoist if the denominator is not 0 or -1.
7425 if (!Denominator->isAllOnes())
7426 return true;
7427 // At this point we know that the denominator is -1. It is safe to hoist as
7428 // long we know that the numerator is not INT_MIN.
7429 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7430 return !Numerator->isMinSignedValue();
7431 // The numerator *might* be MinSignedValue.
7432 return false;
7433 }
7434 case Instruction::Load: {
7435 if (!UseVariableInfo)
7436 return false;
7437
7438 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7439 if (!LI)
7440 return false;
7441 if (mustSuppressSpeculation(*LI))
7442 return false;
7443 const DataLayout &DL = LI->getDataLayout();
7445 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7446 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7447 }
7448 case Instruction::Call: {
7449 auto *CI = dyn_cast<const CallInst>(Inst);
7450 if (!CI)
7451 return false;
7452 const Function *Callee = CI->getCalledFunction();
7453
7454 // The called function could have undefined behavior or side-effects, even
7455 // if marked readnone nounwind.
7456 if (!Callee || !Callee->isSpeculatable())
7457 return false;
7458 // Since the operands may be changed after hoisting, undefined behavior may
7459 // be triggered by some UB-implying attributes.
7460 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7461 }
7462 case Instruction::VAArg:
7463 case Instruction::Alloca:
7464 case Instruction::Invoke:
7465 case Instruction::CallBr:
7466 case Instruction::PHI:
7467 case Instruction::Store:
7468 case Instruction::Ret:
7469 case Instruction::UncondBr:
7470 case Instruction::CondBr:
7471 case Instruction::IndirectBr:
7472 case Instruction::Switch:
7473 case Instruction::Unreachable:
7474 case Instruction::Fence:
7475 case Instruction::AtomicRMW:
7476 case Instruction::AtomicCmpXchg:
7477 case Instruction::LandingPad:
7478 case Instruction::Resume:
7479 case Instruction::CatchSwitch:
7480 case Instruction::CatchPad:
7481 case Instruction::CatchRet:
7482 case Instruction::CleanupPad:
7483 case Instruction::CleanupRet:
7484 return false; // Misc instructions which have effects
7485 }
7486}
7487
7489 if (I.mayReadOrWriteMemory())
7490 // Memory dependency possible
7491 return true;
7493 // Can't move above a maythrow call or infinite loop. Or if an
7494 // inalloca alloca, above a stacksave call.
7495 return true;
7497 // 1) Can't reorder two inf-loop calls, even if readonly
7498 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7499 // safe to speculative execute. (Inverse of above)
7500 return true;
7501 return false;
7502}
7503
7504/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7518
7519/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7522 bool ForSigned,
7523 const SimplifyQuery &SQ) {
7524 ConstantRange CR1 =
7525 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7526 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7529 return CR1.intersectWith(CR2, RangeType);
7530}
7531
7533 const Value *RHS,
7534 const SimplifyQuery &SQ,
7535 bool IsNSW) {
7536 ConstantRange LHSRange =
7537 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7538 ConstantRange RHSRange =
7539 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7540
7541 // mul nsw of two non-negative numbers is also nuw.
7542 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7544
7545 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7546}
7547
7549 const Value *RHS,
7550 const SimplifyQuery &SQ) {
7551 // Multiplying n * m significant bits yields a result of n + m significant
7552 // bits. If the total number of significant bits does not exceed the
7553 // result bit width (minus 1), there is no overflow.
7554 // This means if we have enough leading sign bits in the operands
7555 // we can guarantee that the result does not overflow.
7556 // Ref: "Hacker's Delight" by Henry Warren
7557 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7558
7559 // Note that underestimating the number of sign bits gives a more
7560 // conservative answer.
7561 unsigned SignBits =
7562 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7563
7564 // First handle the easy case: if we have enough sign bits there's
7565 // definitely no overflow.
7566 if (SignBits > BitWidth + 1)
7568
7569 // There are two ambiguous cases where there can be no overflow:
7570 // SignBits == BitWidth + 1 and
7571 // SignBits == BitWidth
7572 // The second case is difficult to check, therefore we only handle the
7573 // first case.
7574 if (SignBits == BitWidth + 1) {
7575 // It overflows only when both arguments are negative and the true
7576 // product is exactly the minimum negative number.
7577 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7578 // For simplicity we just check if at least one side is not negative.
7579 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7580 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7581 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7583 }
7585}
7586
7589 const WithCache<const Value *> &RHS,
7590 const SimplifyQuery &SQ) {
7591 ConstantRange LHSRange =
7592 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7593 ConstantRange RHSRange =
7594 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7595 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7596}
7597
7598static OverflowResult
7601 const AddOperator *Add, const SimplifyQuery &SQ) {
7602 if (Add && Add->hasNoSignedWrap()) {
7604 }
7605
7606 // If LHS and RHS each have at least two sign bits, the addition will look
7607 // like
7608 //
7609 // XX..... +
7610 // YY.....
7611 //
7612 // If the carry into the most significant position is 0, X and Y can't both
7613 // be 1 and therefore the carry out of the addition is also 0.
7614 //
7615 // If the carry into the most significant position is 1, X and Y can't both
7616 // be 0 and therefore the carry out of the addition is also 1.
7617 //
7618 // Since the carry into the most significant position is always equal to
7619 // the carry out of the addition, there is no signed overflow.
7620 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7622
7623 ConstantRange LHSRange =
7624 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7625 ConstantRange RHSRange =
7626 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7627 OverflowResult OR =
7628 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7630 return OR;
7631
7632 // The remaining code needs Add to be available. Early returns if not so.
7633 if (!Add)
7635
7636 // If the sign of Add is the same as at least one of the operands, this add
7637 // CANNOT overflow. If this can be determined from the known bits of the
7638 // operands the above signedAddMayOverflow() check will have already done so.
7639 // The only other way to improve on the known bits is from an assumption, so
7640 // call computeKnownBitsFromContext() directly.
7641 bool LHSOrRHSKnownNonNegative =
7642 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7643 bool LHSOrRHSKnownNegative =
7644 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7645 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7646 KnownBits AddKnown(LHSRange.getBitWidth());
7647 computeKnownBitsFromContext(Add, AddKnown, SQ);
7648 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7649 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7651 }
7652
7654}
7655
7657 const Value *RHS,
7658 const SimplifyQuery &SQ) {
7659 // X - (X % ?)
7660 // The remainder of a value can't have greater magnitude than itself,
7661 // so the subtraction can't overflow.
7662
7663 // X - (X -nuw ?)
7664 // In the minimal case, this would simplify to "?", so there's no subtract
7665 // at all. But if this analysis is used to peek through casts, for example,
7666 // then determining no-overflow may allow other transforms.
7667
7668 // TODO: There are other patterns like this.
7669 // See simplifyICmpWithBinOpOnLHS() for candidates.
7670 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7671 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7672 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7674
7675 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7676 SQ.DL)) {
7677 if (*C)
7680 }
7681
7682 ConstantRange LHSRange =
7683 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7684 ConstantRange RHSRange =
7685 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7686 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7687}
7688
7690 const Value *RHS,
7691 const SimplifyQuery &SQ) {
7692 // X - (X % ?)
7693 // The remainder of a value can't have greater magnitude than itself,
7694 // so the subtraction can't overflow.
7695
7696 // X - (X -nsw ?)
7697 // In the minimal case, this would simplify to "?", so there's no subtract
7698 // at all. But if this analysis is used to peek through casts, for example,
7699 // then determining no-overflow may allow other transforms.
7700 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7701 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7702 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7704
7705 // If LHS and RHS each have at least two sign bits, the subtraction
7706 // cannot overflow.
7707 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7709
7710 ConstantRange LHSRange =
7711 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7712 ConstantRange RHSRange =
7713 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7714 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7715}
7716
7718 const DominatorTree &DT) {
7719 SmallVector<const CondBrInst *, 2> GuardingBranches;
7721
7722 for (const User *U : WO->users()) {
7723 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7724 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7725
7726 if (EVI->getIndices()[0] == 0)
7727 Results.push_back(EVI);
7728 else {
7729 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7730
7731 for (const auto *U : EVI->users())
7732 if (const auto *B = dyn_cast<CondBrInst>(U))
7733 GuardingBranches.push_back(B);
7734 }
7735 } else {
7736 // We are using the aggregate directly in a way we don't want to analyze
7737 // here (storing it to a global, say).
7738 return false;
7739 }
7740 }
7741
7742 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7743 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7744
7745 // Check if all users of the add are provably no-wrap.
7746 for (const auto *Result : Results) {
7747 // If the extractvalue itself is not executed on overflow, the we don't
7748 // need to check each use separately, since domination is transitive.
7749 if (DT.dominates(NoWrapEdge, Result->getParent()))
7750 continue;
7751
7752 for (const auto &RU : Result->uses())
7753 if (!DT.dominates(NoWrapEdge, RU))
7754 return false;
7755 }
7756
7757 return true;
7758 };
7759
7760 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7761}
7762
7763/// Shifts return poison if shiftwidth is larger than the bitwidth.
7764static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7765 auto *C = dyn_cast<Constant>(ShiftAmount);
7766 if (!C)
7767 return false;
7768
7769 // Shifts return poison if shiftwidth is larger than the bitwidth.
7771 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7772 unsigned NumElts = FVTy->getNumElements();
7773 for (unsigned i = 0; i < NumElts; ++i)
7774 ShiftAmounts.push_back(C->getAggregateElement(i));
7775 } else if (isa<ScalableVectorType>(C->getType()))
7776 return false; // Can't tell, just return false to be safe
7777 else
7778 ShiftAmounts.push_back(C);
7779
7780 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7781 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7782 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7783 });
7784
7785 return Safe;
7786}
7787
7789 bool ConsiderFlagsAndMetadata) {
7790
7791 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7792 Op->hasPoisonGeneratingAnnotations())
7793 return true;
7794
7795 unsigned Opcode = Op->getOpcode();
7796
7797 // Check whether opcode is a poison/undef-generating operation
7798 switch (Opcode) {
7799 case Instruction::Shl:
7800 case Instruction::AShr:
7801 case Instruction::LShr:
7802 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7803 case Instruction::FPToSI:
7804 case Instruction::FPToUI:
7805 // fptosi/ui yields poison if the resulting value does not fit in the
7806 // destination type.
7807 return true;
7808 case Instruction::Call:
7809 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7810 switch (II->getIntrinsicID()) {
7811 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7812 case Intrinsic::ctlz:
7813 case Intrinsic::cttz:
7814 case Intrinsic::abs:
7815 // We're not considering flags so it is safe to just return false.
7816 return false;
7817 case Intrinsic::sshl_sat:
7818 case Intrinsic::ushl_sat:
7819 if (!includesPoison(Kind) ||
7820 shiftAmountKnownInRange(II->getArgOperand(1)))
7821 return false;
7822 break;
7823 }
7824 }
7825 [[fallthrough]];
7826 case Instruction::CallBr:
7827 case Instruction::Invoke: {
7828 const auto *CB = cast<CallBase>(Op);
7829 return !CB->hasRetAttr(Attribute::NoUndef) &&
7830 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7831 }
7832 case Instruction::InsertElement:
7833 case Instruction::ExtractElement: {
7834 // If index exceeds the length of the vector, it returns poison
7835 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7836 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7837 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7838 if (includesPoison(Kind))
7839 return !Idx ||
7840 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7841 return false;
7842 }
7843 case Instruction::ShuffleVector: {
7845 ? cast<ConstantExpr>(Op)->getShuffleMask()
7846 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7847 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7848 }
7849 case Instruction::FNeg:
7850 case Instruction::PHI:
7851 case Instruction::Select:
7852 case Instruction::ExtractValue:
7853 case Instruction::InsertValue:
7854 case Instruction::Freeze:
7855 case Instruction::ICmp:
7856 case Instruction::FCmp:
7857 case Instruction::GetElementPtr:
7858 return false;
7859 case Instruction::AddrSpaceCast:
7860 return true;
7861 default: {
7862 const auto *CE = dyn_cast<ConstantExpr>(Op);
7863 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7864 return false;
7865 else if (Instruction::isBinaryOp(Opcode))
7866 return false;
7867 // Be conservative and return true.
7868 return true;
7869 }
7870 }
7871}
7872
7874 bool ConsiderFlagsAndMetadata) {
7875 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7876 ConsiderFlagsAndMetadata);
7877}
7878
7879bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7880 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7881 ConsiderFlagsAndMetadata);
7882}
7883
7884static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7885 unsigned Depth) {
7886 if (ValAssumedPoison == V)
7887 return true;
7888
7889 const unsigned MaxDepth = 2;
7890 if (Depth >= MaxDepth)
7891 return false;
7892
7893 if (const auto *I = dyn_cast<Instruction>(V)) {
7894 if (any_of(I->operands(), [=](const Use &Op) {
7895 return propagatesPoison(Op) &&
7896 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7897 }))
7898 return true;
7899
7900 // V = extractvalue V0, idx
7901 // V2 = extractvalue V0, idx2
7902 // V0's elements are all poison or not. (e.g., add_with_overflow)
7903 const WithOverflowInst *II;
7905 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7906 llvm::is_contained(II->args(), ValAssumedPoison)))
7907 return true;
7908 }
7909 return false;
7910}
7911
7912static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7913 unsigned Depth) {
7914 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7915 return true;
7916
7917 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
7918 return true;
7919
7920 const unsigned MaxDepth = 2;
7921 if (Depth >= MaxDepth)
7922 return false;
7923
7924 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
7925 if (I && !canCreatePoison(cast<Operator>(I))) {
7926 return all_of(I->operands(), [=](const Value *Op) {
7927 return impliesPoison(Op, V, Depth + 1);
7928 });
7929 }
7930 return false;
7931}
7932
7933bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
7934 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
7935}
7936
7937static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
7938
7940 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
7941 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
7943 return false;
7944
7945 if (isa<MetadataAsValue>(V))
7946 return false;
7947
7948 if (const auto *A = dyn_cast<Argument>(V)) {
7949 if (A->hasAttribute(Attribute::NoUndef) ||
7950 A->hasAttribute(Attribute::Dereferenceable) ||
7951 A->hasAttribute(Attribute::DereferenceableOrNull))
7952 return true;
7953 }
7954
7955 if (auto *C = dyn_cast<Constant>(V)) {
7956 if (isa<PoisonValue>(C))
7957 return !includesPoison(Kind);
7958
7959 if (isa<UndefValue>(C))
7960 return !includesUndef(Kind);
7961
7964 return true;
7965
7966 if (C->getType()->isVectorTy()) {
7967 if (isa<ConstantExpr>(C)) {
7968 // Scalable vectors can use a ConstantExpr to build a splat.
7969 if (Constant *SplatC = C->getSplatValue())
7970 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
7971 return true;
7972 } else {
7973 if (includesUndef(Kind) && C->containsUndefElement())
7974 return false;
7975 if (includesPoison(Kind) && C->containsPoisonElement())
7976 return false;
7977 return !C->containsConstantExpression();
7978 }
7979 }
7980 }
7981
7982 // Strip cast operations from a pointer value.
7983 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
7984 // inbounds with zero offset. To guarantee that the result isn't poison, the
7985 // stripped pointer is checked as it has to be pointing into an allocated
7986 // object or be null `null` to ensure `inbounds` getelement pointers with a
7987 // zero offset could not produce poison.
7988 // It can strip off addrspacecast that do not change bit representation as
7989 // well. We believe that such addrspacecast is equivalent to no-op.
7990 auto *StrippedV = V->stripPointerCastsSameRepresentation();
7991 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
7992 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
7993 return true;
7994
7995 auto OpCheck = [&](const Value *V) {
7996 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
7997 };
7998
7999 if (auto *Opr = dyn_cast<Operator>(V)) {
8000 // If the value is a freeze instruction, then it can never
8001 // be undef or poison.
8002 if (isa<FreezeInst>(V))
8003 return true;
8004
8005 if (const auto *CB = dyn_cast<CallBase>(V)) {
8006 if (CB->hasRetAttr(Attribute::NoUndef) ||
8007 CB->hasRetAttr(Attribute::Dereferenceable) ||
8008 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8009 return true;
8010 }
8011
8012 if (!::canCreateUndefOrPoison(Opr, Kind,
8013 /*ConsiderFlagsAndMetadata=*/true)) {
8014 if (const auto *PN = dyn_cast<PHINode>(V)) {
8015 unsigned Num = PN->getNumIncomingValues();
8016 bool IsWellDefined = true;
8017 for (unsigned i = 0; i < Num; ++i) {
8018 if (PN == PN->getIncomingValue(i))
8019 continue;
8020 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8021 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8022 DT, Depth + 1, Kind)) {
8023 IsWellDefined = false;
8024 break;
8025 }
8026 }
8027 if (IsWellDefined)
8028 return true;
8029 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8030 : nullptr) {
8031 // For splats we only need to check the value being splatted.
8032 if (OpCheck(Splat))
8033 return true;
8034 } else if (all_of(Opr->operands(), OpCheck))
8035 return true;
8036 }
8037 }
8038
8039 if (auto *I = dyn_cast<LoadInst>(V))
8040 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8041 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8042 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8043 return true;
8044
8046 return true;
8047
8048 // CxtI may be null or a cloned instruction.
8049 if (!CtxI || !CtxI->getParent() || !DT)
8050 return false;
8051
8052 auto *DNode = DT->getNode(CtxI->getParent());
8053 if (!DNode)
8054 // Unreachable block
8055 return false;
8056
8057 // If V is used as a branch condition before reaching CtxI, V cannot be
8058 // undef or poison.
8059 // br V, BB1, BB2
8060 // BB1:
8061 // CtxI ; V cannot be undef or poison here
8062 auto *Dominator = DNode->getIDom();
8063 // This check is purely for compile time reasons: we can skip the IDom walk
8064 // if what we are checking for includes undef and the value is not an integer.
8065 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8066 while (Dominator) {
8067 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8068
8069 Value *Cond = nullptr;
8070 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8071 Cond = BI->getCondition();
8072 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8073 Cond = SI->getCondition();
8074 }
8075
8076 if (Cond) {
8077 if (Cond == V)
8078 return true;
8079 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8080 // For poison, we can analyze further
8081 auto *Opr = cast<Operator>(Cond);
8082 if (any_of(Opr->operands(), [V](const Use &U) {
8083 return V == U && propagatesPoison(U);
8084 }))
8085 return true;
8086 }
8087 }
8088
8089 Dominator = Dominator->getIDom();
8090 }
8091
8092 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8093 return true;
8094
8095 return false;
8096}
8097
8099 const Instruction *CtxI,
8100 const DominatorTree *DT,
8101 unsigned Depth) {
8102 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8104}
8105
8107 const Instruction *CtxI,
8108 const DominatorTree *DT, unsigned Depth) {
8109 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8111}
8112
8114 const Instruction *CtxI,
8115 const DominatorTree *DT, unsigned Depth) {
8116 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8118}
8119
8120/// Return true if undefined behavior would provably be executed on the path to
8121/// OnPathTo if Root produced a posion result. Note that this doesn't say
8122/// anything about whether OnPathTo is actually executed or whether Root is
8123/// actually poison. This can be used to assess whether a new use of Root can
8124/// be added at a location which is control equivalent with OnPathTo (such as
8125/// immediately before it) without introducing UB which didn't previously
8126/// exist. Note that a false result conveys no information.
8128 Instruction *OnPathTo,
8129 DominatorTree *DT) {
8130 // Basic approach is to assume Root is poison, propagate poison forward
8131 // through all users we can easily track, and then check whether any of those
8132 // users are provable UB and must execute before out exiting block might
8133 // exit.
8134
8135 // The set of all recursive users we've visited (which are assumed to all be
8136 // poison because of said visit)
8139 Worklist.push_back(Root);
8140 while (!Worklist.empty()) {
8141 const Instruction *I = Worklist.pop_back_val();
8142
8143 // If we know this must trigger UB on a path leading our target.
8144 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8145 return true;
8146
8147 // If we can't analyze propagation through this instruction, just skip it
8148 // and transitive users. Safe as false is a conservative result.
8149 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8150 return KnownPoison.contains(U) && propagatesPoison(U);
8151 }))
8152 continue;
8153
8154 if (KnownPoison.insert(I).second)
8155 for (const User *User : I->users())
8156 Worklist.push_back(cast<Instruction>(User));
8157 }
8158
8159 // Might be non-UB, or might have a path we couldn't prove must execute on
8160 // way to exiting bb.
8161 return false;
8162}
8163
8165 const SimplifyQuery &SQ) {
8166 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8167 Add, SQ);
8168}
8169
8172 const WithCache<const Value *> &RHS,
8173 const SimplifyQuery &SQ) {
8174 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8175}
8176
8178 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8179 // of time because it's possible for another thread to interfere with it for an
8180 // arbitrary length of time, but programs aren't allowed to rely on that.
8181
8182 // If there is no successor, then execution can't transfer to it.
8183 if (isa<ReturnInst>(I))
8184 return false;
8186 return false;
8187
8188 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8189 // Instruction::willReturn.
8190 //
8191 // FIXME: Move this check into Instruction::willReturn.
8192 if (isa<CatchPadInst>(I)) {
8193 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8194 default:
8195 // A catchpad may invoke exception object constructors and such, which
8196 // in some languages can be arbitrary code, so be conservative by default.
8197 return false;
8199 // For CoreCLR, it just involves a type test.
8200 return true;
8201 }
8202 }
8203
8204 // An instruction that returns without throwing must transfer control flow
8205 // to a successor.
8206 return !I->mayThrow() && I->willReturn();
8207}
8208
8210 // TODO: This is slightly conservative for invoke instruction since exiting
8211 // via an exception *is* normal control for them.
8212 for (const Instruction &I : *BB)
8214 return false;
8215 return true;
8216}
8217
8224
8227 assert(ScanLimit && "scan limit must be non-zero");
8228 for (const Instruction &I : Range) {
8229 if (--ScanLimit == 0)
8230 return false;
8232 return false;
8233 }
8234 return true;
8235}
8236
8238 const Loop *L) {
8239 // The loop header is guaranteed to be executed for every iteration.
8240 //
8241 // FIXME: Relax this constraint to cover all basic blocks that are
8242 // guaranteed to be executed at every iteration.
8243 if (I->getParent() != L->getHeader()) return false;
8244
8245 for (const Instruction &LI : *L->getHeader()) {
8246 if (&LI == I) return true;
8247 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8248 }
8249 llvm_unreachable("Instruction not contained in its own parent basic block.");
8250}
8251
8253 switch (IID) {
8254 // TODO: Add more intrinsics.
8255 case Intrinsic::sadd_with_overflow:
8256 case Intrinsic::ssub_with_overflow:
8257 case Intrinsic::smul_with_overflow:
8258 case Intrinsic::uadd_with_overflow:
8259 case Intrinsic::usub_with_overflow:
8260 case Intrinsic::umul_with_overflow:
8261 // If an input is a vector containing a poison element, the
8262 // two output vectors (calculated results, overflow bits)'
8263 // corresponding lanes are poison.
8264 return true;
8265 case Intrinsic::ctpop:
8266 case Intrinsic::ctlz:
8267 case Intrinsic::cttz:
8268 case Intrinsic::abs:
8269 case Intrinsic::smax:
8270 case Intrinsic::smin:
8271 case Intrinsic::umax:
8272 case Intrinsic::umin:
8273 case Intrinsic::scmp:
8274 case Intrinsic::is_fpclass:
8275 case Intrinsic::ptrmask:
8276 case Intrinsic::ucmp:
8277 case Intrinsic::bitreverse:
8278 case Intrinsic::bswap:
8279 case Intrinsic::sadd_sat:
8280 case Intrinsic::ssub_sat:
8281 case Intrinsic::sshl_sat:
8282 case Intrinsic::uadd_sat:
8283 case Intrinsic::usub_sat:
8284 case Intrinsic::ushl_sat:
8285 case Intrinsic::smul_fix:
8286 case Intrinsic::smul_fix_sat:
8287 case Intrinsic::umul_fix:
8288 case Intrinsic::umul_fix_sat:
8289 case Intrinsic::pow:
8290 case Intrinsic::powi:
8291 case Intrinsic::sin:
8292 case Intrinsic::sinh:
8293 case Intrinsic::cos:
8294 case Intrinsic::cosh:
8295 case Intrinsic::sincos:
8296 case Intrinsic::sincospi:
8297 case Intrinsic::tan:
8298 case Intrinsic::tanh:
8299 case Intrinsic::asin:
8300 case Intrinsic::acos:
8301 case Intrinsic::atan:
8302 case Intrinsic::atan2:
8303 case Intrinsic::canonicalize:
8304 case Intrinsic::sqrt:
8305 case Intrinsic::exp:
8306 case Intrinsic::exp2:
8307 case Intrinsic::exp10:
8308 case Intrinsic::log:
8309 case Intrinsic::log2:
8310 case Intrinsic::log10:
8311 case Intrinsic::modf:
8312 case Intrinsic::floor:
8313 case Intrinsic::ceil:
8314 case Intrinsic::trunc:
8315 case Intrinsic::rint:
8316 case Intrinsic::nearbyint:
8317 case Intrinsic::round:
8318 case Intrinsic::roundeven:
8319 case Intrinsic::lrint:
8320 case Intrinsic::llrint:
8321 case Intrinsic::fshl:
8322 case Intrinsic::fshr:
8323 case Intrinsic::frexp:
8324 case Intrinsic::get_active_lane_mask:
8325 return true;
8326 default:
8327 return false;
8328 }
8329}
8330
8331bool llvm::propagatesPoison(const Use &PoisonOp) {
8332 const Operator *I = cast<Operator>(PoisonOp.getUser());
8333 switch (I->getOpcode()) {
8334 case Instruction::Freeze:
8335 case Instruction::PHI:
8336 case Instruction::Invoke:
8337 return false;
8338 case Instruction::Select:
8339 return PoisonOp.getOperandNo() == 0;
8340 case Instruction::Call:
8341 if (auto *II = dyn_cast<IntrinsicInst>(I))
8342 return intrinsicPropagatesPoison(II->getIntrinsicID());
8343 return false;
8344 case Instruction::ICmp:
8345 case Instruction::FCmp:
8346 case Instruction::GetElementPtr:
8347 return true;
8348 default:
8350 return true;
8351
8352 // Be conservative and return false.
8353 return false;
8354 }
8355}
8356
8357/// Enumerates all operands of \p I that are guaranteed to not be undef or
8358/// poison. If the callback \p Handle returns true, stop processing and return
8359/// true. Otherwise, return false.
8360template <typename CallableT>
8362 const CallableT &Handle) {
8363 switch (I->getOpcode()) {
8364 case Instruction::Store:
8365 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8366 return true;
8367 break;
8368
8369 case Instruction::Load:
8370 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8371 return true;
8372 break;
8373
8374 // Since dereferenceable attribute imply noundef, atomic operations
8375 // also implicitly have noundef pointers too
8376 case Instruction::AtomicCmpXchg:
8378 return true;
8379 break;
8380
8381 case Instruction::AtomicRMW:
8382 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8383 return true;
8384 break;
8385
8386 case Instruction::Call:
8387 case Instruction::Invoke: {
8388 const CallBase *CB = cast<CallBase>(I);
8389 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8390 return true;
8391 for (unsigned i = 0; i < CB->arg_size(); ++i)
8392 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8393 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8394 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8395 Handle(CB->getArgOperand(i)))
8396 return true;
8397 break;
8398 }
8399 case Instruction::Ret:
8400 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8401 Handle(I->getOperand(0)))
8402 return true;
8403 break;
8404 case Instruction::Switch:
8405 if (Handle(cast<SwitchInst>(I)->getCondition()))
8406 return true;
8407 break;
8408 case Instruction::CondBr:
8409 if (Handle(cast<CondBrInst>(I)->getCondition()))
8410 return true;
8411 break;
8412 default:
8413 break;
8414 }
8415
8416 return false;
8417}
8418
8419/// Enumerates all operands of \p I that are guaranteed to not be poison.
8420template <typename CallableT>
8422 const CallableT &Handle) {
8423 if (handleGuaranteedWellDefinedOps(I, Handle))
8424 return true;
8425 switch (I->getOpcode()) {
8426 // Divisors of these operations are allowed to be partially undef.
8427 case Instruction::UDiv:
8428 case Instruction::SDiv:
8429 case Instruction::URem:
8430 case Instruction::SRem:
8431 return Handle(I->getOperand(1));
8432 default:
8433 return false;
8434 }
8435}
8436
8438 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8440 I, [&](const Value *V) { return KnownPoison.count(V); });
8441}
8442
8444 bool PoisonOnly) {
8445 // We currently only look for uses of values within the same basic
8446 // block, as that makes it easier to guarantee that the uses will be
8447 // executed given that Inst is executed.
8448 //
8449 // FIXME: Expand this to consider uses beyond the same basic block. To do
8450 // this, look out for the distinction between post-dominance and strong
8451 // post-dominance.
8452 const BasicBlock *BB = nullptr;
8454 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8455 BB = Inst->getParent();
8456 Begin = Inst->getIterator();
8457 Begin++;
8458 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8459 if (Arg->getParent()->isDeclaration())
8460 return false;
8461 BB = &Arg->getParent()->getEntryBlock();
8462 Begin = BB->begin();
8463 } else {
8464 return false;
8465 }
8466
8467 // Limit number of instructions we look at, to avoid scanning through large
8468 // blocks. The current limit is chosen arbitrarily.
8469 unsigned ScanLimit = 32;
8470 BasicBlock::const_iterator End = BB->end();
8471
8472 if (!PoisonOnly) {
8473 // Since undef does not propagate eagerly, be conservative & just check
8474 // whether a value is directly passed to an instruction that must take
8475 // well-defined operands.
8476
8477 for (const auto &I : make_range(Begin, End)) {
8478 if (--ScanLimit == 0)
8479 break;
8480
8481 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8482 return WellDefinedOp == V;
8483 }))
8484 return true;
8485
8487 break;
8488 }
8489 return false;
8490 }
8491
8492 // Set of instructions that we have proved will yield poison if Inst
8493 // does.
8494 SmallPtrSet<const Value *, 16> YieldsPoison;
8496
8497 YieldsPoison.insert(V);
8498 Visited.insert(BB);
8499
8500 while (true) {
8501 for (const auto &I : make_range(Begin, End)) {
8502 if (--ScanLimit == 0)
8503 return false;
8504 if (mustTriggerUB(&I, YieldsPoison))
8505 return true;
8507 return false;
8508
8509 // If an operand is poison and propagates it, mark I as yielding poison.
8510 for (const Use &Op : I.operands()) {
8511 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8512 YieldsPoison.insert(&I);
8513 break;
8514 }
8515 }
8516
8517 // Special handling for select, which returns poison if its operand 0 is
8518 // poison (handled in the loop above) *or* if both its true/false operands
8519 // are poison (handled here).
8520 if (I.getOpcode() == Instruction::Select &&
8521 YieldsPoison.count(I.getOperand(1)) &&
8522 YieldsPoison.count(I.getOperand(2))) {
8523 YieldsPoison.insert(&I);
8524 }
8525 }
8526
8527 BB = BB->getSingleSuccessor();
8528 if (!BB || !Visited.insert(BB).second)
8529 break;
8530
8531 Begin = BB->getFirstNonPHIIt();
8532 End = BB->end();
8533 }
8534 return false;
8535}
8536
8538 return ::programUndefinedIfUndefOrPoison(Inst, false);
8539}
8540
8542 return ::programUndefinedIfUndefOrPoison(Inst, true);
8543}
8544
8545static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8546 if (FMF.noNaNs())
8547 return true;
8548
8549 if (auto *C = dyn_cast<ConstantFP>(V))
8550 return !C->isNaN();
8551
8552 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8553 if (!C->getElementType()->isFloatingPointTy())
8554 return false;
8555 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8556 if (C->getElementAsAPFloat(I).isNaN())
8557 return false;
8558 }
8559 return true;
8560 }
8561
8563 return true;
8564
8565 return false;
8566}
8567
8568static bool isKnownNonZero(const Value *V) {
8569 if (auto *C = dyn_cast<ConstantFP>(V))
8570 return !C->isZero();
8571
8572 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8573 if (!C->getElementType()->isFloatingPointTy())
8574 return false;
8575 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8576 if (C->getElementAsAPFloat(I).isZero())
8577 return false;
8578 }
8579 return true;
8580 }
8581
8582 return false;
8583}
8584
8585/// Match clamp pattern for float types without care about NaNs or signed zeros.
8586/// Given non-min/max outer cmp/select from the clamp pattern this
8587/// function recognizes if it can be substitued by a "canonical" min/max
8588/// pattern.
8590 Value *CmpLHS, Value *CmpRHS,
8591 Value *TrueVal, Value *FalseVal,
8592 Value *&LHS, Value *&RHS) {
8593 // Try to match
8594 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8595 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8596 // and return description of the outer Max/Min.
8597
8598 // First, check if select has inverse order:
8599 if (CmpRHS == FalseVal) {
8600 std::swap(TrueVal, FalseVal);
8601 Pred = CmpInst::getInversePredicate(Pred);
8602 }
8603
8604 // Assume success now. If there's no match, callers should not use these anyway.
8605 LHS = TrueVal;
8606 RHS = FalseVal;
8607
8608 const APFloat *FC1;
8609 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8610 return {SPF_UNKNOWN, SPNB_NA, false};
8611
8612 const APFloat *FC2;
8613 switch (Pred) {
8614 case CmpInst::FCMP_OLT:
8615 case CmpInst::FCMP_OLE:
8616 case CmpInst::FCMP_ULT:
8617 case CmpInst::FCMP_ULE:
8618 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8619 *FC1 < *FC2)
8620 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8621 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8622 *FC1 < *FC2)
8623 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8624 break;
8625 case CmpInst::FCMP_OGT:
8626 case CmpInst::FCMP_OGE:
8627 case CmpInst::FCMP_UGT:
8628 case CmpInst::FCMP_UGE:
8629 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8630 *FC1 > *FC2)
8631 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8632 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8633 *FC1 > *FC2)
8634 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8635 break;
8636 default:
8637 break;
8638 }
8639
8640 return {SPF_UNKNOWN, SPNB_NA, false};
8641}
8642
8643/// Recognize variations of:
8644/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8646 Value *CmpLHS, Value *CmpRHS,
8647 Value *TrueVal, Value *FalseVal) {
8648 // Swap the select operands and predicate to match the patterns below.
8649 if (CmpRHS != TrueVal) {
8650 Pred = ICmpInst::getSwappedPredicate(Pred);
8651 std::swap(TrueVal, FalseVal);
8652 }
8653 const APInt *C1;
8654 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8655 const APInt *C2;
8656 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8657 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8658 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8659 return {SPF_SMAX, SPNB_NA, false};
8660
8661 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8662 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8663 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8664 return {SPF_SMIN, SPNB_NA, false};
8665
8666 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8667 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8668 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8669 return {SPF_UMAX, SPNB_NA, false};
8670
8671 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8672 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8673 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8674 return {SPF_UMIN, SPNB_NA, false};
8675 }
8676 return {SPF_UNKNOWN, SPNB_NA, false};
8677}
8678
8679/// Recognize variations of:
8680/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8682 Value *CmpLHS, Value *CmpRHS,
8683 Value *TVal, Value *FVal,
8684 unsigned Depth) {
8685 // TODO: Allow FP min/max with nnan/nsz.
8686 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8687
8688 Value *A = nullptr, *B = nullptr;
8689 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8690 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8691 return {SPF_UNKNOWN, SPNB_NA, false};
8692
8693 Value *C = nullptr, *D = nullptr;
8694 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8695 if (L.Flavor != R.Flavor)
8696 return {SPF_UNKNOWN, SPNB_NA, false};
8697
8698 // We have something like: x Pred y ? min(a, b) : min(c, d).
8699 // Try to match the compare to the min/max operations of the select operands.
8700 // First, make sure we have the right compare predicate.
8701 switch (L.Flavor) {
8702 case SPF_SMIN:
8703 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8704 Pred = ICmpInst::getSwappedPredicate(Pred);
8705 std::swap(CmpLHS, CmpRHS);
8706 }
8707 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8708 break;
8709 return {SPF_UNKNOWN, SPNB_NA, false};
8710 case SPF_SMAX:
8711 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8712 Pred = ICmpInst::getSwappedPredicate(Pred);
8713 std::swap(CmpLHS, CmpRHS);
8714 }
8715 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8716 break;
8717 return {SPF_UNKNOWN, SPNB_NA, false};
8718 case SPF_UMIN:
8719 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8720 Pred = ICmpInst::getSwappedPredicate(Pred);
8721 std::swap(CmpLHS, CmpRHS);
8722 }
8723 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8724 break;
8725 return {SPF_UNKNOWN, SPNB_NA, false};
8726 case SPF_UMAX:
8727 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8728 Pred = ICmpInst::getSwappedPredicate(Pred);
8729 std::swap(CmpLHS, CmpRHS);
8730 }
8731 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8732 break;
8733 return {SPF_UNKNOWN, SPNB_NA, false};
8734 default:
8735 return {SPF_UNKNOWN, SPNB_NA, false};
8736 }
8737
8738 // If there is a common operand in the already matched min/max and the other
8739 // min/max operands match the compare operands (either directly or inverted),
8740 // then this is min/max of the same flavor.
8741
8742 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8743 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8744 if (D == B) {
8745 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8746 match(A, m_Not(m_Specific(CmpRHS)))))
8747 return {L.Flavor, SPNB_NA, false};
8748 }
8749 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8750 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8751 if (C == B) {
8752 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8753 match(A, m_Not(m_Specific(CmpRHS)))))
8754 return {L.Flavor, SPNB_NA, false};
8755 }
8756 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8757 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8758 if (D == A) {
8759 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8760 match(B, m_Not(m_Specific(CmpRHS)))))
8761 return {L.Flavor, SPNB_NA, false};
8762 }
8763 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8764 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8765 if (C == A) {
8766 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8767 match(B, m_Not(m_Specific(CmpRHS)))))
8768 return {L.Flavor, SPNB_NA, false};
8769 }
8770
8771 return {SPF_UNKNOWN, SPNB_NA, false};
8772}
8773
8774/// If the input value is the result of a 'not' op, constant integer, or vector
8775/// splat of a constant integer, return the bitwise-not source value.
8776/// TODO: This could be extended to handle non-splat vector integer constants.
8778 Value *NotV;
8779 if (match(V, m_Not(m_Value(NotV))))
8780 return NotV;
8781
8782 const APInt *C;
8783 if (match(V, m_APInt(C)))
8784 return ConstantInt::get(V->getType(), ~(*C));
8785
8786 return nullptr;
8787}
8788
8789/// Match non-obvious integer minimum and maximum sequences.
8791 Value *CmpLHS, Value *CmpRHS,
8792 Value *TrueVal, Value *FalseVal,
8793 Value *&LHS, Value *&RHS,
8794 unsigned Depth) {
8795 // Assume success. If there's no match, callers should not use these anyway.
8796 LHS = TrueVal;
8797 RHS = FalseVal;
8798
8799 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8801 return SPR;
8802
8803 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8805 return SPR;
8806
8807 // Look through 'not' ops to find disguised min/max.
8808 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8809 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8810 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8811 switch (Pred) {
8812 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8813 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8814 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8815 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8816 default: break;
8817 }
8818 }
8819
8820 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8821 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8822 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8823 switch (Pred) {
8824 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8825 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8826 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8827 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8828 default: break;
8829 }
8830 }
8831
8832 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8833 return {SPF_UNKNOWN, SPNB_NA, false};
8834
8835 const APInt *C1;
8836 if (!match(CmpRHS, m_APInt(C1)))
8837 return {SPF_UNKNOWN, SPNB_NA, false};
8838
8839 // An unsigned min/max can be written with a signed compare.
8840 const APInt *C2;
8841 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8842 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8843 // Is the sign bit set?
8844 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8845 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8846 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
8847 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8848
8849 // Is the sign bit clear?
8850 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
8851 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
8852 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
8853 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8854 }
8855
8856 return {SPF_UNKNOWN, SPNB_NA, false};
8857}
8858
8859bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
8860 bool AllowPoison) {
8861 assert(X && Y && "Invalid operand");
8862
8863 auto IsNegationOf = [&](const Value *X, const Value *Y) {
8864 if (!match(X, m_Neg(m_Specific(Y))))
8865 return false;
8866
8867 auto *BO = cast<BinaryOperator>(X);
8868 if (NeedNSW && !BO->hasNoSignedWrap())
8869 return false;
8870
8871 auto *Zero = cast<Constant>(BO->getOperand(0));
8872 if (!AllowPoison && !Zero->isNullValue())
8873 return false;
8874
8875 return true;
8876 };
8877
8878 // X = -Y or Y = -X
8879 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
8880 return true;
8881
8882 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
8883 Value *A, *B;
8884 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
8885 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
8886 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
8888}
8889
8890bool llvm::isKnownInversion(const Value *X, const Value *Y) {
8891 // Handle X = icmp pred A, B, Y = icmp pred A, C.
8892 Value *A, *B, *C;
8893 CmpPredicate Pred1, Pred2;
8894 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
8895 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
8896 return false;
8897
8898 // They must both have samesign flag or not.
8899 if (Pred1.hasSameSign() != Pred2.hasSameSign())
8900 return false;
8901
8902 if (B == C)
8903 return Pred1 == ICmpInst::getInversePredicate(Pred2);
8904
8905 // Try to infer the relationship from constant ranges.
8906 const APInt *RHSC1, *RHSC2;
8907 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
8908 return false;
8909
8910 // Sign bits of two RHSCs should match.
8911 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
8912 return false;
8913
8914 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
8915 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
8916
8917 return CR1.inverse() == CR2;
8918}
8919
8921 SelectPatternNaNBehavior NaNBehavior,
8922 bool Ordered) {
8923 switch (Pred) {
8924 default:
8925 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
8926 case ICmpInst::ICMP_UGT:
8927 case ICmpInst::ICMP_UGE:
8928 return {SPF_UMAX, SPNB_NA, false};
8929 case ICmpInst::ICMP_SGT:
8930 case ICmpInst::ICMP_SGE:
8931 return {SPF_SMAX, SPNB_NA, false};
8932 case ICmpInst::ICMP_ULT:
8933 case ICmpInst::ICMP_ULE:
8934 return {SPF_UMIN, SPNB_NA, false};
8935 case ICmpInst::ICMP_SLT:
8936 case ICmpInst::ICMP_SLE:
8937 return {SPF_SMIN, SPNB_NA, false};
8938 case FCmpInst::FCMP_UGT:
8939 case FCmpInst::FCMP_UGE:
8940 case FCmpInst::FCMP_OGT:
8941 case FCmpInst::FCMP_OGE:
8942 return {SPF_FMAXNUM, NaNBehavior, Ordered};
8943 case FCmpInst::FCMP_ULT:
8944 case FCmpInst::FCMP_ULE:
8945 case FCmpInst::FCMP_OLT:
8946 case FCmpInst::FCMP_OLE:
8947 return {SPF_FMINNUM, NaNBehavior, Ordered};
8948 }
8949}
8950
8951std::optional<std::pair<CmpPredicate, Constant *>>
8954 "Only for relational integer predicates.");
8955 if (isa<UndefValue>(C))
8956 return std::nullopt;
8957
8958 Type *Type = C->getType();
8959 bool IsSigned = ICmpInst::isSigned(Pred);
8960
8962 bool WillIncrement =
8963 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
8964
8965 // Check if the constant operand can be safely incremented/decremented
8966 // without overflowing/underflowing.
8967 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
8968 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
8969 };
8970
8971 Constant *SafeReplacementConstant = nullptr;
8972 if (auto *CI = dyn_cast<ConstantInt>(C)) {
8973 // Bail out if the constant can't be safely incremented/decremented.
8974 if (!ConstantIsOk(CI))
8975 return std::nullopt;
8976 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
8977 unsigned NumElts = FVTy->getNumElements();
8978 for (unsigned i = 0; i != NumElts; ++i) {
8979 Constant *Elt = C->getAggregateElement(i);
8980 if (!Elt)
8981 return std::nullopt;
8982
8983 if (isa<UndefValue>(Elt))
8984 continue;
8985
8986 // Bail out if we can't determine if this constant is min/max or if we
8987 // know that this constant is min/max.
8988 auto *CI = dyn_cast<ConstantInt>(Elt);
8989 if (!CI || !ConstantIsOk(CI))
8990 return std::nullopt;
8991
8992 if (!SafeReplacementConstant)
8993 SafeReplacementConstant = CI;
8994 }
8995 } else if (isa<VectorType>(C->getType())) {
8996 // Handle scalable splat
8997 Value *SplatC = C->getSplatValue();
8998 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
8999 // Bail out if the constant can't be safely incremented/decremented.
9000 if (!CI || !ConstantIsOk(CI))
9001 return std::nullopt;
9002 } else {
9003 // ConstantExpr?
9004 return std::nullopt;
9005 }
9006
9007 // It may not be safe to change a compare predicate in the presence of
9008 // undefined elements, so replace those elements with the first safe constant
9009 // that we found.
9010 // TODO: in case of poison, it is safe; let's replace undefs only.
9011 if (C->containsUndefOrPoisonElement()) {
9012 assert(SafeReplacementConstant && "Replacement constant not set");
9013 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9014 }
9015
9017
9018 // Increment or decrement the constant.
9019 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9020 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9021
9022 return std::make_pair(NewPred, NewC);
9023}
9024
9026 FastMathFlags FMF,
9027 Value *CmpLHS, Value *CmpRHS,
9028 Value *TrueVal, Value *FalseVal,
9029 Value *&LHS, Value *&RHS,
9030 unsigned Depth) {
9031 if (CmpInst::isFPPredicate(Pred)) {
9032 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9033 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9034 // purpose of identifying min/max. Disregard vector constants with undefined
9035 // elements because those can not be back-propagated for analysis.
9036 Value *OutputZeroVal = nullptr;
9037 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9038 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9039 OutputZeroVal = TrueVal;
9040 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9041 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9042 OutputZeroVal = FalseVal;
9043
9044 if (OutputZeroVal) {
9045 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9046 CmpLHS = OutputZeroVal;
9047 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9048 CmpRHS = OutputZeroVal;
9049 }
9050 }
9051
9052 LHS = CmpLHS;
9053 RHS = CmpRHS;
9054
9055 // Signed zero may return inconsistent results between implementations.
9056 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9057 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9058 // Therefore, we behave conservatively and only proceed if at least one of the
9059 // operands is known to not be zero or if we don't care about signed zero.
9060 if (CmpInst::isFPPredicate(Pred)) {
9061 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9062 !isKnownNonZero(CmpRHS))
9063 return {SPF_UNKNOWN, SPNB_NA, false};
9064 }
9065
9066 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9067 bool Ordered = false;
9068
9069 // When given one NaN and one non-NaN input:
9070 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9071 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9072 // ordered comparison fails), which could be NaN or non-NaN.
9073 // so here we discover exactly what NaN behavior is required/accepted.
9074 if (CmpInst::isFPPredicate(Pred)) {
9075 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9076 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9077
9078 if (LHSSafe && RHSSafe) {
9079 // Both operands are known non-NaN.
9080 NaNBehavior = SPNB_RETURNS_ANY;
9081 Ordered = CmpInst::isOrdered(Pred);
9082 } else if (CmpInst::isOrdered(Pred)) {
9083 // An ordered comparison will return false when given a NaN, so it
9084 // returns the RHS.
9085 Ordered = true;
9086 if (LHSSafe)
9087 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9088 NaNBehavior = SPNB_RETURNS_NAN;
9089 else if (RHSSafe)
9090 NaNBehavior = SPNB_RETURNS_OTHER;
9091 else
9092 // Completely unsafe.
9093 return {SPF_UNKNOWN, SPNB_NA, false};
9094 } else {
9095 Ordered = false;
9096 // An unordered comparison will return true when given a NaN, so it
9097 // returns the LHS.
9098 if (LHSSafe)
9099 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9100 NaNBehavior = SPNB_RETURNS_OTHER;
9101 else if (RHSSafe)
9102 NaNBehavior = SPNB_RETURNS_NAN;
9103 else
9104 // Completely unsafe.
9105 return {SPF_UNKNOWN, SPNB_NA, false};
9106 }
9107 }
9108
9109 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9110 std::swap(CmpLHS, CmpRHS);
9111 Pred = CmpInst::getSwappedPredicate(Pred);
9112 if (NaNBehavior == SPNB_RETURNS_NAN)
9113 NaNBehavior = SPNB_RETURNS_OTHER;
9114 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9115 NaNBehavior = SPNB_RETURNS_NAN;
9116 Ordered = !Ordered;
9117 }
9118
9119 // ([if]cmp X, Y) ? X : Y
9120 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9121 return getSelectPattern(Pred, NaNBehavior, Ordered);
9122
9123 if (isKnownNegation(TrueVal, FalseVal)) {
9124 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9125 // match against either LHS or sign-preserving operations on LHS, like
9126 // sext(LHS), or binary ops that do not wrap in signed sense.
9127 auto CmpLHSOrSExt =
9128 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9129 auto MaybeSExtOrMulCmpLHS =
9130 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9131 m_NSWShl(CmpLHSOrSExt, m_Value()));
9132 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9133 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9134 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9135 // Set the return values. If the compare uses the negated value (-X >s 0),
9136 // swap the return values because the negated value is always 'RHS'.
9137 LHS = TrueVal;
9138 RHS = FalseVal;
9139 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9140 std::swap(LHS, RHS);
9141
9142 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9143 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9144 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9145 return {SPF_ABS, SPNB_NA, false};
9146
9147 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9148 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9149 return {SPF_ABS, SPNB_NA, false};
9150
9151 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9152 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9153 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9154 return {SPF_NABS, SPNB_NA, false};
9155 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9156 // Set the return values. If the compare uses the negated value (-X >s 0),
9157 // swap the return values because the negated value is always 'RHS'.
9158 LHS = FalseVal;
9159 RHS = TrueVal;
9160 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9161 std::swap(LHS, RHS);
9162
9163 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9164 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9165 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9166 return {SPF_NABS, SPNB_NA, false};
9167
9168 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9169 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9170 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9171 return {SPF_ABS, SPNB_NA, false};
9172 }
9173 }
9174
9175 if (CmpInst::isIntPredicate(Pred))
9176 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9177
9178 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9179 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9180 // semantics than minNum. Be conservative in such case.
9181 if (NaNBehavior != SPNB_RETURNS_ANY ||
9182 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9183 !isKnownNonZero(CmpRHS)))
9184 return {SPF_UNKNOWN, SPNB_NA, false};
9185
9186 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9187}
9188
9190 Instruction::CastOps *CastOp) {
9191 const DataLayout &DL = CmpI->getDataLayout();
9192
9193 Constant *CastedTo = nullptr;
9194 switch (*CastOp) {
9195 case Instruction::ZExt:
9196 if (CmpI->isUnsigned())
9197 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9198 break;
9199 case Instruction::SExt:
9200 if (CmpI->isSigned())
9201 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9202 break;
9203 case Instruction::Trunc:
9204 Constant *CmpConst;
9205 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9206 CmpConst->getType() == SrcTy) {
9207 // Here we have the following case:
9208 //
9209 // %cond = cmp iN %x, CmpConst
9210 // %tr = trunc iN %x to iK
9211 // %narrowsel = select i1 %cond, iK %t, iK C
9212 //
9213 // We can always move trunc after select operation:
9214 //
9215 // %cond = cmp iN %x, CmpConst
9216 // %widesel = select i1 %cond, iN %x, iN CmpConst
9217 // %tr = trunc iN %widesel to iK
9218 //
9219 // Note that C could be extended in any way because we don't care about
9220 // upper bits after truncation. It can't be abs pattern, because it would
9221 // look like:
9222 //
9223 // select i1 %cond, x, -x.
9224 //
9225 // So only min/max pattern could be matched. Such match requires widened C
9226 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9227 // CmpConst == C is checked below.
9228 CastedTo = CmpConst;
9229 } else {
9230 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9231 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9232 }
9233 break;
9234 case Instruction::FPTrunc:
9235 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9236 break;
9237 case Instruction::FPExt:
9238 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9239 break;
9240 case Instruction::FPToUI:
9241 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9242 break;
9243 case Instruction::FPToSI:
9244 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9245 break;
9246 case Instruction::UIToFP:
9247 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9248 break;
9249 case Instruction::SIToFP:
9250 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9251 break;
9252 default:
9253 break;
9254 }
9255
9256 if (!CastedTo)
9257 return nullptr;
9258
9259 // Make sure the cast doesn't lose any information.
9260 Constant *CastedBack =
9261 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9262 if (CastedBack && CastedBack != C)
9263 return nullptr;
9264
9265 return CastedTo;
9266}
9267
9268/// Helps to match a select pattern in case of a type mismatch.
9269///
9270/// The function processes the case when type of true and false values of a
9271/// select instruction differs from type of the cmp instruction operands because
9272/// of a cast instruction. The function checks if it is legal to move the cast
9273/// operation after "select". If yes, it returns the new second value of
9274/// "select" (with the assumption that cast is moved):
9275/// 1. As operand of cast instruction when both values of "select" are same cast
9276/// instructions.
9277/// 2. As restored constant (by applying reverse cast operation) when the first
9278/// value of the "select" is a cast operation and the second value is a
9279/// constant. It is implemented in lookThroughCastConst().
9280/// 3. As one operand is cast instruction and the other is not. The operands in
9281/// sel(cmp) are in different type integer.
9282/// NOTE: We return only the new second value because the first value could be
9283/// accessed as operand of cast instruction.
9285 Instruction::CastOps *CastOp) {
9286 auto *Cast1 = dyn_cast<CastInst>(V1);
9287 if (!Cast1)
9288 return nullptr;
9289
9290 *CastOp = Cast1->getOpcode();
9291 Type *SrcTy = Cast1->getSrcTy();
9292 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9293 // If V1 and V2 are both the same cast from the same type, look through V1.
9294 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9295 return Cast2->getOperand(0);
9296 return nullptr;
9297 }
9298
9299 auto *C = dyn_cast<Constant>(V2);
9300 if (C)
9301 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9302
9303 Value *CastedTo = nullptr;
9304 if (*CastOp == Instruction::Trunc) {
9305 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9306 // Here we have the following case:
9307 // %y_ext = sext iK %y to iN
9308 // %cond = cmp iN %x, %y_ext
9309 // %tr = trunc iN %x to iK
9310 // %narrowsel = select i1 %cond, iK %tr, iK %y
9311 //
9312 // We can always move trunc after select operation:
9313 // %y_ext = sext iK %y to iN
9314 // %cond = cmp iN %x, %y_ext
9315 // %widesel = select i1 %cond, iN %x, iN %y_ext
9316 // %tr = trunc iN %widesel to iK
9317 assert(V2->getType() == Cast1->getType() &&
9318 "V2 and Cast1 should be the same type.");
9319 CastedTo = CmpI->getOperand(1);
9320 }
9321 }
9322
9323 return CastedTo;
9324}
9326 Instruction::CastOps *CastOp,
9327 unsigned Depth) {
9329 return {SPF_UNKNOWN, SPNB_NA, false};
9330
9332 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9333
9334 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9335 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9336
9337 Value *TrueVal = SI->getTrueValue();
9338 Value *FalseVal = SI->getFalseValue();
9339
9340 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9341 SI->getFastMathFlagsOrNone(),
9342 CastOp, Depth);
9343}
9344
9346 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9347 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9348 CmpInst::Predicate Pred = CmpI->getPredicate();
9349 Value *CmpLHS = CmpI->getOperand(0);
9350 Value *CmpRHS = CmpI->getOperand(1);
9351 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9352 FMF.setNoNaNs();
9353
9354 // Bail out early.
9355 if (CmpI->isEquality())
9356 return {SPF_UNKNOWN, SPNB_NA, false};
9357
9358 // Deal with type mismatches.
9359 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9360 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9361 // If this is a potential fmin/fmax with a cast to integer, then ignore
9362 // -0.0 because there is no corresponding integer value.
9363 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9364 FMF.setNoSignedZeros();
9365 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9366 cast<CastInst>(TrueVal)->getOperand(0), C,
9367 LHS, RHS, Depth);
9368 }
9369 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9370 // If this is a potential fmin/fmax with a cast to integer, then ignore
9371 // -0.0 because there is no corresponding integer value.
9372 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9373 FMF.setNoSignedZeros();
9374 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9375 C, cast<CastInst>(FalseVal)->getOperand(0),
9376 LHS, RHS, Depth);
9377 }
9378 }
9379 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9380 LHS, RHS, Depth);
9381}
9382
9384 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9385 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9386 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9387 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9388 if (SPF == SPF_FMINNUM)
9389 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9390 if (SPF == SPF_FMAXNUM)
9391 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9392 llvm_unreachable("unhandled!");
9393}
9394
9396 switch (SPF) {
9398 return Intrinsic::umin;
9400 return Intrinsic::umax;
9402 return Intrinsic::smin;
9404 return Intrinsic::smax;
9405 default:
9406 llvm_unreachable("Unexpected SPF");
9407 }
9408}
9409
9411 if (SPF == SPF_SMIN) return SPF_SMAX;
9412 if (SPF == SPF_UMIN) return SPF_UMAX;
9413 if (SPF == SPF_SMAX) return SPF_SMIN;
9414 if (SPF == SPF_UMAX) return SPF_UMIN;
9415 llvm_unreachable("unhandled!");
9416}
9417
9419 switch (MinMaxID) {
9420 case Intrinsic::smax: return Intrinsic::smin;
9421 case Intrinsic::smin: return Intrinsic::smax;
9422 case Intrinsic::umax: return Intrinsic::umin;
9423 case Intrinsic::umin: return Intrinsic::umax;
9424 // Please note that next four intrinsics may produce the same result for
9425 // original and inverted case even if X != Y due to NaN is handled specially.
9426 case Intrinsic::maximum: return Intrinsic::minimum;
9427 case Intrinsic::minimum: return Intrinsic::maximum;
9428 case Intrinsic::maxnum: return Intrinsic::minnum;
9429 case Intrinsic::minnum: return Intrinsic::maxnum;
9430 case Intrinsic::maximumnum:
9431 return Intrinsic::minimumnum;
9432 case Intrinsic::minimumnum:
9433 return Intrinsic::maximumnum;
9434 default: llvm_unreachable("Unexpected intrinsic");
9435 }
9436}
9437
9439 switch (SPF) {
9442 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9443 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9444 default: llvm_unreachable("Unexpected flavor");
9445 }
9446}
9447
9448std::pair<Intrinsic::ID, bool>
9450 // Check if VL contains select instructions that can be folded into a min/max
9451 // vector intrinsic and return the intrinsic if it is possible.
9452 // TODO: Support floating point min/max.
9453 bool AllCmpSingleUse = true;
9454 SelectPatternResult SelectPattern;
9455 SelectPattern.Flavor = SPF_UNKNOWN;
9456 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9457 Value *LHS, *RHS;
9458 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9459 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9460 return false;
9461 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9462 SelectPattern.Flavor != CurrentPattern.Flavor)
9463 return false;
9464 SelectPattern = CurrentPattern;
9465 AllCmpSingleUse &=
9467 return true;
9468 })) {
9469 switch (SelectPattern.Flavor) {
9470 case SPF_SMIN:
9471 return {Intrinsic::smin, AllCmpSingleUse};
9472 case SPF_UMIN:
9473 return {Intrinsic::umin, AllCmpSingleUse};
9474 case SPF_SMAX:
9475 return {Intrinsic::smax, AllCmpSingleUse};
9476 case SPF_UMAX:
9477 return {Intrinsic::umax, AllCmpSingleUse};
9478 case SPF_FMAXNUM:
9479 return {Intrinsic::maxnum, AllCmpSingleUse};
9480 case SPF_FMINNUM:
9481 return {Intrinsic::minnum, AllCmpSingleUse};
9482 default:
9483 llvm_unreachable("unexpected select pattern flavor");
9484 }
9485 }
9486 return {Intrinsic::not_intrinsic, false};
9487}
9488
9489template <typename InstTy>
9490static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9491 Value *&Init, Value *&OtherOp) {
9492 // Handle the case of a simple two-predecessor recurrence PHI.
9493 // There's a lot more that could theoretically be done here, but
9494 // this is sufficient to catch some interesting cases.
9495 // TODO: Expand list -- gep, uadd.sat etc.
9496 if (PN->getNumIncomingValues() != 2)
9497 return false;
9498
9499 for (unsigned I = 0; I != 2; ++I) {
9500 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9501 Operation && Operation->getNumOperands() >= 2) {
9502 Value *LHS = Operation->getOperand(0);
9503 Value *RHS = Operation->getOperand(1);
9504 if (LHS != PN && RHS != PN)
9505 continue;
9506
9507 Inst = Operation;
9508 Init = PN->getIncomingValue(!I);
9509 OtherOp = (LHS == PN) ? RHS : LHS;
9510 return true;
9511 }
9512 }
9513 return false;
9514}
9515
9516template <typename InstTy>
9517static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9518 Value *&Init, Value *&OtherOp0,
9519 Value *&OtherOp1) {
9520 if (PN->getNumIncomingValues() != 2)
9521 return false;
9522
9523 for (unsigned I = 0; I != 2; ++I) {
9524 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9525 Operation && Operation->getNumOperands() >= 3) {
9526 Value *Op0 = Operation->getOperand(0);
9527 Value *Op1 = Operation->getOperand(1);
9528 Value *Op2 = Operation->getOperand(2);
9529
9530 if (Op0 != PN && Op1 != PN && Op2 != PN)
9531 continue;
9532
9533 Inst = Operation;
9534 Init = PN->getIncomingValue(!I);
9535 if (Op0 == PN) {
9536 OtherOp0 = Op1;
9537 OtherOp1 = Op2;
9538 } else if (Op1 == PN) {
9539 OtherOp0 = Op0;
9540 OtherOp1 = Op2;
9541 } else {
9542 OtherOp0 = Op0;
9543 OtherOp1 = Op1;
9544 }
9545 return true;
9546 }
9547 }
9548 return false;
9549}
9551 Value *&Start, Value *&Step) {
9552 // We try to match a recurrence of the form:
9553 // %iv = [Start, %entry], [%iv.next, %backedge]
9554 // %iv.next = binop %iv, Step
9555 // Or:
9556 // %iv = [Start, %entry], [%iv.next, %backedge]
9557 // %iv.next = binop Step, %iv
9558 return matchTwoInputRecurrence(P, BO, Start, Step);
9559}
9560
9562 Value *&Start, Value *&Step) {
9563 BinaryOperator *BO = nullptr;
9564 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9565 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9566}
9567
9569 PHINode *&P, Value *&Init,
9570 Value *&OtherOp) {
9571 // Binary intrinsics only supported for now.
9572 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9573 I->getType() != I->getArgOperand(1)->getType())
9574 return false;
9575
9576 IntrinsicInst *II = nullptr;
9577 P = dyn_cast<PHINode>(I->getArgOperand(0));
9578 if (!P)
9579 P = dyn_cast<PHINode>(I->getArgOperand(1));
9580
9581 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9582}
9583
9585 PHINode *&P, Value *&Init,
9586 Value *&OtherOp0,
9587 Value *&OtherOp1) {
9588 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9589 I->getType() != I->getArgOperand(1)->getType() ||
9590 I->getType() != I->getArgOperand(2)->getType())
9591 return false;
9592 IntrinsicInst *II = nullptr;
9593 P = dyn_cast<PHINode>(I->getArgOperand(0));
9594 if (!P) {
9595 P = dyn_cast<PHINode>(I->getArgOperand(1));
9596 if (!P)
9597 P = dyn_cast<PHINode>(I->getArgOperand(2));
9598 }
9599 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9600 II == I;
9601}
9602
9603/// Return true if "icmp Pred LHS RHS" is always true.
9605 const Value *RHS) {
9606 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9607 return true;
9608
9609 switch (Pred) {
9610 default:
9611 return false;
9612
9613 case CmpInst::ICMP_SLE: {
9614 const APInt *C;
9615
9616 // LHS s<= LHS +_{nsw} C if C >= 0
9617 // LHS s<= LHS | C if C >= 0
9618 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9620 return !C->isNegative();
9621
9622 // LHS s<= smax(LHS, V) for any V
9624 return true;
9625
9626 // smin(RHS, V) s<= RHS for any V
9628 return true;
9629
9630 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9631 const Value *X;
9632 const APInt *CLHS, *CRHS;
9633 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9635 return CLHS->sle(*CRHS);
9636
9637 return false;
9638 }
9639
9640 case CmpInst::ICMP_ULE: {
9641 // LHS u<= LHS +_{nuw} V for any V
9642 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9644 return true;
9645
9646 // LHS u<= LHS | V for any V
9647 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9648 return true;
9649
9650 // LHS u<= umax(LHS, V) for any V
9652 return true;
9653
9654 // RHS >> V u<= RHS for any V
9655 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9656 return true;
9657
9658 // RHS u/ C_ugt_1 u<= RHS
9659 const APInt *C;
9660 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9661 return true;
9662
9663 // RHS & V u<= RHS for any V
9665 return true;
9666
9667 // umin(RHS, V) u<= RHS for any V
9669 return true;
9670
9671 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9672 const Value *X;
9673 const APInt *CLHS, *CRHS;
9674 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9676 return CLHS->ule(*CRHS);
9677
9678 return false;
9679 }
9680 }
9681}
9682
9683/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9684/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9685static std::optional<bool>
9687 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9688 switch (Pred) {
9689 default:
9690 return std::nullopt;
9691
9692 case CmpInst::ICMP_SLT:
9693 case CmpInst::ICMP_SLE:
9694 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9696 return true;
9697 return std::nullopt;
9698
9699 case CmpInst::ICMP_SGT:
9700 case CmpInst::ICMP_SGE:
9701 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9703 return true;
9704 return std::nullopt;
9705
9706 case CmpInst::ICMP_ULT:
9707 case CmpInst::ICMP_ULE:
9708 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9710 return true;
9711 return std::nullopt;
9712
9713 case CmpInst::ICMP_UGT:
9714 case CmpInst::ICMP_UGE:
9715 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9717 return true;
9718 return std::nullopt;
9719 }
9720}
9721
9722/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9723/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9724/// Otherwise, return std::nullopt if we can't infer anything.
9725static std::optional<bool>
9727 CmpPredicate RPred, const ConstantRange &RCR) {
9728 auto CRImpliesPred = [&](ConstantRange CR,
9729 CmpInst::Predicate Pred) -> std::optional<bool> {
9730 // If all true values for lhs and true for rhs, lhs implies rhs
9731 if (CR.icmp(Pred, RCR))
9732 return true;
9733
9734 // If there is no overlap, lhs implies not rhs
9735 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9736 return false;
9737
9738 return std::nullopt;
9739 };
9740 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9741 RPred))
9742 return Res;
9743 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9745 : LPred.dropSameSign();
9747 : RPred.dropSameSign();
9748 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9749 RPred);
9750 }
9751 return std::nullopt;
9752}
9753
9754/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9755/// is true. Return false if LHS implies RHS is false. Otherwise, return
9756/// std::nullopt if we can't infer anything.
9757static std::optional<bool>
9758isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9759 CmpPredicate RPred, const Value *R0, const Value *R1,
9760 const DataLayout &DL, bool LHSIsTrue) {
9761 // The rest of the logic assumes the LHS condition is true. If that's not the
9762 // case, invert the predicate to make it so.
9763 if (!LHSIsTrue)
9764 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9765
9766 // We can have non-canonical operands, so try to normalize any common operand
9767 // to L0/R0.
9768 if (L0 == R1) {
9769 std::swap(R0, R1);
9770 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9771 }
9772 if (R0 == L1) {
9773 std::swap(L0, L1);
9774 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9775 }
9776 if (L1 == R1) {
9777 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9778 if (L0 != R0 || match(L0, m_ImmConstant())) {
9779 std::swap(L0, L1);
9780 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9781 std::swap(R0, R1);
9782 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9783 }
9784 }
9785
9786 // See if we can infer anything if operand-0 matches and we have at least one
9787 // constant.
9788 const APInt *Unused;
9789 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9790 // Potential TODO: We could also further use the constant range of L0/R0 to
9791 // further constraint the constant ranges. At the moment this leads to
9792 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9793 // C1` (see discussion: D58633).
9794 SimplifyQuery SQ(DL);
9799
9800 // Even if L1/R1 are not both constant, we can still sometimes deduce
9801 // relationship from a single constant. For example X u> Y implies X != 0.
9802 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9803 return R;
9804 // If both L1/R1 were exact constant ranges and we didn't get anything
9805 // here, we won't be able to deduce this.
9806 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9807 return std::nullopt;
9808 }
9809
9810 // Can we infer anything when the two compares have matching operands?
9811 if (L0 == R0 && L1 == R1)
9812 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9813
9814 // It only really makes sense in the context of signed comparison for "X - Y
9815 // must be positive if X >= Y and no overflow".
9816 // Take SGT as an example: L0:x > L1:y and C >= 0
9817 // ==> R0:(x -nsw y) < R1:(-C) is false
9818 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9819 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9820 SignedLPred == ICmpInst::ICMP_SGE) &&
9821 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9822 if (match(R1, m_NonPositive()) &&
9823 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9824 return false;
9825 }
9826
9827 // Take SLT as an example: L0:x < L1:y and C <= 0
9828 // ==> R0:(x -nsw y) < R1:(-C) is true
9829 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9830 SignedLPred == ICmpInst::ICMP_SLE) &&
9831 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9832 if (match(R1, m_NonNegative()) &&
9833 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9834 return true;
9835 }
9836
9837 // a - b == NonZero -> a != b
9838 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
9839 const APInt *L1C;
9840 Value *A, *B;
9841 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
9842 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
9843 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
9844 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
9849 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
9850 }
9851
9852 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
9853 if (L0 == R0 &&
9854 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
9855 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
9856 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
9857 return CmpPredicate::getMatching(LPred, RPred).has_value();
9858
9859 if (auto P = CmpPredicate::getMatching(LPred, RPred))
9860 return isImpliedCondOperands(*P, L0, L1, R0, R1);
9861
9862 return std::nullopt;
9863}
9864
9865/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9866/// is true. Return false if LHS implies RHS is false. Otherwise, return
9867/// std::nullopt if we can't infer anything.
9868static std::optional<bool>
9870 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
9871 const DataLayout &DL, bool LHSIsTrue) {
9872 // The rest of the logic assumes the LHS condition is true. If that's not the
9873 // case, invert the predicate to make it so.
9874 if (!LHSIsTrue)
9875 LPred = FCmpInst::getInversePredicate(LPred);
9876
9877 // We can have non-canonical operands, so try to normalize any common operand
9878 // to L0/R0.
9879 if (L0 == R1) {
9880 std::swap(R0, R1);
9881 RPred = FCmpInst::getSwappedPredicate(RPred);
9882 }
9883 if (R0 == L1) {
9884 std::swap(L0, L1);
9885 LPred = FCmpInst::getSwappedPredicate(LPred);
9886 }
9887 if (L1 == R1) {
9888 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9889 if (L0 != R0 || match(L0, m_ImmConstant())) {
9890 std::swap(L0, L1);
9891 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9892 std::swap(R0, R1);
9893 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9894 }
9895 }
9896
9897 // Can we infer anything when the two compares have matching operands?
9898 if (L0 == R0 && L1 == R1) {
9899 if ((LPred & RPred) == LPred)
9900 return true;
9901 if ((LPred & ~RPred) == LPred)
9902 return false;
9903 }
9904
9905 // See if we can infer anything if operand-0 matches and we have at least one
9906 // constant.
9907 const APFloat *L1C, *R1C;
9908 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
9909 if (std::optional<ConstantFPRange> DomCR =
9911 if (std::optional<ConstantFPRange> ImpliedCR =
9913 if (ImpliedCR->contains(*DomCR))
9914 return true;
9915 }
9916 if (std::optional<ConstantFPRange> ImpliedCR =
9918 FCmpInst::getInversePredicate(RPred), *R1C)) {
9919 if (ImpliedCR->contains(*DomCR))
9920 return false;
9921 }
9922 }
9923 }
9924
9925 return std::nullopt;
9926}
9927
9928/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
9929/// false. Otherwise, return std::nullopt if we can't infer anything. We
9930/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
9931/// instruction.
9932static std::optional<bool>
9934 const Value *RHSOp0, const Value *RHSOp1,
9935 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
9936 // The LHS must be an 'or', 'and', or a 'select' instruction.
9937 assert((LHS->getOpcode() == Instruction::And ||
9938 LHS->getOpcode() == Instruction::Or ||
9939 LHS->getOpcode() == Instruction::Select) &&
9940 "Expected LHS to be 'and', 'or', or 'select'.");
9941
9942 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
9943
9944 // If the result of an 'or' is false, then we know both legs of the 'or' are
9945 // false. Similarly, if the result of an 'and' is true, then we know both
9946 // legs of the 'and' are true.
9947 const Value *ALHS, *ARHS;
9948 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
9949 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
9950 // FIXME: Make this non-recursion.
9951 if (std::optional<bool> Implication = isImpliedCondition(
9952 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
9953 return Implication;
9954 if (std::optional<bool> Implication = isImpliedCondition(
9955 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
9956 return Implication;
9957 return std::nullopt;
9958 }
9959 return std::nullopt;
9960}
9961
9962std::optional<bool>
9964 const Value *RHSOp0, const Value *RHSOp1,
9965 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
9966 // Bail out when we hit the limit.
9968 return std::nullopt;
9969
9970 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
9971 // example.
9972 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
9973 return std::nullopt;
9974
9975 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
9976 "Expected integer type only!");
9977
9978 // Match not
9979 if (match(LHS, m_Not(m_Value(LHS))))
9980 LHSIsTrue = !LHSIsTrue;
9981
9982 // Both LHS and RHS are icmps.
9983 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
9984 CmpPredicate LHSPred;
9985 Value *LHSOp0, *LHSOp1;
9986 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
9987 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
9988 RHSOp1, DL, LHSIsTrue);
9989 } else {
9990 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
9991 "Expected floating point type only!");
9992 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
9993 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
9994 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
9995 DL, LHSIsTrue);
9996 }
9997
9998 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
9999 /// the RHS to be an icmp.
10000 /// FIXME: Add support for and/or/select on the RHS.
10001 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10002 if ((LHSI->getOpcode() == Instruction::And ||
10003 LHSI->getOpcode() == Instruction::Or ||
10004 LHSI->getOpcode() == Instruction::Select))
10005 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10006 Depth);
10007 }
10008 return std::nullopt;
10009}
10010
10011std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10012 const DataLayout &DL,
10013 bool LHSIsTrue, unsigned Depth) {
10014 // LHS ==> RHS by definition
10015 if (LHS == RHS)
10016 return LHSIsTrue;
10017
10018 // Match not
10019 bool InvertRHS = false;
10020 if (match(RHS, m_Not(m_Value(RHS)))) {
10021 if (LHS == RHS)
10022 return !LHSIsTrue;
10023 InvertRHS = true;
10024 }
10025
10026 CmpPredicate RHSPred;
10027 Value *RHSOp0, *RHSOp1;
10028 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10029 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10030 LHSIsTrue, Depth))
10031 return InvertRHS ? !*Implied : *Implied;
10032 return std::nullopt;
10033 }
10034 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10035 if (auto Implied = isImpliedCondition(
10036 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10037 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10038 return InvertRHS ? !*Implied : *Implied;
10039 return std::nullopt;
10040 }
10041
10043 return std::nullopt;
10044
10045 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10046 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10047 const Value *RHS1, *RHS2;
10048 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10049 if (std::optional<bool> Imp =
10050 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10051 if (*Imp == true)
10052 return !InvertRHS;
10053 if (std::optional<bool> Imp =
10054 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10055 if (*Imp == true)
10056 return !InvertRHS;
10057 }
10058 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10059 if (std::optional<bool> Imp =
10060 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10061 if (*Imp == false)
10062 return InvertRHS;
10063 if (std::optional<bool> Imp =
10064 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10065 if (*Imp == false)
10066 return InvertRHS;
10067 }
10068
10069 return std::nullopt;
10070}
10071
10072// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10073// condition dominating ContextI or nullptr, if no condition is found.
10074static std::pair<Value *, bool>
10076 if (!ContextI || !ContextI->getParent())
10077 return {nullptr, false};
10078
10079 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10080 // dominator tree (eg, from a SimplifyQuery) instead?
10081 const BasicBlock *ContextBB = ContextI->getParent();
10082 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10083 if (!PredBB)
10084 return {nullptr, false};
10085
10086 // We need a conditional branch in the predecessor.
10087 Value *PredCond;
10088 BasicBlock *TrueBB, *FalseBB;
10089 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10090 return {nullptr, false};
10091
10092 // The branch should get simplified. Don't bother simplifying this condition.
10093 if (TrueBB == FalseBB)
10094 return {nullptr, false};
10095
10096 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10097 "Predecessor block does not point to successor?");
10098
10099 // Is this condition implied by the predecessor condition?
10100 return {PredCond, TrueBB == ContextBB};
10101}
10102
10103std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10104 const Instruction *ContextI,
10105 const DataLayout &DL) {
10106 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10107 auto PredCond = getDomPredecessorCondition(ContextI);
10108 if (PredCond.first)
10109 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10110 return std::nullopt;
10111}
10112
10114 const Value *LHS,
10115 const Value *RHS,
10116 const Instruction *ContextI,
10117 const DataLayout &DL) {
10118 auto PredCond = getDomPredecessorCondition(ContextI);
10119 if (PredCond.first)
10120 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10121 PredCond.second);
10122 return std::nullopt;
10123}
10124
10126 APInt &Upper, const InstrInfoQuery &IIQ,
10127 bool PreferSignedRange) {
10128 unsigned Width = Lower.getBitWidth();
10129 const APInt *C;
10130 switch (BO.getOpcode()) {
10131 case Instruction::Sub:
10132 if (match(BO.getOperand(0), m_APInt(C))) {
10133 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10134 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10135
10136 // If the caller expects a signed compare, then try to use a signed range.
10137 // Otherwise if both no-wraps are set, use the unsigned range because it
10138 // is never larger than the signed range. Example:
10139 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10140 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10141 if (PreferSignedRange && HasNSW && HasNUW)
10142 HasNUW = false;
10143
10144 if (HasNUW) {
10145 // 'sub nuw c, x' produces [0, C].
10146 Upper = *C + 1;
10147 } else if (HasNSW) {
10148 if (C->isNegative()) {
10149 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10151 Upper = *C - APInt::getSignedMaxValue(Width);
10152 } else {
10153 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10154 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10155 Lower = *C - APInt::getSignedMaxValue(Width);
10157 }
10158 }
10159 }
10160 break;
10161 case Instruction::Add:
10162 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10163 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10164 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10165
10166 // If the caller expects a signed compare, then try to use a signed
10167 // range. Otherwise if both no-wraps are set, use the unsigned range
10168 // because it is never larger than the signed range. Example: "add nuw
10169 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10170 if (PreferSignedRange && HasNSW && HasNUW)
10171 HasNUW = false;
10172
10173 if (HasNUW) {
10174 // 'add nuw x, C' produces [C, UINT_MAX].
10175 Lower = *C;
10176 } else if (HasNSW) {
10177 if (C->isNegative()) {
10178 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10180 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10181 } else {
10182 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10183 Lower = APInt::getSignedMinValue(Width) + *C;
10184 Upper = APInt::getSignedMaxValue(Width) + 1;
10185 }
10186 }
10187 }
10188 break;
10189
10190 case Instruction::And:
10191 if (match(BO.getOperand(1), m_APInt(C)))
10192 // 'and x, C' produces [0, C].
10193 Upper = *C + 1;
10194 // X & -X is a power of two or zero. So we can cap the value at max power of
10195 // two.
10196 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10197 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10198 Upper = APInt::getSignedMinValue(Width) + 1;
10199 break;
10200
10201 case Instruction::Or:
10202 if (match(BO.getOperand(1), m_APInt(C)))
10203 // 'or x, C' produces [C, UINT_MAX].
10204 Lower = *C;
10205 break;
10206
10207 case Instruction::AShr:
10208 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10209 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10211 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10212 } else if (match(BO.getOperand(0), m_APInt(C))) {
10213 unsigned ShiftAmount = Width - 1;
10214 if (!C->isZero() && IIQ.isExact(&BO))
10215 ShiftAmount = C->countr_zero();
10216 if (C->isNegative()) {
10217 // 'ashr C, x' produces [C, C >> (Width-1)]
10218 Lower = *C;
10219 Upper = C->ashr(ShiftAmount) + 1;
10220 } else {
10221 // 'ashr C, x' produces [C >> (Width-1), C]
10222 Lower = C->ashr(ShiftAmount);
10223 Upper = *C + 1;
10224 }
10225 }
10226 break;
10227
10228 case Instruction::LShr:
10229 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10230 // 'lshr x, C' produces [0, UINT_MAX >> C].
10231 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10232 } else if (match(BO.getOperand(0), m_APInt(C))) {
10233 // 'lshr C, x' produces [C >> (Width-1), C].
10234 unsigned ShiftAmount = Width - 1;
10235 if (!C->isZero() && IIQ.isExact(&BO))
10236 ShiftAmount = C->countr_zero();
10237 Lower = C->lshr(ShiftAmount);
10238 Upper = *C + 1;
10239 }
10240 break;
10241
10242 case Instruction::Shl:
10243 if (match(BO.getOperand(0), m_APInt(C))) {
10244 if (IIQ.hasNoUnsignedWrap(&BO)) {
10245 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10246 Lower = *C;
10247 Upper = Lower.shl(Lower.countl_zero()) + 1;
10248 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10249 if (C->isNegative()) {
10250 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10251 unsigned ShiftAmount = C->countl_one() - 1;
10252 Lower = C->shl(ShiftAmount);
10253 Upper = *C + 1;
10254 } else {
10255 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10256 unsigned ShiftAmount = C->countl_zero() - 1;
10257 Lower = *C;
10258 Upper = C->shl(ShiftAmount) + 1;
10259 }
10260 } else {
10261 // If lowbit is set, value can never be zero.
10262 if ((*C)[0])
10263 Lower = APInt::getOneBitSet(Width, 0);
10264 // If we are shifting a constant the largest it can be is if the longest
10265 // sequence of consecutive ones is shifted to the highbits (breaking
10266 // ties for which sequence is higher). At the moment we take a liberal
10267 // upper bound on this by just popcounting the constant.
10268 // TODO: There may be a bitwise trick for it longest/highest
10269 // consecutative sequence of ones (naive method is O(Width) loop).
10270 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10271 }
10272 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10273 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10274 }
10275 break;
10276
10277 case Instruction::SDiv:
10278 if (match(BO.getOperand(1), m_APInt(C))) {
10279 APInt IntMin = APInt::getSignedMinValue(Width);
10280 APInt IntMax = APInt::getSignedMaxValue(Width);
10281 if (C->isAllOnes()) {
10282 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10283 // where C != -1 and C != 0 and C != 1
10284 Lower = IntMin + 1;
10285 Upper = IntMax + 1;
10286 } else if (C->countl_zero() < Width - 1) {
10287 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10288 // where C != -1 and C != 0 and C != 1
10289 Lower = IntMin.sdiv(*C);
10290 Upper = IntMax.sdiv(*C);
10291 if (Lower.sgt(Upper))
10293 Upper = Upper + 1;
10294 assert(Upper != Lower && "Upper part of range has wrapped!");
10295 }
10296 } else if (match(BO.getOperand(0), m_APInt(C))) {
10297 if (C->isMinSignedValue()) {
10298 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10299 Lower = *C;
10300 Upper = Lower.lshr(1) + 1;
10301 } else {
10302 // 'sdiv C, x' produces [-|C|, |C|].
10303 Upper = C->abs() + 1;
10304 Lower = (-Upper) + 1;
10305 }
10306 }
10307 break;
10308
10309 case Instruction::UDiv:
10310 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10311 // 'udiv x, C' produces [0, UINT_MAX / C].
10312 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10313 } else if (match(BO.getOperand(0), m_APInt(C))) {
10314 // 'udiv C, x' produces [0, C].
10315 Upper = *C + 1;
10316 }
10317 break;
10318
10319 case Instruction::SRem:
10320 if (match(BO.getOperand(1), m_APInt(C))) {
10321 // 'srem x, C' produces (-|C|, |C|).
10322 Upper = C->abs();
10323 Lower = (-Upper) + 1;
10324 } else if (match(BO.getOperand(0), m_APInt(C))) {
10325 if (C->isNegative()) {
10326 // 'srem -|C|, x' produces [-|C|, 0].
10327 Upper = 1;
10328 Lower = *C;
10329 } else {
10330 // 'srem |C|, x' produces [0, |C|].
10331 Upper = *C + 1;
10332 }
10333 }
10334 break;
10335
10336 case Instruction::URem:
10337 if (match(BO.getOperand(1), m_APInt(C)))
10338 // 'urem x, C' produces [0, C).
10339 Upper = *C;
10340 else if (match(BO.getOperand(0), m_APInt(C)))
10341 // 'urem C, x' produces [0, C].
10342 Upper = *C + 1;
10343 break;
10344
10345 default:
10346 break;
10347 }
10348}
10349
10351 bool UseInstrInfo) {
10352 unsigned Width = II.getType()->getScalarSizeInBits();
10353 const APInt *C;
10354 switch (II.getIntrinsicID()) {
10355 case Intrinsic::ctlz:
10356 case Intrinsic::cttz: {
10357 APInt Upper(Width, Width);
10358 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10359 Upper += 1;
10360 // Maximum of set/clear bits is the bit width.
10362 }
10363 case Intrinsic::ctpop:
10364 // Maximum of set/clear bits is the bit width.
10366 APInt(Width, Width) + 1);
10367 case Intrinsic::uadd_sat:
10368 // uadd.sat(x, C) produces [C, UINT_MAX].
10369 if (match(II.getOperand(0), m_APInt(C)) ||
10370 match(II.getOperand(1), m_APInt(C)))
10372 break;
10373 case Intrinsic::sadd_sat:
10374 if (match(II.getOperand(0), m_APInt(C)) ||
10375 match(II.getOperand(1), m_APInt(C))) {
10376 if (C->isNegative())
10377 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10379 APInt::getSignedMaxValue(Width) + *C +
10380 1);
10381
10382 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10384 APInt::getSignedMaxValue(Width) + 1);
10385 }
10386 break;
10387 case Intrinsic::usub_sat:
10388 // usub.sat(C, x) produces [0, C].
10389 if (match(II.getOperand(0), m_APInt(C)))
10390 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10391
10392 // usub.sat(x, C) produces [0, UINT_MAX - C].
10393 if (match(II.getOperand(1), m_APInt(C)))
10395 APInt::getMaxValue(Width) - *C + 1);
10396 break;
10397 case Intrinsic::ssub_sat:
10398 if (match(II.getOperand(0), m_APInt(C))) {
10399 if (C->isNegative())
10400 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10402 *C - APInt::getSignedMinValue(Width) +
10403 1);
10404
10405 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10407 APInt::getSignedMaxValue(Width) + 1);
10408 } else if (match(II.getOperand(1), m_APInt(C))) {
10409 if (C->isNegative())
10410 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10412 APInt::getSignedMaxValue(Width) + 1);
10413
10414 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10416 APInt::getSignedMaxValue(Width) - *C +
10417 1);
10418 }
10419 break;
10420 case Intrinsic::umin:
10421 case Intrinsic::umax:
10422 case Intrinsic::smin:
10423 case Intrinsic::smax:
10424 if (!match(II.getOperand(0), m_APInt(C)) &&
10425 !match(II.getOperand(1), m_APInt(C)))
10426 break;
10427
10428 switch (II.getIntrinsicID()) {
10429 case Intrinsic::umin:
10430 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10431 case Intrinsic::umax:
10433 case Intrinsic::smin:
10435 *C + 1);
10436 case Intrinsic::smax:
10438 APInt::getSignedMaxValue(Width) + 1);
10439 default:
10440 llvm_unreachable("Must be min/max intrinsic");
10441 }
10442 break;
10443 case Intrinsic::abs:
10444 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10445 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10446 if (match(II.getOperand(1), m_One()))
10448 APInt::getSignedMaxValue(Width) + 1);
10449
10451 APInt::getSignedMinValue(Width) + 1);
10452 case Intrinsic::vscale:
10453 if (!II.getParent() || !II.getFunction())
10454 break;
10455 return getVScaleRange(II.getFunction(), Width);
10456 default:
10457 break;
10458 }
10459
10460 return ConstantRange::getFull(Width);
10461}
10462
10464 const InstrInfoQuery &IIQ) {
10465 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10466 const Value *LHS = nullptr, *RHS = nullptr;
10468 if (R.Flavor == SPF_UNKNOWN)
10469 return ConstantRange::getFull(BitWidth);
10470
10471 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10472 // If the negation part of the abs (in RHS) has the NSW flag,
10473 // then the result of abs(X) is [0..SIGNED_MAX],
10474 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10475 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10479
10482 }
10483
10484 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10485 // The result of -abs(X) is <= 0.
10487 APInt(BitWidth, 1));
10488 }
10489
10490 const APInt *C;
10491 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10492 return ConstantRange::getFull(BitWidth);
10493
10494 switch (R.Flavor) {
10495 case SPF_UMIN:
10497 case SPF_UMAX:
10499 case SPF_SMIN:
10501 *C + 1);
10502 case SPF_SMAX:
10505 default:
10506 return ConstantRange::getFull(BitWidth);
10507 }
10508}
10509
10511 // The maximum representable value of a half is 65504. For floats the maximum
10512 // value is 3.4e38 which requires roughly 129 bits.
10513 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10514 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10515 return;
10516 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10517 Lower = APInt(BitWidth, -65504, true);
10518 Upper = APInt(BitWidth, 65505);
10519 }
10520
10521 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10522 // For a fptoui the lower limit is left as 0.
10523 Upper = APInt(BitWidth, 65505);
10524 }
10525}
10526
10528 const SimplifyQuery &SQ,
10529 unsigned Depth) {
10530 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10531
10533 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10534
10535 if (auto *C = dyn_cast<Constant>(V))
10536 return C->toConstantRange();
10537
10538 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10539 ConstantRange CR = ConstantRange::getFull(BitWidth);
10540 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10541 APInt Lower = APInt(BitWidth, 0);
10542 APInt Upper = APInt(BitWidth, 0);
10543 // TODO: Return ConstantRange.
10544 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10546 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10548 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10549 ConstantRange CRTrue =
10550 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10551 ConstantRange CRFalse =
10552 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10553 CR = CRTrue.unionWith(CRFalse);
10555 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10556 ConstantRange SrcCR =
10557 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10558 CR = SrcCR.truncate(BitWidth);
10559 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10560 APInt Lower = APInt(BitWidth, 0);
10561 APInt Upper = APInt(BitWidth, 0);
10562 // TODO: Return ConstantRange.
10565 } else if (const auto *A = dyn_cast<Argument>(V))
10566 if (std::optional<ConstantRange> Range = A->getRange())
10567 CR = *Range;
10568
10569 if (auto *I = dyn_cast<Instruction>(V)) {
10570 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10572
10573 Value *FrexpSrc;
10574 if (const auto *CB = dyn_cast<CallBase>(V)) {
10575 if (std::optional<ConstantRange> Range = CB->getRange())
10576 CR = CR.intersectWith(*Range);
10578 m_Value(FrexpSrc))))) {
10579 const fltSemantics &FltSem =
10580 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10581 // It should be possible to implement this for any type, but this logic
10582 // only computes the range assuming standard subnormal handling.
10583 if (APFloat::isIEEELikeFP(FltSem)) {
10585 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10586
10587 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10588 // constrain its range when the source can be neither.
10589 if (KnownSrc.isKnownNeverInfOrNaN()) {
10590 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10591
10592 // Offset to find the true minimum exponent value for a denormal.
10593 if (!KnownSrc.isKnownNeverSubnormal())
10594 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10595
10596 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10597
10598 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10600
10601 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10602 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10603
10604 MinExp = std::max(AdjustedMin, MinExp);
10605 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10606 MaxExp);
10607
10609 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10610 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10611 /*isSigned=*/true));
10612 }
10613 }
10614 }
10615 }
10616
10617 if (SQ.CxtI && SQ.AC) {
10618 // Try to restrict the range based on information from assumptions.
10619 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10620 if (!AssumeVH)
10621 continue;
10622 CallInst *I = cast<CallInst>(AssumeVH);
10623 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10624 "Got assumption for the wrong function!");
10625 assert(I->getIntrinsicID() == Intrinsic::assume &&
10626 "must be an assume intrinsic");
10627
10628 if (!isValidAssumeForContext(I, SQ))
10629 continue;
10630 Value *Arg = I->getArgOperand(0);
10631 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10632 // Currently we just use information from comparisons.
10633 if (!Cmp || Cmp->getOperand(0) != V)
10634 continue;
10635 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10636 ConstantRange RHS =
10637 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10638 SQ.getWithInstruction(I), Depth + 1);
10639 CR = CR.intersectWith(
10640 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10641 }
10642 }
10643
10644 return CR;
10645}
10646
10647static void
10649 function_ref<void(Value *)> InsertAffected) {
10650 assert(V != nullptr);
10651 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10652 InsertAffected(V);
10653 } else if (auto *I = dyn_cast<Instruction>(V)) {
10654 InsertAffected(V);
10655
10656 // Peek through unary operators to find the source of the condition.
10657 Value *Op;
10659 m_Trunc(m_Value(Op))))) {
10661 InsertAffected(Op);
10662 }
10663 }
10664}
10665
10667 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10668 auto AddAffected = [&InsertAffected](Value *V) {
10669 addValueAffectedByCondition(V, InsertAffected);
10670 };
10671
10672 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10673 if (IsAssume) {
10674 AddAffected(LHS);
10675 AddAffected(RHS);
10676 } else if (match(RHS, m_Constant()))
10677 AddAffected(LHS);
10678 };
10679
10680 SmallVector<Value *, 8> Worklist;
10682 Worklist.push_back(Cond);
10683 while (!Worklist.empty()) {
10684 Value *V = Worklist.pop_back_val();
10685 if (!Visited.insert(V).second)
10686 continue;
10687
10688 CmpPredicate Pred;
10689 Value *A, *B, *X;
10690
10691 if (IsAssume) {
10692 AddAffected(V);
10693 if (match(V, m_Not(m_Value(X))))
10694 AddAffected(X);
10695 }
10696
10697 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10698 // assume(A && B) is split to -> assume(A); assume(B);
10699 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10700 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10701 // enough information to be worth handling (intersection of information as
10702 // opposed to union).
10703 if (!IsAssume) {
10704 Worklist.push_back(A);
10705 Worklist.push_back(B);
10706 }
10707 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10708 bool HasRHSC = match(B, m_ConstantInt());
10709 if (ICmpInst::isEquality(Pred)) {
10710 AddAffected(A);
10711 if (IsAssume)
10712 AddAffected(B);
10713 if (HasRHSC) {
10714 Value *Y;
10715 // (X << C) or (X >>_s C) or (X >>_u C).
10716 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10717 AddAffected(X);
10718 // (X & C) or (X | C).
10719 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10720 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10721 AddAffected(X);
10722 AddAffected(Y);
10723 }
10724 // X - Y
10725 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10726 AddAffected(X);
10727 AddAffected(Y);
10728 }
10729 }
10730 } else {
10731 AddCmpOperands(A, B);
10732 if (HasRHSC) {
10733 // Handle (A + C1) u< C2, which is the canonical form of
10734 // A > C3 && A < C4.
10736 AddAffected(X);
10737
10738 if (ICmpInst::isUnsigned(Pred)) {
10739 Value *Y;
10740 // X & Y u> C -> X >u C && Y >u C
10741 // X | Y u< C -> X u< C && Y u< C
10742 // X nuw+ Y u< C -> X u< C && Y u< C
10743 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10744 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10745 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10746 AddAffected(X);
10747 AddAffected(Y);
10748 }
10749 // X nuw- Y u> C -> X u> C
10750 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10751 AddAffected(X);
10752 }
10753 }
10754
10755 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10756 // by computeKnownFPClass().
10758 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10759 InsertAffected(X);
10760 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10761 InsertAffected(X);
10762 }
10763 }
10764
10765 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10766 Value *SquareOp = nullptr;
10767 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10768 AddAffected(SquareOp);
10769 };
10770 AddNuwSquareOperand(A);
10771 AddNuwSquareOperand(B);
10772
10773 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10774 AddAffected(X);
10775 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10776 AddCmpOperands(A, B);
10777
10778 // fcmp fneg(x), y
10779 // fcmp fabs(x), y
10780 // fcmp fneg(fabs(x)), y
10781 if (match(A, m_FNeg(m_Value(A))))
10782 AddAffected(A);
10783 if (match(A, m_FAbs(m_Value(A))))
10784 AddAffected(A);
10785
10787 m_Value()))) {
10788 // Handle patterns that computeKnownFPClass() support.
10789 AddAffected(A);
10790 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10791 // Assume is checked here as X is already added above for assumes in
10792 // addValueAffectedByCondition
10793 AddAffected(X);
10794 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10795 // Assume is checked here to avoid issues with ephemeral values
10796 Worklist.push_back(X);
10797 }
10798 }
10799}
10800
10802 // (X >> C) or/add (X & mask(C) != 0)
10803 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10804 if (BO->getOpcode() == Instruction::Add ||
10805 BO->getOpcode() == Instruction::Or) {
10806 const Value *X;
10807 const APInt *C1, *C2;
10808 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10812 m_Zero())))) &&
10813 C2->popcount() == C1->getZExtValue())
10814 return X;
10815 }
10816 }
10817 return nullptr;
10818}
10819
10821 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
10822}
10823
10826 unsigned MaxCount, bool AllowUndefOrPoison) {
10829 auto Push = [&](const Value *V) -> bool {
10830 Constant *C;
10831 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
10832 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
10833 return false;
10834 // Check existence first to avoid unnecessary allocations.
10835 if (Constants.contains(C))
10836 return true;
10837 if (Constants.size() == MaxCount)
10838 return false;
10839 Constants.insert(C);
10840 return true;
10841 }
10842
10843 if (auto *Inst = dyn_cast<Instruction>(V)) {
10844 if (Visited.insert(Inst).second)
10845 Worklist.push_back(Inst);
10846 return true;
10847 }
10848 return false;
10849 };
10850 if (!Push(V))
10851 return false;
10852 while (!Worklist.empty()) {
10853 const Instruction *CurInst = Worklist.pop_back_val();
10854 switch (CurInst->getOpcode()) {
10855 case Instruction::Select:
10856 if (!Push(CurInst->getOperand(1)))
10857 return false;
10858 if (!Push(CurInst->getOperand(2)))
10859 return false;
10860 break;
10861 case Instruction::PHI:
10862 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
10863 // Fast path for recurrence PHI.
10864 if (IncomingValue == CurInst)
10865 continue;
10866 if (!Push(IncomingValue))
10867 return false;
10868 }
10869 break;
10870 default:
10871 return false;
10872 }
10873 }
10874 return true;
10875}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:287
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:262
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:283
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:258
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:254
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:291
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:279
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:304
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:295
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6050
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1631
bool isFinite() const
Definition APFloat.h:1580
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1234
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
bool isInteger() const
Definition APFloat.h:1592
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2006
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1416
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1695
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
unsigned ceilLogBase2() const
Definition APInt.h:1789
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1210
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1258
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1670
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:790
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1653
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:357
unsigned logBase2() const
Definition APInt.h:1786
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:472
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:406
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1139
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1413
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:786
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:36
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:727
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3040
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2294
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:578
@ Length
Definition DWP.cpp:578
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:445
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1684
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
bool cannotBeOrderedGreaterThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never greater tha...
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS)
Report known values for atan2.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
std::optional< bool > SignBit
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1033