LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98template <typename InstTy>
99static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
100 Value *&Init, Value *&OtherOp);
101
102/// Returns the bitwidth of the given scalar or pointer type. For vector types,
103/// returns the element type's bitwidth.
104static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
105 if (unsigned BitWidth = Ty->getScalarSizeInBits())
106 return BitWidth;
107
108 return DL.getPointerTypeSizeInBits(Ty);
109}
110
111// Given the provided Value and, potentially, a context instruction, return
112// the preferred context instruction (if any).
113static const Instruction *safeCtxI(const Value *V, const Instruction *CtxI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CtxI && CtxI->getParent())
117 return CtxI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CtxI = dyn_cast<Instruction>(V);
121 if (CtxI && CtxI->getParent())
122 return CtxI;
123
124 return nullptr;
125}
126
128 const APInt &DemandedElts,
129 APInt &DemandedLHS, APInt &DemandedRHS) {
130 if (isa<ScalableVectorType>(Shuf->getType())) {
131 assert(DemandedElts == APInt(1,1));
132 DemandedLHS = DemandedRHS = DemandedElts;
133 return true;
134 }
135
136 int NumElts =
137 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
138 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
139 DemandedElts, DemandedLHS, DemandedRHS);
140}
141
142static void computeKnownBits(const Value *V, const APInt &DemandedElts,
143 KnownBits &Known, const SimplifyQuery &Q,
144 unsigned Depth);
145
147 const SimplifyQuery &Q, unsigned Depth) {
148 // Since the number of lanes in a scalable vector is unknown at compile time,
149 // we track one bit which is implicitly broadcast to all lanes. This means
150 // that all lanes in a scalable vector are considered demanded.
151 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
152 APInt DemandedElts =
153 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
154 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
155}
156
158 const DataLayout &DL, AssumptionCache *AC,
159 const Instruction *CtxI, const DominatorTree *DT,
160 bool UseInstrInfo, unsigned Depth) {
162 SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
163 Depth);
164}
165
167 AssumptionCache *AC, const Instruction *CtxI,
168 const DominatorTree *DT, bool UseInstrInfo,
169 unsigned Depth) {
170 return computeKnownBits(
171 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
172}
173
176 const SimplifyQuery &SQ) {
177 // Look for an inverted mask: (X & ~M) op (Y & M).
178 {
179 Value *M;
180 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
182 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CtxI, SQ.DT)
185 }
186
187 // X op (Y & ~X)
189 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT)
192
193 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
194 // for constant Y.
195 Value *Y;
196 if (match(RHS,
198 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT) &&
199 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT);
200 return IsNoUndef ? NoCommonBitsSetResult::Known
202 }
203
204 // Peek through extends to find a 'not' of the other side:
205 // (ext Y) op ext(~Y)
206 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
208 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT)
211
212 // Look for: (A & B) op ~(A | B)
213 {
214 Value *A, *B;
215 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
217 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CtxI, SQ.DT) &&
218 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CtxI, SQ.DT);
219 return IsNoUndef ? NoCommonBitsSetResult::Known
221 }
222 }
223
224 // Look for: (X << V) op (Y >> (BitWidth - V))
225 // or (X >> V) op (Y << (BitWidth - V))
226 {
227 const Value *V;
228 const APInt *R;
229 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
230 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
231 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
232 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
233 R->uge(LHS->getType()->getScalarSizeInBits()))
235 }
236
238}
239
242 const WithCache<const Value *> &RHSCache,
243 const SimplifyQuery &SQ) {
244 const Value *LHS = LHSCache.getValue();
245 const Value *RHS = RHSCache.getValue();
246
247 assert(LHS->getType() == RHS->getType() &&
248 "LHS and RHS should have the same type");
249 assert(LHS->getType()->isIntOrIntVectorTy() &&
250 "LHS and RHS should be integers");
251
253 if (Result == NoCommonBitsSetResult::Known)
255
256 NoCommonBitsSetResult CommuteResult =
258 if (CommuteResult == NoCommonBitsSetResult::Known)
260
262 RHSCache.getKnownBits(SQ)))
264
268
270}
271
273 const WithCache<const Value *> &RHSCache,
274 const SimplifyQuery &SQ) {
275 NoCommonBitsSetResult Result =
276 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
277 return Result == NoCommonBitsSetResult::Known;
278}
279
281 return !I->user_empty() &&
282 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
283}
284
286 return !I->user_empty() && all_of(I->users(), [](const User *U) {
287 CmpPredicate P;
288 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
289 });
290}
291
293 bool OrZero, AssumptionCache *AC,
294 const Instruction *CtxI,
295 const DominatorTree *DT, bool UseInstrInfo,
296 unsigned Depth) {
297 return ::isKnownToBeAPowerOfTwo(
298 V, OrZero, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
299 Depth);
300}
301
302static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
303 const SimplifyQuery &Q, unsigned Depth);
304
306 unsigned Depth) {
307 return computeKnownBits(V, SQ, Depth).isNonNegative();
308}
309
311 unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
318 return Known.isNonNegative() &&
319 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
320}
321
323 unsigned Depth) {
324 return computeKnownBits(V, SQ, Depth).isNegative();
325}
326
327static bool isKnownNonEqual(const Value *V1, const Value *V2,
328 const APInt &DemandedElts, const SimplifyQuery &Q,
329 unsigned Depth);
330
331static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
332 const Value *RHS);
333
334bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
335 const SimplifyQuery &Q, unsigned Depth) {
336 // We don't support looking through casts.
337 if (V1 == V2 || V1->getType() != V2->getType())
338 return false;
339 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
340 APInt DemandedElts =
341 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
342 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
343}
344
345bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
346 const SimplifyQuery &SQ, unsigned Depth) {
347 KnownBits Known(Mask.getBitWidth());
349 return Mask.isSubsetOf(Known.Zero);
350}
351
352static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
353 const SimplifyQuery &Q, unsigned Depth);
354
355static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
356 unsigned Depth = 0) {
357 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
358 APInt DemandedElts =
359 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
360 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
361}
362
363unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
364 AssumptionCache *AC, const Instruction *CtxI,
365 const DominatorTree *DT, bool UseInstrInfo,
366 unsigned Depth) {
367 return ::ComputeNumSignBits(
368 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
369}
370
372 AssumptionCache *AC,
373 const Instruction *CtxI,
374 const DominatorTree *DT,
375 unsigned Depth) {
376 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
377 return V->getType()->getScalarSizeInBits() - SignBits + 1;
378}
379
380/// Try to detect the lerp pattern: a * (b - c) + c * d
381/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
382///
383/// In that particular case, we can use the following chain of reasoning:
384///
385/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
386///
387/// Since that is true for arbitrary a, b, c and d within our constraints, we
388/// can conclude that:
389///
390/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
391///
392/// Considering that any result of the lerp would be less or equal to U, it
393/// would have at least the number of leading 0s as in U.
394///
395/// While being quite a specific situation, it is fairly common in computer
396/// graphics in the shape of alpha blending.
397///
398/// Modifies given KnownOut in-place with the inferred information.
399static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
400 const APInt &DemandedElts,
401 KnownBits &KnownOut,
402 const SimplifyQuery &Q,
403 unsigned Depth) {
404
405 Type *Ty = Op0->getType();
406 const unsigned BitWidth = Ty->getScalarSizeInBits();
407
408 // Only handle scalar types for now
409 if (Ty->isVectorTy())
410 return;
411
412 // Try to match: a * (b - c) + c * d.
413 // When a == 1 => A == nullptr, the same applies to d/D as well.
414 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
415 const Instruction *SubBC = nullptr;
416
417 const auto MatchSubBC = [&]() {
418 // (b - c) can have two forms that interest us:
419 //
420 // 1. sub nuw %b, %c
421 // 2. xor %c, %b
422 //
423 // For the first case, nuw flag guarantees our requirement b >= c.
424 //
425 // The second case might happen when the analysis can infer that b is a mask
426 // for c and we can transform sub operation into xor (that is usually true
427 // for constant b's). Even though xor is symmetrical, canonicalization
428 // ensures that the constant will be the RHS. We have additional checks
429 // later on to ensure that this xor operation is equivalent to subtraction.
431 m_Xor(m_Value(C), m_Value(B))));
432 };
433
434 const auto MatchASubBC = [&]() {
435 // Cases:
436 // - a * (b - c)
437 // - (b - c) * a
438 // - (b - c) <- a implicitly equals 1
439 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
440 };
441
442 const auto MatchCD = [&]() {
443 // Cases:
444 // - d * c
445 // - c * d
446 // - c <- d implicitly equals 1
448 };
449
450 const auto Match = [&](const Value *LHS, const Value *RHS) {
451 // We do use m_Specific(C) in MatchCD, so we have to make sure that
452 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
453 // has to evaluate first and return true.
454 //
455 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
456 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
457 };
458
459 if (!Match(Op0, Op1) && !Match(Op1, Op0))
460 return;
461
462 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
463 // For some of the values we use the convention of leaving
464 // it nullptr to signify an implicit constant 1.
465 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
467 };
468
469 // Check that all operands are non-negative
470 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
471 if (!KnownA.isNonNegative())
472 return;
473
474 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
475 if (!KnownD.isNonNegative())
476 return;
477
478 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
479 if (!KnownB.isNonNegative())
480 return;
481
482 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
483 if (!KnownC.isNonNegative())
484 return;
485
486 // If we matched subtraction as xor, we need to actually check that xor
487 // is semantically equivalent to subtraction.
488 //
489 // For that to be true, b has to be a mask for c or that b's known
490 // ones cover all known and possible ones of c.
491 if (SubBC->getOpcode() == Instruction::Xor &&
492 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
493 return;
494
495 const APInt MaxA = KnownA.getMaxValue();
496 const APInt MaxD = KnownD.getMaxValue();
497 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
498 const APInt MaxB = KnownB.getMaxValue();
499
500 // We can't infer leading zeros info if the upper-bound estimate wraps.
501 bool Overflow;
502 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
503
504 if (Overflow)
505 return;
506
507 // If we know that x <= y and both are positive than x has at least the same
508 // number of leading zeros as y.
509 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
510 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
511}
512
513static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
514 bool NSW, bool NUW,
515 const APInt &DemandedElts,
516 KnownBits &KnownOut, KnownBits &Known2,
517 const SimplifyQuery &Q, unsigned Depth) {
518 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
519
520 // If one operand is unknown and we have no nowrap information,
521 // the result will be unknown independently of the second operand.
522 if (KnownOut.isUnknown() && !NSW && !NUW)
523 return;
524
525 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
526 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
527
528 if (!Add && NSW && !KnownOut.isNonNegative() &&
530 .value_or(false) ||
531 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
532 KnownOut.makeNonNegative();
533
534 if (Add)
535 // Try to match lerp pattern and combine results
536 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
537}
538
539static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
540 bool NUW, const APInt &DemandedElts,
541 KnownBits &Known, KnownBits &Known2,
542 const SimplifyQuery &Q, unsigned Depth) {
543 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
544 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
545
546 bool isKnownNegative = false;
547 bool isKnownNonNegative = false;
548 // If the multiplication is known not to overflow, compute the sign bit.
549 if (NSW) {
550 if (Op0 == Op1) {
551 // The product of a number with itself is non-negative.
552 isKnownNonNegative = true;
553 } else {
554 bool isKnownNonNegativeOp1 = Known.isNonNegative();
555 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
556 bool isKnownNegativeOp1 = Known.isNegative();
557 bool isKnownNegativeOp0 = Known2.isNegative();
558 // The product of two numbers with the same sign is non-negative.
559 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
560 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
561 if (!isKnownNonNegative && NUW) {
562 // mul nuw nsw with a factor > 1 is non-negative.
563 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
564 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
565 KnownBits::sgt(Known2, One).value_or(false);
566 }
567
568 // The product of a negative number and a non-negative number is either
569 // negative or zero.
572 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
573 Known2.isNonZero()) ||
574 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
575 }
576 }
577
578 bool SelfMultiply = Op0 == Op1;
579 if (SelfMultiply)
580 SelfMultiply &=
581 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
582 Known = KnownBits::mul(Known, Known2, SelfMultiply);
583
584 if (SelfMultiply) {
585 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
586 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
587 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
588
589 if (OutValidBits < TyBits) {
590 APInt KnownZeroMask =
591 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
592 Known.Zero |= KnownZeroMask;
593 }
594 }
595
596 // Only make use of no-wrap flags if we failed to compute the sign bit
597 // directly. This matters if the multiplication always overflows, in
598 // which case we prefer to follow the result of the direct computation,
599 // though as the program is invoking undefined behaviour we can choose
600 // whatever we like here.
601 if (isKnownNonNegative && !Known.isNegative())
602 Known.makeNonNegative();
603 else if (isKnownNegative && !Known.isNonNegative())
604 Known.makeNegative();
605}
606
608 KnownBits &Known) {
609 unsigned BitWidth = Known.getBitWidth();
610 unsigned NumRanges = Ranges.getNumOperands() / 2;
611 assert(NumRanges >= 1);
612
613 Known.setAllConflict();
614
615 for (unsigned i = 0; i < NumRanges; ++i) {
617 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
619 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
620 ConstantRange Range(Lower->getValue(), Upper->getValue());
621 // BitWidth must equal the Ranges BitWidth for the correct number of high
622 // bits to be set.
623 assert(BitWidth == Range.getBitWidth() &&
624 "Known bit width must match range bit width!");
625
626 // The first CommonPrefixBits of all values in Range are equal.
627 unsigned CommonPrefixBits =
628 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
629 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
630 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
631 Known.One &= UnsignedMax & Mask;
632 Known.Zero &= ~UnsignedMax & Mask;
633 }
634}
635
636static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
637 // The instruction defining an assumption's condition itself is always
638 // considered ephemeral to that assumption (even if it has other
639 // non-ephemeral users). See r246696's test case for an example.
640 if (is_contained(I->operands(), E))
641 return true;
642
643 const auto *EI = dyn_cast<Instruction>(E);
644 if (!EI)
645 return false;
646
647 if (EI == I)
648 return true;
649
652 Visited.insert(EI);
653 WorkList.push_back(EI);
654 bool ReachesI = false;
655 while (!WorkList.empty()) {
656 const Instruction *V = WorkList.pop_back_val();
657 for (const User *U : V->users()) {
658 const auto *UI = cast<Instruction>(U);
659 if (UI == I) {
660 ReachesI = true;
661 continue;
662 }
663 if (UI->mayHaveSideEffects() || UI->isTerminator())
664 return false;
665 if (Visited.insert(UI).second)
666 WorkList.push_back(UI);
667 }
668 }
669 return ReachesI;
670}
671
672// Is this an intrinsic that cannot be speculated but also cannot trap?
674 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
675 return CI->isAssumeLikeIntrinsic();
676
677 return false;
678}
679
681 const Instruction *CtxI,
682 const DominatorTree *DT,
683 bool AllowEphemerals) {
684 // There are two restrictions on the use of an assume:
685 // 1. The assume must dominate the context (or the control flow must
686 // reach the assume whenever it reaches the context).
687 // 2. The context must not be in the assume's set of ephemeral values
688 // (otherwise we will use the assume to prove that the condition
689 // feeding the assume is trivially true, thus causing the removal of
690 // the assume).
691
692 if (Inv->getParent() == CtxI->getParent()) {
693 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
694 // in the BB.
695 if (Inv->comesBefore(CtxI))
696 return true;
697
698 // Don't let an assume affect itself - this would cause the problems
699 // `isEphemeralValueOf` is trying to prevent, and it would also make
700 // the loop below go out of bounds.
701 if (!AllowEphemerals && Inv == CtxI)
702 return false;
703
704 // The context comes first, but they're both in the same block.
705 // Make sure there is nothing in between that might interrupt
706 // the control flow, not even CtxI itself.
707 // We limit the scan distance between the assume and its context instruction
708 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
709 // it can be adjusted if needed (could be turned into a cl::opt).
710 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
712 return false;
713
714 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
715 }
716
717 // Inv and CtxI are in different blocks.
718 if (DT) {
719 if (DT->dominates(Inv, CtxI))
720 return true;
721 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
722 Inv->getParent()->isEntryBlock()) {
723 // We don't have a DT, but this trivially dominates.
724 return true;
725 }
726
727 return false;
728}
729
732 unsigned &NumChecked) {
733 for (const Instruction &I : make_range(Begin, End)) {
734 if (NumChecked++ > MaxInstrsToCheckForFree)
735 return false;
736 if (auto *CB = dyn_cast<CallBase>(&I)) {
737 if (!CB->hasFnAttr(Attribute::NoFree))
738 return false;
739 } else if (I.maySynchronize()) {
740 return false;
741 }
742 }
743 return true;
744}
745
747 const Instruction *CtxI,
748 const DominatorTree *DT) {
749 const BasicBlock *CtxBB = CtxI->getParent();
750 const BasicBlock *AssumeBB = Assume->getParent();
751 unsigned NumChecked = 0;
752 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
753 if (CtxBB == AssumeBB) {
754 if (Assume != CtxI && !Assume->comesBefore(CtxI))
755 return false;
756 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
757 }
758 if (DT && !DT->dominates(Assume, CtxI))
759 return false;
760 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
761 return false;
762 if (pred_empty(CtxBB))
763 return false;
764
765 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
766 // backedges returning to CtxBB are enqueued and checked correctly.
769 while (!Worklist.empty()) {
770 const BasicBlock *CurBB = Worklist.pop_back_val();
771 if (!Visited.insert(CurBB).second)
772 continue;
773
774 if (CurBB == AssumeBB) {
775 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
776 return false;
777 continue;
778 }
779 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
780 "Blocks between Assume and CtxI must be dominated by AssumeBB");
781
782 if (pred_empty(CurBB))
783 return false;
784
785 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
786 // instructions from CtxIter to the end of CtxBB (instructions before
787 // CtxIter were checked above). Otherwise, check the entire block.
788 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
789 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
790 return false;
791 append_range(Worklist, predecessors(CurBB));
792 }
793 return true;
794}
795
796// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
797// we still have enough information about `RHS` to conclude non-zero. For
798// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
799// so the extra compile time may not be worth it, but possibly a second API
800// should be created for use outside of loops.
801static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
802 // v u> y implies v != 0.
803 if (Pred == ICmpInst::ICMP_UGT)
804 return true;
805
806 // Special-case v != 0 to also handle v != null.
807 if (Pred == ICmpInst::ICMP_NE)
808 return match(RHS, m_Zero());
809
810 // All other predicates - rely on generic ConstantRange handling.
811 const APInt *C;
812 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
813 if (match(RHS, m_APInt(C))) {
815 return !TrueValues.contains(Zero);
816 }
817
819 if (VC == nullptr)
820 return false;
821
822 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
823 ++ElemIdx) {
825 Pred, VC->getElementAsAPInt(ElemIdx));
826 if (TrueValues.contains(Zero))
827 return false;
828 }
829 return true;
830}
831
832static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
833 Value *&ValOut, Instruction *&CtxIOut,
834 const PHINode **PhiOut = nullptr) {
835 ValOut = U->get();
836 if (ValOut == PHI)
837 return;
838 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
839 if (PhiOut)
840 *PhiOut = PHI;
841 Value *V;
842 // If the Use is a select of this phi, compute analysis on other arm to break
843 // recursion.
844 // TODO: Min/Max
845 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
846 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
847 ValOut = V;
848
849 // Same for select, if this phi is 2-operand phi, compute analysis on other
850 // incoming value to break recursion.
851 // TODO: We could handle any number of incoming edges as long as we only have
852 // two unique values.
853 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
854 IncPhi && IncPhi->getNumIncomingValues() == 2) {
855 for (int Idx = 0; Idx < 2; ++Idx) {
856 if (IncPhi->getIncomingValue(Idx) == PHI) {
857 ValOut = IncPhi->getIncomingValue(1 - Idx);
858 if (PhiOut)
859 *PhiOut = IncPhi;
860 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
861 break;
862 }
863 }
864 }
865}
866
867static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
868 // Use of assumptions is context-sensitive. If we don't have a context, we
869 // cannot use them!
870 if (!Q.AC || !Q.CtxI)
871 return false;
872
873 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
874 if (!Elem.Assume)
875 continue;
876
877 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
878 assert(I->getFunction() == Q.CtxI->getFunction() &&
879 "Got assumption for the wrong function!");
880
881 if (Elem.Index != AssumptionCache::ExprResultIdx) {
883 I->getOperandBundleAt(Elem.Index)) &&
885 return true;
886 continue;
887 }
888
889 // Warning: This loop can end up being somewhat performance sensitive.
890 // We're running this loop for once for each value queried resulting in a
891 // runtime of ~O(#assumes * #values).
892
893 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
895 return true;
896
897 Value *RHS;
898 CmpPredicate Pred;
899 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
900 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
901 continue;
902
904 return true;
905 }
906
907 return false;
908}
909
912 const SimplifyQuery &Q) {
913 if (RHS->getType()->isPointerTy()) {
914 // Handle comparison of pointer to null explicitly, as it will not be
915 // covered by the m_APInt() logic below.
916 if (LHS == V && match(RHS, m_Zero())) {
917 switch (Pred) {
919 Known.setAllZero();
920 break;
923 Known.makeNonNegative();
924 break;
926 Known.makeNegative();
927 break;
928 default:
929 break;
930 }
931 }
932 return;
933 }
934
935 unsigned BitWidth = Known.getBitWidth();
936 auto m_V =
938
939 Value *Y;
940 const APInt *Mask, *C;
941 if (!match(RHS, m_APInt(C)))
942 return;
943
944 uint64_t ShAmt;
945 switch (Pred) {
947 // assume(V = C)
948 if (match(LHS, m_V)) {
949 Known = Known.unionWith(KnownBits::makeConstant(*C));
950 // assume(V & Mask = C)
951 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
952 // For one bits in Mask, we can propagate bits from C to V.
953 Known.One |= *C;
954 if (match(Y, m_APInt(Mask)))
955 Known.Zero |= ~*C & *Mask;
956 // assume(V | Mask = C)
957 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
958 // For zero bits in Mask, we can propagate bits from C to V.
959 Known.Zero |= ~*C;
960 if (match(Y, m_APInt(Mask)))
961 Known.One |= *C & ~*Mask;
962 // assume(V << ShAmt = C)
963 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
964 ShAmt < BitWidth) {
965 // For those bits in C that are known, we can propagate them to known
966 // bits in V shifted to the right by ShAmt.
968 RHSKnown >>= ShAmt;
969 Known = Known.unionWith(RHSKnown);
970 // assume(V >> ShAmt = C)
971 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
972 ShAmt < BitWidth) {
973 // For those bits in RHS that are known, we can propagate them to known
974 // bits in V shifted to the right by C.
976 RHSKnown <<= ShAmt;
977 Known = Known.unionWith(RHSKnown);
978 }
979 break;
980 case ICmpInst::ICMP_NE: {
981 // assume (V & B != 0) where B is a power of 2
982 const APInt *BPow2;
983 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
984 Known.One |= *BPow2;
985 break;
986 }
987 default: {
988 const APInt *Offset = nullptr;
989 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
991 if (Offset)
992 LHSRange = LHSRange.sub(*Offset);
993 Known = Known.unionWith(LHSRange.toKnownBits());
994 }
995 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
996 // X & Y u> C -> X u> C && Y u> C
997 // X nuw- Y u> C -> X u> C
998 if (match(LHS, m_c_And(m_V, m_Value())) ||
999 match(LHS, m_NUWSub(m_V, m_Value())))
1000 Known.One.setHighBits(
1001 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1002 }
1003 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1004 // X | Y u< C -> X u< C && Y u< C
1005 // X nuw+ Y u< C -> X u< C && Y u< C
1006 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1007 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1008 Known.Zero.setHighBits(
1009 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1010 }
1011 }
1012 } break;
1013 }
1014}
1015
1018 const SimplifyQuery &SQ, bool Invert) {
1019 ICmpInst::Predicate Pred =
1020 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1021 Value *LHS = Cmp->getOperand(0);
1022 Value *RHS = Cmp->getOperand(1);
1023
1024 // Handle icmp pred (trunc V), C
1025 if (match(LHS, m_Trunc(m_Specific(V)))) {
1026 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1027 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1029 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1030 else
1031 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1032 return;
1033 }
1034
1035 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1036}
1037
1039 KnownBits &Known, const SimplifyQuery &SQ,
1040 bool Invert, unsigned Depth) {
1041 Value *A, *B;
1044 KnownBits Known2(Known.getBitWidth());
1045 KnownBits Known3(Known.getBitWidth());
1046 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1047 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1048 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1050 Known2 = Known2.unionWith(Known3);
1051 else
1052 Known2 = Known2.intersectWith(Known3);
1053 Known = Known.unionWith(Known2);
1054 return;
1055 }
1056
1057 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1058 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1059 return;
1060 }
1061
1062 if (match(Cond, m_Trunc(m_Specific(V)))) {
1063 KnownBits DstKnown(1);
1064 if (Invert) {
1065 DstKnown.setAllZero();
1066 } else {
1067 DstKnown.setAllOnes();
1068 }
1070 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1071 return;
1072 }
1073 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1074 return;
1075 }
1076
1078 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1079}
1080
1082 const SimplifyQuery &Q, unsigned Depth) {
1083 // Handle injected condition.
1084 if (Q.CC && Q.CC->AffectedValues.contains(V))
1086
1087 if (!Q.CtxI)
1088 return;
1089
1090 if (Q.DC && Q.DT) {
1091 // Handle dominating conditions.
1092 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1093 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1094 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1095 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1096 /*Invert*/ false, Depth);
1097
1098 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1099 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1100 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1101 /*Invert*/ true, Depth);
1102 }
1103
1104 if (Known.hasConflict())
1105 Known.resetAll();
1106 }
1107
1108 if (!Q.AC)
1109 return;
1110
1111 unsigned BitWidth = Known.getBitWidth();
1112
1113 // Note that the patterns below need to be kept in sync with the code
1114 // in AssumptionCache::updateAffectedValues.
1115
1116 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1117 if (!Elem.Assume)
1118 continue;
1119
1120 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1121 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1122 "Got assumption for the wrong function!");
1123
1124 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1125 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1126 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1127 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1128 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1130 Known.Zero |= (*Alignment - 1) & ~*Offset;
1131 Known.One |= (*Alignment - 1) & *Offset;
1132 }
1133 }
1134 continue;
1135 }
1136
1137 // Warning: This loop can end up being somewhat performance sensitive.
1138 // We're running this loop for once for each value queried resulting in a
1139 // runtime of ~O(#assumes * #values).
1140
1141 Value *Arg = I->getArgOperand(0);
1142
1143 if (Arg == V && isValidAssumeForContext(I, Q)) {
1144 assert(BitWidth == 1 && "assume operand is not i1?");
1145 (void)BitWidth;
1146 Known.setAllOnes();
1147 return;
1148 }
1149 if (match(Arg, m_Not(m_Specific(V))) &&
1151 assert(BitWidth == 1 && "assume operand is not i1?");
1152 (void)BitWidth;
1153 Known.setAllZero();
1154 return;
1155 }
1156 auto *Trunc = dyn_cast<TruncInst>(Arg);
1157 if (Trunc && Trunc->getOperand(0) == V &&
1159 if (Trunc->hasNoUnsignedWrap()) {
1161 return;
1162 }
1163 Known.One.setBit(0);
1164 return;
1165 }
1166
1167 // The remaining tests are all recursive, so bail out if we hit the limit.
1169 continue;
1170
1171 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1172 if (!Cmp)
1173 continue;
1174
1175 if (!isValidAssumeForContext(I, Q))
1176 continue;
1177
1178 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1179 }
1180
1181 // Conflicting assumption: Undefined behavior will occur on this execution
1182 // path.
1183 if (Known.hasConflict())
1184 Known.resetAll();
1185}
1186
1187/// Compute known bits from a shift operator, including those with a
1188/// non-constant shift amount. Known is the output of this function. Known2 is a
1189/// pre-allocated temporary with the same bit width as Known and on return
1190/// contains the known bit of the shift value source. KF is an
1191/// operator-specific function that, given the known-bits and a shift amount,
1192/// compute the implied known-bits of the shift operator's result respectively
1193/// for that shift amount. The results from calling KF are conservatively
1194/// combined for all permitted shift amounts.
1196 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1197 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1198 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1199 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1200 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1201 // To limit compile-time impact, only query isKnownNonZero() if we know at
1202 // least something about the shift amount.
1203 bool ShAmtNonZero =
1204 Known.isNonZero() ||
1205 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1206 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1207 Known = KF(Known2, Known, ShAmtNonZero);
1208}
1209
1210static KnownBits
1211getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1212 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1213 const SimplifyQuery &Q, unsigned Depth) {
1214 unsigned BitWidth = KnownLHS.getBitWidth();
1215 KnownBits KnownOut(BitWidth);
1216 bool IsAnd = false;
1217 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1218 Value *X = nullptr, *Y = nullptr;
1219
1220 switch (I->getOpcode()) {
1221 case Instruction::And:
1222 KnownOut = KnownLHS & KnownRHS;
1223 IsAnd = true;
1224 // and(x, -x) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: instcombine often reassociates independent `and` which can hide
1228 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1229 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1230 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1231 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1232 KnownOut = KnownLHS.blsi();
1233 else
1234 KnownOut = KnownRHS.blsi();
1235 }
1236 break;
1237 case Instruction::Or:
1238 KnownOut = KnownLHS | KnownRHS;
1239 break;
1240 case Instruction::Xor:
1241 KnownOut = KnownLHS ^ KnownRHS;
1242 // xor(x, x-1) is common idioms that will clear all but lowest set
1243 // bit. If we have a single known bit in x, we can clear all bits
1244 // above it.
1245 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1246 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1247 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1248 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1249 if (HasKnownOne &&
1251 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1252 KnownOut = XBits.blsmsk();
1253 }
1254 break;
1255 default:
1256 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1257 }
1258
1259 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1260 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1261 // here we handle the more general case of adding any odd number by
1262 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1263 // TODO: This could be generalized to clearing any bit set in y where the
1264 // following bit is known to be unset in y.
1265 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1269 KnownBits KnownY(BitWidth);
1270 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1271 if (KnownY.countMinTrailingOnes() > 0) {
1272 if (IsAnd)
1273 KnownOut.Zero.setBit(0);
1274 else
1275 KnownOut.One.setBit(0);
1276 }
1277 }
1278 return KnownOut;
1279}
1280
1282 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1283 unsigned Depth,
1284 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1285 KnownBitsFunc) {
1286 APInt DemandedEltsLHS, DemandedEltsRHS;
1288 DemandedElts, DemandedEltsLHS,
1289 DemandedEltsRHS);
1290
1291 const auto ComputeForSingleOpFunc =
1292 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1293 return KnownBitsFunc(
1294 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1295 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1296 };
1297
1298 if (DemandedEltsRHS.isZero())
1299 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1300 if (DemandedEltsLHS.isZero())
1301 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1302
1303 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1304 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1305}
1306
1307// Public so this can be used in `SimplifyDemandedUseBits`.
1309 const KnownBits &KnownLHS,
1310 const KnownBits &KnownRHS,
1311 const SimplifyQuery &SQ,
1312 unsigned Depth) {
1313 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1314 APInt DemandedElts =
1315 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1316
1317 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1318 Depth);
1319}
1320
1322 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1323 // Without vscale_range, we only know that vscale is non-zero.
1324 if (!Attr.isValid())
1326
1327 unsigned AttrMin = Attr.getVScaleRangeMin();
1328 // Minimum is larger than vscale width, result is always poison.
1329 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1330 return ConstantRange::getEmpty(BitWidth);
1331
1332 APInt Min(BitWidth, AttrMin);
1333 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1334 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1336
1337 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1338}
1339
1340/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1341/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1342/// target's VLEN range. Callers must ensure the target is RISC-V.
1343static bool isReadVLENB(const IntrinsicInst &II) {
1344 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1345 if (!MAV)
1346 return false;
1347 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1348 if (!MD || MD->getNumOperands() != 1)
1349 return false;
1350 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1351 return RegName && RegName->getString() == "vlenb";
1352}
1353
1354/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1355/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1356/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1357/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1358/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1359/// attribute, when present, pins the subtarget's VLEN in units of
1360/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1361/// RVVBytesPerBlock.
1363 unsigned Width) {
1364 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1365 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1366
1367 const Function *F = II.getFunction();
1368 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1369 ConstantRange VScale = getVScaleRange(F, Width);
1370 Range = Range.intersectWith(
1372 }
1373 return Range;
1374}
1375
1377 Value *Arm, bool Invert,
1378 const SimplifyQuery &Q, unsigned Depth) {
1379 // If we have a constant arm, we are done.
1380 if (Known.isConstant())
1381 return;
1382
1383 // See what condition implies about the bits of the select arm.
1384 KnownBits CondRes(Known.getBitWidth());
1385 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1386 // If we don't get any information from the condition, no reason to
1387 // proceed.
1388 if (CondRes.isUnknown())
1389 return;
1390
1391 // We can have conflict if the condition is dead. I.e if we have
1392 // (x | 64) < 32 ? (x | 64) : y
1393 // we will have conflict at bit 6 from the condition/the `or`.
1394 // In that case just return. Its not particularly important
1395 // what we do, as this select is going to be simplified soon.
1396 CondRes = CondRes.unionWith(Known);
1397 if (CondRes.hasConflict())
1398 return;
1399
1400 // Finally make sure the information we found is valid. This is relatively
1401 // expensive so it's left for the very end.
1402 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1403 return;
1404
1405 // Finally, we know we get information from the condition and its valid,
1406 // so return it.
1407 Known = std::move(CondRes);
1408}
1409
1410// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1411// Returns the input and lower/upper bounds.
1412static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1413 const APInt *&CLow, const APInt *&CHigh) {
1415 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1416 "Input should be a Select!");
1417
1418 const Value *LHS = nullptr, *RHS = nullptr;
1420 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1421 return false;
1422
1423 if (!match(RHS, m_APInt(CLow)))
1424 return false;
1425
1426 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1428 if (getInverseMinMaxFlavor(SPF) != SPF2)
1429 return false;
1430
1431 if (!match(RHS2, m_APInt(CHigh)))
1432 return false;
1433
1434 if (SPF == SPF_SMIN)
1435 std::swap(CLow, CHigh);
1436
1437 In = LHS2;
1438 return CLow->sle(*CHigh);
1439}
1440
1442 const APInt *&CLow,
1443 const APInt *&CHigh) {
1444 assert((II->getIntrinsicID() == Intrinsic::smin ||
1445 II->getIntrinsicID() == Intrinsic::smax) &&
1446 "Must be smin/smax");
1447
1448 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1449 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1450 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1451 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1452 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1453 return false;
1454
1455 if (II->getIntrinsicID() == Intrinsic::smin)
1456 std::swap(CLow, CHigh);
1457 return CLow->sle(*CHigh);
1458}
1459
1461 KnownBits &Known) {
1462 const APInt *CLow, *CHigh;
1463 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1464 Known = Known.unionWith(
1465 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1466}
1467
1469 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1470 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1471 unsigned Depth) {
1472 // Change the context instruction to the "edge" that flows into the phi. This
1473 // is important because that is where the value is actually "evaluated" even
1474 // though it is used later somewhere else. (see also D69571).
1476 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1477
1478 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1479 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1480
1481 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1482 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1483}
1484
1486 const APInt &DemandedElts,
1488 const SimplifyQuery &Q,
1489 unsigned Depth) {
1490 unsigned BitWidth = Known.getBitWidth();
1491
1492 KnownBits Known2(BitWidth);
1493 switch (I->getOpcode()) {
1494 default: break;
1495 case Instruction::Load:
1496 if (MDNode *MD =
1497 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1499 break;
1500 case Instruction::And:
1501 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1502 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1503
1504 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1505 break;
1506 case Instruction::Or:
1507 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1508 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1509
1510 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1511 break;
1512 case Instruction::Xor:
1513 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1514 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1515
1516 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1517 break;
1518 case Instruction::Mul: {
1521 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1522 DemandedElts, Known, Known2, Q, Depth);
1523 break;
1524 }
1525 case Instruction::UDiv: {
1526 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1527 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1528 Known =
1530 break;
1531 }
1532 case Instruction::SDiv: {
1533 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1534 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1535 Known =
1537 break;
1538 }
1539 case Instruction::Select: {
1540 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1541 KnownBits Res(Known.getBitWidth());
1542 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1543 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1544 return Res;
1545 };
1546 // Only known if known in both the LHS and RHS.
1547 Known =
1548 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1549 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1550 break;
1551 }
1552 case Instruction::FPToSI: {
1553 // fptosi is poison if the rounded value doesn't fit in the result type,
1554 // so we can assume the conversion is well-defined and rounds towards
1555 // zero. +-Inf can never fit in an integer type, so it is always poison,
1556 // like NaN. Negative subnormals and negative zero round to 0. That
1557 // leaves negative normals as the only class that can produce a defined
1558 // negative result.
1559 KnownFPClass SrcFPClass = computeKnownFPClass(
1560 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1561 if (SrcFPClass.isKnownNever(fcNegNormal))
1562 Known.makeNonNegative();
1563 break;
1564 }
1565 case Instruction::FPTrunc:
1566 case Instruction::FPExt:
1567 case Instruction::FPToUI:
1568 case Instruction::SIToFP:
1569 case Instruction::UIToFP:
1570 break; // Can't work with floating point.
1571 case Instruction::PtrToInt:
1572 case Instruction::PtrToAddr:
1573 case Instruction::IntToPtr:
1574 // Fall through and handle them the same as zext/trunc.
1575 [[fallthrough]];
1576 case Instruction::ZExt:
1577 case Instruction::Trunc: {
1578 Type *SrcTy = I->getOperand(0)->getType();
1579
1580 unsigned SrcBitWidth;
1581 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1582 // which fall through here.
1583 Type *ScalarTy = SrcTy->getScalarType();
1584 SrcBitWidth = ScalarTy->isPointerTy() ?
1585 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1586 Q.DL.getTypeSizeInBits(ScalarTy);
1587
1588 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1589 Known = Known.anyextOrTrunc(SrcBitWidth);
1590 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1591 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1592 Inst && Inst->hasNonNeg() && !Known.isNegative())
1593 Known.makeNonNegative();
1594 Known = Known.zextOrTrunc(BitWidth);
1595 break;
1596 }
1597 case Instruction::BitCast: {
1598 Type *SrcTy = I->getOperand(0)->getType();
1599 if (SrcTy->isIntOrPtrTy() &&
1600 // TODO: For now, not handling conversions like:
1601 // (bitcast i64 %x to <2 x i32>)
1602 !I->getType()->isVectorTy()) {
1603 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1604 break;
1605 }
1606
1607 const Value *V;
1608 // Handle bitcast from floating point to integer.
1609 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1610 V->getType()->isFPOrFPVectorTy()) {
1611 Type *FPType = V->getType()->getScalarType();
1612 KnownFPClass Result =
1613 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1614
1615 Known = Result.toKnownBits(FPType->getFltSemantics());
1616
1617 break;
1618 }
1619
1620 // Handle cast from vector integer type to scalar or vector integer.
1621 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1622 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1623 !I->getType()->isIntOrIntVectorTy() ||
1624 isa<ScalableVectorType>(I->getType()))
1625 break;
1626
1627 unsigned NumElts = DemandedElts.getBitWidth();
1628 bool IsLE = Q.DL.isLittleEndian();
1629 // Look through a cast from narrow vector elements to wider type.
1630 // Examples: v4i32 -> v2i64, v3i8 -> v24
1631 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1632 if (BitWidth % SubBitWidth == 0) {
1633 // Known bits are automatically intersected across demanded elements of a
1634 // vector. So for example, if a bit is computed as known zero, it must be
1635 // zero across all demanded elements of the vector.
1636 //
1637 // For this bitcast, each demanded element of the output is sub-divided
1638 // across a set of smaller vector elements in the source vector. To get
1639 // the known bits for an entire element of the output, compute the known
1640 // bits for each sub-element sequentially. This is done by shifting the
1641 // one-set-bit demanded elements parameter across the sub-elements for
1642 // consecutive calls to computeKnownBits. We are using the demanded
1643 // elements parameter as a mask operator.
1644 //
1645 // The known bits of each sub-element are then inserted into place
1646 // (dependent on endian) to form the full result of known bits.
1647 unsigned SubScale = BitWidth / SubBitWidth;
1648 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1649 for (unsigned i = 0; i != NumElts; ++i) {
1650 if (DemandedElts[i])
1651 SubDemandedElts.setBit(i * SubScale);
1652 }
1653
1654 KnownBits KnownSrc(SubBitWidth);
1655 for (unsigned i = 0; i != SubScale; ++i) {
1656 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1657 Depth + 1);
1658 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1659 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1660 }
1661 }
1662 // Look through a cast from wider vector elements to narrow type.
1663 // Examples: v2i64 -> v4i32
1664 if (SubBitWidth % BitWidth == 0) {
1665 unsigned SubScale = SubBitWidth / BitWidth;
1666 KnownBits KnownSrc(SubBitWidth);
1667 APInt SubDemandedElts =
1668 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1669 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1670 Depth + 1);
1671
1672 Known.setAllConflict();
1673 for (unsigned i = 0; i != NumElts; ++i) {
1674 if (DemandedElts[i]) {
1675 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1676 unsigned Offset = (Shifts % SubScale) * BitWidth;
1677 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1678 if (Known.isUnknown())
1679 break;
1680 }
1681 }
1682 }
1683 break;
1684 }
1685 case Instruction::SExt: {
1686 // Compute the bits in the result that are not present in the input.
1687 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1688
1689 Known = Known.trunc(SrcBitWidth);
1690 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1691 // If the sign bit of the input is known set or clear, then we know the
1692 // top bits of the result.
1693 Known = Known.sext(BitWidth);
1694 break;
1695 }
1696 case Instruction::Shl: {
1699 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1700 bool ShAmtNonZero) {
1701 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1702 };
1703 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1704 KF);
1705 // Trailing zeros of a right-shifted constant never decrease.
1706 const APInt *C;
1707 if (match(I->getOperand(0), m_APInt(C)))
1708 Known.Zero.setLowBits(C->countr_zero());
1709
1710 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1711 // lands at bit Y, when BitWidth is a power of 2.
1712 const APInt *YC;
1713 Value *X = I->getOperand(0);
1714 if (isPowerOf2_32(BitWidth) &&
1715 match(I->getOperand(1),
1717 m_SpecificInt(BitWidth - 1)))) &&
1718 YC->ult(BitWidth - 1)) {
1719 unsigned Y = YC->getZExtValue();
1720 Known.One.setBit(Y);
1721 Known.Zero.setBitsFrom(Y + 1);
1722 }
1723 break;
1724 }
1725 case Instruction::LShr: {
1726 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1727 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1728 bool ShAmtNonZero) {
1729 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1730 };
1731 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1732 KF);
1733 // Leading zeros of a left-shifted constant never decrease.
1734 const APInt *C;
1735 if (match(I->getOperand(0), m_APInt(C)))
1736 Known.Zero.setHighBits(C->countl_zero());
1737 break;
1738 }
1739 case Instruction::AShr: {
1740 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1741 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1742 bool ShAmtNonZero) {
1743 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1744 };
1745 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1746 KF);
1747 break;
1748 }
1749 case Instruction::Sub: {
1752 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1753 DemandedElts, Known, Known2, Q, Depth);
1754 break;
1755 }
1756 case Instruction::Add: {
1759 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1760 DemandedElts, Known, Known2, Q, Depth);
1761 break;
1762 }
1763 case Instruction::SRem:
1764 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1765 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1766 Known = KnownBits::srem(Known, Known2);
1767 break;
1768
1769 case Instruction::URem:
1770 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1771 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1772 Known = KnownBits::urem(Known, Known2);
1773 break;
1774 case Instruction::Alloca:
1775 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1776 break;
1777 case Instruction::GetElementPtr: {
1778 // Analyze all of the subscripts of this getelementptr instruction
1779 // to determine if we can prove known low zero bits.
1780 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1781 // Accumulate the constant indices in a separate variable
1782 // to minimize the number of calls to computeForAddSub.
1783 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1784 APInt AccConstIndices(IndexWidth, 0);
1785
1786 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1787 if (IndexWidth == BitWidth) {
1788 // Note that inbounds does *not* guarantee nsw for the addition, as only
1789 // the offset is signed, while the base address is unsigned.
1790 Known = KnownBits::add(Known, IndexBits);
1791 } else {
1792 // If the index width is smaller than the pointer width, only add the
1793 // value to the low bits.
1794 assert(IndexWidth < BitWidth &&
1795 "Index width can't be larger than pointer width");
1796 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1797 }
1798 };
1799
1801 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1802 // TrailZ can only become smaller, short-circuit if we hit zero.
1803 if (Known.isUnknown())
1804 break;
1805
1806 Value *Index = I->getOperand(i);
1807
1808 // Handle case when index is zero.
1809 Constant *CIndex = dyn_cast<Constant>(Index);
1810 if (CIndex && CIndex->isNullValue())
1811 continue;
1812
1813 if (StructType *STy = GTI.getStructTypeOrNull()) {
1814 // Handle struct member offset arithmetic.
1815
1816 assert(CIndex &&
1817 "Access to structure field must be known at compile time");
1818
1819 if (CIndex->getType()->isVectorTy())
1820 Index = CIndex->getSplatValue();
1821
1822 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1823 const StructLayout *SL = Q.DL.getStructLayout(STy);
1824 uint64_t Offset = SL->getElementOffset(Idx);
1825 AccConstIndices += Offset;
1826 continue;
1827 }
1828
1829 // Handle array index arithmetic.
1830 Type *IndexedTy = GTI.getIndexedType();
1831 if (!IndexedTy->isSized()) {
1832 Known.resetAll();
1833 break;
1834 }
1835
1836 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1837 uint64_t StrideInBytes = Stride.getKnownMinValue();
1838 if (!Stride.isScalable()) {
1839 // Fast path for constant offset.
1840 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1841 AccConstIndices +=
1842 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1843 continue;
1844 }
1845 }
1846
1847 KnownBits IndexBits =
1848 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1849 KnownBits ScalingFactor(IndexWidth);
1850 // Multiply by current sizeof type.
1851 // &A[i] == A + i * sizeof(*A[i]).
1852 if (Stride.isScalable()) {
1853 // For scalable types the only thing we know about sizeof is
1854 // that this is a multiple of the minimum size.
1855 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1856 } else {
1857 ScalingFactor =
1858 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1859 }
1860 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1861 }
1862 if (!Known.isUnknown() && !AccConstIndices.isZero())
1863 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1864 break;
1865 }
1866 case Instruction::PHI: {
1867 const PHINode *P = cast<PHINode>(I);
1868 BinaryOperator *BO = nullptr;
1869 Value *Start = nullptr, *Step = nullptr;
1870 KnownBits &KnownStart = Known2;
1871 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1872 // Handle the case of a simple two-predecessor recurrence PHI.
1873 // There's a lot more that could theoretically be done here, but
1874 // this is sufficient to catch some interesting cases.
1875 unsigned Opcode = BO->getOpcode();
1876
1877 switch (Opcode) {
1878 // If this is a shift recurrence, we know the bits being shifted in. We
1879 // can combine that with information about the start value of the
1880 // recurrence to conclude facts about the result. If this is a udiv
1881 // recurrence, we know that the result can never exceed either the
1882 // numerator or the start value, whichever is greater.
1883 case Instruction::LShr:
1884 case Instruction::AShr:
1885 case Instruction::Shl:
1886 case Instruction::UDiv:
1887 if (BO->getOperand(0) != I)
1888 break;
1889 [[fallthrough]];
1890
1891 // For a urem recurrence, the result can never exceed the start value. The
1892 // phi could either be the numerator or the denominator.
1893 case Instruction::URem: {
1894 // We have matched a recurrence of the form:
1895 // %iv = [R, %entry], [%iv.next, %backedge]
1896 // %iv.next = shift_op %iv, L
1897
1898 // Recurse with the phi context to avoid concern about whether facts
1899 // inferred hold at original context instruction. TODO: It may be
1900 // correct to use the original context. IF warranted, explore and
1901 // add sufficient tests to cover.
1903 RecQ.CtxI = P;
1904 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1905 switch (Opcode) {
1906 case Instruction::Shl:
1907 // A shl recurrence will only increase the tailing zeros
1908 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1909 break;
1910 case Instruction::LShr:
1911 case Instruction::UDiv:
1912 case Instruction::URem:
1913 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1914 // the start value.
1915 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1916 break;
1917 case Instruction::AShr:
1918 // An ashr recurrence will extend the initial sign bit
1919 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1920 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1921 break;
1922 }
1923 break;
1924 }
1925
1926 case Instruction::And: {
1927 // Bits that are zero in the start value stay zero, and bits that are
1928 // one in both the start value and the step stay one.
1929 KnownBits KnownStep(BitWidth);
1930 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1931 KnownStart, KnownStep, Q, Depth);
1932 Known.Zero |= KnownStart.Zero;
1933 Known.One |= KnownStart.One & KnownStep.One;
1934 break;
1935 }
1936
1937 case Instruction::Or: {
1938 // Bits that are zero in both the start value and the step stay zero,
1939 // and bits that are one in the start value stay one.
1940 KnownBits KnownStep(BitWidth);
1941 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1942 KnownStart, KnownStep, Q, Depth);
1943 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
1944 Known.One |= KnownStart.One;
1945 break;
1946 }
1947
1948 // Check for operations that have the property that if
1949 // both their operands have low zero bits, the result
1950 // will have low zero bits.
1951 case Instruction::Add:
1952 case Instruction::Sub:
1953 case Instruction::Mul: {
1954 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1955 // zero bits.
1956 KnownBits KnownStep(BitWidth);
1957 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1958 KnownStart, KnownStep, Q, Depth);
1959
1960 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1961 KnownStep.countMinTrailingZeros()));
1962
1963 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1964 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1965 break;
1966
1967 switch (Opcode) {
1968 // If initial value of recurrence is nonnegative, and we are adding
1969 // a nonnegative number with nsw, the result can only be nonnegative
1970 // or poison value regardless of the number of times we execute the
1971 // add in phi recurrence. If initial value is negative and we are
1972 // adding a negative number with nsw, the result can only be
1973 // negative or poison value. Similar arguments apply to sub and mul.
1974 //
1975 // (add non-negative, non-negative) --> non-negative
1976 // (add negative, negative) --> negative
1977 case Instruction::Add: {
1978 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1979 Known.makeNonNegative();
1980 else if (KnownStart.isNegative() && KnownStep.isNegative())
1981 Known.makeNegative();
1982 break;
1983 }
1984
1985 // (sub nsw non-negative, negative) --> non-negative
1986 // (sub nsw negative, non-negative) --> negative
1987 case Instruction::Sub: {
1988 if (BO->getOperand(0) != I)
1989 break;
1990 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1991 Known.makeNonNegative();
1992 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1993 Known.makeNegative();
1994 break;
1995 }
1996
1997 // (mul nsw non-negative, non-negative) --> non-negative
1998 case Instruction::Mul:
1999 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2000 Known.makeNonNegative();
2001 break;
2002
2003 default:
2004 break;
2005 }
2006 break;
2007 }
2008
2009 default:
2010 break;
2011 }
2012 } else {
2013 IntrinsicInst *II = nullptr;
2014 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2015 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2016 //
2017 // %iv.next = <II>(%iv, <Step>)
2018 // or
2019 // %iv.next = <II>(<Step>, %iv)
2020 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2021 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2022 KnownBits KnownStep(BitWidth);
2024 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2025
2026 if (IntrinsicID == Intrinsic::umin) {
2027 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2028 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2029 KnownStep.countMinLeadingOnes()));
2030 } else {
2031 // umax
2032 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2033 KnownStep.countMinLeadingZeros()));
2034 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2035 }
2036 }
2037 }
2038 }
2039
2040 // Unreachable blocks may have zero-operand PHI nodes.
2041 if (P->getNumIncomingValues() == 0)
2042 break;
2043
2044 // Otherwise take the unions of the known bit sets of the operands,
2045 // taking conservative care to avoid excessive recursion.
2046 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2047 // Skip if every incoming value references to ourself.
2048 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2049 break;
2050
2051 Known.setAllConflict();
2052 for (const Use &U : P->operands()) {
2053 Value *IncValue;
2054 const PHINode *CtxPhi;
2055 Instruction *CtxI;
2056 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2057 // Skip direct self references.
2058 if (IncValue == P)
2059 continue;
2060
2061 // Change the context instruction to the "edge" that flows into the
2062 // phi. This is important because that is where the value is actually
2063 // "evaluated" even though it is used later somewhere else. (see also
2064 // D69571).
2066
2067 Known2 = KnownBits(BitWidth);
2068
2069 // Recurse, but cap the recursion to one level, because we don't
2070 // want to waste time spinning around in loops.
2071 // TODO: See if we can base recursion limiter on number of incoming phi
2072 // edges so we don't overly clamp analysis.
2073 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2075
2076 // See if we can further use a conditional branch into the phi
2077 // to help us determine the range of the value.
2078 if (!Known2.isConstant()) {
2079 CmpPredicate Pred;
2080 const APInt *RHSC;
2081 BasicBlock *TrueSucc, *FalseSucc;
2082 // TODO: Use RHS Value and compute range from its known bits.
2083 if (match(RecQ.CtxI,
2084 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2085 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2086 // Check for cases of duplicate successors.
2087 if ((TrueSucc == CtxPhi->getParent()) !=
2088 (FalseSucc == CtxPhi->getParent())) {
2089 // If we're using the false successor, invert the predicate.
2090 if (FalseSucc == CtxPhi->getParent())
2091 Pred = CmpInst::getInversePredicate(Pred);
2092 // Get the knownbits implied by the incoming phi condition.
2093 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2094 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2095 // We can have conflicts here if we are analyzing deadcode (its
2096 // impossible for us reach this BB based the icmp).
2097 if (KnownUnion.hasConflict()) {
2098 // No reason to continue analyzing in a known dead region, so
2099 // just resetAll and break. This will cause us to also exit the
2100 // outer loop.
2101 Known.resetAll();
2102 break;
2103 }
2104 Known2 = KnownUnion;
2105 }
2106 }
2107 }
2108
2109 Known = Known.intersectWith(Known2);
2110 // If all bits have been ruled out, there's no need to check
2111 // more operands.
2112 if (Known.isUnknown())
2113 break;
2114 }
2115 }
2116 break;
2117 }
2118 case Instruction::Call:
2119 case Instruction::Invoke: {
2120 // If range metadata is attached to this call, set known bits from that,
2121 // and then intersect with known bits based on other properties of the
2122 // function.
2123 if (MDNode *MD =
2124 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2126
2127 const auto *CB = cast<CallBase>(I);
2128
2129 if (std::optional<ConstantRange> Range = CB->getRange())
2130 Known = Known.unionWith(Range->toKnownBits());
2131
2132 if (const Value *RV = CB->getReturnedArgOperand()) {
2133 if (RV->getType() == I->getType()) {
2134 computeKnownBits(RV, Known2, Q, Depth + 1);
2135 Known = Known.unionWith(Known2);
2136 // If the function doesn't return properly for all input values
2137 // (e.g. unreachable exits) then there might be conflicts between the
2138 // argument value and the range metadata. Simply discard the known bits
2139 // in case of conflicts.
2140 if (Known.hasConflict())
2141 Known.resetAll();
2142 }
2143 }
2144 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2145 switch (II->getIntrinsicID()) {
2146 default:
2147 break;
2148 case Intrinsic::abs: {
2149 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2150 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2151 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2152 break;
2153 }
2154 case Intrinsic::bitreverse:
2155 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2156 Known = Known.unionWith(Known2.reverseBits());
2157 break;
2158 case Intrinsic::bswap:
2159 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2160 Known = Known.unionWith(Known2.byteSwap());
2161 break;
2162 case Intrinsic::ctlz: {
2163 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2164 // If we have a known 1, its position is our upper bound.
2165 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2166 // If this call is poison for 0 input, the result will be less than 2^n.
2167 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2168 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2169 unsigned LowBits = llvm::bit_width(PossibleLZ);
2170 Known.Zero.setBitsFrom(LowBits);
2171 break;
2172 }
2173 case Intrinsic::cttz: {
2174 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2175 // If we have a known 1, its position is our upper bound.
2176 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2177 // If this call is poison for 0 input, the result will be less than 2^n.
2178 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2179 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2180 unsigned LowBits = llvm::bit_width(PossibleTZ);
2181 Known.Zero.setBitsFrom(LowBits);
2182 break;
2183 }
2184 case Intrinsic::ctpop: {
2185 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2186 // We can bound the space the count needs. Also, bits known to be zero
2187 // can't contribute to the population.
2188 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2189 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2190 Known.Zero.setBitsFrom(LowBits);
2191 // TODO: we could bound KnownOne using the lower bound on the number
2192 // of bits which might be set provided by popcnt KnownOne2.
2193 break;
2194 }
2195 case Intrinsic::fshr:
2196 case Intrinsic::fshl: {
2197 const APInt *SA;
2198 if (!match(I->getOperand(2), m_APInt(SA)))
2199 break;
2200
2201 KnownBits Known3(BitWidth);
2202 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2203 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2204 Known = II->getIntrinsicID() == Intrinsic::fshl
2205 ? KnownBits::fshl(Known2, Known3, *SA)
2206 : KnownBits::fshr(Known2, Known3, *SA);
2207 break;
2208 }
2209 case Intrinsic::clmul:
2210 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2211 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2212 Known = KnownBits::clmul(Known, Known2);
2213 break;
2214 case Intrinsic::pext:
2215 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2216 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2217 Known = KnownBits::pext(Known, Known2);
2218 break;
2219 case Intrinsic::pdep:
2220 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2221 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2222 Known = KnownBits::pdep(Known, Known2);
2223 break;
2224 case Intrinsic::smulh:
2225 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2226 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2227 Known = KnownBits::mulhs(Known, Known2);
2228 break;
2229 case Intrinsic::umulh:
2230 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2231 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2232 Known = KnownBits::mulhu(Known, Known2);
2233 break;
2234 case Intrinsic::uadd_sat:
2235 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2236 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2237 Known = KnownBits::uadd_sat(Known, Known2);
2238 break;
2239 case Intrinsic::usub_sat:
2240 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2241 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2242 Known = KnownBits::usub_sat(Known, Known2);
2243 break;
2244 case Intrinsic::sadd_sat:
2245 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2246 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2247 Known = KnownBits::sadd_sat(Known, Known2);
2248 break;
2249 case Intrinsic::ssub_sat:
2250 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2251 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2252 Known = KnownBits::ssub_sat(Known, Known2);
2253 break;
2254 // Vec reverse preserves bits from input vec.
2255 case Intrinsic::vector_reverse:
2256 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2257 Depth + 1);
2258 break;
2259 // for min/max/and/or reduce, any bit common to each element in the
2260 // input vec is set in the output.
2261 case Intrinsic::vector_reduce_and:
2262 case Intrinsic::vector_reduce_or:
2263 case Intrinsic::vector_reduce_umax:
2264 case Intrinsic::vector_reduce_umin:
2265 case Intrinsic::vector_reduce_smax:
2266 case Intrinsic::vector_reduce_smin:
2267 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2268 break;
2269 case Intrinsic::vector_reduce_xor: {
2270 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2271 // The zeros common to all vecs are zero in the output.
2272 // If the number of elements is odd, then the common ones remain. If the
2273 // number of elements is even, then the common ones becomes zeros.
2274 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2275 // Even, so the ones become zeros.
2276 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2277 if (EvenCnt)
2278 Known.Zero |= Known.One;
2279 // Maybe even element count so need to clear ones.
2280 if (VecTy->isScalableTy() || EvenCnt)
2281 Known.One.clearAllBits();
2282 break;
2283 }
2284 case Intrinsic::vector_reduce_add: {
2285 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2286 if (!VecTy)
2287 break;
2288 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2289 Known = Known.reduceAdd(VecTy->getNumElements());
2290 break;
2291 }
2292 case Intrinsic::umin:
2293 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2294 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2295 Known = KnownBits::umin(Known, Known2);
2296 break;
2297 case Intrinsic::umax:
2298 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2299 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2300 Known = KnownBits::umax(Known, Known2);
2301 break;
2302 case Intrinsic::smin:
2303 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2304 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2305 Known = KnownBits::smin(Known, Known2);
2307 break;
2308 case Intrinsic::smax:
2309 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2310 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2311 Known = KnownBits::smax(Known, Known2);
2313 break;
2314 case Intrinsic::ptrmask: {
2315 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2316
2317 const Value *Mask = I->getOperand(1);
2318 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2319 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2320 // TODO: 1-extend would be more precise.
2321 Known &= Known2.anyextOrTrunc(BitWidth);
2322 break;
2323 }
2324 case Intrinsic::x86_sse42_crc32_64_64:
2325 Known.Zero.setBitsFrom(32);
2326 break;
2327 case Intrinsic::x86_ssse3_phadd_d_128:
2328 case Intrinsic::x86_ssse3_phadd_w_128:
2329 case Intrinsic::x86_avx2_phadd_d:
2330 case Intrinsic::x86_avx2_phadd_w: {
2332 I, DemandedElts, Q, Depth,
2333 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2334 return KnownBits::add(KnownLHS, KnownRHS);
2335 });
2336 break;
2337 }
2338 case Intrinsic::x86_ssse3_phadd_sw_128:
2339 case Intrinsic::x86_avx2_phadd_sw: {
2341 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2342 break;
2343 }
2344 case Intrinsic::x86_ssse3_phsub_d_128:
2345 case Intrinsic::x86_ssse3_phsub_w_128:
2346 case Intrinsic::x86_avx2_phsub_d:
2347 case Intrinsic::x86_avx2_phsub_w: {
2349 I, DemandedElts, Q, Depth,
2350 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2351 return KnownBits::sub(KnownLHS, KnownRHS);
2352 });
2353 break;
2354 }
2355 case Intrinsic::x86_ssse3_phsub_sw_128:
2356 case Intrinsic::x86_avx2_phsub_sw: {
2358 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2359 break;
2360 }
2361 case Intrinsic::riscv_vsetvli:
2362 case Intrinsic::riscv_vsetvlimax: {
2363 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2364 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2366 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2367 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2368 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2369 uint64_t MaxVLEN =
2370 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2371 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2372
2373 // Result of vsetvli must be not larger than AVL.
2374 if (HasAVL)
2375 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2376 MaxVL = std::min(MaxVL, CI->getZExtValue());
2377
2378 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2379 if (BitWidth > KnownZeroFirstBit)
2380 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2381 break;
2382 }
2383 case Intrinsic::amdgcn_mbcnt_hi:
2384 case Intrinsic::amdgcn_mbcnt_lo: {
2385 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2386 // most 31 + src1.
2387 KnownBits MbcntKnown(BitWidth);
2388 MbcntKnown.Zero.setBitsFrom(
2389 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2390 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2391 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2392 break;
2393 }
2394 case Intrinsic::vscale: {
2395 if (!II->getParent() || !II->getFunction())
2396 break;
2397
2398 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2399 break;
2400 }
2401 case Intrinsic::stepvector: {
2402 auto *VecTy = cast<VectorType>(II->getType());
2403 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2404 if (!isUIntN(BitWidth, MinNumElts))
2405 break;
2406
2407 bool Overflow = false;
2408 APInt MaxNumElts(BitWidth, MinNumElts);
2409 if (VecTy->isScalableTy()) {
2410 if (!II->getParent() || !II->getFunction())
2411 break;
2412 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2414 .umul_ov(MaxNumElts, Overflow);
2415 }
2416
2417 // Give up if the lane count could wrap. Stepvector truncates lane
2418 // indices that do not fit in the element type.
2419 if (Overflow)
2420 break;
2421
2422 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2423 break;
2424 }
2425 }
2426 }
2427 break;
2428 }
2429 case Instruction::ShuffleVector: {
2430 if (auto *Splat = getSplatValue(I)) {
2432 break;
2433 }
2434
2435 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2436 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2437 if (!Shuf) {
2438 Known.resetAll();
2439 return;
2440 }
2441 // For undef elements, we don't know anything about the common state of
2442 // the shuffle result.
2443 APInt DemandedLHS, DemandedRHS;
2444 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2445 Known.resetAll();
2446 return;
2447 }
2448 Known.setAllConflict();
2449 if (!!DemandedLHS) {
2450 const Value *LHS = Shuf->getOperand(0);
2451 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2452 // If we don't know any bits, early out.
2453 if (Known.isUnknown())
2454 break;
2455 }
2456 if (!!DemandedRHS) {
2457 const Value *RHS = Shuf->getOperand(1);
2458 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2459 Known = Known.intersectWith(Known2);
2460 }
2461 break;
2462 }
2463 case Instruction::InsertElement: {
2464 if (isa<ScalableVectorType>(I->getType())) {
2465 Known.resetAll();
2466 return;
2467 }
2468 const Value *Vec = I->getOperand(0);
2469 const Value *Elt = I->getOperand(1);
2470 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2471 unsigned NumElts = DemandedElts.getBitWidth();
2472 APInt DemandedVecElts = DemandedElts;
2473 bool NeedsElt = true;
2474 // If we know the index we are inserting too, clear it from Vec check.
2475 if (CIdx && CIdx->getValue().ult(NumElts)) {
2476 DemandedVecElts.clearBit(CIdx->getZExtValue());
2477 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2478 }
2479
2480 Known.setAllConflict();
2481 if (NeedsElt) {
2482 computeKnownBits(Elt, Known, Q, Depth + 1);
2483 // If we don't know any bits, early out.
2484 if (Known.isUnknown())
2485 break;
2486 }
2487
2488 if (!DemandedVecElts.isZero()) {
2489 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2490 Known = Known.intersectWith(Known2);
2491 }
2492 break;
2493 }
2494 case Instruction::ExtractElement: {
2495 // Look through extract element. If the index is non-constant or
2496 // out-of-range demand all elements, otherwise just the extracted element.
2497 const Value *Vec = I->getOperand(0);
2498 const Value *Idx = I->getOperand(1);
2499 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2500 if (isa<ScalableVectorType>(Vec->getType())) {
2501 // FIXME: there's probably *something* we can do with scalable vectors
2502 Known.resetAll();
2503 break;
2504 }
2505 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2506 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2507 if (CIdx && CIdx->getValue().ult(NumElts))
2508 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2509 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2510 break;
2511 }
2512 case Instruction::ExtractValue:
2513 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2515 if (EVI->getNumIndices() != 1) break;
2516 if (EVI->getIndices()[0] == 0) {
2517 switch (II->getIntrinsicID()) {
2518 default: break;
2519 case Intrinsic::uadd_with_overflow:
2520 case Intrinsic::sadd_with_overflow:
2522 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2523 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2524 break;
2525 case Intrinsic::usub_with_overflow:
2526 case Intrinsic::ssub_with_overflow:
2528 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2529 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2530 break;
2531 case Intrinsic::umul_with_overflow:
2532 case Intrinsic::smul_with_overflow:
2533 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2534 false, DemandedElts, Known, Known2, Q, Depth);
2535 break;
2536 }
2537 }
2538 }
2539 break;
2540 case Instruction::Freeze:
2541 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2542 Depth + 1))
2543 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2544 break;
2545 }
2546}
2547
2548/// Determine which bits of V are known to be either zero or one and return
2549/// them.
2550KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2551 const SimplifyQuery &Q, unsigned Depth) {
2552 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2553 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2554 return Known;
2555}
2556
2557/// Determine which bits of V are known to be either zero or one and return
2558/// them.
2560 unsigned Depth) {
2561 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2563 return Known;
2564}
2565
2566/// Determine which bits of V are known to be either zero or one and return
2567/// them in the Known bit set.
2568///
2569/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2570/// we cannot optimize based on the assumption that it is zero without changing
2571/// it to be an explicit zero. If we don't change it to zero, other code could
2572/// optimized based on the contradictory assumption that it is non-zero.
2573/// Because instcombine aggressively folds operations with undef args anyway,
2574/// this won't lose us code quality.
2575///
2576/// This function is defined on values with integer type, values with pointer
2577/// type, and vectors of integers. In the case
2578/// where V is a vector, known zero, and known one values are the
2579/// same width as the vector element, and the bit is set only if it is true
2580/// for all of the demanded elements in the vector specified by DemandedElts.
2581void computeKnownBits(const Value *V, const APInt &DemandedElts,
2582 KnownBits &Known, const SimplifyQuery &Q,
2583 unsigned Depth) {
2584 if (!DemandedElts) {
2585 // No demanded elts, better to assume we don't know anything.
2586 Known.resetAll();
2587 return;
2588 }
2589
2590 assert(V && "No Value?");
2591 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2592
2593#ifndef NDEBUG
2594 Type *Ty = V->getType();
2595 unsigned BitWidth = Known.getBitWidth();
2596
2597 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2598 "Not integer or pointer type!");
2599
2600 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2601 assert(
2602 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2603 "DemandedElt width should equal the fixed vector number of elements");
2604 } else {
2605 assert(DemandedElts == APInt(1, 1) &&
2606 "DemandedElt width should be 1 for scalars or scalable vectors");
2607 }
2608
2609 Type *ScalarTy = Ty->getScalarType();
2610 if (ScalarTy->isPointerTy()) {
2611 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2612 "V and Known should have same BitWidth");
2613 } else {
2614 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2615 "V and Known should have same BitWidth");
2616 }
2617#endif
2618
2619 const APInt *C;
2620 if (match(V, m_APInt(C))) {
2621 // We know all of the bits for a scalar constant or a splat vector constant!
2623 return;
2624 }
2625 // Null and aggregate-zero are all-zeros.
2627 Known.setAllZero();
2628 return;
2629 }
2630 // Handle a constant vector by taking the intersection of the known bits of
2631 // each element.
2633 assert(!isa<ScalableVectorType>(V->getType()));
2634 // We know that CDV must be a vector of integers. Take the intersection of
2635 // each element.
2636 Known.setAllConflict();
2637 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2638 if (!DemandedElts[i])
2639 continue;
2640 APInt Elt = CDV->getElementAsAPInt(i);
2641 Known.Zero &= ~Elt;
2642 Known.One &= Elt;
2643 }
2644 if (Known.hasConflict())
2645 Known.resetAll();
2646 return;
2647 }
2648
2649 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2650 assert(!isa<ScalableVectorType>(V->getType()));
2651 // We know that CV must be a vector of integers. Take the intersection of
2652 // each element.
2653 Known.setAllConflict();
2654 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2655 if (!DemandedElts[i])
2656 continue;
2657 Constant *Element = CV->getAggregateElement(i);
2658 if (isa<PoisonValue>(Element))
2659 continue;
2660 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2661 if (!ElementCI) {
2662 Known.resetAll();
2663 return;
2664 }
2665 const APInt &Elt = ElementCI->getValue();
2666 Known.Zero &= ~Elt;
2667 Known.One &= Elt;
2668 }
2669 if (Known.hasConflict())
2670 Known.resetAll();
2671 return;
2672 }
2673
2674 // Start out not knowing anything.
2675 Known.resetAll();
2676
2677 // We can't imply anything about undefs.
2678 if (isa<UndefValue>(V))
2679 return;
2680
2681 // There's no point in looking through other users of ConstantData for
2682 // assumptions. Confirm that we've handled them all.
2683 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2684
2685 if (const auto *A = dyn_cast<Argument>(V))
2686 if (std::optional<ConstantRange> Range = A->getRange())
2687 Known = Range->toKnownBits();
2688
2689 // All recursive calls that increase depth must come after this.
2691 return;
2692
2693 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2694 // the bits of its aliasee.
2695 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2696 if (!GA->isInterposable())
2697 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2698 return;
2699 }
2700
2701 if (const Operator *I = dyn_cast<Operator>(V))
2702 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2703 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2704 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2705 Known = CR->toKnownBits();
2706 }
2707
2708 // Aligned pointers have trailing zeros - refine Known.Zero set
2709 if (isa<PointerType>(V->getType())) {
2710 Align Alignment = V->getPointerAlignment(Q.DL);
2711 Known.Zero.setLowBits(Log2(Alignment));
2712 }
2713
2714 // computeKnownBitsFromContext strictly refines Known.
2715 // Therefore, we run them after computeKnownBitsFromOperator.
2716
2717 // Check whether we can determine known bits from context such as assumes.
2719}
2720
2721/// Try to detect a recurrence that the value of the induction variable is
2722/// always a power of two (or zero).
2723static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2724 SimplifyQuery &Q, unsigned Depth) {
2725 BinaryOperator *BO = nullptr;
2726 Value *Start = nullptr, *Step = nullptr;
2727 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2728 return false;
2729
2730 // Initial value must be a power of two.
2731 for (const Use &U : PN->operands()) {
2732 if (U.get() == Start) {
2733 // Initial value comes from a different BB, need to adjust context
2734 // instruction for analysis.
2735 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2736 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2737 return false;
2738 }
2739 }
2740
2741 // Except for Mul, the induction variable must be on the left side of the
2742 // increment expression, otherwise its value can be arbitrary.
2743 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2744 return false;
2745
2746 Q.CtxI = BO->getParent()->getTerminator();
2747 switch (BO->getOpcode()) {
2748 case Instruction::Mul:
2749 // Power of two is closed under multiplication.
2750 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2751 Q.IIQ.hasNoSignedWrap(BO)) &&
2752 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2753 case Instruction::SDiv:
2754 // Start value must not be signmask for signed division, so simply being a
2755 // power of two is not sufficient, and it has to be a constant.
2756 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2757 return false;
2758 [[fallthrough]];
2759 case Instruction::UDiv:
2760 // Divisor must be a power of two.
2761 // If OrZero is false, cannot guarantee induction variable is non-zero after
2762 // division, same for Shr, unless it is exact division.
2763 return (OrZero || Q.IIQ.isExact(BO)) &&
2764 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2765 case Instruction::Shl:
2766 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2767 case Instruction::AShr:
2768 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2769 return false;
2770 [[fallthrough]];
2771 case Instruction::LShr:
2772 return OrZero || Q.IIQ.isExact(BO);
2773 default:
2774 return false;
2775 }
2776}
2777
2778/// Return true if we can infer that \p V is known to be a power of 2 from
2779/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2780static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2781 const Value *Cond,
2782 bool CondIsTrue) {
2783 CmpPredicate Pred;
2784 const APInt *RHSC;
2785 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2786 return false;
2787 if (!CondIsTrue)
2788 Pred = ICmpInst::getInversePredicate(Pred);
2789 // ctpop(V) u< 2
2790 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2791 return true;
2792 // ctpop(V) == 1
2793 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2794}
2795
2796/// Return true if the given value is known to have exactly one
2797/// bit set when defined. For vectors return true if every element is known to
2798/// be a power of two when defined. Supports values with integer or pointer
2799/// types and vectors of integers.
2800bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2801 const SimplifyQuery &Q, unsigned Depth) {
2802 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2803
2804 if (isa<Constant>(V))
2805 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2806
2807 // i1 is by definition a power of 2 or zero.
2808 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2809 return true;
2810
2811 // Try to infer from assumptions.
2812 if (Q.AC && Q.CtxI) {
2813 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2814 if (!AssumeVH)
2815 continue;
2816 CallInst *I = cast<CallInst>(AssumeVH);
2817 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2818 /*CondIsTrue=*/true) &&
2820 return true;
2821 }
2822 }
2823
2824 // Handle dominating conditions.
2825 if (Q.DC && Q.CtxI && Q.DT) {
2826 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2827 Value *Cond = BI->getCondition();
2828
2829 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2831 /*CondIsTrue=*/true) &&
2832 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2833 return true;
2834
2835 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2837 /*CondIsTrue=*/false) &&
2838 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2839 return true;
2840 }
2841 }
2842
2843 auto *I = dyn_cast<Instruction>(V);
2844 if (!I)
2845 return false;
2846
2847 if (Q.CtxI && match(V, m_VScale())) {
2848 const Function *F = Q.CtxI->getFunction();
2849 // The vscale_range indicates vscale is a power-of-two.
2850 return F->hasFnAttribute(Attribute::VScaleRange);
2851 }
2852
2853 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2854 // it is shifted off the end then the result is undefined.
2855 if (match(I, m_Shl(m_One(), m_Value())))
2856 return true;
2857
2858 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2859 // the bottom. If it is shifted off the bottom then the result is undefined.
2860 if (match(I, m_LShr(m_SignMask(), m_Value())))
2861 return true;
2862
2863 // The remaining tests are all recursive, so bail out if we hit the limit.
2865 return false;
2866
2867 switch (I->getOpcode()) {
2868 case Instruction::ZExt:
2869 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2870 case Instruction::Trunc:
2871 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2872 case Instruction::Shl:
2873 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2874 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2875 return false;
2876 case Instruction::LShr:
2877 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2878 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2879 return false;
2880 case Instruction::UDiv:
2882 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2883 return false;
2884 case Instruction::Mul:
2885 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2886 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2887 (OrZero || isKnownNonZero(I, Q, Depth));
2888 case Instruction::And:
2889 // A power of two and'd with anything is a power of two or zero.
2890 if (OrZero &&
2891 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2892 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2893 return true;
2894 // X & (-X) is always a power of two or zero.
2895 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2896 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2897 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2898 return false;
2899 case Instruction::Add: {
2900 // Adding a power-of-two or zero to the same power-of-two or zero yields
2901 // either the original power-of-two, a larger power-of-two or zero.
2903 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2904 Q.IIQ.hasNoSignedWrap(VOBO)) {
2905 if (match(I->getOperand(0),
2906 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2907 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2908 return true;
2909 if (match(I->getOperand(1),
2910 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2911 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2912 return true;
2913
2914 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2915 KnownBits LHSBits(BitWidth);
2916 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2917
2918 KnownBits RHSBits(BitWidth);
2919 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2920 // If i8 V is a power of two or zero:
2921 // ZeroBits: 1 1 1 0 1 1 1 1
2922 // ~ZeroBits: 0 0 0 1 0 0 0 0
2923 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2924 // If OrZero isn't set, we cannot give back a zero result.
2925 // Make sure either the LHS or RHS has a bit set.
2926 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2927 return true;
2928 }
2929
2930 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2931 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2932 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2933 return true;
2934 return false;
2935 }
2936 case Instruction::Select:
2937 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2938 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2939 case Instruction::PHI: {
2940 // A PHI node is power of two if all incoming values are power of two, or if
2941 // it is an induction variable where in each step its value is a power of
2942 // two.
2943 auto *PN = cast<PHINode>(I);
2945
2946 // Check if it is an induction variable and always power of two.
2947 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2948 return true;
2949
2950 // Recursively check all incoming values. Limit recursion to 2 levels, so
2951 // that search complexity is limited to number of operands^2.
2952 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2953 return llvm::all_of(PN->operands(), [&](const Use &U) {
2954 // Value is power of 2 if it is coming from PHI node itself by induction.
2955 if (U.get() == PN)
2956 return true;
2957
2958 // Change the context instruction to the incoming block where it is
2959 // evaluated.
2960 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
2961 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2962 });
2963 }
2964 case Instruction::Invoke:
2965 case Instruction::Call: {
2966 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2967 switch (II->getIntrinsicID()) {
2968 case Intrinsic::umax:
2969 case Intrinsic::smax:
2970 case Intrinsic::umin:
2971 case Intrinsic::smin:
2972 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2973 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2974 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2975 // thus dont change pow2/non-pow2 status.
2976 case Intrinsic::bitreverse:
2977 case Intrinsic::bswap:
2978 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2979 case Intrinsic::fshr:
2980 case Intrinsic::fshl:
2981 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2982 if (II->getArgOperand(0) == II->getArgOperand(1))
2983 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2984 break;
2985 case Intrinsic::riscv_vsetvlimax:
2986 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2987 // for any valid vtype, so it is a power of two regardless of OrZero.
2988 return true;
2989 case Intrinsic::read_register:
2990 case Intrinsic::read_volatile_register: {
2991 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2992 // of two, so it is a power of two regardless of OrZero.
2993 const Module *M = II->getModule();
2994 if (!M || !M->getTargetTriple().isRISCV())
2995 break;
2996 return isReadVLENB(*II);
2997 }
2998 default:
2999 break;
3000 }
3001 }
3002 return false;
3003 }
3004 default:
3005 return false;
3006 }
3007}
3008
3009/// Test whether a GEP's result is known to be non-null.
3010///
3011/// Uses properties inherent in a GEP to try to determine whether it is known
3012/// to be non-null.
3013///
3014/// Currently this routine does not support vector GEPs.
3015static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3016 unsigned Depth) {
3017 const Function *F = nullptr;
3018 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3019 F = I->getFunction();
3020
3021 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3022 // may be null iff the base pointer is null and the offset is zero.
3023 if (!GEP->hasNoUnsignedWrap() &&
3024 !(GEP->isInBounds() &&
3025 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3026 return false;
3027
3028 // FIXME: Support vector-GEPs.
3029 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3030
3031 // If the base pointer is non-null, we cannot walk to a null address with an
3032 // inbounds GEP in address space zero.
3033 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3034 return true;
3035
3036 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3037 // If so, then the GEP cannot produce a null pointer, as doing so would
3038 // inherently violate the inbounds contract within address space zero.
3040 GTI != GTE; ++GTI) {
3041 // Struct types are easy -- they must always be indexed by a constant.
3042 if (StructType *STy = GTI.getStructTypeOrNull()) {
3043 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3044 unsigned ElementIdx = OpC->getZExtValue();
3045 const StructLayout *SL = Q.DL.getStructLayout(STy);
3046 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3047 if (ElementOffset > 0)
3048 return true;
3049 continue;
3050 }
3051
3052 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3053 if (GTI.getSequentialElementStride(Q.DL).isZero())
3054 continue;
3055
3056 // Fast path the constant operand case both for efficiency and so we don't
3057 // increment Depth when just zipping down an all-constant GEP.
3058 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3059 if (!OpC->isZero())
3060 return true;
3061 continue;
3062 }
3063
3064 // We post-increment Depth here because while isKnownNonZero increments it
3065 // as well, when we pop back up that increment won't persist. We don't want
3066 // to recurse 10k times just because we have 10k GEP operands. We don't
3067 // bail completely out because we want to handle constant GEPs regardless
3068 // of depth.
3070 continue;
3071
3072 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3073 return true;
3074 }
3075
3076 return false;
3077}
3078
3080 const Instruction *CtxI,
3081 const DominatorTree *DT) {
3082 assert(!isa<Constant>(V) && "Called for constant?");
3083
3084 if (!CtxI || !DT)
3085 return false;
3086
3087 unsigned NumUsesExplored = 0;
3088 for (auto &U : V->uses()) {
3089 // Avoid massive lists
3090 if (NumUsesExplored >= DomConditionsMaxUses)
3091 break;
3092 NumUsesExplored++;
3093
3094 const Instruction *UI = cast<Instruction>(U.getUser());
3095 // If the value is used as an argument to a call or invoke, then argument
3096 // attributes may provide an answer about null-ness.
3097 if (V->getType()->isPointerTy()) {
3098 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3099 if (CB->isArgOperand(&U) &&
3100 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3101 /*AllowUndefOrPoison=*/false) &&
3102 DT->dominates(CB, CtxI))
3103 return true;
3104 }
3105 }
3106
3107 // If the value is used as a load/store, then the pointer must be non null.
3108 if (V == getLoadStorePointerOperand(UI)) {
3111 DT->dominates(UI, CtxI))
3112 return true;
3113 }
3114
3115 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3116 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3117 isValidAssumeForContext(UI, CtxI, DT))
3118 return true;
3119
3120 // Consider only compare instructions uniquely controlling a branch
3121 Value *RHS;
3122 CmpPredicate Pred;
3123 bool NonNullIfTrue;
3124 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3125 if (cmpExcludesZero(Pred, RHS))
3126 NonNullIfTrue = true;
3128 NonNullIfTrue = false;
3129 else
3130 continue;
3131 } else if (UI->getType()->isIntegerTy(1) &&
3132 match(UI, m_Trunc(m_Specific(V)))) {
3133 NonNullIfTrue = true;
3134 } else
3135 continue;
3136
3139 for (const auto *CmpU : UI->users()) {
3140 assert(WorkList.empty() && "Should be!");
3141 if (Visited.insert(CmpU).second)
3142 WorkList.push_back(CmpU);
3143
3144 while (!WorkList.empty()) {
3145 auto *Curr = WorkList.pop_back_val();
3146
3147 // If a user is an AND, add all its users to the work list. We only
3148 // propagate "pred != null" condition through AND because it is only
3149 // correct to assume that all conditions of AND are met in true branch.
3150 // TODO: Support similar logic of OR and EQ predicate?
3151 if (NonNullIfTrue)
3152 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3153 for (const auto *CurrU : Curr->users())
3154 if (Visited.insert(CurrU).second)
3155 WorkList.push_back(CurrU);
3156 continue;
3157 }
3158
3159 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3160 BasicBlock *NonNullSuccessor =
3161 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3162 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3163 if (DT->dominates(Edge, CtxI->getParent()))
3164 return true;
3165 } else if (NonNullIfTrue && isGuard(Curr) &&
3166 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3167 return true;
3168 }
3169 }
3170 }
3171 }
3172
3173 return false;
3174}
3175
3176/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3177/// ensure that the value it's attached to is never Value? 'RangeType' is
3178/// is the type of the value described by the range.
3179static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3180 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3181 assert(NumRanges >= 1);
3182 for (unsigned i = 0; i < NumRanges; ++i) {
3184 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3186 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3187 ConstantRange Range(Lower->getValue(), Upper->getValue());
3188 if (Range.contains(Value))
3189 return false;
3190 }
3191 return true;
3192}
3193
3194/// Try to detect a recurrence that monotonically increases/decreases from a
3195/// non-zero starting value. These are common as induction variables.
3196static bool isNonZeroRecurrence(const PHINode *PN) {
3197 BinaryOperator *BO = nullptr;
3198 Value *Start = nullptr, *Step = nullptr;
3199 const APInt *StartC, *StepC;
3200 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3201 !match(Start, m_APInt(StartC)) || StartC->isZero())
3202 return false;
3203
3204 switch (BO->getOpcode()) {
3205 case Instruction::Add:
3206 // Starting from non-zero and stepping away from zero can never wrap back
3207 // to zero.
3208 return BO->hasNoUnsignedWrap() ||
3209 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3210 StartC->isNegative() == StepC->isNegative());
3211 case Instruction::Mul:
3212 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3213 match(Step, m_APInt(StepC)) && !StepC->isZero();
3214 case Instruction::Shl:
3215 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3216 case Instruction::AShr:
3217 case Instruction::LShr:
3218 return BO->isExact();
3219 case Instruction::Or:
3220 return true;
3221 default:
3222 return false;
3223 }
3224}
3225
3226static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3228 m_Specific(Op1), m_Zero()))) ||
3230 m_Specific(Op0), m_Zero())));
3231}
3232
3233static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3234 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3235 bool NUW, unsigned Depth) {
3236 // (X + (X != 0)) is non zero
3237 if (matchOpWithOpEqZero(X, Y))
3238 return true;
3239
3240 if (NUW)
3241 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3242 isKnownNonZero(X, DemandedElts, Q, Depth);
3243
3244 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3245 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3246
3247 // If X and Y are both non-negative (as signed values) then their sum is not
3248 // zero unless both X and Y are zero.
3249 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3250 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3251 isKnownNonZero(X, DemandedElts, Q, Depth))
3252 return true;
3253
3254 // If X and Y are both negative (as signed values) then their sum is not
3255 // zero unless both X and Y equal INT_MIN.
3256 if (XKnown.isNegative() && YKnown.isNegative()) {
3258 // The sign bit of X is set. If some other bit is set then X is not equal
3259 // to INT_MIN.
3260 if (XKnown.One.intersects(Mask))
3261 return true;
3262 // The sign bit of Y is set. If some other bit is set then Y is not equal
3263 // to INT_MIN.
3264 if (YKnown.One.intersects(Mask))
3265 return true;
3266 }
3267
3268 // The sum of a non-negative number and a power of two is not zero.
3269 if (XKnown.isNonNegative() &&
3270 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3271 return true;
3272 if (YKnown.isNonNegative() &&
3273 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3274 return true;
3275
3276 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3277}
3278
3279static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3280 unsigned BitWidth, Value *X, Value *Y,
3281 unsigned Depth) {
3282 // (X - (X != 0)) is non zero
3283 // ((X != 0) - X) is non zero
3284 if (matchOpWithOpEqZero(X, Y))
3285 return true;
3286
3287 // TODO: Move this case into isKnownNonEqual().
3288 if (auto *C = dyn_cast<Constant>(X))
3289 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3290 return true;
3291
3292 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3293}
3294
3295static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3296 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3297 bool NUW, unsigned Depth) {
3298 // If X and Y are non-zero then so is X * Y as long as the multiplication
3299 // does not overflow.
3300 if (NSW || NUW)
3301 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3302 isKnownNonZero(Y, DemandedElts, Q, Depth);
3303
3304 // If either X or Y is odd, then if the other is non-zero the result can't
3305 // be zero.
3306 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3307 if (XKnown.One[0])
3308 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3309
3310 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3311 if (YKnown.One[0])
3312 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3313
3314 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3315 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3316 // the lowest known One of X and Y. If they are non-zero, the result
3317 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3318 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3319 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3320 BitWidth;
3321}
3322
3323static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3324 const SimplifyQuery &Q, const KnownBits &KnownVal,
3325 unsigned Depth) {
3326 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3327 switch (I->getOpcode()) {
3328 case Instruction::Shl:
3329 return Lhs.shl(Rhs);
3330 case Instruction::LShr:
3331 return Lhs.lshr(Rhs);
3332 case Instruction::AShr:
3333 return Lhs.ashr(Rhs);
3334 default:
3335 llvm_unreachable("Unknown Shift Opcode");
3336 }
3337 };
3338
3339 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3340 switch (I->getOpcode()) {
3341 case Instruction::Shl:
3342 return Lhs.lshr(Rhs);
3343 case Instruction::LShr:
3344 case Instruction::AShr:
3345 return Lhs.shl(Rhs);
3346 default:
3347 llvm_unreachable("Unknown Shift Opcode");
3348 }
3349 };
3350
3351 if (KnownVal.isUnknown())
3352 return false;
3353
3354 KnownBits KnownCnt =
3355 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3356 APInt MaxShift = KnownCnt.getMaxValue();
3357 unsigned NumBits = KnownVal.getBitWidth();
3358 if (MaxShift.uge(NumBits))
3359 return false;
3360
3361 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3362 return true;
3363
3364 // If all of the bits shifted out are known to be zero, and Val is known
3365 // non-zero then at least one non-zero bit must remain.
3366 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3367 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3368 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3369 return true;
3370
3371 return false;
3372}
3373
3375 const APInt &DemandedElts,
3376 const SimplifyQuery &Q, unsigned Depth) {
3377 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3378 switch (I->getOpcode()) {
3379 case Instruction::Alloca:
3380 // Alloca never returns null, malloc might.
3381 return I->getType()->getPointerAddressSpace() == 0;
3382 case Instruction::GetElementPtr:
3383 if (I->getType()->isPointerTy())
3385 break;
3386 case Instruction::BitCast: {
3387 // We need to be a bit careful here. We can only peek through the bitcast
3388 // if the scalar size of elements in the operand are smaller than and a
3389 // multiple of the size they are casting too. Take three cases:
3390 //
3391 // 1) Unsafe:
3392 // bitcast <2 x i16> %NonZero to <4 x i8>
3393 //
3394 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3395 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3396 // guranteed (imagine just sign bit set in the 2 i16 elements).
3397 //
3398 // 2) Unsafe:
3399 // bitcast <4 x i3> %NonZero to <3 x i4>
3400 //
3401 // Even though the scalar size of the src (`i3`) is smaller than the
3402 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3403 // its possible for the `3 x i4` elements to be zero because there are
3404 // some elements in the destination that don't contain any full src
3405 // element.
3406 //
3407 // 3) Safe:
3408 // bitcast <4 x i8> %NonZero to <2 x i16>
3409 //
3410 // This is always safe as non-zero in the 4 i8 elements implies
3411 // non-zero in the combination of any two adjacent ones. Since i8 is a
3412 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3413 // This all implies the 2 i16 elements are non-zero.
3414 Type *FromTy = I->getOperand(0)->getType();
3415 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3416 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3417 return isKnownNonZero(I->getOperand(0), Q, Depth);
3418 } break;
3419 case Instruction::IntToPtr:
3420 // Note that we have to take special care to avoid looking through
3421 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3422 // as casts that can alter the value, e.g., AddrSpaceCasts.
3423 if (!isa<ScalableVectorType>(I->getType()) &&
3424 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3425 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3426 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3427 break;
3428 case Instruction::PtrToAddr:
3429 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3430 // so we can directly forward.
3431 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3432 case Instruction::PtrToInt:
3433 // For inttoptr, make sure the result size is >= the address size. If the
3434 // address is non-zero, any larger value is also non-zero.
3435 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3436 I->getType()->getScalarSizeInBits())
3437 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3438 break;
3439 case Instruction::Trunc:
3440 // nuw/nsw trunc preserves zero/non-zero status of input.
3441 if (auto *TI = dyn_cast<TruncInst>(I))
3442 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3443 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3444 break;
3445
3446 // Iff x - y != 0, then x ^ y != 0
3447 // Therefore we can do the same exact checks
3448 case Instruction::Xor:
3449 case Instruction::Sub:
3450 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3451 I->getOperand(1), Depth);
3452 case Instruction::Or:
3453 // (X | (X != 0)) is non zero
3454 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3455 return true;
3456 // X | Y != 0 if X != Y.
3457 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3458 Depth))
3459 return true;
3460 // X | Y != 0 if X != 0 or Y != 0.
3461 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3462 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3463 case Instruction::SExt:
3464 case Instruction::ZExt:
3465 // ext X != 0 if X != 0.
3466 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3467
3468 case Instruction::Shl: {
3469 // shl nsw/nuw can't remove any non-zero bits.
3471 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3472 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3473
3474 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3475 // if the lowest bit is shifted off the end.
3477 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3478 if (Known.One[0])
3479 return true;
3480
3481 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3482 }
3483 case Instruction::LShr:
3484 case Instruction::AShr: {
3485 // shr exact can only shift out zero bits.
3487 if (BO->isExact())
3488 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3489
3490 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3491 // defined if the sign bit is shifted off the end.
3493 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3494 if (Known.isNegative())
3495 return true;
3496
3497 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3498 // position >= C, because the sum >= max(A, B).
3499 Value *A, *B;
3500 const APInt *C;
3501 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3502 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3503 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3504 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3505 if (!KnownA.One.lshr(*C).isZero())
3506 return true;
3507 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3508 if (!KnownB.One.lshr(*C).isZero())
3509 return true;
3510 }
3511
3512 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3513 }
3514 case Instruction::UDiv:
3515 case Instruction::SDiv: {
3516 // X / Y
3517 // div exact can only produce a zero if the dividend is zero.
3518 if (cast<PossiblyExactOperator>(I)->isExact())
3519 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3520
3521 KnownBits XKnown =
3522 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3523 // If X is fully unknown we won't be able to figure anything out so don't
3524 // both computing knownbits for Y.
3525 if (XKnown.isUnknown())
3526 return false;
3527
3528 KnownBits YKnown =
3529 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3530 if (I->getOpcode() == Instruction::SDiv) {
3531 // For signed division need to compare abs value of the operands.
3532 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3533 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3534 }
3535 // If X u>= Y then div is non zero (0/0 is UB).
3536 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3537 // If X is total unknown or X u< Y we won't be able to prove non-zero
3538 // with compute known bits so just return early.
3539 return XUgeY && *XUgeY;
3540 }
3541 case Instruction::Add: {
3542 // X + Y.
3543
3544 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3545 // non-zero.
3547 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3548 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3549 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3550 }
3551 case Instruction::Mul: {
3553 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3554 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3555 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3556 }
3557 case Instruction::Select: {
3558 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3559
3560 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3561 // then see if the select condition implies the arm is non-zero. For example
3562 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3563 // dominated by `X != 0`.
3564 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3565 Value *Op;
3566 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3567 // Op is trivially non-zero.
3568 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3569 return true;
3570
3571 // The condition of the select dominates the true/false arm. Check if the
3572 // condition implies that a given arm is non-zero.
3573 Value *X;
3574 CmpPredicate Pred;
3575 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3576 return false;
3577
3578 if (!IsTrueArm)
3579 Pred = ICmpInst::getInversePredicate(Pred);
3580
3581 return cmpExcludesZero(Pred, X);
3582 };
3583
3584 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3585 SelectArmIsNonZero(/* IsTrueArm */ false))
3586 return true;
3587 break;
3588 }
3589 case Instruction::PHI: {
3590 auto *PN = cast<PHINode>(I);
3592 return true;
3593
3594 // Check if all incoming values are non-zero using recursion.
3596 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3597 return llvm::all_of(PN->operands(), [&](const Use &U) {
3598 if (U.get() == PN)
3599 return true;
3600 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3601 // Check if the branch on the phi excludes zero.
3602 CmpPredicate Pred;
3603 Value *X;
3604 BasicBlock *TrueSucc, *FalseSucc;
3605 if (match(RecQ.CtxI,
3606 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3607 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3608 // Check for cases of duplicate successors.
3609 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3610 // If we're using the false successor, invert the predicate.
3611 if (FalseSucc == PN->getParent())
3612 Pred = CmpInst::getInversePredicate(Pred);
3613 if (cmpExcludesZero(Pred, X))
3614 return true;
3615 }
3616 }
3617 // Finally recurse on the edge and check it directly.
3618 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3619 });
3620 }
3621 case Instruction::InsertElement: {
3622 if (isa<ScalableVectorType>(I->getType()))
3623 break;
3624
3625 const Value *Vec = I->getOperand(0);
3626 const Value *Elt = I->getOperand(1);
3627 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3628
3629 unsigned NumElts = DemandedElts.getBitWidth();
3630 APInt DemandedVecElts = DemandedElts;
3631 bool SkipElt = false;
3632 // If we know the index we are inserting too, clear it from Vec check.
3633 if (CIdx && CIdx->getValue().ult(NumElts)) {
3634 DemandedVecElts.clearBit(CIdx->getZExtValue());
3635 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3636 }
3637
3638 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3639 // are non-zero.
3640 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3641 (DemandedVecElts.isZero() ||
3642 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3643 }
3644 case Instruction::ExtractElement:
3645 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3646 const Value *Vec = EEI->getVectorOperand();
3647 const Value *Idx = EEI->getIndexOperand();
3648 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3649 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3650 unsigned NumElts = VecTy->getNumElements();
3651 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3652 if (CIdx && CIdx->getValue().ult(NumElts))
3653 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3654 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3655 }
3656 }
3657 break;
3658 case Instruction::ShuffleVector: {
3659 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3660 if (!Shuf)
3661 break;
3662 APInt DemandedLHS, DemandedRHS;
3663 // For undef elements, we don't know anything about the common state of
3664 // the shuffle result.
3665 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3666 break;
3667 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3668 return (DemandedRHS.isZero() ||
3669 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3670 (DemandedLHS.isZero() ||
3671 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3672 }
3673 case Instruction::Freeze:
3674 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3675 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3676 Depth);
3677 case Instruction::Load: {
3678 auto *LI = cast<LoadInst>(I);
3679 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3680 // is never null.
3681 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3682 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3683 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3684 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3685 return true;
3686 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3688 }
3689
3690 // No need to fall through to computeKnownBits as range metadata is already
3691 // handled in isKnownNonZero.
3692 return false;
3693 }
3694 case Instruction::ExtractValue: {
3695 const WithOverflowInst *WO;
3697 switch (WO->getBinaryOp()) {
3698 default:
3699 break;
3700 case Instruction::Add:
3701 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3702 WO->getArgOperand(1),
3703 /*NSW=*/false,
3704 /*NUW=*/false, Depth);
3705 case Instruction::Sub:
3706 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3707 WO->getArgOperand(1), Depth);
3708 case Instruction::Mul:
3709 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3710 WO->getArgOperand(1),
3711 /*NSW=*/false, /*NUW=*/false, Depth);
3712 break;
3713 }
3714 }
3715 break;
3716 }
3717 case Instruction::Call:
3718 case Instruction::Invoke: {
3719 const auto *Call = cast<CallBase>(I);
3720 if (I->getType()->isPointerTy()) {
3721 if (Call->isReturnNonNull())
3722 return true;
3723 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3724 Call, /*MustPreserveOffset=*/true))
3725 return isKnownNonZero(RP, Q, Depth);
3726 } else {
3727 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3729 if (std::optional<ConstantRange> Range = Call->getRange()) {
3730 const APInt ZeroValue(Range->getBitWidth(), 0);
3731 if (!Range->contains(ZeroValue))
3732 return true;
3733 }
3734 if (const Value *RV = Call->getReturnedArgOperand())
3735 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3736 return true;
3737 }
3738
3739 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3740 switch (II->getIntrinsicID()) {
3741 case Intrinsic::sshl_sat:
3742 case Intrinsic::ushl_sat:
3743 case Intrinsic::abs:
3744 case Intrinsic::bitreverse:
3745 case Intrinsic::bswap:
3746 case Intrinsic::ctpop:
3747 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3748 // NB: We don't do usub_sat here as in any case we can prove its
3749 // non-zero, we will fold it to `sub nuw` in InstCombine.
3750 case Intrinsic::ssub_sat:
3751 // For most types, if x != y then ssub.sat x, y != 0. But
3752 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3753 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3754 if (BitWidth == 1)
3755 return false;
3756 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3757 II->getArgOperand(1), Depth);
3758 case Intrinsic::sadd_sat:
3759 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3760 II->getArgOperand(1),
3761 /*NSW=*/true, /* NUW=*/false, Depth);
3762 // Vec reverse preserves zero/non-zero status from input vec.
3763 case Intrinsic::vector_reverse:
3764 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3765 Q, Depth);
3766 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3767 case Intrinsic::vector_reduce_or:
3768 case Intrinsic::vector_reduce_umax:
3769 case Intrinsic::vector_reduce_umin:
3770 case Intrinsic::vector_reduce_smax:
3771 case Intrinsic::vector_reduce_smin:
3772 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3773 case Intrinsic::umax:
3774 case Intrinsic::uadd_sat:
3775 // umax(X, (X != 0)) is non zero
3776 // X +usat (X != 0) is non zero
3777 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3778 return true;
3779
3780 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3781 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3782 case Intrinsic::smax: {
3783 // If either arg is strictly positive the result is non-zero. Otherwise
3784 // the result is non-zero if both ops are non-zero.
3785 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3786 const KnownBits &OpKnown) {
3787 if (!OpNonZero.has_value())
3788 OpNonZero = OpKnown.isNonZero() ||
3789 isKnownNonZero(Op, DemandedElts, Q, Depth);
3790 return *OpNonZero;
3791 };
3792 // Avoid re-computing isKnownNonZero.
3793 std::optional<bool> Op0NonZero, Op1NonZero;
3794 KnownBits Op1Known =
3795 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3796 if (Op1Known.isNonNegative() &&
3797 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3798 return true;
3799 KnownBits Op0Known =
3800 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3801 if (Op0Known.isNonNegative() &&
3802 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3803 return true;
3804 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3805 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3806 }
3807 case Intrinsic::smin: {
3808 // If either arg is negative the result is non-zero. Otherwise
3809 // the result is non-zero if both ops are non-zero.
3810 KnownBits Op1Known =
3811 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3812 if (Op1Known.isNegative())
3813 return true;
3814 KnownBits Op0Known =
3815 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3816 if (Op0Known.isNegative())
3817 return true;
3818
3819 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3820 return true;
3821 }
3822 [[fallthrough]];
3823 case Intrinsic::umin:
3824 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3825 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3826 case Intrinsic::cttz:
3827 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3828 .Zero[0];
3829 case Intrinsic::ctlz:
3830 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3831 .isNonNegative();
3832 case Intrinsic::fshr:
3833 case Intrinsic::fshl:
3834 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3835 if (II->getArgOperand(0) == II->getArgOperand(1))
3836 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3837 break;
3838 case Intrinsic::vscale:
3839 return true;
3840 case Intrinsic::experimental_get_vector_length:
3841 return isKnownNonZero(I->getOperand(0), Q, Depth);
3842 default:
3843 break;
3844 }
3845 break;
3846 }
3847
3848 return false;
3849 }
3850 }
3851
3853 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3854 return Known.One != 0;
3855}
3856
3857/// Return true if the given value is known to be non-zero when defined. For
3858/// vectors, return true if every demanded element is known to be non-zero when
3859/// defined. For pointers, if the context instruction and dominator tree are
3860/// specified, perform context-sensitive analysis and return true if the
3861/// pointer couldn't possibly be null at the specified instruction.
3862/// Supports values with integer or pointer type and vectors of integers.
3863bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3864 const SimplifyQuery &Q, unsigned Depth) {
3865 Type *Ty = V->getType();
3866
3867#ifndef NDEBUG
3868 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3869
3870 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3871 assert(
3872 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3873 "DemandedElt width should equal the fixed vector number of elements");
3874 } else {
3875 assert(DemandedElts == APInt(1, 1) &&
3876 "DemandedElt width should be 1 for scalars");
3877 }
3878#endif
3879
3880 if (auto *C = dyn_cast<Constant>(V)) {
3881 if (C->isNullValue())
3882 return false;
3883 if (isa<ConstantInt>(C))
3884 // Must be non-zero due to null test above.
3885 return true;
3886
3887 // For constant vectors, check that all elements are poison or known
3888 // non-zero to determine that the whole vector is known non-zero.
3889 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3890 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3891 if (!DemandedElts[i])
3892 continue;
3893 Constant *Elt = C->getAggregateElement(i);
3894 if (!Elt || Elt->isNullValue())
3895 return false;
3896 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3897 return false;
3898 }
3899 return true;
3900 }
3901
3902 // Constant ptrauth can be null, iff the base pointer can be.
3903 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3904 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3905
3906 // A global variable in address space 0 is non null unless extern weak
3907 // or an absolute symbol reference. Other address spaces may have null as a
3908 // valid address for a global, so we can't assume anything.
3909 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3910 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3911 GV->getType()->getAddressSpace() == 0)
3912 return true;
3913 }
3914
3915 // For constant expressions, fall through to the Operator code below.
3916 if (!isa<ConstantExpr>(V))
3917 return false;
3918 }
3919
3920 if (const auto *A = dyn_cast<Argument>(V))
3921 if (std::optional<ConstantRange> Range = A->getRange()) {
3922 const APInt ZeroValue(Range->getBitWidth(), 0);
3923 if (!Range->contains(ZeroValue))
3924 return true;
3925 }
3926
3927 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3928 return true;
3929
3930 // Some of the tests below are recursive, so bail out if we hit the limit.
3932 return false;
3933
3934 // Check for pointer simplifications.
3935
3936 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3937 // A byval, inalloca may not be null in a non-default addres space. A
3938 // nonnull argument is assumed never 0.
3939 if (const Argument *A = dyn_cast<Argument>(V)) {
3940 if (((A->hasPassPointeeByValueCopyAttr() &&
3941 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3942 A->hasNonNullAttr()))
3943 return true;
3944 }
3945 }
3946
3947 if (const auto *I = dyn_cast<Operator>(V))
3948 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3949 return true;
3950
3951 if (!isa<Constant>(V) &&
3953 return true;
3954
3955 if (const Value *Stripped = stripNullTest(V))
3956 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3957
3958 return false;
3959}
3960
3962 unsigned Depth) {
3963 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3964 APInt DemandedElts =
3965 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3966 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3967}
3968
3969/// If the pair of operators are the same invertible function, return the
3970/// the operands of the function corresponding to each input. Otherwise,
3971/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3972/// every input value to exactly one output value. This is equivalent to
3973/// saying that Op1 and Op2 are equal exactly when the specified pair of
3974/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3975static std::optional<std::pair<Value*, Value*>>
3977 const Operator *Op2) {
3978 if (Op1->getOpcode() != Op2->getOpcode())
3979 return std::nullopt;
3980
3981 auto getOperands = [&](unsigned OpNum) -> auto {
3982 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3983 };
3984
3985 switch (Op1->getOpcode()) {
3986 default:
3987 break;
3988 case Instruction::Or:
3989 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3990 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3991 break;
3992 [[fallthrough]];
3993 case Instruction::Xor:
3994 case Instruction::Add: {
3995 Value *Other;
3996 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3997 return std::make_pair(Op1->getOperand(1), Other);
3998 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3999 return std::make_pair(Op1->getOperand(0), Other);
4000 break;
4001 }
4002 case Instruction::Sub:
4003 if (Op1->getOperand(0) == Op2->getOperand(0))
4004 return getOperands(1);
4005 if (Op1->getOperand(1) == Op2->getOperand(1))
4006 return getOperands(0);
4007 break;
4008 case Instruction::Mul: {
4009 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4010 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4011 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4012 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4013 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4014 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4015 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4016 break;
4017
4018 // Assume operand order has been canonicalized
4019 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4020 isa<ConstantInt>(Op1->getOperand(1)) &&
4021 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4022 return getOperands(0);
4023 break;
4024 }
4025 case Instruction::Shl: {
4026 // Same as multiplies, with the difference that we don't need to check
4027 // for a non-zero multiply. Shifts always multiply by non-zero.
4028 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4029 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4030 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4031 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4032 break;
4033
4034 if (Op1->getOperand(1) == Op2->getOperand(1))
4035 return getOperands(0);
4036 break;
4037 }
4038 case Instruction::AShr:
4039 case Instruction::LShr: {
4040 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4041 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4042 if (!PEO1->isExact() || !PEO2->isExact())
4043 break;
4044
4045 if (Op1->getOperand(1) == Op2->getOperand(1))
4046 return getOperands(0);
4047 break;
4048 }
4049 case Instruction::SExt:
4050 case Instruction::ZExt:
4051 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4052 return getOperands(0);
4053 break;
4054 case Instruction::PHI: {
4055 const PHINode *PN1 = cast<PHINode>(Op1);
4056 const PHINode *PN2 = cast<PHINode>(Op2);
4057
4058 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4059 // are a single invertible function of the start values? Note that repeated
4060 // application of an invertible function is also invertible
4061 BinaryOperator *BO1 = nullptr;
4062 Value *Start1 = nullptr, *Step1 = nullptr;
4063 BinaryOperator *BO2 = nullptr;
4064 Value *Start2 = nullptr, *Step2 = nullptr;
4065 if (PN1->getParent() != PN2->getParent() ||
4066 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4067 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4068 break;
4069
4071 cast<Operator>(BO2));
4072 if (!Values)
4073 break;
4074
4075 // We have to be careful of mutually defined recurrences here. Ex:
4076 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4077 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4078 // The invertibility of these is complicated, and not worth reasoning
4079 // about (yet?).
4080 if (Values->first != PN1 || Values->second != PN2)
4081 break;
4082
4083 return std::make_pair(Start1, Start2);
4084 }
4085 }
4086 return std::nullopt;
4087}
4088
4089/// Return true if V1 == (binop V2, X), where X is known non-zero.
4090/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4091/// implies V2 != V1.
4092static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4093 const APInt &DemandedElts,
4094 const SimplifyQuery &Q, unsigned Depth) {
4096 if (!BO)
4097 return false;
4098 switch (BO->getOpcode()) {
4099 default:
4100 break;
4101 case Instruction::Or:
4102 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4103 break;
4104 [[fallthrough]];
4105 case Instruction::Xor:
4106 case Instruction::Add:
4107 Value *Op = nullptr;
4108 if (V2 == BO->getOperand(0))
4109 Op = BO->getOperand(1);
4110 else if (V2 == BO->getOperand(1))
4111 Op = BO->getOperand(0);
4112 else
4113 return false;
4114 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4115 }
4116 return false;
4117}
4118
4119/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4120/// the multiplication is nuw or nsw.
4121static bool isNonEqualMul(const Value *V1, const Value *V2,
4122 const APInt &DemandedElts, const SimplifyQuery &Q,
4123 unsigned Depth) {
4124 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4125 const APInt *C;
4126 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4127 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4128 !C->isZero() && !C->isOne() &&
4129 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4130 }
4131 return false;
4132}
4133
4134/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4135/// the shift is nuw or nsw.
4136static bool isNonEqualShl(const Value *V1, const Value *V2,
4137 const APInt &DemandedElts, const SimplifyQuery &Q,
4138 unsigned Depth) {
4139 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4140 const APInt *C;
4141 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4142 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4143 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4144 }
4145 return false;
4146}
4147
4148static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4149 const APInt &DemandedElts, const SimplifyQuery &Q,
4150 unsigned Depth) {
4151 // Check two PHIs are in same block.
4152 if (PN1->getParent() != PN2->getParent())
4153 return false;
4154
4156 bool UsedFullRecursion = false;
4157 for (const BasicBlock *IncomBB : PN1->blocks()) {
4158 if (!VisitedBBs.insert(IncomBB).second)
4159 continue; // Don't reprocess blocks that we have dealt with already.
4160 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4161 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4162 const APInt *C1, *C2;
4163 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4164 continue;
4165
4166 // Only one pair of phi operands is allowed for full recursion.
4167 if (UsedFullRecursion)
4168 return false;
4169
4171 RecQ.CtxI = IncomBB->getTerminator();
4172 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4173 return false;
4174 UsedFullRecursion = true;
4175 }
4176 return true;
4177}
4178
4179static bool isNonEqualSelect(const Value *V1, const Value *V2,
4180 const APInt &DemandedElts, const SimplifyQuery &Q,
4181 unsigned Depth) {
4182 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4183 if (!SI1)
4184 return false;
4185
4186 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4187 const Value *Cond1 = SI1->getCondition();
4188 const Value *Cond2 = SI2->getCondition();
4189 if (Cond1 == Cond2)
4190 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4191 DemandedElts, Q, Depth + 1) &&
4192 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4193 DemandedElts, Q, Depth + 1);
4194 }
4195 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4196 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4197}
4198
4199// Check to see if A is both a GEP and is the incoming value for a PHI in the
4200// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4201// one of them being the recursive GEP A and the other a ptr at same base and at
4202// the same/higher offset than B we are only incrementing the pointer further in
4203// loop if offset of recursive GEP is greater than 0.
4205 const SimplifyQuery &Q) {
4206 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4207 return false;
4208
4209 auto *GEPA = dyn_cast<GEPOperator>(A);
4210 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4211 return false;
4212
4213 // Handle 2 incoming PHI values with one being a recursive GEP.
4214 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4215 if (!PN || PN->getNumIncomingValues() != 2)
4216 return false;
4217
4218 // Search for the recursive GEP as an incoming operand, and record that as
4219 // Step.
4220 Value *Start = nullptr;
4221 Value *Step = const_cast<Value *>(A);
4222 if (PN->getIncomingValue(0) == Step)
4223 Start = PN->getIncomingValue(1);
4224 else if (PN->getIncomingValue(1) == Step)
4225 Start = PN->getIncomingValue(0);
4226 else
4227 return false;
4228
4229 // Other incoming node base should match the B base.
4230 // StartOffset >= OffsetB && StepOffset > 0?
4231 // StartOffset <= OffsetB && StepOffset < 0?
4232 // Is non-equal if above are true.
4233 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4234 // optimisation to inbounds GEPs only.
4235 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4236 APInt StartOffset(IndexWidth, 0);
4237 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4238 APInt StepOffset(IndexWidth, 0);
4239 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4240
4241 // Check if Base Pointer of Step matches the PHI.
4242 if (Step != PN)
4243 return false;
4244 APInt OffsetB(IndexWidth, 0);
4245 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4246 return Start == B &&
4247 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4248 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4249}
4250
4251static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4252 const SimplifyQuery &Q, unsigned Depth) {
4253 if (!Q.CtxI)
4254 return false;
4255
4256 // Try to infer NonEqual based on information from dominating conditions.
4257 if (Q.DC && Q.DT) {
4258 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4259 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4260 Value *Cond = BI->getCondition();
4261 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4262 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4264 /*LHSIsTrue=*/true, Depth)
4265 .value_or(false))
4266 return true;
4267
4268 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4269 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4271 /*LHSIsTrue=*/false, Depth)
4272 .value_or(false))
4273 return true;
4274 }
4275
4276 return false;
4277 };
4278
4279 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4280 IsKnownNonEqualFromDominatingCondition(V2))
4281 return true;
4282 }
4283
4284 if (!Q.AC)
4285 return false;
4286
4287 // Try to infer NonEqual based on information from assumptions.
4288 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4289 if (!AssumeVH)
4290 continue;
4291 CallInst *I = cast<CallInst>(AssumeVH);
4292
4293 assert(I->getFunction() == Q.CtxI->getFunction() &&
4294 "Got assumption for the wrong function!");
4295 assert(I->getIntrinsicID() == Intrinsic::assume &&
4296 "must be an assume intrinsic");
4297
4298 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4299 /*LHSIsTrue=*/true, Depth)
4300 .value_or(false) &&
4302 return true;
4303 }
4304
4305 return false;
4306}
4307
4308static bool isNonEqualURem(const Value *X, const Value *Rem,
4309 const SimplifyQuery &Q) {
4310 const Value *Y;
4311 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4312 return false;
4313
4314 // For a defined urem, X != X urem Y exactly when X u>= Y.
4315 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4317 return true;
4318
4319 std::optional<bool> Implied =
4321 return Implied && *Implied;
4322}
4323
4324/// Return true if it is known that V1 != V2.
4325static bool isKnownNonEqual(const Value *V1, const Value *V2,
4326 const APInt &DemandedElts, const SimplifyQuery &Q,
4327 unsigned Depth) {
4328 if (V1 == V2)
4329 return false;
4330 if (V1->getType() != V2->getType())
4331 // We can't look through casts yet.
4332 return false;
4333
4335 return false;
4336
4337 // See if we can recurse through (exactly one of) our operands. This
4338 // requires our operation be 1-to-1 and map every input value to exactly
4339 // one output value. Such an operation is invertible.
4340 auto *O1 = dyn_cast<Operator>(V1);
4341 auto *O2 = dyn_cast<Operator>(V2);
4342 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4343 if (auto Values = getInvertibleOperands(O1, O2))
4344 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4345 Depth + 1);
4346
4347 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4348 const PHINode *PN2 = cast<PHINode>(V2);
4349 // FIXME: This is missing a generalization to handle the case where one is
4350 // a PHI and another one isn't.
4351 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4352 return true;
4353 };
4354 }
4355
4356 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4357 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4358 return true;
4359
4360 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4361 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4362 return true;
4363
4364 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4365 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4366 return true;
4367
4368 if (V1->getType()->isIntOrIntVectorTy()) {
4369 // Are any known bits in V1 contradictory to known bits in V2? If V1
4370 // has a known zero where V2 has a known one, they must not be equal.
4371 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4372 if (!Known1.isUnknown()) {
4373 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4374 if (Known1.Zero.intersects(Known2.One) ||
4375 Known2.Zero.intersects(Known1.One))
4376 return true;
4377 }
4378 }
4379
4380 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4381 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4382 return true;
4383
4386 return true;
4387
4388 Value *A, *B;
4389 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4390 // Check PtrToInt type matches the pointer size.
4391 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4393 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4394
4395 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4396 return true;
4397
4398 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4399 return true;
4400
4401 return false;
4402}
4403
4404/// For vector constants, loop over the elements and find the constant with the
4405/// minimum number of sign bits. Return 0 if the value is not a vector constant
4406/// or if any element was not analyzed; otherwise, return the count for the
4407/// element with the minimum number of sign bits.
4409 const APInt &DemandedElts,
4410 unsigned TyBits) {
4411 const auto *CV = dyn_cast<Constant>(V);
4412 if (!CV || !isa<FixedVectorType>(CV->getType()))
4413 return 0;
4414
4415 unsigned MinSignBits = TyBits;
4416 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4417 for (unsigned i = 0; i != NumElts; ++i) {
4418 if (!DemandedElts[i])
4419 continue;
4420 // If we find a non-ConstantInt, bail out.
4421 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4422 if (!Elt)
4423 return 0;
4424
4425 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4426 }
4427
4428 return MinSignBits;
4429}
4430
4431static unsigned ComputeNumSignBitsImpl(const Value *V,
4432 const APInt &DemandedElts,
4433 const SimplifyQuery &Q, unsigned Depth);
4434
4435static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4436 const SimplifyQuery &Q, unsigned Depth) {
4437 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4438 assert(Result > 0 && "At least one sign bit needs to be present!");
4439 return Result;
4440}
4441
4442/// Return the number of times the sign bit of the register is replicated into
4443/// the other bits. We know that at least 1 bit is always equal to the sign bit
4444/// (itself), but other cases can give us information. For example, immediately
4445/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4446/// other, so we return 3. For vectors, return the number of sign bits for the
4447/// vector element with the minimum number of known sign bits of the demanded
4448/// elements in the vector specified by DemandedElts.
4449static unsigned ComputeNumSignBitsImpl(const Value *V,
4450 const APInt &DemandedElts,
4451 const SimplifyQuery &Q, unsigned Depth) {
4452 Type *Ty = V->getType();
4453#ifndef NDEBUG
4454 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4455
4456 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4457 assert(
4458 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4459 "DemandedElt width should equal the fixed vector number of elements");
4460 } else {
4461 assert(DemandedElts == APInt(1, 1) &&
4462 "DemandedElt width should be 1 for scalars");
4463 }
4464#endif
4465
4466 // We return the minimum number of sign bits that are guaranteed to be present
4467 // in V, so for undef we have to conservatively return 1. We don't have the
4468 // same behavior for poison though -- that's a FIXME today.
4469
4470 Type *ScalarTy = Ty->getScalarType();
4471 unsigned TyBits = ScalarTy->isPointerTy() ?
4472 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4473 Q.DL.getTypeSizeInBits(ScalarTy);
4474
4475 unsigned Tmp, Tmp2;
4476 unsigned FirstAnswer = 1;
4477
4478 // Note that ConstantInt is handled by the general computeKnownBits case
4479 // below.
4480
4482 return 1;
4483
4484 if (auto *U = dyn_cast<Operator>(V)) {
4485 switch (Operator::getOpcode(V)) {
4486 default: break;
4487 case Instruction::BitCast: {
4488 Value *Src = U->getOperand(0);
4489 Type *SrcTy = Src->getType();
4490
4491 // Skip if the source type is not an integer or integer vector type
4492 // This ensures we only process integer-like types
4493 if (!SrcTy->isIntOrIntVectorTy())
4494 break;
4495
4496 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4497
4498 // Bitcast 'large element' scalar/vector to 'small element' vector.
4499 if ((SrcBits % TyBits) != 0)
4500 break;
4501
4502 // Only proceed if the destination type is a fixed-size vector
4503 if (isa<FixedVectorType>(Ty)) {
4504 // Fast case - sign splat can be simply split across the small elements.
4505 // This works for both vector and scalar sources
4506 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4507 if (Tmp == SrcBits)
4508 return TyBits;
4509 }
4510 break;
4511 }
4512 case Instruction::SExt:
4513 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4514 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4515 Tmp;
4516
4517 case Instruction::SDiv: {
4518 const APInt *Denominator;
4519 // sdiv X, C -> adds log(C) sign bits.
4520 if (match(U->getOperand(1), m_APInt(Denominator))) {
4521
4522 // Ignore non-positive denominator.
4523 if (!Denominator->isStrictlyPositive())
4524 break;
4525
4526 // Calculate the incoming numerator bits.
4527 unsigned NumBits =
4528 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4529
4530 // Add floor(log(C)) bits to the numerator bits.
4531 return std::min(TyBits, NumBits + Denominator->logBase2());
4532 }
4533 break;
4534 }
4535
4536 case Instruction::SRem: {
4537 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4538
4539 const APInt *Denominator;
4540 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4541 // positive constant. This let us put a lower bound on the number of sign
4542 // bits.
4543 if (match(U->getOperand(1), m_APInt(Denominator))) {
4544
4545 // Ignore non-positive denominator.
4546 if (Denominator->isStrictlyPositive()) {
4547 // Calculate the leading sign bit constraints by examining the
4548 // denominator. Given that the denominator is positive, there are two
4549 // cases:
4550 //
4551 // 1. The numerator is positive. The result range is [0,C) and
4552 // [0,C) u< (1 << ceilLogBase2(C)).
4553 //
4554 // 2. The numerator is negative. Then the result range is (-C,0] and
4555 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4556 //
4557 // Thus a lower bound on the number of sign bits is `TyBits -
4558 // ceilLogBase2(C)`.
4559
4560 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4561 Tmp = std::max(Tmp, ResBits);
4562 }
4563 }
4564 return Tmp;
4565 }
4566
4567 case Instruction::AShr: {
4568 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4569 // ashr X, C -> adds C sign bits. Vectors too.
4570 const APInt *ShAmt;
4571 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4572 if (ShAmt->uge(TyBits))
4573 break; // Bad shift.
4574 unsigned ShAmtLimited = ShAmt->getZExtValue();
4575 Tmp += ShAmtLimited;
4576 if (Tmp > TyBits) Tmp = TyBits;
4577 }
4578 return Tmp;
4579 }
4580 case Instruction::Shl: {
4581 const APInt *ShAmt;
4582 Value *X = nullptr;
4583 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4584 // shl destroys sign bits.
4585 if (ShAmt->uge(TyBits))
4586 break; // Bad shift.
4587 // We can look through a zext (more or less treating it as a sext) if
4588 // all extended bits are shifted out.
4589 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4590 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4591 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4592 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4593 } else
4594 Tmp =
4595 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4596 if (ShAmt->uge(Tmp))
4597 break; // Shifted all sign bits out.
4598 Tmp2 = ShAmt->getZExtValue();
4599 return Tmp - Tmp2;
4600 }
4601 break;
4602 }
4603 case Instruction::And:
4604 case Instruction::Or:
4605 case Instruction::Xor: // NOT is handled here.
4606 // Logical binary ops preserve the number of sign bits at the worst.
4607 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4608 if (Tmp != 1) {
4609 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4610 FirstAnswer = std::min(Tmp, Tmp2);
4611 // We computed what we know about the sign bits as our first
4612 // answer. Now proceed to the generic code that uses
4613 // computeKnownBits, and pick whichever answer is better.
4614 }
4615 break;
4616
4617 case Instruction::Select: {
4618 // If we have a clamp pattern, we know that the number of sign bits will
4619 // be the minimum of the clamp min/max range.
4620 const Value *X;
4621 const APInt *CLow, *CHigh;
4622 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4623 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4624
4625 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4626 if (Tmp == 1)
4627 break;
4628 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4629 return std::min(Tmp, Tmp2);
4630 }
4631
4632 case Instruction::Add:
4633 // Add can have at most one carry bit. Thus we know that the output
4634 // is, at worst, one more bit than the inputs.
4635 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4636 if (Tmp == 1) break;
4637
4638 // Special case decrementing a value (ADD X, -1):
4639 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4640 if (CRHS->isAllOnesValue()) {
4641 KnownBits Known(TyBits);
4642 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4643
4644 // If the input is known to be 0 or 1, the output is 0/-1, which is
4645 // all sign bits set.
4646 if ((Known.Zero | 1).isAllOnes())
4647 return TyBits;
4648
4649 // If we are subtracting one from a positive number, there is no carry
4650 // out of the result.
4651 if (Known.isNonNegative())
4652 return Tmp;
4653 }
4654
4655 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4656 if (Tmp2 == 1)
4657 break;
4658 return std::min(Tmp, Tmp2) - 1;
4659
4660 case Instruction::Sub:
4661 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4662 if (Tmp2 == 1)
4663 break;
4664
4665 // Handle NEG.
4666 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4667 if (CLHS->isNullValue()) {
4668 KnownBits Known(TyBits);
4669 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4670 // If the input is known to be 0 or 1, the output is 0/-1, which is
4671 // all sign bits set.
4672 if ((Known.Zero | 1).isAllOnes())
4673 return TyBits;
4674
4675 // If the input is known to be positive (the sign bit is known clear),
4676 // the output of the NEG has the same number of sign bits as the
4677 // input.
4678 if (Known.isNonNegative())
4679 return Tmp2;
4680
4681 // Otherwise, we treat this like a SUB.
4682 }
4683
4684 // Sub can have at most one carry bit. Thus we know that the output
4685 // is, at worst, one more bit than the inputs.
4686 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4687 if (Tmp == 1)
4688 break;
4689 return std::min(Tmp, Tmp2) - 1;
4690
4691 case Instruction::Mul: {
4692 // The output of the Mul can be at most twice the valid bits in the
4693 // inputs.
4694 unsigned SignBitsOp0 =
4695 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4696 if (SignBitsOp0 == 1)
4697 break;
4698 unsigned SignBitsOp1 =
4699 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4700 if (SignBitsOp1 == 1)
4701 break;
4702 unsigned OutValidBits =
4703 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4704 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4705 }
4706
4707 case Instruction::PHI: {
4708 const PHINode *PN = cast<PHINode>(U);
4709 unsigned NumIncomingValues = PN->getNumIncomingValues();
4710 // Don't analyze large in-degree PHIs.
4711 if (NumIncomingValues > 4) break;
4712 // Unreachable blocks may have zero-operand PHI nodes.
4713 if (NumIncomingValues == 0) break;
4714
4715 // Take the minimum of all incoming values. This can't infinitely loop
4716 // because of our depth threshold.
4718 Tmp = TyBits;
4719 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4720 if (Tmp == 1) return Tmp;
4721 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4722 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4723 DemandedElts, RecQ, Depth + 1));
4724 }
4725 return Tmp;
4726 }
4727
4728 case Instruction::Trunc: {
4729 // If the input contained enough sign bits that some remain after the
4730 // truncation, then we can make use of that. Otherwise we don't know
4731 // anything.
4732 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4733 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4734 if (Tmp > (OperandTyBits - TyBits))
4735 return Tmp - (OperandTyBits - TyBits);
4736
4737 return 1;
4738 }
4739
4740 case Instruction::ExtractElement:
4741 // Look through extract element. At the moment we keep this simple and
4742 // skip tracking the specific element. But at least we might find
4743 // information valid for all elements of the vector (for example if vector
4744 // is sign extended, shifted, etc).
4745 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4746
4747 case Instruction::ShuffleVector: {
4748 // Collect the minimum number of sign bits that are shared by every vector
4749 // element referenced by the shuffle.
4750 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4751 if (!Shuf) {
4752 // FIXME: Add support for shufflevector constant expressions.
4753 return 1;
4754 }
4755 APInt DemandedLHS, DemandedRHS;
4756 // For undef elements, we don't know anything about the common state of
4757 // the shuffle result.
4758 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4759 return 1;
4760 Tmp = std::numeric_limits<unsigned>::max();
4761 if (!!DemandedLHS) {
4762 const Value *LHS = Shuf->getOperand(0);
4763 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4764 }
4765 // If we don't know anything, early out and try computeKnownBits
4766 // fall-back.
4767 if (Tmp == 1)
4768 break;
4769 if (!!DemandedRHS) {
4770 const Value *RHS = Shuf->getOperand(1);
4771 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4772 Tmp = std::min(Tmp, Tmp2);
4773 }
4774 // If we don't know anything, early out and try computeKnownBits
4775 // fall-back.
4776 if (Tmp == 1)
4777 break;
4778 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4779 return Tmp;
4780 }
4781 case Instruction::Call: {
4782 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4783 switch (II->getIntrinsicID()) {
4784 default:
4785 break;
4786 case Intrinsic::abs:
4787 Tmp =
4788 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4789 if (Tmp == 1)
4790 break;
4791
4792 // Absolute value reduces number of sign bits by at most 1.
4793 return Tmp - 1;
4794 case Intrinsic::smin:
4795 case Intrinsic::smax: {
4796 const APInt *CLow, *CHigh;
4797 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4798 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4799 }
4800 }
4801 }
4802 }
4803 }
4804 }
4805
4806 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4807 // use this information.
4808
4809 // If we can examine all elements of a vector constant successfully, we're
4810 // done (we can't do any better than that). If not, keep trying.
4811 if (unsigned VecSignBits =
4812 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4813 return VecSignBits;
4814
4815 KnownBits Known(TyBits);
4816 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4817
4818 // If we know that the sign bit is either zero or one, determine the number of
4819 // identical bits in the top of the input value.
4820 return std::max(FirstAnswer, Known.countMinSignBits());
4821}
4822
4824 const TargetLibraryInfo *TLI) {
4825 const Function *F = CB.getCalledFunction();
4826 if (!F)
4828
4829 if (F->isIntrinsic())
4830 return F->getIntrinsicID();
4831
4832 // We are going to infer semantics of a library function based on mapping it
4833 // to an LLVM intrinsic. Check that the library function is available from
4834 // this callbase and in this environment.
4835 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4837
4838 LibFunc Func = TLI->getLibFunc(CB);
4839 if (Func == NotLibFunc)
4841
4842 switch (Func) {
4843 default:
4844 break;
4845 case LibFunc_sin:
4846 case LibFunc_sinf:
4847 case LibFunc_sinl:
4848 return Intrinsic::sin;
4849 case LibFunc_cos:
4850 case LibFunc_cosf:
4851 case LibFunc_cosl:
4852 return Intrinsic::cos;
4853 case LibFunc_tan:
4854 case LibFunc_tanf:
4855 case LibFunc_tanl:
4856 return Intrinsic::tan;
4857 case LibFunc_asin:
4858 case LibFunc_asinf:
4859 case LibFunc_asinl:
4860 return Intrinsic::asin;
4861 case LibFunc_acos:
4862 case LibFunc_acosf:
4863 case LibFunc_acosl:
4864 return Intrinsic::acos;
4865 case LibFunc_atan:
4866 case LibFunc_atanf:
4867 case LibFunc_atanl:
4868 return Intrinsic::atan;
4869 case LibFunc_atan2:
4870 case LibFunc_atan2f:
4871 case LibFunc_atan2l:
4872 return Intrinsic::atan2;
4873 case LibFunc_sinh:
4874 case LibFunc_sinhf:
4875 case LibFunc_sinhl:
4876 return Intrinsic::sinh;
4877 case LibFunc_cosh:
4878 case LibFunc_coshf:
4879 case LibFunc_coshl:
4880 return Intrinsic::cosh;
4881 case LibFunc_tanh:
4882 case LibFunc_tanhf:
4883 case LibFunc_tanhl:
4884 return Intrinsic::tanh;
4885 case LibFunc_exp:
4886 case LibFunc_expf:
4887 case LibFunc_expl:
4888 return Intrinsic::exp;
4889 case LibFunc_exp2:
4890 case LibFunc_exp2f:
4891 case LibFunc_exp2l:
4892 return Intrinsic::exp2;
4893 case LibFunc_exp10:
4894 case LibFunc_exp10f:
4895 case LibFunc_exp10l:
4896 return Intrinsic::exp10;
4897 case LibFunc_log:
4898 case LibFunc_logf:
4899 case LibFunc_logl:
4900 return Intrinsic::log;
4901 case LibFunc_log10:
4902 case LibFunc_log10f:
4903 case LibFunc_log10l:
4904 return Intrinsic::log10;
4905 case LibFunc_log2:
4906 case LibFunc_log2f:
4907 case LibFunc_log2l:
4908 return Intrinsic::log2;
4909 case LibFunc_fabs:
4910 case LibFunc_fabsf:
4911 case LibFunc_fabsl:
4912 return Intrinsic::fabs;
4913 case LibFunc_fmin:
4914 case LibFunc_fminf:
4915 case LibFunc_fminl:
4916 return Intrinsic::minnum;
4917 case LibFunc_fmax:
4918 case LibFunc_fmaxf:
4919 case LibFunc_fmaxl:
4920 return Intrinsic::maxnum;
4921 case LibFunc_copysign:
4922 case LibFunc_copysignf:
4923 case LibFunc_copysignl:
4924 return Intrinsic::copysign;
4925 case LibFunc_floor:
4926 case LibFunc_floorf:
4927 case LibFunc_floorl:
4928 return Intrinsic::floor;
4929 case LibFunc_ceil:
4930 case LibFunc_ceilf:
4931 case LibFunc_ceill:
4932 return Intrinsic::ceil;
4933 case LibFunc_trunc:
4934 case LibFunc_truncf:
4935 case LibFunc_truncl:
4936 return Intrinsic::trunc;
4937 case LibFunc_rint:
4938 case LibFunc_rintf:
4939 case LibFunc_rintl:
4940 return Intrinsic::rint;
4941 case LibFunc_nearbyint:
4942 case LibFunc_nearbyintf:
4943 case LibFunc_nearbyintl:
4944 return Intrinsic::nearbyint;
4945 case LibFunc_round:
4946 case LibFunc_roundf:
4947 case LibFunc_roundl:
4948 return Intrinsic::round;
4949 case LibFunc_roundeven:
4950 case LibFunc_roundevenf:
4951 case LibFunc_roundevenl:
4952 return Intrinsic::roundeven;
4953 case LibFunc_pow:
4954 case LibFunc_powf:
4955 case LibFunc_powl:
4956 return Intrinsic::pow;
4957 case LibFunc_sqrt:
4958 case LibFunc_sqrtf:
4959 case LibFunc_sqrtl:
4960 return Intrinsic::sqrt;
4961 }
4962
4964}
4965
4966/// Given an exploded icmp instruction, return true if the comparison only
4967/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4968/// the result of the comparison is true when the input value is signed.
4970 bool &TrueIfSigned) {
4971 switch (Pred) {
4972 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4973 TrueIfSigned = true;
4974 return RHS.isZero();
4975 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4976 TrueIfSigned = true;
4977 return RHS.isAllOnes();
4978 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4979 TrueIfSigned = false;
4980 return RHS.isAllOnes();
4981 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4982 TrueIfSigned = false;
4983 return RHS.isZero();
4984 case ICmpInst::ICMP_UGT:
4985 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4986 TrueIfSigned = true;
4987 return RHS.isMaxSignedValue();
4988 case ICmpInst::ICMP_UGE:
4989 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4990 TrueIfSigned = true;
4991 return RHS.isMinSignedValue();
4992 case ICmpInst::ICMP_ULT:
4993 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4994 TrueIfSigned = false;
4995 return RHS.isMinSignedValue();
4996 case ICmpInst::ICMP_ULE:
4997 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4998 TrueIfSigned = false;
4999 return RHS.isMaxSignedValue();
5000 default:
5001 return false;
5002 }
5003}
5004
5006 bool CondIsTrue,
5007 const Instruction *CtxI,
5008 KnownFPClass &KnownFromContext,
5009 unsigned Depth = 0) {
5010 Value *A, *B;
5012 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5013 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5014 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5015 Depth + 1);
5016 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5017 Depth + 1);
5018 return;
5019 }
5021 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5022 Depth + 1);
5023 return;
5024 }
5025 CmpPredicate Pred;
5026 Value *LHS;
5027 uint64_t ClassVal = 0;
5028 const APFloat *CRHS;
5029 const APInt *RHS;
5030 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5031 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5032 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5033 LHS != V);
5034 if (CmpVal == V)
5035 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5037 m_Specific(V), m_ConstantInt(ClassVal)))) {
5038 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5039 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5040 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5041 m_APInt(RHS)))) {
5042 bool TrueIfSigned;
5043 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5044 return;
5045 if (TrueIfSigned == CondIsTrue)
5046 KnownFromContext.signBitMustBeOne();
5047 else
5048 KnownFromContext.signBitMustBeZero();
5049 }
5050}
5051
5052/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5053/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5054/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5055/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5056/// exponent range is [-149, -2], but the 0 edge case is above this range).
5057static std::tuple<int, int, int>
5059 if (!Q.CtxI || !Q.DC || !Q.DT)
5061
5062 // Intersect the bounds implied by every dominating condition, keeping the
5063 // tightest maximum. A value may participate in multiple compares
5064 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5065 int MaxExp = APFloat::IEK_Inf;
5066 int MaxExpNonZero = APFloat::IEK_Inf;
5067
5068 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5069 CmpPredicate Pred;
5070 const APFloat *LimitC;
5071 if (!match(BI->getCondition(),
5072 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5073 continue;
5074
5075 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5076 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5077 continue;
5078
5079 // If fabs(x) <= K, implies the exponent min exp range.
5080 // if fabs(x) >= K, swap the successor
5081 bool IsLessEqual =
5082 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5083 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5084 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5085
5086 bool KnownStrictlyLess =
5087 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5088 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5089
5090 BasicBlockEdge Edge1(BI->getParent(),
5091 BI->getSuccessor(IsLessEqual ? 0 : 1));
5092 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5093 // frexp returns an exponent one greater than ilogb.
5094 int Exp = ilogb(*LimitC) + 1;
5095
5096 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5097 // exponent drops by one when K is exact power of two.
5098 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5099 --Exp;
5100
5101 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5102 // may exclude.
5103
5104 // TODO: Figure out lower bound to detect no-underflow.
5105 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5106 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5107 }
5108 }
5109
5110 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5111}
5112
5114 const SimplifyQuery &Q) {
5115 KnownFPClass KnownFromContext;
5116
5117 if (Q.CC && Q.CC->AffectedValues.contains(V))
5119 KnownFromContext);
5120
5121 if (!Q.CtxI)
5122 return KnownFromContext;
5123
5124 if (Q.DC && Q.DT) {
5125 // Handle dominating conditions.
5126 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5127 Value *Cond = BI->getCondition();
5128
5129 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5130 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5131 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5132 KnownFromContext);
5133
5134 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5135 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5136 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5137 KnownFromContext);
5138 }
5139 }
5140
5141 if (!Q.AC)
5142 return KnownFromContext;
5143
5144 // Try to restrict the floating-point classes based on information from
5145 // assumptions.
5146 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5147 if (!AssumeVH)
5148 continue;
5149 CallInst *I = cast<CallInst>(AssumeVH);
5150
5151 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5152 "Got assumption for the wrong function!");
5153 assert(I->getIntrinsicID() == Intrinsic::assume &&
5154 "must be an assume intrinsic");
5155
5156 if (!isValidAssumeForContext(I, Q))
5157 continue;
5158
5159 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5160 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5161 }
5162
5163 return KnownFromContext;
5164}
5165
5167 Value *Arm, bool Invert,
5168 const SimplifyQuery &SQ,
5169 unsigned Depth) {
5170
5171 KnownFPClass KnownSrc;
5173 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5174 Depth + 1);
5175 KnownSrc = KnownSrc.unionWith(Known);
5176 if (KnownSrc.isUnknown())
5177 return;
5178
5179 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5180 Known = KnownSrc;
5181}
5182
5183void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5184 FPClassTest InterestedClasses, KnownFPClass &Known,
5185 const SimplifyQuery &Q, unsigned Depth);
5186
5188 FPClassTest InterestedClasses,
5189 const SimplifyQuery &Q, unsigned Depth) {
5190 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5191 APInt DemandedElts =
5192 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5193 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5194}
5195
5197 const APInt &DemandedElts,
5198 FPClassTest InterestedClasses,
5200 const SimplifyQuery &Q,
5201 unsigned Depth) {
5202 if ((InterestedClasses &
5204 return;
5205
5206 KnownFPClass KnownSrc;
5207 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5208 KnownSrc, Q, Depth + 1);
5209 Known = KnownFPClass::fptrunc(KnownSrc);
5210}
5211
5213 switch (IID) {
5214 case Intrinsic::minimum:
5216 case Intrinsic::maximum:
5218 case Intrinsic::minimumnum:
5220 case Intrinsic::maximumnum:
5222 case Intrinsic::minnum:
5224 case Intrinsic::maxnum:
5226 default:
5227 llvm_unreachable("not a floating-point min-max intrinsic");
5228 }
5229}
5230
5231/// \return true if this is a floating point value that is known to have a
5232/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5233static bool isAbsoluteValueULEOne(const Value *V) {
5234 // TODO: Handle frexp
5235 // TODO: Other rounding intrinsics?
5236 // TODO: Try computeKnownExponentRangeFromContext
5237
5238 // fabs(x - floor(x)) <= 1
5239 const Value *SubFloorX;
5240 if (match(V, m_FSub(m_Value(SubFloorX),
5242 return true;
5243
5246}
5247
5248void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5249 FPClassTest InterestedClasses, KnownFPClass &Known,
5250 const SimplifyQuery &Q, unsigned Depth) {
5251 assert(Known.isUnknown() && "should not be called with known information");
5252
5253 if (!DemandedElts) {
5254 // No demanded elts, better to assume we don't know anything.
5255 Known.resetAll();
5256 return;
5257 }
5258
5259 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5260
5261 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5262 Known = KnownFPClass(CFP->getValueAPF());
5263 return;
5264 }
5265
5267 Known.setKnownFPClasses(fcPosZero);
5268 Known.setSignBit(false);
5269 return;
5270 }
5271
5272 if (isa<PoisonValue>(V)) {
5273 Known.setKnownFPClasses(fcNone);
5274 Known.setSignBit(false);
5275 return;
5276 }
5277
5278 // Try to handle fixed width vector constants
5279 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5280 const Constant *CV = dyn_cast<Constant>(V);
5281 if (VFVTy && CV) {
5282 Known.setKnownFPClasses(fcNone);
5283 bool SignBitAllZero = true;
5284 bool SignBitAllOne = true;
5285
5286 // For vectors, verify that each element is not NaN.
5287 unsigned NumElts = VFVTy->getNumElements();
5288 for (unsigned i = 0; i != NumElts; ++i) {
5289 if (!DemandedElts[i])
5290 continue;
5291
5292 Constant *Elt = CV->getAggregateElement(i);
5293 if (!Elt) {
5294 Known = KnownFPClass();
5295 return;
5296 }
5297 if (isa<PoisonValue>(Elt))
5298 continue;
5299 auto *CElt = dyn_cast<ConstantFP>(Elt);
5300 if (!CElt) {
5301 Known = KnownFPClass();
5302 return;
5303 }
5304
5305 const APFloat &C = CElt->getValueAPF();
5306 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5307 if (C.isNegative())
5308 SignBitAllZero = false;
5309 else
5310 SignBitAllOne = false;
5311 }
5312 if (SignBitAllOne != SignBitAllZero)
5313 Known.setSignBit(SignBitAllOne);
5314 return;
5315 }
5316
5317 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5318 Known.setKnownFPClasses(fcNone);
5319 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5320 Known |= CDS->getElementAsAPFloat(I).classify();
5321 return;
5322 }
5323
5324 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5325 // TODO: Handle complex aggregates
5326 Known.setKnownFPClasses(fcNone);
5327 for (const Use &Op : CA->operands()) {
5328 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5329 if (!CFP) {
5330 Known = KnownFPClass();
5331 return;
5332 }
5333
5334 Known |= CFP->getValueAPF().classify();
5335 }
5336
5337 return;
5338 }
5339
5340 FPClassTest KnownNotFromFlags = fcNone;
5341 if (const auto *CB = dyn_cast<CallBase>(V))
5342 KnownNotFromFlags |= CB->getRetNoFPClass();
5343 else if (const auto *Arg = dyn_cast<Argument>(V))
5344 KnownNotFromFlags |= Arg->getNoFPClass();
5345
5346 const Operator *Op = dyn_cast<Operator>(V);
5348 if (FPOp->hasNoNaNs())
5349 KnownNotFromFlags |= fcNan;
5350 if (FPOp->hasNoInfs())
5351 KnownNotFromFlags |= fcInf;
5352 }
5353
5354 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5355 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5356
5357 // We no longer need to find out about these bits from inputs if we can
5358 // assume this from flags/attributes.
5359 InterestedClasses &= ~KnownNotFromFlags;
5360
5361 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5362 Known.knownNot(KnownNotFromFlags);
5363 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5364 if (*AssumedClasses.getSignBit())
5365 Known.signBitMustBeOne();
5366 else
5367 Known.signBitMustBeZero();
5368 }
5369 });
5370
5371 if (!Op)
5372 return;
5373
5374 // All recursive calls that increase depth must come after this.
5376 return;
5377
5378 const unsigned Opc = Op->getOpcode();
5379 switch (Opc) {
5380 case Instruction::FNeg: {
5381 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5382 Known, Q, Depth + 1);
5383 Known.fneg();
5384 break;
5385 }
5386 case Instruction::Select: {
5387 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5388 KnownFPClass Res;
5389 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5390 Depth + 1);
5391 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5392 Depth);
5393 return Res;
5394 };
5395 // Only known if known in both the LHS and RHS.
5396 Known =
5397 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5398 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5399 break;
5400 }
5401 case Instruction::Load: {
5402 const MDNode *NoFPClass =
5403 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5404 if (!NoFPClass)
5405 break;
5406
5407 ConstantInt *MaskVal =
5409 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5410 break;
5411 }
5412 case Instruction::Call: {
5413 const CallInst *II = cast<CallInst>(Op);
5414 const Intrinsic::ID IID = II->getIntrinsicID();
5415 switch (IID) {
5416 case Intrinsic::fabs: {
5417 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5418 // If we only care about the sign bit we don't need to inspect the
5419 // operand.
5420 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5421 InterestedClasses, Known, Q, Depth + 1);
5422 }
5423
5424 Known.fabs();
5425 break;
5426 }
5427 case Intrinsic::copysign: {
5428 KnownFPClass KnownSign;
5429
5430 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5431 Known, Q, Depth + 1);
5432 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5433 KnownSign, Q, Depth + 1);
5434 Known.copysign(KnownSign);
5435 break;
5436 }
5437 case Intrinsic::fma:
5438 case Intrinsic::fmuladd: {
5439 if ((InterestedClasses & fcNegative) == fcNone)
5440 break;
5441
5442 // FIXME: This should check isGuaranteedNotToBeUndef
5443 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5444 KnownFPClass KnownSrc, KnownAddend;
5445 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5446 InterestedClasses, KnownAddend, Q, Depth + 1);
5447 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5448 InterestedClasses, KnownSrc, Q, Depth + 1);
5449
5450 const Function *F = II->getFunction();
5451 const fltSemantics &FltSem =
5452 II->getType()->getScalarType()->getFltSemantics();
5454 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5455
5456 if (KnownNotFromFlags & fcNan) {
5457 KnownSrc.knownNot(fcNan);
5458 KnownAddend.knownNot(fcNan);
5459 }
5460
5461 if (KnownNotFromFlags & fcInf) {
5462 KnownSrc.knownNot(fcInf);
5463 KnownAddend.knownNot(fcInf);
5464 }
5465
5466 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5467 break;
5468 }
5469
5470 KnownFPClass KnownSrc[3];
5471 for (int I = 0; I != 3; ++I) {
5472 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5473 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5474 if (KnownSrc[I].isUnknown())
5475 return;
5476
5477 if (KnownNotFromFlags & fcNan)
5478 KnownSrc[I].knownNot(fcNan);
5479 if (KnownNotFromFlags & fcInf)
5480 KnownSrc[I].knownNot(fcInf);
5481 }
5482
5483 const Function *F = II->getFunction();
5484 const fltSemantics &FltSem =
5485 II->getType()->getScalarType()->getFltSemantics();
5487 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5488 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5489 break;
5490 }
5491 case Intrinsic::sqrt:
5492 case Intrinsic::experimental_constrained_sqrt: {
5493 KnownFPClass KnownSrc;
5494 FPClassTest InterestedSrcs = InterestedClasses;
5495 if (InterestedClasses & fcNan)
5496 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5497
5498 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5499 KnownSrc, Q, Depth + 1);
5500
5502
5503 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5504 if (!HasNSZ) {
5505 const Function *F = II->getFunction();
5506 const fltSemantics &FltSem =
5507 II->getType()->getScalarType()->getFltSemantics();
5508 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5509 }
5510
5511 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5512 if (HasNSZ)
5513 Known.knownNot(fcNegZero);
5514
5515 break;
5516 }
5517 case Intrinsic::sin: {
5518 KnownFPClass KnownSrc;
5519 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5520 KnownSrc, Q, Depth + 1);
5521 Known = KnownFPClass::sin(KnownSrc);
5522 break;
5523 }
5524 case Intrinsic::cos: {
5525 KnownFPClass KnownSrc;
5526 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5527 KnownSrc, Q, Depth + 1);
5528 Known = KnownFPClass::cos(KnownSrc);
5529 break;
5530 }
5531 case Intrinsic::tan: {
5532 KnownFPClass KnownSrc;
5533 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5534 KnownSrc, Q, Depth + 1);
5535 Known = KnownFPClass::tan(KnownSrc);
5536 break;
5537 }
5538 case Intrinsic::sinh: {
5539 KnownFPClass KnownSrc;
5540 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5541 KnownSrc, Q, Depth + 1);
5542 Known = KnownFPClass::sinh(KnownSrc);
5543 break;
5544 }
5545 case Intrinsic::cosh: {
5546 KnownFPClass KnownSrc;
5547 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5548 KnownSrc, Q, Depth + 1);
5549 Known = KnownFPClass::cosh(KnownSrc);
5550 break;
5551 }
5552 case Intrinsic::tanh: {
5553 KnownFPClass KnownSrc;
5554 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5555 KnownSrc, Q, Depth + 1);
5556 Known = KnownFPClass::tanh(KnownSrc);
5557 break;
5558 }
5559 case Intrinsic::asin: {
5560 KnownFPClass KnownSrc;
5561 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5562 KnownSrc, Q, Depth + 1);
5563 Known = KnownFPClass::asin(KnownSrc);
5564 break;
5565 }
5566 case Intrinsic::acos: {
5567 KnownFPClass KnownSrc;
5568 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5569 KnownSrc, Q, Depth + 1);
5570 Known = KnownFPClass::acos(KnownSrc);
5571 break;
5572 }
5573 case Intrinsic::atan: {
5574 KnownFPClass KnownSrc;
5575 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5576 KnownSrc, Q, Depth + 1);
5577 Known = KnownFPClass::atan(KnownSrc);
5578 break;
5579 }
5580 case Intrinsic::atan2: {
5581 FPClassTest InterestedY = InterestedClasses;
5582 FPClassTest InterestedX = InterestedClasses;
5583
5584 // We can rule out negative values if y cannot have a negative value.
5585 if ((InterestedClasses & fcNegFinite) != fcNone)
5586 InterestedY |= fcNegative;
5587
5588 // We can rule out positive values if y cannot have a positive value.
5589 if ((InterestedClasses & fcPosFinite) != fcNone)
5590 InterestedY |= fcPositive | fcNegSubnormal;
5591
5592 // We can rule out zero and subnormal if x cannot have a positive value.
5593 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5594 InterestedX |= fcPositive | fcNegSubnormal;
5595
5596 KnownFPClass KnownY, KnownX;
5597 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5598 KnownY, Q, Depth + 1);
5599 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5600 KnownX, Q, Depth + 1);
5601
5602 const Function *F = II->getFunction();
5604 F ? F->getDenormalMode(
5605 II->getType()->getScalarType()->getFltSemantics())
5607 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5608 break;
5609 }
5610 case Intrinsic::maxnum:
5611 case Intrinsic::minnum:
5612 case Intrinsic::minimum:
5613 case Intrinsic::maximum:
5614 case Intrinsic::minimumnum:
5615 case Intrinsic::maximumnum: {
5616 KnownFPClass KnownLHS, KnownRHS;
5617 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5618 KnownLHS, Q, Depth + 1);
5619 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5620 KnownRHS, Q, Depth + 1);
5621
5622 const Function *F = II->getFunction();
5623
5625 F ? F->getDenormalMode(
5626 II->getType()->getScalarType()->getFltSemantics())
5628
5629 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5630 Mode);
5631 break;
5632 }
5633 case Intrinsic::canonicalize: {
5634 KnownFPClass KnownSrc;
5635 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5636 KnownSrc, Q, Depth + 1);
5637
5638 const Function *F = II->getFunction();
5639 DenormalMode DenormMode =
5640 F ? F->getDenormalMode(
5641 II->getType()->getScalarType()->getFltSemantics())
5643 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5644 break;
5645 }
5646 case Intrinsic::vector_reduce_fmax:
5647 case Intrinsic::vector_reduce_fmin:
5648 case Intrinsic::vector_reduce_fmaximum:
5649 case Intrinsic::vector_reduce_fminimum:
5650 case Intrinsic::vector_reduce_fmaximumnum:
5651 case Intrinsic::vector_reduce_fminimumnum: {
5652 // reduce min/max will choose an element from one of the vector elements,
5653 // so we can infer and class information that is common to all elements.
5654 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5655 InterestedClasses, Q, Depth + 1);
5656 // Can only propagate sign if output is never NaN.
5657 if (!Known.isKnownNeverNaN())
5658 Known.setSignBit(std::nullopt);
5659 break;
5660 }
5661 // reverse preserves all characteristics of the input vec's element.
5662 case Intrinsic::vector_reverse:
5664 II->getArgOperand(0), DemandedElts.reverseBits(),
5665 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5666 break;
5667 case Intrinsic::trunc:
5668 case Intrinsic::floor:
5669 case Intrinsic::ceil:
5670 case Intrinsic::rint:
5671 case Intrinsic::nearbyint:
5672 case Intrinsic::round:
5673 case Intrinsic::roundeven: {
5674 KnownFPClass KnownSrc;
5675 FPClassTest InterestedSrcs = InterestedClasses;
5676
5677 // Negative round ups towards zero produce negative zero.
5678 if (InterestedSrcs & fcNegFinite)
5679 InterestedSrcs |= fcNegFinite;
5680
5681 // Negative subnormals may flush to positive zero.
5682 if (InterestedSrcs & fcPosFinite)
5683 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
5684
5685 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5686 KnownSrc, Q, Depth + 1);
5687
5688 const Function *F = II->getFunction();
5690 F ? F->getDenormalMode(
5691 II->getType()->getScalarType()->getFltSemantics())
5693 const bool IsMultiUnitFPType =
5694 V->getType()->getScalarType()->isMultiUnitFPType();
5695
5696 switch (IID) {
5697 case Intrinsic::trunc:
5698 Known = KnownFPClass::trunc(KnownSrc, Mode);
5699 break;
5700 case Intrinsic::floor:
5701 Known = KnownFPClass::floor(KnownSrc, IsMultiUnitFPType, Mode);
5702 break;
5703 case Intrinsic::ceil:
5704 Known = KnownFPClass::ceil(KnownSrc, IsMultiUnitFPType, Mode);
5705 break;
5706 default:
5707 Known =
5708 KnownFPClass::roundToIntegral(KnownSrc, IsMultiUnitFPType, Mode);
5709 break;
5710 }
5711 break;
5712 }
5713 case Intrinsic::exp:
5714 case Intrinsic::exp2:
5715 case Intrinsic::exp10:
5716 case Intrinsic::amdgcn_exp2: {
5717 KnownFPClass KnownSrc;
5718 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5719 KnownSrc, Q, Depth + 1);
5720
5721 Known = KnownFPClass::exp(KnownSrc);
5722
5723 Type *EltTy = II->getType()->getScalarType();
5724 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5725 Known.knownNot(fcSubnormal);
5726
5727 break;
5728 }
5729 case Intrinsic::fptrunc_round: {
5730 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5731 Q, Depth);
5732 break;
5733 }
5734 case Intrinsic::log:
5735 case Intrinsic::log10:
5736 case Intrinsic::log2:
5737 case Intrinsic::experimental_constrained_log:
5738 case Intrinsic::experimental_constrained_log10:
5739 case Intrinsic::experimental_constrained_log2:
5740 case Intrinsic::amdgcn_log: {
5741 FPClassTest InterestedSrcs = fcNone;
5742
5743 // log(negative) produces NaN.
5744 if ((InterestedClasses & fcNan) != fcNone)
5745 InterestedSrcs |= fcNan | fcNegative;
5746
5747 // log(logical-zero) produces negative infinity.
5748 if ((InterestedClasses & fcNegInf) != fcNone)
5749 InterestedSrcs |= fcZero | fcSubnormal;
5750
5751 // log(x) < -0.0 if x < +1.0
5752 if ((InterestedClasses & fcNegNormal) != fcNone)
5753 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5754
5755 // log(x) >= +0.0 if x >= +1.0
5756 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5757 InterestedSrcs |= fcPosNormal;
5758
5759 // log(x) is positive infinity iff x is positive infinity.
5760 if ((InterestedClasses & fcPosInf) != fcNone)
5761 InterestedSrcs |= fcPosInf;
5762
5763 KnownFPClass KnownSrc;
5764 if (InterestedSrcs != fcNone)
5765 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5766 KnownSrc, Q, Depth + 1);
5767 const Function *F = II->getFunction();
5769 F ? F->getDenormalMode(
5770 II->getType()->getScalarType()->getFltSemantics())
5772 const bool IsMultiUnitFPType =
5773 V->getType()->getScalarType()->isMultiUnitFPType();
5774 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
5775 break;
5776 }
5777 case Intrinsic::pow: {
5778 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5779 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5780 if (!WantNaN && !WantNegative)
5781 break;
5782
5783 FPClassTest InterestedLHS = fcNone;
5784 FPClassTest InterestedRHS = fcNone;
5785 if (WantNaN) {
5786 // pow may return NaN if one of the arguments is NaN. NaN may also be
5787 // produced from a negative, non-zero finite base and a non-integer
5788 // exponent.
5789 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5790 InterestedRHS |= fcNan;
5791 }
5792 if (WantNegative) {
5793 // A negative value is returned when a negative base is raised to an odd
5794 // integer power. Only normal values can be odd integers.
5795 InterestedLHS |= fcNegative;
5796 InterestedRHS |= fcNormal;
5797 }
5798
5799 KnownFPClass KnownLHS;
5800 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5801 KnownLHS, Q, Depth + 1);
5802
5803 // If the LHS is unknown, then querying the RHS is only useful for rare
5804 // edge cases.
5805 if (KnownLHS.isUnknown())
5806 break;
5807
5808 KnownFPClass KnownRHS;
5809 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5810 KnownRHS, Q, Depth + 1);
5811 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5812 break;
5813 }
5814 case Intrinsic::powi: {
5815 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5816 break;
5817
5818 // The exponent is always a scalar, even when raising a vector to a power.
5819 const Value *Exp = II->getArgOperand(1);
5820 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5821 KnownBits ExponentKnownBits(BitWidth);
5822 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5823
5824 FPClassTest InterestedSrcs = fcNone;
5825 if (InterestedClasses & fcNan)
5826 InterestedSrcs |= fcNan;
5827 if (!ExponentKnownBits.isZero()) {
5828 if (InterestedClasses & fcInf)
5829 InterestedSrcs |= fcFinite | fcInf;
5830 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5831 InterestedSrcs |= fcNegative;
5832 }
5833
5834 KnownFPClass KnownSrc;
5835 if (InterestedSrcs != fcNone)
5836 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5837 KnownSrc, Q, Depth + 1);
5838
5839 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5840 break;
5841 }
5842 case Intrinsic::ldexp: {
5843 KnownFPClass KnownSrc;
5844 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5845 KnownSrc, Q, Depth + 1);
5846 // Can refine inf/zero handling based on the exponent operand.
5847 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5848
5849 const Value *ExpArg = II->getArgOperand(1);
5850 ConstantRange ExpKnownRange =
5851 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5852 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5853 : ConstantRange::getFull(
5854 ExpArg->getType()->getScalarSizeInBits());
5855
5856 const fltSemantics &Flt =
5857 II->getType()->getScalarType()->getFltSemantics();
5858
5859 const Function *F = II->getFunction();
5861 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5862
5863 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5864 ExpKnownRange.getSignedMax(), Flt, Mode);
5865 break;
5866 }
5867 case Intrinsic::arithmetic_fence: {
5868 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5869 Known, Q, Depth + 1);
5870 break;
5871 }
5872 case Intrinsic::experimental_constrained_sitofp:
5873 case Intrinsic::experimental_constrained_uitofp:
5874 // Cannot produce nan
5875 Known.knownNot(fcNan);
5876
5877 // sitofp and uitofp turn into +0.0 for zero.
5878 Known.knownNot(fcNegZero);
5879
5880 // Integers cannot be subnormal
5881 Known.knownNot(fcSubnormal);
5882
5883 if (IID == Intrinsic::experimental_constrained_uitofp)
5884 Known.signBitMustBeZero();
5885
5886 // TODO: Copy inf handling from instructions
5887 break;
5888
5889 case Intrinsic::amdgcn_fract: {
5890 Known.knownNot(fcInf);
5891
5892 if (InterestedClasses & fcNan) {
5893 KnownFPClass KnownSrc;
5894 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5895 InterestedClasses, KnownSrc, Q, Depth + 1);
5896
5897 if (KnownSrc.isKnownNeverInfOrNaN())
5898 Known.knownNot(fcNan);
5899 else if (KnownSrc.isKnownNever(fcSNan))
5900 Known.knownNot(fcSNan);
5901 }
5902
5903 break;
5904 }
5905 case Intrinsic::amdgcn_rcp: {
5906 KnownFPClass KnownSrc;
5907 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5908 KnownSrc, Q, Depth + 1);
5909
5910 Known.propagateNonNaN(KnownSrc);
5911
5912 Type *EltTy = II->getType()->getScalarType();
5913
5914 // f32 denormal always flushed.
5915 if (EltTy->isFloatTy()) {
5916 Known.knownNot(fcSubnormal);
5917 KnownSrc.knownNot(fcSubnormal);
5918 }
5919
5920 if (KnownSrc.isKnownNever(fcNegative))
5921 Known.knownNot(fcNegative);
5922 if (KnownSrc.isKnownNever(fcPositive))
5923 Known.knownNot(fcPositive);
5924
5925 if (const Function *F = II->getFunction()) {
5926 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5927 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5928 Known.knownNot(fcPosInf);
5929 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5930 Known.knownNot(fcNegInf);
5931 }
5932
5933 break;
5934 }
5935 case Intrinsic::amdgcn_rsq: {
5936 KnownFPClass KnownSrc;
5937 // The only negative value that can be returned is -inf for -0 inputs.
5939
5940 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5941 KnownSrc, Q, Depth + 1);
5942
5943 // Negative -> nan
5944 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5945 Known.knownNot(fcNan);
5946 else if (KnownSrc.isKnownNever(fcSNan))
5947 Known.knownNot(fcSNan);
5948
5949 // +inf -> +0
5950 if (KnownSrc.isKnownNeverPosInfinity())
5951 Known.knownNot(fcPosZero);
5952
5953 Type *EltTy = II->getType()->getScalarType();
5954
5955 // f32 denormal always flushed.
5956 if (EltTy->isFloatTy())
5957 Known.knownNot(fcPosSubnormal);
5958
5959 if (const Function *F = II->getFunction()) {
5960 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5961
5962 // -0 -> -inf
5963 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5964 Known.knownNot(fcNegInf);
5965
5966 // +0 -> +inf
5967 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5968 Known.knownNot(fcPosInf);
5969 }
5970
5971 break;
5972 }
5973 case Intrinsic::amdgcn_trig_preop: {
5974 // Always returns a value [0, 1)
5975 Known.knownNot(fcNan | fcInf | fcNegative);
5976 break;
5977 }
5978 case Intrinsic::convert_from_arbitrary_fp: {
5979 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5980 StringRef FormatStr = cast<MDString>(MD)->getString();
5981
5982 const fltSemantics *SrcSemantics =
5984 if (!SrcSemantics)
5985 break;
5986
5987 const fltSemantics DstSemantics =
5988 II->getType()->getScalarType()->getFltSemantics();
5989
5990 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5991 Known.knownNot(fcNan);
5992
5993 // fcInf can only be cleared if the source format has no Inf encoding
5994 // and the dst max exp can accommodate src max exp.
5995 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5996 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5997 APFloat::semanticsMaxExponent(DstSemantics))
5998 Known.knownNot(fcInf);
5999
6000 // Check and clear all neg flags for formats that do not have signed
6001 // representation.
6002 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
6003 Known.knownNot(fcNegative);
6004
6005 // Check if format has no zero at all (Float8E8M0FNU), or no negative
6006 // zero.
6007 if (!APFloat::semanticsHasZero(*SrcSemantics))
6008 Known.knownNot(fcZero);
6009 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
6010 Known.knownNot(fcNegZero);
6011
6012 // If src lands normally in dest, the result can never be subnormal.
6013 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6014 Known.knownNot(fcSubnormal);
6015 break;
6016 }
6017 default:
6018 break;
6019 }
6020
6021 break;
6022 }
6023 case Instruction::FAdd:
6024 case Instruction::FSub: {
6025 KnownFPClass KnownLHS, KnownRHS;
6026 bool WantNegative =
6027 Op->getOpcode() == Instruction::FAdd &&
6028 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6029 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6030 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6031
6032 if (!WantNaN && !WantNegative && !WantNegZero)
6033 break;
6034
6035 FPClassTest InterestedSrcs = InterestedClasses;
6036 if (WantNegative)
6037 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6038 if (InterestedClasses & fcNan)
6039 InterestedSrcs |= fcInf;
6040 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6041 KnownRHS, Q, Depth + 1);
6042
6043 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6044 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6045 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6046 Depth + 1);
6047 if (Self)
6048 KnownLHS = KnownRHS;
6049
6050 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6051 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6052 WantNegZero || Opc == Instruction::FSub) {
6053
6054 // FIXME: Context function should always be passed in separately
6055 const Function *F = cast<Instruction>(Op)->getFunction();
6056 const fltSemantics &FltSem =
6057 Op->getType()->getScalarType()->getFltSemantics();
6059 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6060
6061 if (Self && Opc == Instruction::FAdd) {
6062 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6063 } else {
6064 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6065 // there's no point.
6066
6067 if (!Self) {
6068 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6069 KnownLHS, Q, Depth + 1);
6070 }
6071
6072 Known = Opc == Instruction::FAdd
6073 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6074 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6075 }
6076 }
6077
6078 break;
6079 }
6080 case Instruction::FMul: {
6081 const Function *F = cast<Instruction>(Op)->getFunction();
6083 F ? F->getDenormalMode(
6084 Op->getType()->getScalarType()->getFltSemantics())
6086
6087 Value *LHS = Op->getOperand(0);
6088 Value *RHS = Op->getOperand(1);
6089 // X * X is always non-negative or a NaN.
6090 // FIXME: Should check isGuaranteedNotToBeUndef
6091 if (LHS == RHS) {
6092 KnownFPClass KnownSrc;
6093 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6094 Depth + 1);
6095 Known = KnownFPClass::square(KnownSrc, Mode);
6096 break;
6097 }
6098
6099 KnownFPClass KnownLHS, KnownRHS;
6100
6101 const APFloat *CRHS;
6102 if (match(RHS, m_APFloat(CRHS))) {
6103 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6104 Depth + 1);
6105 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6106 } else {
6107 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6108 Depth + 1);
6109 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6110 // additional not-nan if the addend is known-not negative infinity if the
6111 // multiply is known-not infinity.
6112
6113 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6114 Depth + 1);
6115 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6116 }
6117
6118 /// Propgate no-infs if the other source is known smaller than one, such
6119 /// that this cannot introduce overflow.
6120 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6121 Known.knownNot(fcInf);
6122 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6123 Known.knownNot(fcInf);
6124
6125 break;
6126 }
6127 case Instruction::FDiv: {
6128 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6129
6130 const Function *F = cast<Instruction>(Op)->getFunction();
6131 const fltSemantics &FltSem =
6132 Op->getType()->getScalarType()->getFltSemantics();
6134 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6135
6136 if (Op->getOperand(0) == Op->getOperand(1) &&
6137 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6138 // X / X is always exactly 1.0 or a NaN.
6139 Known.setKnownFPClasses(fcNan | fcPosNormal);
6140
6141 if (!WantNan)
6142 break;
6143
6144 KnownFPClass KnownSrc;
6145 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6146 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6147 Depth + 1);
6148
6149 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6150 break;
6151 }
6152
6153 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6154 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6155 if (!WantNan && !WantNegative && !WantPositive)
6156 break;
6157
6158 KnownFPClass KnownLHS, KnownRHS;
6159 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6160 Q, Depth + 1);
6161
6162 bool KnowSomethingUseful =
6163 KnownRHS.isKnownNeverNaN() ||
6166
6167 if (KnowSomethingUseful)
6168 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6169 Q, Depth + 1);
6170
6171 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6172 break;
6173 }
6174 case Instruction::FRem: {
6175 FPClassTest InterestedLHS = fcNone;
6176 FPClassTest InterestedRHS = fcNone;
6177
6178 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6179 if (InterestedClasses & fcNan) {
6180 InterestedLHS |= fcNan | fcInf;
6181 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6182 }
6183
6184 // The sign for frem is the same as the first operand.
6185 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6186 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6187 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6188 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6189
6190 // A negative zero result requires a negative finite first operand.
6191 if (InterestedClasses & fcNegZero)
6192 InterestedLHS |= fcNegFinite;
6193
6194 // A positive zero result can additionally come from a negative finite
6195 // result being flushed to positive zero.
6196 if (InterestedClasses & fcPosZero)
6197 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6198
6199 const Function *F = cast<Instruction>(Op)->getFunction();
6201 F ? F->getDenormalMode(
6202 Op->getType()->getScalarType()->getFltSemantics())
6204
6205 if (Op->getOperand(0) == Op->getOperand(1) &&
6206 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6207 // X % X is always exactly [+-]0.0 or a NaN.
6208 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6209 KnownFPClass KnownSrc;
6210 if (InterestedSrcs != fcNone)
6211 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6212 KnownSrc, Q, Depth + 1);
6213 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6214 break;
6215 }
6216
6217 KnownFPClass KnownLHS;
6218 if (InterestedLHS != fcNone)
6219 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6220 KnownLHS, Q, Depth + 1);
6221
6222 KnownFPClass KnownRHS;
6223 // RHS is only useful for refining NaN classes.
6224 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6225 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6226 KnownRHS, Q, Depth + 1);
6227
6228 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6229
6230 break;
6231 }
6232 case Instruction::FPExt: {
6233 KnownFPClass KnownSrc;
6234 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6235 KnownSrc, Q, Depth + 1);
6236
6237 const fltSemantics &DstTy =
6238 Op->getType()->getScalarType()->getFltSemantics();
6239 const fltSemantics &SrcTy =
6240 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6241
6242 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6243 break;
6244 }
6245 case Instruction::FPTrunc: {
6246 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6247 Depth);
6248 break;
6249 }
6250 case Instruction::SIToFP:
6251 case Instruction::UIToFP: {
6252 // Cannot produce nan
6253 Known.knownNot(fcNan);
6254
6255 // Integers cannot be subnormal
6256 Known.knownNot(fcSubnormal);
6257
6258 // sitofp and uitofp turn into +0.0 for zero.
6259 Known.knownNot(fcNegZero);
6260
6261 // UIToFP is always non-negative regardless of known bits.
6262 if (Op->getOpcode() == Instruction::UIToFP)
6263 Known.signBitMustBeZero();
6264
6265 // Only compute known bits if we can learn something useful from them.
6266 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6267 break;
6268
6269 KnownBits IntKnown =
6270 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6271
6272 // If the integer is non-zero, the result cannot be +0.0
6273 if (IntKnown.isNonZero())
6274 Known.knownNot(fcPosZero);
6275
6276 if (Op->getOpcode() == Instruction::SIToFP) {
6277 // If the signed integer is known non-negative, the result is
6278 // non-negative. If the signed integer is known negative, the result is
6279 // negative.
6280 if (IntKnown.isNonNegative()) {
6281 Known.signBitMustBeZero();
6282 } else if (IntKnown.isNegative()) {
6283 Known.signBitMustBeOne();
6284 }
6285 }
6286
6287 // Guard kept for ilogb()
6288 if (InterestedClasses & fcInf) {
6289 // Get width of largest magnitude integer known.
6290 // This still works for a signed minimum value because the largest FP
6291 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6292 int IntSize = IntKnown.getBitWidth();
6293 if (Op->getOpcode() == Instruction::UIToFP)
6294 IntSize -= IntKnown.countMinLeadingZeros();
6295 else if (Op->getOpcode() == Instruction::SIToFP)
6296 IntSize -= IntKnown.countMinSignBits();
6297
6298 // If the exponent of the largest finite FP value can hold the largest
6299 // integer, the result of the cast must be finite.
6300 Type *FPTy = Op->getType()->getScalarType();
6301 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6302 Known.knownNot(fcInf);
6303 }
6304
6305 break;
6306 }
6307 case Instruction::ExtractElement: {
6308 // Look through extract element. If the index is non-constant or
6309 // out-of-range demand all elements, otherwise just the extracted element.
6310 const Value *Vec = Op->getOperand(0);
6311
6312 APInt DemandedVecElts;
6313 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6314 unsigned NumElts = VecTy->getNumElements();
6315 DemandedVecElts = APInt::getAllOnes(NumElts);
6316 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6317 if (CIdx && CIdx->getValue().ult(NumElts))
6318 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6319 } else {
6320 DemandedVecElts = APInt(1, 1);
6321 }
6322
6323 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6324 Q, Depth + 1);
6325 }
6326 case Instruction::InsertElement: {
6327 if (isa<ScalableVectorType>(Op->getType()))
6328 return;
6329
6330 const Value *Vec = Op->getOperand(0);
6331 const Value *Elt = Op->getOperand(1);
6332 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6333 unsigned NumElts = DemandedElts.getBitWidth();
6334 APInt DemandedVecElts = DemandedElts;
6335 bool NeedsElt = true;
6336 // If we know the index we are inserting to, clear it from Vec check.
6337 if (CIdx && CIdx->getValue().ult(NumElts)) {
6338 DemandedVecElts.clearBit(CIdx->getZExtValue());
6339 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6340 }
6341
6342 // Do we demand the inserted element?
6343 if (NeedsElt) {
6344 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6345 // If we don't know any bits, early out.
6346 if (Known.isUnknown())
6347 break;
6348 } else {
6349 Known.setKnownFPClasses(fcNone);
6350 }
6351
6352 // Do we need anymore elements from Vec?
6353 if (!DemandedVecElts.isZero()) {
6354 KnownFPClass Known2;
6355 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6356 Depth + 1);
6357 Known |= Known2;
6358 }
6359
6360 break;
6361 }
6362 case Instruction::ShuffleVector: {
6363 // Handle vector splat idiom
6364 if (Value *Splat = getSplatValue(V)) {
6365 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6366 break;
6367 }
6368
6369 // For undef elements, we don't know anything about the common state of
6370 // the shuffle result.
6371 APInt DemandedLHS, DemandedRHS;
6372 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6373 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6374 return;
6375
6376 if (!!DemandedLHS) {
6377 const Value *LHS = Shuf->getOperand(0);
6378 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6379 Depth + 1);
6380
6381 // If we don't know any bits, early out.
6382 if (Known.isUnknown())
6383 break;
6384 } else {
6385 Known.setKnownFPClasses(fcNone);
6386 }
6387
6388 if (!!DemandedRHS) {
6389 KnownFPClass Known2;
6390 const Value *RHS = Shuf->getOperand(1);
6391 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6392 Depth + 1);
6393 Known |= Known2;
6394 }
6395
6396 break;
6397 }
6398 case Instruction::ExtractValue: {
6399 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6400 ArrayRef<unsigned> Indices = Extract->getIndices();
6401 const Value *Src = Extract->getAggregateOperand();
6402 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6403 Indices[0] == 0) {
6404 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6405 switch (II->getIntrinsicID()) {
6406 case Intrinsic::frexp: {
6407 FPClassTest InterestedSrcs = InterestedClasses;
6408
6409 // Positive subnormals and negative subnormals could become positive
6410 // zero.
6411 if (InterestedClasses & fcPosZero)
6412 InterestedSrcs |= fcSubnormal;
6413
6414 // Negative subnormals could become negative zero.
6415 if (InterestedClasses & fcNegZero)
6416 InterestedSrcs |= fcNegSubnormal;
6417
6418 if (InterestedClasses & fcPosNormal)
6419 InterestedSrcs |= fcPosSubnormal;
6420
6421 if (InterestedClasses & fcNegNormal)
6422 InterestedSrcs |= fcNegSubnormal;
6423
6424 KnownFPClass KnownSrc;
6425 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6426 InterestedSrcs, KnownSrc, Q, Depth + 1);
6427
6428 const Function *F = cast<Instruction>(Op)->getFunction();
6429 const fltSemantics &FltSem =
6430 Op->getType()->getScalarType()->getFltSemantics();
6431
6433 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6434 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6435 return;
6436 }
6437 default:
6438 break;
6439 }
6440 }
6441 }
6442
6443 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6444 Depth + 1);
6445 break;
6446 }
6447 case Instruction::PHI: {
6448 const PHINode *P = cast<PHINode>(Op);
6449 // Unreachable blocks may have zero-operand PHI nodes.
6450 if (P->getNumIncomingValues() == 0)
6451 break;
6452
6453 // Otherwise take the unions of the known bit sets of the operands,
6454 // taking conservative care to avoid excessive recursion.
6455 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6456
6457 if (Depth < PhiRecursionLimit) {
6458 // Skip if every incoming value references to ourself.
6459 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6460 break;
6461
6462 bool First = true;
6463
6464 for (const Use &U : P->operands()) {
6465 Value *IncValue;
6466 Instruction *CtxI;
6467 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6468 // Skip direct self references.
6469 if (IncValue == P)
6470 continue;
6471
6472 KnownFPClass KnownSrc;
6473 // Recurse, but cap the recursion to two levels, because we don't want
6474 // to waste time spinning around in loops. We need at least depth 2 to
6475 // detect known sign bits.
6476 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6478 PhiRecursionLimit);
6479
6480 if (First) {
6481 Known = KnownSrc;
6482 First = false;
6483 } else {
6484 Known |= KnownSrc;
6485 }
6486
6487 if (Known.getKnownFPClasses() == fcAllFlags)
6488 break;
6489 }
6490 }
6491
6492 // Look for the case of a for loop which has a positive
6493 // initial value and is incremented by a squared value.
6494 // This will propagate sign information out of such loops.
6495 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6496 break;
6497 for (unsigned I = 0; I < 2; I++) {
6498 Value *RecurValue = P->getIncomingValue(1 - I);
6500 if (!II)
6501 continue;
6502 Value *R, *L, *Init;
6503 PHINode *PN;
6505 PN == P) {
6506 switch (II->getIntrinsicID()) {
6507 case Intrinsic::fma:
6508 case Intrinsic::fmuladd: {
6509 KnownFPClass KnownStart;
6510 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6511 Q, Depth + 1);
6512 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6513 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6515 break;
6516 }
6517 }
6518 }
6519 }
6520 break;
6521 }
6522 case Instruction::BitCast: {
6523 const Value *Src;
6524 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6525 !Src->getType()->isIntOrIntVectorTy())
6526 break;
6527
6528 const Type *Ty = Op->getType();
6529
6530 Value *CastLHS, *CastRHS;
6531
6532 // Match bitcast(umax(bitcast(a), bitcast(b)))
6533 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6534 m_BitCast(m_Value(CastRHS)))) &&
6535 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6536 KnownFPClass KnownLHS, KnownRHS;
6537 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6538 Depth + 1);
6539 if (!KnownRHS.isUnknown()) {
6540 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6541 Q, Depth + 1);
6542 Known = KnownLHS | KnownRHS;
6543 }
6544
6545 return;
6546 }
6547
6548 const Type *EltTy = Ty->getScalarType();
6549 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6550 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6551
6553 break;
6554 }
6555 default:
6556 break;
6557 }
6558}
6559
6561 const APInt &DemandedElts,
6562 FPClassTest InterestedClasses,
6563 const SimplifyQuery &SQ,
6564 unsigned Depth) {
6565 KnownFPClass KnownClasses;
6566 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6567 Depth);
6568 return KnownClasses;
6569}
6570
6572 FPClassTest InterestedClasses,
6573 const SimplifyQuery &SQ,
6574 unsigned Depth) {
6576 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6577 return Known;
6578}
6579
6581 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6582 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6583 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6584 return computeKnownFPClass(V, InterestedClasses,
6585 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6586 Depth);
6587}
6588
6590llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6591 FastMathFlags FMF, FPClassTest InterestedClasses,
6592 const SimplifyQuery &SQ, unsigned Depth) {
6593 if (FMF.noNaNs())
6594 InterestedClasses &= ~fcNan;
6595 if (FMF.noInfs())
6596 InterestedClasses &= ~fcInf;
6597
6598 KnownFPClass Result =
6599 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6600
6601 if (FMF.noNaNs())
6602 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6603 if (FMF.noInfs())
6604 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6605 return Result;
6606}
6607
6609 FPClassTest InterestedClasses,
6610 const SimplifyQuery &SQ,
6611 unsigned Depth) {
6612 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6613 APInt DemandedElts =
6614 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6615 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6616 Depth);
6617}
6618
6620 unsigned Depth) {
6622 return Known.isKnownNeverNegZero();
6623}
6624
6626 unsigned Depth) {
6629 return Known.cannotBeOrderedLessThanZero();
6630}
6631
6633 unsigned Depth) {
6635 return Known.isKnownNeverInfinity();
6636}
6637
6638/// Return true if the floating-point value can never contain a NaN or infinity.
6640 unsigned Depth) {
6642 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6643}
6644
6645/// Return true if the floating-point scalar value is not a NaN or if the
6646/// floating-point vector value has no NaN elements. Return false if a value
6647/// could ever be NaN.
6649 unsigned Depth) {
6651 return Known.isKnownNeverNaN();
6652}
6653
6654/// Return false if we can prove that the specified FP value's sign bit is 0.
6655/// Return true if we can prove that the specified FP value's sign bit is 1.
6656/// Otherwise return std::nullopt.
6657std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6658 const SimplifyQuery &SQ,
6659 unsigned Depth) {
6661 return Known.getSignBit();
6662}
6663
6665 auto *User = cast<Instruction>(U.getUser());
6666 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6667 if (FPOp->hasNoSignedZeros())
6668 return true;
6669 }
6670
6671 switch (User->getOpcode()) {
6672 case Instruction::FPToSI:
6673 case Instruction::FPToUI:
6674 return true;
6675 case Instruction::FCmp:
6676 // fcmp treats both positive and negative zero as equal.
6677 return true;
6678 case Instruction::Call:
6679 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6680 switch (II->getIntrinsicID()) {
6681 case Intrinsic::fabs:
6682 return true;
6683 case Intrinsic::copysign:
6684 return U.getOperandNo() == 0;
6685 case Intrinsic::is_fpclass: {
6686 auto Test =
6687 static_cast<FPClassTest>(
6688 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6691 }
6692 default:
6693 return false;
6694 }
6695 }
6696 return false;
6697 default:
6698 return false;
6699 }
6700}
6701
6703 auto *User = cast<Instruction>(U.getUser());
6704 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6705 if (FPOp->hasNoNaNs())
6706 return true;
6707 }
6708
6709 switch (User->getOpcode()) {
6710 case Instruction::FPToSI:
6711 case Instruction::FPToUI:
6712 return true;
6713 // Proper FP math operations ignore the sign bit of NaN.
6714 case Instruction::FAdd:
6715 case Instruction::FSub:
6716 case Instruction::FMul:
6717 case Instruction::FDiv:
6718 case Instruction::FRem:
6719 case Instruction::FPTrunc:
6720 case Instruction::FPExt:
6721 case Instruction::FCmp:
6722 return true;
6723 // Bitwise FP operations should preserve the sign bit of NaN.
6724 case Instruction::FNeg:
6725 case Instruction::Select:
6726 case Instruction::PHI:
6727 return false;
6728 case Instruction::Ret:
6729 return User->getFunction()->getAttributes().getRetNoFPClass() &
6731 case Instruction::Call:
6732 case Instruction::Invoke: {
6733 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6734 switch (II->getIntrinsicID()) {
6735 case Intrinsic::fabs:
6736 return true;
6737 case Intrinsic::copysign:
6738 return U.getOperandNo() == 0;
6739 // Other proper FP math intrinsics ignore the sign bit of NaN.
6740 case Intrinsic::maxnum:
6741 case Intrinsic::minnum:
6742 case Intrinsic::maximum:
6743 case Intrinsic::minimum:
6744 case Intrinsic::maximumnum:
6745 case Intrinsic::minimumnum:
6746 case Intrinsic::canonicalize:
6747 case Intrinsic::fma:
6748 case Intrinsic::fmuladd:
6749 case Intrinsic::sqrt:
6750 case Intrinsic::pow:
6751 case Intrinsic::powi:
6752 case Intrinsic::fptoui_sat:
6753 case Intrinsic::fptosi_sat:
6754 case Intrinsic::is_fpclass:
6755 return true;
6756 default:
6757 return false;
6758 }
6759 }
6760
6761 FPClassTest NoFPClass =
6762 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6763 return NoFPClass & FPClassTest::fcNan;
6764 }
6765 default:
6766 return false;
6767 }
6768}
6769
6771 FastMathFlags FMF) {
6772 if (isa<PoisonValue>(V))
6773 return true;
6774 if (isa<UndefValue>(V))
6775 return false;
6776
6777 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6778 return true;
6779
6781 if (!I)
6782 return false;
6783
6784 switch (I->getOpcode()) {
6785 case Instruction::SIToFP:
6786 case Instruction::UIToFP:
6787 // TODO: Could check nofpclass(inf) on incoming argument
6788 if (FMF.noInfs())
6789 return true;
6790
6791 // Need to check int size cannot produce infinity, which computeKnownFPClass
6792 // knows how to do already.
6793 return isKnownNeverInfinity(I, SQ);
6794 case Instruction::Call: {
6795 const CallInst *CI = cast<CallInst>(I);
6796 switch (CI->getIntrinsicID()) {
6797 case Intrinsic::trunc:
6798 case Intrinsic::floor:
6799 case Intrinsic::ceil:
6800 case Intrinsic::rint:
6801 case Intrinsic::nearbyint:
6802 case Intrinsic::round:
6803 case Intrinsic::roundeven:
6804 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6805 default:
6806 break;
6807 }
6808
6809 break;
6810 }
6811 default:
6812 break;
6813 }
6814
6815 return false;
6816}
6817
6819
6820 // All byte-wide stores are splatable, even of arbitrary variables.
6821 if (V->getType()->isIntegerTy(8))
6822 return V;
6823
6824 LLVMContext &Ctx = V->getContext();
6825
6826 // Undef don't care.
6827 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6828 if (isa<UndefValue>(V))
6829 return UndefInt8;
6830
6831 // Return poison for zero-sized type.
6832 if (DL.getTypeStoreSize(V->getType()).isZero())
6833 return PoisonValue::get(Type::getInt8Ty(Ctx));
6834
6836 if (!C) {
6837 // Conceptually, we could handle things like:
6838 // %a = zext i8 %X to i16
6839 // %b = shl i16 %a, 8
6840 // %c = or i16 %a, %b
6841 // but until there is an example that actually needs this, it doesn't seem
6842 // worth worrying about.
6843 return nullptr;
6844 }
6845
6846 // Handle 'null' ConstantArrayZero etc.
6847 if (C->isNullValue())
6849
6850 // Constant floating-point values can be handled as integer values if the
6851 // corresponding integer value is "byteable". An important case is 0.0.
6852 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6853 Type *ScalarTy = CFP->getType()->getScalarType();
6854 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6855 return isBytewiseValue(
6856 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6857
6858 // Don't handle long double formats, which have strange constraints.
6859 return nullptr;
6860 }
6861
6862 // We can handle constant integers that are multiple of 8 bits.
6863 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6864 if (CI->getBitWidth() % 8 == 0) {
6865 if (!CI->getValue().isSplat(8))
6866 return nullptr;
6867 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6868 }
6869 }
6870
6871 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6872 if (CE->getOpcode() == Instruction::IntToPtr) {
6873 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6874 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6876 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6877 return isBytewiseValue(Op, DL);
6878 }
6879 }
6880 }
6881
6882 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6883 if (LHS == RHS)
6884 return LHS;
6885 if (!LHS || !RHS)
6886 return nullptr;
6887 if (LHS == UndefInt8)
6888 return RHS;
6889 if (RHS == UndefInt8)
6890 return LHS;
6891 return nullptr;
6892 };
6893
6895 Value *Val = UndefInt8;
6896 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6897 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6898 return nullptr;
6899 return Val;
6900 }
6901
6903 Value *Val = UndefInt8;
6904 for (Value *Op : C->operands())
6905 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6906 return nullptr;
6907 return Val;
6908 }
6909
6910 // Don't try to handle the handful of other constants.
6911 return nullptr;
6912}
6913
6914// This is the recursive version of BuildSubAggregate. It takes a few different
6915// arguments. Idxs is the index within the nested struct From that we are
6916// looking at now (which is of type IndexedType). IdxSkip is the number of
6917// indices from Idxs that should be left out when inserting into the resulting
6918// struct. To is the result struct built so far, new insertvalue instructions
6919// build on that.
6920static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6922 unsigned IdxSkip,
6923 BasicBlock::iterator InsertBefore) {
6924 StructType *STy = dyn_cast<StructType>(IndexedType);
6925 if (STy) {
6926 // Save the original To argument so we can modify it
6927 Value *OrigTo = To;
6928 // General case, the type indexed by Idxs is a struct
6929 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6930 // Process each struct element recursively
6931 Idxs.push_back(i);
6932 Value *PrevTo = To;
6933 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6934 InsertBefore);
6935 Idxs.pop_back();
6936 if (!To) {
6937 // Couldn't find any inserted value for this index? Cleanup
6938 while (PrevTo != OrigTo) {
6940 PrevTo = Del->getAggregateOperand();
6941 Del->eraseFromParent();
6942 }
6943 // Stop processing elements
6944 break;
6945 }
6946 }
6947 // If we successfully found a value for each of our subaggregates
6948 if (To)
6949 return To;
6950 }
6951 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6952 // the struct's elements had a value that was inserted directly. In the latter
6953 // case, perhaps we can't determine each of the subelements individually, but
6954 // we might be able to find the complete struct somewhere.
6955
6956 // Find the value that is at that particular spot
6957 Value *V = FindInsertedValue(From, Idxs);
6958
6959 if (!V)
6960 return nullptr;
6961
6962 // Insert the value in the new (sub) aggregate
6963 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6964 InsertBefore);
6965}
6966
6967// This helper takes a nested struct and extracts a part of it (which is again a
6968// struct) into a new value. For example, given the struct:
6969// { a, { b, { c, d }, e } }
6970// and the indices "1, 1" this returns
6971// { c, d }.
6972//
6973// It does this by inserting an insertvalue for each element in the resulting
6974// struct, as opposed to just inserting a single struct. This will only work if
6975// each of the elements of the substruct are known (ie, inserted into From by an
6976// insertvalue instruction somewhere).
6977//
6978// All inserted insertvalue instructions are inserted before InsertBefore
6980 BasicBlock::iterator InsertBefore) {
6981 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6982 idx_range);
6983 Value *To = PoisonValue::get(IndexedType);
6984 SmallVector<unsigned, 10> Idxs(idx_range);
6985 unsigned IdxSkip = Idxs.size();
6986
6987 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6988}
6989
6990/// Given an aggregate and a sequence of indices, see if the scalar value
6991/// indexed is already around as a register, for example if it was inserted
6992/// directly into the aggregate.
6993///
6994/// If InsertBefore is not null, this function will duplicate (modified)
6995/// insertvalues when a part of a nested struct is extracted.
6996Value *
6998 std::optional<BasicBlock::iterator> InsertBefore) {
6999 // Nothing to index? Just return V then (this is useful at the end of our
7000 // recursion).
7001 if (idx_range.empty())
7002 return V;
7003 // We have indices, so V should have an indexable type.
7004 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
7005 "Not looking at a struct or array?");
7006 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
7007 "Invalid indices for type?");
7008
7009 if (Constant *C = dyn_cast<Constant>(V)) {
7010 C = C->getAggregateElement(idx_range[0]);
7011 if (!C) return nullptr;
7012 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7013 }
7014
7016 // Loop the indices for the insertvalue instruction in parallel with the
7017 // requested indices
7018 const unsigned *req_idx = idx_range.begin();
7019 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7020 i != e; ++i, ++req_idx) {
7021 if (req_idx == idx_range.end()) {
7022 // We can't handle this without inserting insertvalues
7023 if (!InsertBefore)
7024 return nullptr;
7025
7026 // The requested index identifies a part of a nested aggregate. Handle
7027 // this specially. For example,
7028 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7029 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7030 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7031 // This can be changed into
7032 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7033 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7034 // which allows the unused 0,0 element from the nested struct to be
7035 // removed.
7036 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7037 *InsertBefore);
7038 }
7039
7040 // This insert value inserts something else than what we are looking for.
7041 // See if the (aggregate) value inserted into has the value we are
7042 // looking for, then.
7043 if (*req_idx != *i)
7044 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7045 InsertBefore);
7046 }
7047 // If we end up here, the indices of the insertvalue match with those
7048 // requested (though possibly only partially). Now we recursively look at
7049 // the inserted value, passing any remaining indices.
7050 return FindInsertedValue(I->getInsertedValueOperand(),
7051 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7052 }
7053
7055 // If we're extracting a value from an aggregate that was extracted from
7056 // something else, we can extract from that something else directly instead.
7057 // However, we will need to chain I's indices with the requested indices.
7058
7059 // Calculate the number of indices required
7060 unsigned size = I->getNumIndices() + idx_range.size();
7061 // Allocate some space to put the new indices in
7063 Idxs.reserve(size);
7064 // Add indices from the extract value instruction
7065 Idxs.append(I->idx_begin(), I->idx_end());
7066
7067 // Add requested indices
7068 Idxs.append(idx_range.begin(), idx_range.end());
7069
7070 assert(Idxs.size() == size
7071 && "Number of indices added not correct?");
7072
7073 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7074 }
7075 // Otherwise, we don't know (such as, extracting from a function return value
7076 // or load instruction)
7077 return nullptr;
7078}
7079
7080// If V refers to an initialized global constant, set Slice either to
7081// its initializer if the size of its elements equals ElementSize, or,
7082// for ElementSize == 8, to its representation as an array of unsiged
7083// char. Return true on success.
7084// Offset is in the unit "nr of ElementSize sized elements".
7087 unsigned ElementSize, uint64_t Offset) {
7088 assert(V && "V should not be null.");
7089 assert((ElementSize % 8) == 0 &&
7090 "ElementSize expected to be a multiple of the size of a byte.");
7091 unsigned ElementSizeInBytes = ElementSize / 8;
7092
7093 // Drill down into the pointer expression V, ignoring any intervening
7094 // casts, and determine the identity of the object it references along
7095 // with the cumulative byte offset into it.
7096 const GlobalVariable *GV =
7098 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7099 // Fail if V is not based on constant global object.
7100 return false;
7101
7102 const DataLayout &DL = GV->getDataLayout();
7103 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7104
7106 /*AllowNonInbounds*/ true))
7107 // Fail if a constant offset could not be determined.
7108 return false;
7109
7110 uint64_t StartIdx = Off.getLimitedValue();
7111 if (StartIdx == UINT64_MAX)
7112 // Fail if the constant offset is excessive.
7113 return false;
7114
7115 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7116 // elements. Simply bail out if that isn't possible.
7117 if ((StartIdx % ElementSizeInBytes) != 0)
7118 return false;
7119
7120 Offset += StartIdx / ElementSizeInBytes;
7121 ConstantDataArray *Array = nullptr;
7122 ArrayType *ArrayTy = nullptr;
7123
7124 if (GV->getInitializer()->isNullValue()) {
7125 Type *GVTy = GV->getValueType();
7126 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7127 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7128
7129 Slice.Array = nullptr;
7130 Slice.Offset = 0;
7131 // Return an empty Slice for undersized constants to let callers
7132 // transform even undefined library calls into simpler, well-defined
7133 // expressions. This is preferable to making the calls although it
7134 // prevents sanitizers from detecting such calls.
7135 Slice.Length = Length < Offset ? 0 : Length - Offset;
7136 return true;
7137 }
7138
7139 auto *Init = const_cast<Constant *>(GV->getInitializer());
7140 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7141 Type *InitElTy = ArrayInit->getElementType();
7142 if (InitElTy->isIntegerTy(ElementSize)) {
7143 // If Init is an initializer for an array of the expected type
7144 // and size, use it as is.
7145 Array = ArrayInit;
7146 ArrayTy = ArrayInit->getType();
7147 }
7148 }
7149
7150 if (!Array) {
7151 if (ElementSize != 8)
7152 // TODO: Handle conversions to larger integral types.
7153 return false;
7154
7155 // Otherwise extract the portion of the initializer starting
7156 // at Offset as an array of bytes, and reset Offset.
7158 if (!Init)
7159 return false;
7160
7161 Offset = 0;
7163 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7164 }
7165
7166 uint64_t NumElts = ArrayTy->getArrayNumElements();
7167 if (Offset > NumElts)
7168 return false;
7169
7170 Slice.Array = Array;
7171 Slice.Offset = Offset;
7172 Slice.Length = NumElts - Offset;
7173 return true;
7174}
7175
7176/// Extract bytes from the initializer of the constant array V, which need
7177/// not be a nul-terminated string. On success, store the bytes in Str and
7178/// return true. When TrimAtNul is set, Str will contain only the bytes up
7179/// to but not including the first nul. Return false on failure.
7181 bool TrimAtNul) {
7183 if (!getConstantDataArrayInfo(V, Slice, 8))
7184 return false;
7185
7186 if (Slice.Array == nullptr) {
7187 if (TrimAtNul) {
7188 // Return a nul-terminated string even for an empty Slice. This is
7189 // safe because all existing SimplifyLibcalls callers require string
7190 // arguments and the behavior of the functions they fold is undefined
7191 // otherwise. Folding the calls this way is preferable to making
7192 // the undefined library calls, even though it prevents sanitizers
7193 // from reporting such calls.
7194 Str = StringRef();
7195 return true;
7196 }
7197 if (Slice.Length == 1) {
7198 Str = StringRef("", 1);
7199 return true;
7200 }
7201 // We cannot instantiate a StringRef as we do not have an appropriate string
7202 // of 0s at hand.
7203 return false;
7204 }
7205
7206 // Start out with the entire array in the StringRef.
7207 Str = Slice.Array->getAsString();
7208 // Skip over 'offset' bytes.
7209 Str = Str.substr(Slice.Offset);
7210
7211 if (TrimAtNul) {
7212 // Trim off the \0 and anything after it. If the array is not nul
7213 // terminated, we just return the whole end of string. The client may know
7214 // some other way that the string is length-bound.
7215 Str = Str.substr(0, Str.find('\0'));
7216 }
7217 return true;
7218}
7219
7220// These next two are very similar to the above, but also look through PHI
7221// nodes.
7222// TODO: See if we can integrate these two together.
7223
7224/// If we can compute the length of the string pointed to by
7225/// the specified pointer, return 'len+1'. If we can't, return 0.
7228 unsigned CharSize) {
7229 // Look through noop bitcast instructions.
7230 V = V->stripPointerCasts();
7231
7232 // If this is a PHI node, there are two cases: either we have already seen it
7233 // or we haven't.
7234 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7235 if (!PHIs.insert(PN).second)
7236 return ~0ULL; // already in the set.
7237
7238 // If it was new, see if all the input strings are the same length.
7239 uint64_t LenSoFar = ~0ULL;
7240 for (Value *IncValue : PN->incoming_values()) {
7241 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7242 if (Len == 0) return 0; // Unknown length -> unknown.
7243
7244 if (Len == ~0ULL) continue;
7245
7246 if (Len != LenSoFar && LenSoFar != ~0ULL)
7247 return 0; // Disagree -> unknown.
7248 LenSoFar = Len;
7249 }
7250
7251 // Success, all agree.
7252 return LenSoFar;
7253 }
7254
7255 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7256 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7257 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7258 if (Len1 == 0) return 0;
7259 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7260 if (Len2 == 0) return 0;
7261 if (Len1 == ~0ULL) return Len2;
7262 if (Len2 == ~0ULL) return Len1;
7263 if (Len1 != Len2) return 0;
7264 return Len1;
7265 }
7266
7267 // Otherwise, see if we can read the string.
7269 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7270 return 0;
7271
7272 if (Slice.Array == nullptr)
7273 // Zeroinitializer (including an empty one).
7274 return 1;
7275
7276 // Search for the first nul character. Return a conservative result even
7277 // when there is no nul. This is safe since otherwise the string function
7278 // being folded such as strlen is undefined, and can be preferable to
7279 // making the undefined library call.
7280 unsigned NullIndex = 0;
7281 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7282 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7283 break;
7284 }
7285
7286 return NullIndex + 1;
7287}
7288
7289/// If we can compute the length of the string pointed to by
7290/// the specified pointer, return 'len+1'. If we can't, return 0.
7291uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7292 if (!V->getType()->isPointerTy())
7293 return 0;
7294
7296 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7297 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7298 // an empty string as a length.
7299 return Len == ~0ULL ? 1 : Len;
7300}
7301
7302const Value *
7304 bool MustPreserveOffset,
7305 bool MustPreserveProvenance) {
7306 assert(Call &&
7307 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7308 if (const Value *RV = Call->getReturnedArgOperand())
7309 return RV;
7310 // This can be used only as a aliasing property.
7312 Call, MustPreserveOffset, MustPreserveProvenance))
7313 return Call->getArgOperand(0);
7314 return nullptr;
7315}
7316
7318 const CallBase *Call, bool MustPreserveOffset,
7319 bool MustPreserveProvenance) {
7320 switch (Call->getIntrinsicID()) {
7321 case Intrinsic::launder_invariant_group:
7322 case Intrinsic::aarch64_irg:
7323 case Intrinsic::aarch64_tagp:
7324 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7325 // input pointer (and thus preserves the byte offset, which is the property
7326 // the MustPreserveOffset flag selects). However, it will not necessarily
7327 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7328 // descriptor", which has "all loads return 0, all stores are dropped"
7329 // semantics. Given the context of this intrinsic list, no one should be
7330 // relying on such a strict bit-exact null mapping (and, at time of
7331 // writing, they are not), but we document this fact out of an abundance
7332 // of caution.
7333 case Intrinsic::amdgcn_make_buffer_rsrc:
7334 return !MustPreserveProvenance;
7335 case Intrinsic::ptrmask:
7336 return !MustPreserveOffset;
7337 case Intrinsic::threadlocal_address:
7338 // The underlying variable changes with thread ID. The Thread ID may change
7339 // at coroutine suspend points.
7340 return !Call->getParent()->getParent()->isPresplitCoroutine();
7341 default:
7342 return false;
7343 }
7344}
7345
7346/// \p PN defines a loop-variant pointer to an object. Check if the
7347/// previous iteration of the loop was referring to the same object as \p PN.
7349 const LoopInfo *LI) {
7350 // Find the loop-defined value.
7351 Loop *L = LI->getLoopFor(PN->getParent());
7352 if (PN->getNumIncomingValues() != 2)
7353 return true;
7354
7355 // Find the value from previous iteration.
7356 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7357 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7358 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7359 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7360 return true;
7361
7362 // If a new pointer is loaded in the loop, the pointer references a different
7363 // object in every iteration. E.g.:
7364 // for (i)
7365 // int *p = a[i];
7366 // ...
7367 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7368 if (!L->isLoopInvariant(Load->getPointerOperand()))
7369 return false;
7370 return true;
7371}
7372
7373const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7374 bool MustPreserveProvenance) {
7375 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7376 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7377 const Value *PtrOp = GEP->getPointerOperand();
7378 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7379 return V;
7380 V = PtrOp;
7381 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7382 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7383 Value *NewV = cast<Operator>(V)->getOperand(0);
7384 if (!NewV->getType()->isPointerTy())
7385 return V;
7386 V = NewV;
7387 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7388 if (GA->isInterposable())
7389 return V;
7390 V = GA->getAliasee();
7391 } else {
7392 if (auto *PHI = dyn_cast<PHINode>(V)) {
7393 // Look through single-arg phi nodes created by LCSSA.
7394 if (PHI->getNumIncomingValues() == 1) {
7395 V = PHI->getIncomingValue(0);
7396 continue;
7397 }
7398 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7399 // CaptureTracking can know about special capturing properties of some
7400 // intrinsics like launder.invariant.group, that can't be expressed with
7401 // the attributes, but have properties like returning aliasing pointer.
7402 // Because some analysis may assume that nocaptured pointer is not
7403 // returned from some special intrinsic (because function would have to
7404 // be marked with returns attribute), it is crucial to use this function
7405 // because it should be in sync with CaptureTracking. Not using it may
7406 // cause weird miscompilations where 2 aliasing pointers are assumed to
7407 // noalias.
7409 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7410 V = RP;
7411 continue;
7412 }
7413 }
7414
7415 return V;
7416 }
7417 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7418 }
7419 return V;
7420}
7421
7424 const LoopInfo *LI, unsigned MaxLookup) {
7427 Worklist.push_back(V);
7428 do {
7429 const Value *P = Worklist.pop_back_val();
7430 P = getUnderlyingObject(P, MaxLookup);
7431
7432 if (!Visited.insert(P).second)
7433 continue;
7434
7435 if (auto *SI = dyn_cast<SelectInst>(P)) {
7436 Worklist.push_back(SI->getTrueValue());
7437 Worklist.push_back(SI->getFalseValue());
7438 continue;
7439 }
7440
7441 if (auto *PN = dyn_cast<PHINode>(P)) {
7442 // If this PHI changes the underlying object in every iteration of the
7443 // loop, don't look through it. Consider:
7444 // int **A;
7445 // for (i) {
7446 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7447 // Curr = A[i];
7448 // *Prev, *Curr;
7449 //
7450 // Prev is tracking Curr one iteration behind so they refer to different
7451 // underlying objects.
7452 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7454 append_range(Worklist, PN->incoming_values());
7455 else
7456 Objects.push_back(P);
7457 continue;
7458 }
7459
7460 Objects.push_back(P);
7461 } while (!Worklist.empty());
7462}
7463
7465 bool MustPreserveProvenance) {
7466 const unsigned MaxVisited = 8;
7467
7470 Worklist.push_back(V);
7471 const Value *Object = nullptr;
7472 // Used as fallback if we can't find a common underlying object through
7473 // recursion.
7474 bool First = true;
7475 const Value *FirstObject =
7476 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7477 do {
7478 const Value *P = Worklist.pop_back_val();
7479 P = First ? FirstObject
7481 MustPreserveProvenance);
7482 First = false;
7483
7484 if (!Visited.insert(P).second)
7485 continue;
7486
7487 if (Visited.size() == MaxVisited)
7488 return FirstObject;
7489
7490 if (auto *SI = dyn_cast<SelectInst>(P)) {
7491 Worklist.push_back(SI->getTrueValue());
7492 Worklist.push_back(SI->getFalseValue());
7493 continue;
7494 }
7495
7496 if (auto *PN = dyn_cast<PHINode>(P)) {
7497 append_range(Worklist, PN->incoming_values());
7498 continue;
7499 }
7500
7501 if (!Object)
7502 Object = P;
7503 else if (Object != P)
7504 return FirstObject;
7505 } while (!Worklist.empty());
7506
7507 return Object ? Object : FirstObject;
7508}
7509
7510/// This is the function that does the work of looking through basic
7511/// ptrtoint+arithmetic+inttoptr sequences.
7512static const Value *getUnderlyingObjectFromInt(const Value *V) {
7513 do {
7514 if (const Operator *U = dyn_cast<Operator>(V)) {
7515 // If we find a ptrtoint, we can transfer control back to the
7516 // regular getUnderlyingObjectFromInt.
7517 if (U->getOpcode() == Instruction::PtrToInt)
7518 return U->getOperand(0);
7519 // If we find an add of a constant, a multiplied value, or a phi, it's
7520 // likely that the other operand will lead us to the base
7521 // object. We don't have to worry about the case where the
7522 // object address is somehow being computed by the multiply,
7523 // because our callers only care when the result is an
7524 // identifiable object.
7525 if (U->getOpcode() != Instruction::Add ||
7526 (!isa<ConstantInt>(U->getOperand(1)) &&
7527 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7528 !isa<PHINode>(U->getOperand(1))))
7529 return V;
7530 V = U->getOperand(0);
7531 } else {
7532 return V;
7533 }
7534 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7535 } while (true);
7536}
7537
7538/// This is a wrapper around getUnderlyingObjects and adds support for basic
7539/// ptrtoint+arithmetic+inttoptr sequences.
7540/// It returns false if unidentified object is found in getUnderlyingObjects.
7542 SmallVectorImpl<Value *> &Objects) {
7544 SmallVector<const Value *, 4> Working(1, V);
7545 bool AllObjectsIdentified = true;
7546 do {
7547 V = Working.pop_back_val();
7548
7550 getUnderlyingObjects(V, Objs);
7551
7552 for (const Value *V : Objs) {
7553 if (!Visited.insert(V).second)
7554 continue;
7555 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7556 const Value *O =
7557 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7558 if (O->getType()->isPointerTy()) {
7559 Working.push_back(O);
7560 continue;
7561 }
7562 }
7563 AllObjectsIdentified &= isIdentifiedObject(V);
7564 Objects.push_back(const_cast<Value *>(V));
7565 }
7566 } while (!Working.empty());
7567 return AllObjectsIdentified;
7568}
7569
7571 AllocaInst *Result = nullptr;
7573 SmallVector<Value *, 4> Worklist;
7574
7575 auto AddWork = [&](Value *V) {
7576 if (Visited.insert(V).second)
7577 Worklist.push_back(V);
7578 };
7579
7580 AddWork(V);
7581 do {
7582 V = Worklist.pop_back_val();
7583 assert(Visited.count(V));
7584
7585 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7586 if (Result && Result != AI)
7587 return nullptr;
7588 Result = AI;
7589 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7590 AddWork(CI->getOperand(0));
7591 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7592 for (Value *IncValue : PN->incoming_values())
7593 AddWork(IncValue);
7594 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7595 AddWork(SI->getTrueValue());
7596 AddWork(SI->getFalseValue());
7598 if (OffsetZero && !GEP->hasAllZeroIndices())
7599 return nullptr;
7600 AddWork(GEP->getPointerOperand());
7601 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7602 Value *Returned = CB->getReturnedArgOperand();
7603 if (Returned)
7604 AddWork(Returned);
7605 else
7606 return nullptr;
7607 } else {
7608 return nullptr;
7609 }
7610 } while (!Worklist.empty());
7611
7612 return Result;
7613}
7614
7616 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7617 for (const User *U : V->users()) {
7619 if (!II)
7620 return false;
7621
7622 if (AllowLifetime && II->isLifetimeStartOrEnd())
7623 continue;
7624
7625 if (AllowDroppable && II->isDroppable())
7626 continue;
7627
7628 return false;
7629 }
7630 return true;
7631}
7632
7635 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7636}
7639 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7640}
7641
7643 if (auto *II = dyn_cast<IntrinsicInst>(I))
7644 return isTriviallyVectorizable(II->getIntrinsicID());
7645 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7646 return (!Shuffle || Shuffle->isSelect()) &&
7648}
7649
7651 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7652 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7653 bool IgnoreUBImplyingAttrs) {
7654 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7655 AC, DT, TLI, UseVariableInfo,
7656 IgnoreUBImplyingAttrs);
7657}
7658
7660 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7661 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7662 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7663#ifndef NDEBUG
7664 if (Inst->getOpcode() != Opcode) {
7665 // Check that the operands are actually compatible with the Opcode override.
7666 auto hasEqualReturnAndLeadingOperandTypes =
7667 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7668 if (Inst->getNumOperands() < NumLeadingOperands)
7669 return false;
7670 const Type *ExpectedType = Inst->getType();
7671 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7672 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7673 return false;
7674 return true;
7675 };
7677 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7678 assert(!Instruction::isUnaryOp(Opcode) ||
7679 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7680 }
7681#endif
7682
7683 switch (Opcode) {
7684 default:
7685 return true;
7686 case Instruction::UDiv:
7687 case Instruction::URem: {
7688 // x / y is undefined if y == 0.
7689 const APInt *V;
7690 if (match(Inst->getOperand(1), m_APInt(V)))
7691 return *V != 0;
7692 return false;
7693 }
7694 case Instruction::SDiv:
7695 case Instruction::SRem: {
7696 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7697 const APInt *Numerator, *Denominator;
7698 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7699 return false;
7700 // We cannot hoist this division if the denominator is 0.
7701 if (*Denominator == 0)
7702 return false;
7703 // It's safe to hoist if the denominator is not 0 or -1.
7704 if (!Denominator->isAllOnes())
7705 return true;
7706 // At this point we know that the denominator is -1. It is safe to hoist as
7707 // long we know that the numerator is not INT_MIN.
7708 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7709 return !Numerator->isMinSignedValue();
7710 // The numerator *might* be MinSignedValue.
7711 return false;
7712 }
7713 case Instruction::Load: {
7714 if (!UseVariableInfo)
7715 return false;
7716
7717 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7718 if (!LI)
7719 return false;
7720 if (mustSuppressSpeculation(*LI))
7721 return false;
7722 const DataLayout &DL = LI->getDataLayout();
7724 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7725 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7726 }
7727 case Instruction::Call: {
7728 auto *CI = dyn_cast<const CallInst>(Inst);
7729 if (!CI)
7730 return false;
7731 const Function *Callee = CI->getCalledFunction();
7732
7733 // The called function could have undefined behavior or side-effects, even
7734 // if marked readnone nounwind.
7735 if (!Callee || !Callee->isSpeculatable())
7736 return false;
7737 // Since the operands may be changed after hoisting, undefined behavior may
7738 // be triggered by some UB-implying attributes.
7739 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7740 }
7741 case Instruction::VAArg:
7742 case Instruction::Alloca:
7743 case Instruction::Invoke:
7744 case Instruction::CallBr:
7745 case Instruction::PHI:
7746 case Instruction::Store:
7747 case Instruction::Ret:
7748 case Instruction::UncondBr:
7749 case Instruction::CondBr:
7750 case Instruction::IndirectBr:
7751 case Instruction::Switch:
7752 case Instruction::Unreachable:
7753 case Instruction::Fence:
7754 case Instruction::AtomicRMW:
7755 case Instruction::AtomicCmpXchg:
7756 case Instruction::LandingPad:
7757 case Instruction::Resume:
7758 case Instruction::CatchSwitch:
7759 case Instruction::CatchPad:
7760 case Instruction::CatchRet:
7761 case Instruction::CleanupPad:
7762 case Instruction::CleanupRet:
7763 return false; // Misc instructions which have effects
7764 }
7765}
7766
7768 if (I.mayReadOrWriteMemory())
7769 // Memory dependency possible
7770 return true;
7772 // Can't move above a maythrow call or infinite loop. Or if an
7773 // inalloca alloca, above a stacksave call.
7774 return true;
7776 // 1) Can't reorder two inf-loop calls, even if readonly
7777 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7778 // safe to speculative execute. (Inverse of above)
7779 return true;
7780 return false;
7781}
7782
7783/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7797
7798/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7801 bool ForSigned,
7802 const SimplifyQuery &SQ) {
7803 ConstantRange CR1 =
7804 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7805 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7808 return CR1.intersectWith(CR2, RangeType);
7809}
7810
7812 const Value *RHS,
7813 const SimplifyQuery &SQ,
7814 bool IsNSW) {
7815 ConstantRange LHSRange =
7816 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7817 ConstantRange RHSRange =
7818 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7819
7820 // mul nsw of two non-negative numbers is also nuw.
7821 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7823
7824 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7825}
7826
7828 const Value *RHS,
7829 const SimplifyQuery &SQ) {
7830 // Multiplying n * m significant bits yields a result of n + m significant
7831 // bits. If the total number of significant bits does not exceed the
7832 // result bit width (minus 1), there is no overflow.
7833 // This means if we have enough leading sign bits in the operands
7834 // we can guarantee that the result does not overflow.
7835 // Ref: "Hacker's Delight" by Henry Warren
7836 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7837
7838 // Note that underestimating the number of sign bits gives a more
7839 // conservative answer.
7840 unsigned SignBits =
7841 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7842
7843 // First handle the easy case: if we have enough sign bits there's
7844 // definitely no overflow.
7845 if (SignBits > BitWidth + 1)
7847
7848 // There are two ambiguous cases where there can be no overflow:
7849 // SignBits == BitWidth + 1 and
7850 // SignBits == BitWidth
7851 // The second case is difficult to check, therefore we only handle the
7852 // first case.
7853 if (SignBits == BitWidth + 1) {
7854 // It overflows only when both arguments are negative and the true
7855 // product is exactly the minimum negative number.
7856 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7857 // For simplicity we just check if at least one side is not negative.
7858 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7859 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7860 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7862 }
7864}
7865
7868 const WithCache<const Value *> &RHS,
7869 const SimplifyQuery &SQ) {
7870 ConstantRange LHSRange =
7871 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7872 ConstantRange RHSRange =
7873 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7874 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7875}
7876
7877static OverflowResult
7880 const AddOperator *Add, const SimplifyQuery &SQ) {
7881 if (Add && Add->hasNoSignedWrap()) {
7883 }
7884
7885 // If LHS and RHS each have at least two sign bits, the addition will look
7886 // like
7887 //
7888 // XX..... +
7889 // YY.....
7890 //
7891 // If the carry into the most significant position is 0, X and Y can't both
7892 // be 1 and therefore the carry out of the addition is also 0.
7893 //
7894 // If the carry into the most significant position is 1, X and Y can't both
7895 // be 0 and therefore the carry out of the addition is also 1.
7896 //
7897 // Since the carry into the most significant position is always equal to
7898 // the carry out of the addition, there is no signed overflow.
7899 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7901
7902 ConstantRange LHSRange =
7903 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7904 ConstantRange RHSRange =
7905 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7906 OverflowResult OR =
7907 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7909 return OR;
7910
7911 // The remaining code needs Add to be available. Early returns if not so.
7912 if (!Add)
7914
7915 // If the sign of Add is the same as at least one of the operands, this add
7916 // CANNOT overflow. If this can be determined from the known bits of the
7917 // operands the above signedAddMayOverflow() check will have already done so.
7918 // The only other way to improve on the known bits is from an assumption, so
7919 // call computeKnownBitsFromContext() directly.
7920 bool LHSOrRHSKnownNonNegative =
7921 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7922 bool LHSOrRHSKnownNegative =
7923 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7924 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7925 KnownBits AddKnown(LHSRange.getBitWidth());
7926 computeKnownBitsFromContext(Add, AddKnown, SQ);
7927 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7928 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7930 }
7931
7933}
7934
7936 const Value *RHS,
7937 const SimplifyQuery &SQ) {
7938 // X - (X % ?)
7939 // The remainder of a value can't have greater magnitude than itself,
7940 // so the subtraction can't overflow.
7941
7942 // X - (X -nuw ?)
7943 // In the minimal case, this would simplify to "?", so there's no subtract
7944 // at all. But if this analysis is used to peek through casts, for example,
7945 // then determining no-overflow may allow other transforms.
7946
7947 // TODO: There are other patterns like this.
7948 // See simplifyICmpWithBinOpOnLHS() for candidates.
7949 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7950 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7951 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7953
7954 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
7955 SQ.DL)) {
7956 if (*C)
7959 }
7960
7961 ConstantRange LHSRange =
7962 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7963 ConstantRange RHSRange =
7964 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7965 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7966}
7967
7969 const Value *RHS,
7970 const SimplifyQuery &SQ) {
7971 // X - (X % ?)
7972 // The remainder of a value can't have greater magnitude than itself,
7973 // so the subtraction can't overflow.
7974
7975 // X - (X -nsw ?)
7976 // In the minimal case, this would simplify to "?", so there's no subtract
7977 // at all. But if this analysis is used to peek through casts, for example,
7978 // then determining no-overflow may allow other transforms.
7979 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7980 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7981 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7983
7984 // If LHS and RHS each have at least two sign bits, the subtraction
7985 // cannot overflow.
7986 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7988
7989 ConstantRange LHSRange =
7990 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7991 ConstantRange RHSRange =
7992 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7993 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7994}
7995
7997 const DominatorTree &DT) {
7998 SmallVector<const CondBrInst *, 2> GuardingBranches;
8000
8001 for (const User *U : WO->users()) {
8002 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
8003 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
8004
8005 if (EVI->getIndices()[0] == 0)
8006 Results.push_back(EVI);
8007 else {
8008 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
8009
8010 for (const auto *U : EVI->users())
8011 if (const auto *B = dyn_cast<CondBrInst>(U))
8012 GuardingBranches.push_back(B);
8013 }
8014 } else {
8015 // We are using the aggregate directly in a way we don't want to analyze
8016 // here (storing it to a global, say).
8017 return false;
8018 }
8019 }
8020
8021 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8022 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8023
8024 // Check if all users of the add are provably no-wrap.
8025 for (const auto *Result : Results) {
8026 // If the extractvalue itself is not executed on overflow, the we don't
8027 // need to check each use separately, since domination is transitive.
8028 if (DT.dominates(NoWrapEdge, Result->getParent()))
8029 continue;
8030
8031 for (const auto &RU : Result->uses())
8032 if (!DT.dominates(NoWrapEdge, RU))
8033 return false;
8034 }
8035
8036 return true;
8037 };
8038
8039 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8040}
8041
8042/// Shifts return poison if shiftwidth is larger than the bitwidth.
8043static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8044 auto *C = dyn_cast<Constant>(ShiftAmount);
8045 if (!C)
8046 return false;
8047
8048 // Shifts return poison if shiftwidth is larger than the bitwidth.
8050 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8051 unsigned NumElts = FVTy->getNumElements();
8052 for (unsigned i = 0; i < NumElts; ++i)
8053 ShiftAmounts.push_back(C->getAggregateElement(i));
8054 } else if (isa<ScalableVectorType>(C->getType()))
8055 return false; // Can't tell, just return false to be safe
8056 else
8057 ShiftAmounts.push_back(C);
8058
8059 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8060 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8061 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8062 });
8063
8064 return Safe;
8065}
8066
8068 bool ConsiderFlagsAndMetadata) {
8069
8070 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8071 Op->hasPoisonGeneratingAnnotations())
8072 return true;
8073
8074 unsigned Opcode = Op->getOpcode();
8075
8076 // Check whether opcode is a poison/undef-generating operation
8077 switch (Opcode) {
8078 case Instruction::Shl:
8079 case Instruction::AShr:
8080 case Instruction::LShr:
8081 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8082 case Instruction::FPToSI:
8083 case Instruction::FPToUI:
8084 // fptosi/ui yields poison if the resulting value does not fit in the
8085 // destination type.
8086 return true;
8087 case Instruction::Call:
8088 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8089 switch (II->getIntrinsicID()) {
8090 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8091 case Intrinsic::ctlz:
8092 case Intrinsic::cttz:
8093 case Intrinsic::abs:
8094 // We're not considering flags so it is safe to just return false.
8095 return false;
8096 case Intrinsic::sshl_sat:
8097 case Intrinsic::ushl_sat:
8098 if (!includesPoison(Kind) ||
8099 shiftAmountKnownInRange(II->getArgOperand(1)))
8100 return false;
8101 break;
8102 }
8103 }
8104 [[fallthrough]];
8105 case Instruction::CallBr:
8106 case Instruction::Invoke: {
8107 const auto *CB = cast<CallBase>(Op);
8108 return !CB->hasRetAttr(Attribute::NoUndef) &&
8109 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8110 }
8111 case Instruction::InsertElement:
8112 case Instruction::ExtractElement: {
8113 // If index exceeds the length of the vector, it returns poison
8114 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8115 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8116 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8117 if (includesPoison(Kind))
8118 return !Idx ||
8119 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8120 return false;
8121 }
8122 case Instruction::ShuffleVector: {
8124 ? cast<ConstantExpr>(Op)->getShuffleMask()
8125 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8126 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8127 }
8128 case Instruction::FNeg:
8129 case Instruction::PHI:
8130 case Instruction::Select:
8131 case Instruction::ExtractValue:
8132 case Instruction::InsertValue:
8133 case Instruction::Freeze:
8134 case Instruction::ICmp:
8135 case Instruction::FCmp:
8136 case Instruction::GetElementPtr:
8137 return false;
8138 case Instruction::AddrSpaceCast:
8139 return true;
8140 default: {
8141 const auto *CE = dyn_cast<ConstantExpr>(Op);
8142 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8143 return false;
8144 else if (Instruction::isBinaryOp(Opcode))
8145 return false;
8146 // Be conservative and return true.
8147 return true;
8148 }
8149 }
8150}
8151
8153 bool ConsiderFlagsAndMetadata) {
8154 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8155 ConsiderFlagsAndMetadata);
8156}
8157
8158bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8159 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8160 ConsiderFlagsAndMetadata);
8161}
8162
8163static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8164 unsigned Depth) {
8165 if (ValAssumedPoison == V)
8166 return true;
8167
8168 const unsigned MaxDepth = 2;
8169 if (Depth >= MaxDepth)
8170 return false;
8171
8172 if (const auto *I = dyn_cast<Instruction>(V)) {
8173 if (any_of(I->operands(), [=](const Use &Op) {
8174 return propagatesPoison(Op) &&
8175 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8176 }))
8177 return true;
8178
8179 // V = extractvalue V0, idx
8180 // V2 = extractvalue V0, idx2
8181 // V0's elements are all poison or not. (e.g., add_with_overflow)
8182 const WithOverflowInst *II;
8184 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8185 llvm::is_contained(II->args(), ValAssumedPoison)))
8186 return true;
8187 }
8188 return false;
8189}
8190
8191static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8192 unsigned Depth) {
8193 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8194 return true;
8195
8196 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8197 return true;
8198
8199 const unsigned MaxDepth = 2;
8200 if (Depth >= MaxDepth)
8201 return false;
8202
8203 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8204 if (I && !canCreatePoison(cast<Operator>(I))) {
8205 return all_of(I->operands(), [=](const Value *Op) {
8206 return impliesPoison(Op, V, Depth + 1);
8207 });
8208 }
8209 return false;
8210}
8211
8212bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8213 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8214}
8215
8216static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8217
8219 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8220 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8222 return false;
8223
8224 if (isa<MetadataAsValue>(V))
8225 return false;
8226
8227 if (const auto *A = dyn_cast<Argument>(V)) {
8228 if (A->hasAttribute(Attribute::NoUndef) ||
8229 A->hasAttribute(Attribute::Dereferenceable) ||
8230 A->hasAttribute(Attribute::DereferenceableOrNull))
8231 return true;
8232 }
8233
8234 if (auto *C = dyn_cast<Constant>(V)) {
8235 if (isa<PoisonValue>(C))
8236 return !includesPoison(Kind);
8237
8238 if (isa<UndefValue>(C))
8239 return !includesUndef(Kind);
8240
8243 return true;
8244
8245 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8246 if (isa<ConstantExpr>(C)) {
8247 // Scalable vectors can use a ConstantExpr to build a splat.
8248 if (Constant *SplatC = C->getSplatValue())
8249 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8250 return true;
8251 } else {
8252 if (includesUndef(Kind) && C->containsUndefElement())
8253 return false;
8254 if (includesPoison(Kind) && C->containsPoisonElement())
8255 return false;
8256 return !C->containsConstantExpression();
8257 }
8258 }
8259 }
8260
8261 // Strip cast operations from a pointer value.
8262 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8263 // inbounds with zero offset. To guarantee that the result isn't poison, the
8264 // stripped pointer is checked as it has to be pointing into an allocated
8265 // object or be null `null` to ensure `inbounds` getelement pointers with a
8266 // zero offset could not produce poison.
8267 // It can strip off addrspacecast that do not change bit representation as
8268 // well. We believe that such addrspacecast is equivalent to no-op.
8269 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8270 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8271 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8272 return true;
8273
8274 auto OpCheck = [&](const Value *V) {
8275 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8276 };
8277
8278 if (auto *Opr = dyn_cast<Operator>(V)) {
8279 // If the value is a freeze instruction, then it can never
8280 // be undef or poison.
8281 if (isa<FreezeInst>(V))
8282 return true;
8283
8284 if (const auto *CB = dyn_cast<CallBase>(V)) {
8285 if (CB->hasRetAttr(Attribute::NoUndef) ||
8286 CB->hasRetAttr(Attribute::Dereferenceable) ||
8287 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8288 return true;
8289 }
8290
8291 if (!::canCreateUndefOrPoison(Opr, Kind,
8292 /*ConsiderFlagsAndMetadata=*/true)) {
8293 if (const auto *PN = dyn_cast<PHINode>(V)) {
8294 unsigned Num = PN->getNumIncomingValues();
8295 bool IsWellDefined = true;
8296 for (unsigned i = 0; i < Num; ++i) {
8297 if (PN == PN->getIncomingValue(i))
8298 continue;
8299 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8300 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8301 DT, Depth + 1, Kind)) {
8302 IsWellDefined = false;
8303 break;
8304 }
8305 }
8306 if (IsWellDefined)
8307 return true;
8308 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8309 : nullptr) {
8310 // For splats we only need to check the value being splatted.
8311 if (OpCheck(Splat))
8312 return true;
8313 } else if (all_of(Opr->operands(), OpCheck))
8314 return true;
8315 }
8316 }
8317
8318 if (auto *I = dyn_cast<LoadInst>(V))
8319 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8320 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8321 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8322 return true;
8323
8325 return true;
8326
8327 // CtxI may be null or a cloned instruction.
8328 if (!CtxI || !CtxI->getParent() || !DT)
8329 return false;
8330
8331 auto *DNode = DT->getNode(CtxI->getParent());
8332 if (!DNode)
8333 // Unreachable block
8334 return false;
8335
8336 // If V is used as a branch condition before reaching CtxI, V cannot be
8337 // undef or poison.
8338 // br V, BB1, BB2
8339 // BB1:
8340 // CtxI ; V cannot be undef or poison here
8341 auto *Dominator = DNode->getIDom();
8342 // This check is purely for compile time reasons: we can skip the IDom walk
8343 // if what we are checking for includes undef and the value is not an integer.
8344 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8345 while (Dominator) {
8346 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8347
8348 Value *Cond = nullptr;
8349 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8350 Cond = BI->getCondition();
8351 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8352 Cond = SI->getCondition();
8353 }
8354
8355 if (Cond) {
8356 if (Cond == V)
8357 return true;
8358 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8359 // For poison, we can analyze further
8360 auto *Opr = cast<Operator>(Cond);
8361 if (any_of(Opr->operands(), [V](const Use &U) {
8362 return V == U && propagatesPoison(U);
8363 }))
8364 return true;
8365 }
8366 }
8367
8368 Dominator = Dominator->getIDom();
8369 }
8370
8371 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8372 return true;
8373
8374 return false;
8375}
8376
8378 const Instruction *CtxI,
8379 const DominatorTree *DT,
8380 unsigned Depth) {
8381 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8383}
8384
8386 const Instruction *CtxI,
8387 const DominatorTree *DT, unsigned Depth) {
8388 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8390}
8391
8393 const Instruction *CtxI,
8394 const DominatorTree *DT, unsigned Depth) {
8395 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8397}
8398
8399/// Return true if undefined behavior would provably be executed on the path to
8400/// OnPathTo if Root produced a posion result. Note that this doesn't say
8401/// anything about whether OnPathTo is actually executed or whether Root is
8402/// actually poison. This can be used to assess whether a new use of Root can
8403/// be added at a location which is control equivalent with OnPathTo (such as
8404/// immediately before it) without introducing UB which didn't previously
8405/// exist. Note that a false result conveys no information.
8407 Instruction *OnPathTo,
8408 DominatorTree *DT) {
8409 // Basic approach is to assume Root is poison, propagate poison forward
8410 // through all users we can easily track, and then check whether any of those
8411 // users are provable UB and must execute before out exiting block might
8412 // exit.
8413
8414 // The set of all recursive users we've visited (which are assumed to all be
8415 // poison because of said visit)
8418 Worklist.push_back(Root);
8419 while (!Worklist.empty()) {
8420 const Instruction *I = Worklist.pop_back_val();
8421
8422 // If we know this must trigger UB on a path leading our target.
8423 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8424 return true;
8425
8426 // If we can't analyze propagation through this instruction, just skip it
8427 // and transitive users. Safe as false is a conservative result.
8428 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8429 return KnownPoison.contains(U) && propagatesPoison(U);
8430 }))
8431 continue;
8432
8433 if (KnownPoison.insert(I).second)
8434 for (const User *User : I->users())
8435 Worklist.push_back(cast<Instruction>(User));
8436 }
8437
8438 // Might be non-UB, or might have a path we couldn't prove must execute on
8439 // way to exiting bb.
8440 return false;
8441}
8442
8444 const SimplifyQuery &SQ) {
8445 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8446 Add, SQ);
8447}
8448
8451 const WithCache<const Value *> &RHS,
8452 const SimplifyQuery &SQ) {
8453 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8454}
8455
8457 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8458 // of time because it's possible for another thread to interfere with it for an
8459 // arbitrary length of time, but programs aren't allowed to rely on that.
8460
8461 // If there is no successor, then execution can't transfer to it.
8462 if (isa<ReturnInst>(I))
8463 return false;
8465 return false;
8466
8467 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8468 // Instruction::willReturn.
8469 //
8470 // FIXME: Move this check into Instruction::willReturn.
8471 if (isa<CatchPadInst>(I)) {
8472 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8473 default:
8474 // A catchpad may invoke exception object constructors and such, which
8475 // in some languages can be arbitrary code, so be conservative by default.
8476 return false;
8478 // For CoreCLR, it just involves a type test.
8479 return true;
8480 }
8481 }
8482
8483 // An instruction that returns without throwing must transfer control flow
8484 // to a successor.
8485 return !I->mayThrow() && I->willReturn();
8486}
8487
8489 // TODO: This is slightly conservative for invoke instruction since exiting
8490 // via an exception *is* normal control for them.
8491 for (const Instruction &I : *BB)
8493 return false;
8494 return true;
8495}
8496
8503
8506 assert(ScanLimit && "scan limit must be non-zero");
8507 for (const Instruction &I : Range) {
8508 if (--ScanLimit == 0)
8509 return false;
8511 return false;
8512 }
8513 return true;
8514}
8515
8517 const Loop *L) {
8518 // The loop header is guaranteed to be executed for every iteration.
8519 //
8520 // FIXME: Relax this constraint to cover all basic blocks that are
8521 // guaranteed to be executed at every iteration.
8522 if (I->getParent() != L->getHeader()) return false;
8523
8524 for (const Instruction &LI : *L->getHeader()) {
8525 if (&LI == I) return true;
8526 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8527 }
8528 llvm_unreachable("Instruction not contained in its own parent basic block.");
8529}
8530
8532 switch (IID) {
8533 // TODO: Add more intrinsics.
8534 case Intrinsic::sadd_with_overflow:
8535 case Intrinsic::ssub_with_overflow:
8536 case Intrinsic::smul_with_overflow:
8537 case Intrinsic::uadd_with_overflow:
8538 case Intrinsic::usub_with_overflow:
8539 case Intrinsic::umul_with_overflow:
8540 // If an input is a vector containing a poison element, the
8541 // two output vectors (calculated results, overflow bits)'
8542 // corresponding lanes are poison.
8543 return true;
8544 case Intrinsic::ctpop:
8545 case Intrinsic::ctlz:
8546 case Intrinsic::cttz:
8547 case Intrinsic::abs:
8548 case Intrinsic::smax:
8549 case Intrinsic::smin:
8550 case Intrinsic::umax:
8551 case Intrinsic::umin:
8552 case Intrinsic::scmp:
8553 case Intrinsic::smulh:
8554 case Intrinsic::umulh:
8555 case Intrinsic::is_fpclass:
8556 case Intrinsic::ptrmask:
8557 case Intrinsic::ucmp:
8558 case Intrinsic::bitreverse:
8559 case Intrinsic::bswap:
8560 case Intrinsic::sadd_sat:
8561 case Intrinsic::ssub_sat:
8562 case Intrinsic::sshl_sat:
8563 case Intrinsic::uadd_sat:
8564 case Intrinsic::usub_sat:
8565 case Intrinsic::ushl_sat:
8566 case Intrinsic::smul_fix:
8567 case Intrinsic::smul_fix_sat:
8568 case Intrinsic::umul_fix:
8569 case Intrinsic::umul_fix_sat:
8570 case Intrinsic::pow:
8571 case Intrinsic::powi:
8572 case Intrinsic::sin:
8573 case Intrinsic::sinh:
8574 case Intrinsic::cos:
8575 case Intrinsic::cosh:
8576 case Intrinsic::sincos:
8577 case Intrinsic::sincospi:
8578 case Intrinsic::tan:
8579 case Intrinsic::tanh:
8580 case Intrinsic::asin:
8581 case Intrinsic::acos:
8582 case Intrinsic::atan:
8583 case Intrinsic::atan2:
8584 case Intrinsic::canonicalize:
8585 case Intrinsic::sqrt:
8586 case Intrinsic::fma:
8587 case Intrinsic::fmuladd:
8588 case Intrinsic::exp:
8589 case Intrinsic::exp2:
8590 case Intrinsic::exp10:
8591 case Intrinsic::log:
8592 case Intrinsic::log2:
8593 case Intrinsic::log10:
8594 case Intrinsic::modf:
8595 case Intrinsic::floor:
8596 case Intrinsic::ceil:
8597 case Intrinsic::trunc:
8598 case Intrinsic::rint:
8599 case Intrinsic::nearbyint:
8600 case Intrinsic::round:
8601 case Intrinsic::roundeven:
8602 case Intrinsic::lrint:
8603 case Intrinsic::llrint:
8604 case Intrinsic::fshl:
8605 case Intrinsic::fshr:
8606 case Intrinsic::frexp:
8607 case Intrinsic::get_active_lane_mask:
8608 return true;
8609 default:
8610 return false;
8611 }
8612}
8613
8614bool llvm::propagatesPoison(const Use &PoisonOp) {
8615 const Operator *I = cast<Operator>(PoisonOp.getUser());
8616 switch (I->getOpcode()) {
8617 case Instruction::Freeze:
8618 case Instruction::PHI:
8619 case Instruction::Invoke:
8620 return false;
8621 case Instruction::Select:
8622 return PoisonOp.getOperandNo() == 0;
8623 case Instruction::Call:
8624 if (auto *II = dyn_cast<IntrinsicInst>(I))
8625 return intrinsicPropagatesPoison(II->getIntrinsicID());
8626 return false;
8627 case Instruction::ICmp:
8628 case Instruction::FCmp:
8629 case Instruction::GetElementPtr:
8630 return true;
8631 default:
8633 return true;
8634
8635 // Be conservative and return false.
8636 return false;
8637 }
8638}
8639
8640/// Enumerates all operands of \p I that are guaranteed to not be undef or
8641/// poison. If the callback \p Handle returns true, stop processing and return
8642/// true. Otherwise, return false.
8643template <typename CallableT>
8645 const CallableT &Handle) {
8646 switch (I->getOpcode()) {
8647 case Instruction::Store:
8648 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8649 return true;
8650 break;
8651
8652 case Instruction::Load:
8653 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8654 return true;
8655 break;
8656
8657 // Since dereferenceable attribute imply noundef, atomic operations
8658 // also implicitly have noundef pointers too
8659 case Instruction::AtomicCmpXchg:
8661 return true;
8662 break;
8663
8664 case Instruction::AtomicRMW:
8665 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8666 return true;
8667 break;
8668
8669 case Instruction::Call:
8670 case Instruction::Invoke: {
8671 const CallBase *CB = cast<CallBase>(I);
8672 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8673 return true;
8674 for (unsigned i = 0; i < CB->arg_size(); ++i)
8675 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8676 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8677 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8678 Handle(CB->getArgOperand(i)))
8679 return true;
8680 break;
8681 }
8682 case Instruction::Ret:
8683 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8684 Handle(I->getOperand(0)))
8685 return true;
8686 break;
8687 case Instruction::Switch:
8688 if (Handle(cast<SwitchInst>(I)->getCondition()))
8689 return true;
8690 break;
8691 case Instruction::CondBr:
8692 if (Handle(cast<CondBrInst>(I)->getCondition()))
8693 return true;
8694 break;
8695 default:
8696 break;
8697 }
8698
8699 return false;
8700}
8701
8702/// Enumerates all operands of \p I that are guaranteed to not be poison.
8703template <typename CallableT>
8705 const CallableT &Handle) {
8706 if (handleGuaranteedWellDefinedOps(I, Handle))
8707 return true;
8708 switch (I->getOpcode()) {
8709 // Divisors of these operations are allowed to be partially undef.
8710 case Instruction::UDiv:
8711 case Instruction::SDiv:
8712 case Instruction::URem:
8713 case Instruction::SRem:
8714 return Handle(I->getOperand(1));
8715 default:
8716 return false;
8717 }
8718}
8719
8721 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8723 I, [&](const Value *V) { return KnownPoison.count(V); });
8724}
8725
8727 bool PoisonOnly) {
8728 // We currently only look for uses of values within the same basic
8729 // block, as that makes it easier to guarantee that the uses will be
8730 // executed given that Inst is executed.
8731 //
8732 // FIXME: Expand this to consider uses beyond the same basic block. To do
8733 // this, look out for the distinction between post-dominance and strong
8734 // post-dominance.
8735 const BasicBlock *BB = nullptr;
8737 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8738 BB = Inst->getParent();
8739 Begin = Inst->getIterator();
8740 Begin++;
8741 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8742 if (Arg->getParent()->isDeclaration())
8743 return false;
8744 BB = &Arg->getParent()->getEntryBlock();
8745 Begin = BB->begin();
8746 } else {
8747 return false;
8748 }
8749
8750 // Limit number of instructions we look at, to avoid scanning through large
8751 // blocks. The current limit is chosen arbitrarily.
8752 unsigned ScanLimit = 32;
8754
8755 if (!PoisonOnly) {
8756 // Since undef does not propagate eagerly, be conservative & just check
8757 // whether a value is directly passed to an instruction that must take
8758 // well-defined operands.
8759
8760 for (const auto &I : make_range(Begin, End)) {
8761 if (--ScanLimit == 0)
8762 break;
8763
8764 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8765 return WellDefinedOp == V;
8766 }))
8767 return true;
8768
8770 break;
8771 }
8772 return false;
8773 }
8774
8775 // Set of instructions that we have proved will yield poison if Inst
8776 // does.
8777 SmallPtrSet<const Value *, 16> YieldsPoison;
8779
8780 YieldsPoison.insert(V);
8781 Visited.insert(BB);
8782
8783 while (true) {
8784 for (const auto &I : make_range(Begin, End)) {
8785 if (--ScanLimit == 0)
8786 return false;
8787 if (mustTriggerUB(&I, YieldsPoison))
8788 return true;
8790 return false;
8791
8792 // If an operand is poison and propagates it, mark I as yielding poison.
8793 for (const Use &Op : I.operands()) {
8794 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8795 YieldsPoison.insert(&I);
8796 break;
8797 }
8798 }
8799
8800 // Special handling for select, which returns poison if its operand 0 is
8801 // poison (handled in the loop above) *or* if both its true/false operands
8802 // are poison (handled here).
8803 if (I.getOpcode() == Instruction::Select &&
8804 YieldsPoison.count(I.getOperand(1)) &&
8805 YieldsPoison.count(I.getOperand(2))) {
8806 YieldsPoison.insert(&I);
8807 }
8808 }
8809
8810 BB = BB->getSingleSuccessor();
8811 if (!BB || !Visited.insert(BB).second)
8812 break;
8813
8814 Begin = BB->getFirstNonPHIIt();
8815 End = BB->end();
8816 }
8817 return false;
8818}
8819
8821 return ::programUndefinedIfUndefOrPoison(Inst, false);
8822}
8823
8825 return ::programUndefinedIfUndefOrPoison(Inst, true);
8826}
8827
8828static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8829 if (FMF.noNaNs())
8830 return true;
8831
8832 if (auto *C = dyn_cast<ConstantFP>(V))
8833 return !C->isNaN();
8834
8835 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8836 if (!C->getElementType()->isFloatingPointTy())
8837 return false;
8838 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8839 if (C->getElementAsAPFloat(I).isNaN())
8840 return false;
8841 }
8842 return true;
8843 }
8844
8846 return true;
8847
8848 return false;
8849}
8850
8851static bool isKnownNonZero(const Value *V) {
8852 if (auto *C = dyn_cast<ConstantFP>(V))
8853 return !C->isZero();
8854
8855 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8856 if (!C->getElementType()->isFloatingPointTy())
8857 return false;
8858 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8859 if (C->getElementAsAPFloat(I).isZero())
8860 return false;
8861 }
8862 return true;
8863 }
8864
8865 return false;
8866}
8867
8868/// Match clamp pattern for float types without care about NaNs or signed zeros.
8869/// Given non-min/max outer cmp/select from the clamp pattern this
8870/// function recognizes if it can be substitued by a "canonical" min/max
8871/// pattern.
8873 Value *CmpLHS, Value *CmpRHS,
8874 Value *TrueVal, Value *FalseVal,
8875 Value *&LHS, Value *&RHS) {
8876 // Try to match
8877 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8878 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8879 // and return description of the outer Max/Min.
8880
8881 // First, check if select has inverse order:
8882 if (CmpRHS == FalseVal) {
8883 std::swap(TrueVal, FalseVal);
8884 Pred = CmpInst::getInversePredicate(Pred);
8885 }
8886
8887 // Assume success now. If there's no match, callers should not use these anyway.
8888 LHS = TrueVal;
8889 RHS = FalseVal;
8890
8891 const APFloat *FC1;
8892 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8893 return {SPF_UNKNOWN, SPNB_NA, false};
8894
8895 const APFloat *FC2;
8896 switch (Pred) {
8897 case CmpInst::FCMP_OLT:
8898 case CmpInst::FCMP_OLE:
8899 case CmpInst::FCMP_ULT:
8900 case CmpInst::FCMP_ULE:
8901 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8902 *FC1 < *FC2)
8903 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8904 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8905 *FC1 < *FC2)
8906 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8907 break;
8908 case CmpInst::FCMP_OGT:
8909 case CmpInst::FCMP_OGE:
8910 case CmpInst::FCMP_UGT:
8911 case CmpInst::FCMP_UGE:
8912 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8913 *FC1 > *FC2)
8914 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8915 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8916 *FC1 > *FC2)
8917 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8918 break;
8919 default:
8920 break;
8921 }
8922
8923 return {SPF_UNKNOWN, SPNB_NA, false};
8924}
8925
8926/// Recognize variations of:
8927/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8929 Value *CmpLHS, Value *CmpRHS,
8930 Value *TrueVal, Value *FalseVal) {
8931 // Swap the select operands and predicate to match the patterns below.
8932 if (CmpRHS != TrueVal) {
8933 Pred = ICmpInst::getSwappedPredicate(Pred);
8934 std::swap(TrueVal, FalseVal);
8935 }
8936 const APInt *C1;
8937 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8938 const APInt *C2;
8939 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8940 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8941 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8942 return {SPF_SMAX, SPNB_NA, false};
8943
8944 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8945 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8946 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8947 return {SPF_SMIN, SPNB_NA, false};
8948
8949 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8950 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8951 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8952 return {SPF_UMAX, SPNB_NA, false};
8953
8954 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8955 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8956 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8957 return {SPF_UMIN, SPNB_NA, false};
8958 }
8959 return {SPF_UNKNOWN, SPNB_NA, false};
8960}
8961
8962/// If the input value is the result of a 'not' op, constant integer, or vector
8963/// splat of a constant integer, return the bitwise-not source value.
8964/// TODO: This could be extended to handle non-splat vector integer constants.
8966 Value *NotV;
8967 if (match(V, m_Not(m_Value(NotV))))
8968 return NotV;
8969
8970 const APInt *C;
8971 if (match(V, m_APInt(C)))
8972 return ConstantInt::get(V->getType(), ~(*C));
8973
8974 return nullptr;
8975}
8976
8977/// Match non-obvious integer minimum and maximum sequences.
8979 Value *CmpRHS, Value *TrueVal,
8980 Value *FalseVal, Value *&LHS,
8981 Value *&RHS) {
8982 // Assume success. If there's no match, callers should not use these anyway.
8983 LHS = TrueVal;
8984 RHS = FalseVal;
8985
8986 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8988 return SPR;
8989
8990 // Look through 'not' ops to find disguised min/max.
8991 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8992 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8993 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8994 switch (Pred) {
8995 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8996 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8997 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8998 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8999 default: break;
9000 }
9001 }
9002
9003 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9004 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9005 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9006 switch (Pred) {
9007 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9008 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9009 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9010 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9011 default: break;
9012 }
9013 }
9014
9015 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9016 return {SPF_UNKNOWN, SPNB_NA, false};
9017
9018 const APInt *C1;
9019 if (!match(CmpRHS, m_APInt(C1)))
9020 return {SPF_UNKNOWN, SPNB_NA, false};
9021
9022 // An unsigned min/max can be written with a signed compare.
9023 const APInt *C2;
9024 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9025 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9026 // Is the sign bit set?
9027 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9028 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9029 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9030 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9031
9032 // Is the sign bit clear?
9033 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9034 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9035 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9036 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9037 }
9038
9039 return {SPF_UNKNOWN, SPNB_NA, false};
9040}
9041
9042bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9043 bool AllowPoison) {
9044 assert(X && Y && "Invalid operand");
9045
9046 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9047 if (!match(X, m_Neg(m_Specific(Y))))
9048 return false;
9049
9050 auto *BO = cast<BinaryOperator>(X);
9051 if (NeedNSW && !BO->hasNoSignedWrap())
9052 return false;
9053
9054 auto *Zero = cast<Constant>(BO->getOperand(0));
9055 if (!AllowPoison && !Zero->isNullValue())
9056 return false;
9057
9058 return true;
9059 };
9060
9061 // X = -Y or Y = -X
9062 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9063 return true;
9064
9065 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9066 Value *A, *B;
9067 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9068 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9069 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9071}
9072
9073bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9074 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9075 Value *A, *B, *C;
9076 CmpPredicate Pred1, Pred2;
9077 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9078 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9079 return false;
9080
9081 // They must both have samesign flag or not.
9082 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9083 return false;
9084
9085 if (B == C)
9086 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9087
9088 // Try to infer the relationship from constant ranges.
9089 const APInt *RHSC1, *RHSC2;
9090 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9091 return false;
9092
9093 // Sign bits of two RHSCs should match.
9094 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9095 return false;
9096
9097 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9098 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9099
9100 return CR1.inverse() == CR2;
9101}
9102
9104 SelectPatternNaNBehavior NaNBehavior,
9105 bool Ordered) {
9106 switch (Pred) {
9107 default:
9108 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9109 case ICmpInst::ICMP_UGT:
9110 case ICmpInst::ICMP_UGE:
9111 return {SPF_UMAX, SPNB_NA, false};
9112 case ICmpInst::ICMP_SGT:
9113 case ICmpInst::ICMP_SGE:
9114 return {SPF_SMAX, SPNB_NA, false};
9115 case ICmpInst::ICMP_ULT:
9116 case ICmpInst::ICMP_ULE:
9117 return {SPF_UMIN, SPNB_NA, false};
9118 case ICmpInst::ICMP_SLT:
9119 case ICmpInst::ICMP_SLE:
9120 return {SPF_SMIN, SPNB_NA, false};
9121 case FCmpInst::FCMP_UGT:
9122 case FCmpInst::FCMP_UGE:
9123 case FCmpInst::FCMP_OGT:
9124 case FCmpInst::FCMP_OGE:
9125 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9126 case FCmpInst::FCMP_ULT:
9127 case FCmpInst::FCMP_ULE:
9128 case FCmpInst::FCMP_OLT:
9129 case FCmpInst::FCMP_OLE:
9130 return {SPF_FMINNUM, NaNBehavior, Ordered};
9131 }
9132}
9133
9134std::optional<std::pair<CmpPredicate, Constant *>>
9137 "Only for relational integer predicates.");
9138 if (isa<UndefValue>(C))
9139 return std::nullopt;
9140
9141 Type *Type = C->getType();
9142 bool IsSigned = ICmpInst::isSigned(Pred);
9143
9145 bool WillIncrement =
9146 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9147
9148 // Check if the constant operand can be safely incremented/decremented
9149 // without overflowing/underflowing.
9150 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9151 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9152 return false;
9153
9154 if (!Pred.hasSameSign())
9155 return true;
9156
9157 // Crossing the corresponding boundary in the other ordering changes the
9158 // sign bit, and therefore changes the poison domain.
9159 return WillIncrement ? !C->isMaxValue(!IsSigned)
9160 : !C->isMinValue(!IsSigned);
9161 };
9162
9163 Constant *SafeReplacementConstant = nullptr;
9164 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9165 // Bail out if the constant can't be safely incremented/decremented.
9166 if (!ConstantIsOk(CI))
9167 return std::nullopt;
9168 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9169 unsigned NumElts = FVTy->getNumElements();
9170 for (unsigned i = 0; i != NumElts; ++i) {
9171 Constant *Elt = C->getAggregateElement(i);
9172 if (!Elt)
9173 return std::nullopt;
9174
9175 if (isa<UndefValue>(Elt))
9176 continue;
9177
9178 // Bail out if we can't determine if this constant is min/max or if we
9179 // know that this constant is min/max.
9180 auto *CI = dyn_cast<ConstantInt>(Elt);
9181 if (!CI || !ConstantIsOk(CI))
9182 return std::nullopt;
9183
9184 if (!SafeReplacementConstant)
9185 SafeReplacementConstant = CI;
9186 }
9187 } else if (isa<VectorType>(C->getType())) {
9188 // Handle scalable splat
9189 Value *SplatC = C->getSplatValue();
9190 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9191 // Bail out if the constant can't be safely incremented/decremented.
9192 if (!CI || !ConstantIsOk(CI))
9193 return std::nullopt;
9194 } else {
9195 // ConstantExpr?
9196 return std::nullopt;
9197 }
9198
9199 // It may not be safe to change a compare predicate in the presence of
9200 // undefined elements, so replace those elements with the first safe constant
9201 // that we found.
9202 // TODO: in case of poison, it is safe; let's replace undefs only.
9203 if (C->containsUndefOrPoisonElement()) {
9204 assert(SafeReplacementConstant && "Replacement constant not set");
9205 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9206 }
9207
9209 Pred.hasSameSign());
9210
9211 // Increment or decrement the constant.
9212 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9213 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9214
9215 return std::make_pair(NewPred, NewC);
9216}
9217
9219 FastMathFlags FMF, Value *CmpLHS,
9220 Value *CmpRHS, Value *TrueVal,
9221 Value *FalseVal, Value *&LHS,
9222 Value *&RHS) {
9223 if (CmpInst::isFPPredicate(Pred)) {
9224 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9225 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9226 // purpose of identifying min/max. Disregard vector constants with undefined
9227 // elements because those can not be back-propagated for analysis.
9228 Value *OutputZeroVal = nullptr;
9229 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9230 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9231 OutputZeroVal = TrueVal;
9232 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9233 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9234 OutputZeroVal = FalseVal;
9235
9236 if (OutputZeroVal) {
9237 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9238 CmpLHS = OutputZeroVal;
9239 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9240 CmpRHS = OutputZeroVal;
9241 }
9242 }
9243
9244 LHS = CmpLHS;
9245 RHS = CmpRHS;
9246
9247 // Signed zero may return inconsistent results between implementations.
9248 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9249 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9250 // Therefore, we behave conservatively and only proceed if at least one of the
9251 // operands is known to not be zero or if we don't care about signed zero.
9252 if (CmpInst::isFPPredicate(Pred)) {
9253 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9254 !isKnownNonZero(CmpRHS))
9255 return {SPF_UNKNOWN, SPNB_NA, false};
9256 }
9257
9258 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9259 bool Ordered = false;
9260
9261 // When given one NaN and one non-NaN input:
9262 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9263 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9264 // ordered comparison fails), which could be NaN or non-NaN.
9265 // so here we discover exactly what NaN behavior is required/accepted.
9266 if (CmpInst::isFPPredicate(Pred)) {
9267 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9268 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9269
9270 if (LHSSafe && RHSSafe) {
9271 // Both operands are known non-NaN.
9272 NaNBehavior = SPNB_RETURNS_ANY;
9273 Ordered = CmpInst::isOrdered(Pred);
9274 } else if (CmpInst::isOrdered(Pred)) {
9275 // An ordered comparison will return false when given a NaN, so it
9276 // returns the RHS.
9277 Ordered = true;
9278 if (LHSSafe)
9279 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9280 NaNBehavior = SPNB_RETURNS_NAN;
9281 else if (RHSSafe)
9282 NaNBehavior = SPNB_RETURNS_OTHER;
9283 else
9284 // Completely unsafe.
9285 return {SPF_UNKNOWN, SPNB_NA, false};
9286 } else {
9287 Ordered = false;
9288 // An unordered comparison will return true when given a NaN, so it
9289 // returns the LHS.
9290 if (LHSSafe)
9291 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9292 NaNBehavior = SPNB_RETURNS_OTHER;
9293 else if (RHSSafe)
9294 NaNBehavior = SPNB_RETURNS_NAN;
9295 else
9296 // Completely unsafe.
9297 return {SPF_UNKNOWN, SPNB_NA, false};
9298 }
9299 }
9300
9301 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9302 std::swap(CmpLHS, CmpRHS);
9303 Pred = CmpInst::getSwappedPredicate(Pred);
9304 if (NaNBehavior == SPNB_RETURNS_NAN)
9305 NaNBehavior = SPNB_RETURNS_OTHER;
9306 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9307 NaNBehavior = SPNB_RETURNS_NAN;
9308 Ordered = !Ordered;
9309 }
9310
9311 // ([if]cmp X, Y) ? X : Y
9312 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9313 return getSelectPattern(Pred, NaNBehavior, Ordered);
9314
9315 if (isKnownNegation(TrueVal, FalseVal)) {
9316 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9317 // match against either LHS or sign-preserving operations on LHS, like
9318 // sext(LHS), or binary ops that do not wrap in signed sense.
9319 auto CmpLHSOrSExt =
9320 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9321 auto MaybeSExtOrMulCmpLHS =
9322 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9323 m_NSWShl(CmpLHSOrSExt, m_Value()));
9324 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9325 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9326 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9327 // Set the return values. If the compare uses the negated value (-X >s 0),
9328 // swap the return values because the negated value is always 'RHS'.
9329 LHS = TrueVal;
9330 RHS = FalseVal;
9331 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9332 std::swap(LHS, RHS);
9333
9334 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9335 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9336 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9337 return {SPF_ABS, SPNB_NA, false};
9338
9339 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9340 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9341 return {SPF_ABS, SPNB_NA, false};
9342
9343 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9344 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9345 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9346 return {SPF_NABS, SPNB_NA, false};
9347 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9348 // Set the return values. If the compare uses the negated value (-X >s 0),
9349 // swap the return values because the negated value is always 'RHS'.
9350 LHS = FalseVal;
9351 RHS = TrueVal;
9352 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9353 std::swap(LHS, RHS);
9354
9355 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9356 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9357 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9358 return {SPF_NABS, SPNB_NA, false};
9359
9360 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9361 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9362 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9363 return {SPF_ABS, SPNB_NA, false};
9364 }
9365 }
9366
9367 if (CmpInst::isIntPredicate(Pred))
9368 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9369
9370 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9371 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9372 // semantics than minNum. Be conservative in such case.
9373 if (NaNBehavior != SPNB_RETURNS_ANY ||
9374 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9375 !isKnownNonZero(CmpRHS)))
9376 return {SPF_UNKNOWN, SPNB_NA, false};
9377
9378 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9379}
9380
9382 Instruction::CastOps *CastOp) {
9383 const DataLayout &DL = CmpI->getDataLayout();
9384
9385 Constant *CastedTo = nullptr;
9386 switch (*CastOp) {
9387 case Instruction::ZExt:
9388 if (CmpI->isUnsigned())
9389 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9390 break;
9391 case Instruction::SExt:
9392 if (CmpI->isSigned())
9393 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9394 break;
9395 case Instruction::Trunc:
9396 Constant *CmpConst;
9397 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9398 CmpConst->getType() == SrcTy) {
9399 // Here we have the following case:
9400 //
9401 // %cond = cmp iN %x, CmpConst
9402 // %tr = trunc iN %x to iK
9403 // %narrowsel = select i1 %cond, iK %t, iK C
9404 //
9405 // We can always move trunc after select operation:
9406 //
9407 // %cond = cmp iN %x, CmpConst
9408 // %widesel = select i1 %cond, iN %x, iN CmpConst
9409 // %tr = trunc iN %widesel to iK
9410 //
9411 // Note that C could be extended in any way because we don't care about
9412 // upper bits after truncation. It can't be abs pattern, because it would
9413 // look like:
9414 //
9415 // select i1 %cond, x, -x.
9416 //
9417 // So only min/max pattern could be matched. Such match requires widened C
9418 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9419 // CmpConst == C is checked below.
9420 CastedTo = CmpConst;
9421 } else {
9422 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9423 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9424 }
9425 break;
9426 case Instruction::FPTrunc:
9427 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9428 break;
9429 case Instruction::FPExt:
9430 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9431 break;
9432 case Instruction::FPToUI:
9433 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9434 break;
9435 case Instruction::FPToSI:
9436 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9437 break;
9438 case Instruction::UIToFP:
9439 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9440 break;
9441 case Instruction::SIToFP:
9442 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9443 break;
9444 default:
9445 break;
9446 }
9447
9448 if (!CastedTo)
9449 return nullptr;
9450
9451 // Make sure the cast doesn't lose any information.
9452 Constant *CastedBack =
9453 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9454 if (CastedBack && CastedBack != C)
9455 return nullptr;
9456
9457 return CastedTo;
9458}
9459
9460/// Helps to match a select pattern in case of a type mismatch.
9461///
9462/// The function processes the case when type of true and false values of a
9463/// select instruction differs from type of the cmp instruction operands because
9464/// of a cast instruction. The function checks if it is legal to move the cast
9465/// operation after "select". If yes, it returns the new second value of
9466/// "select" (with the assumption that cast is moved):
9467/// 1. As operand of cast instruction when both values of "select" are same cast
9468/// instructions.
9469/// 2. As restored constant (by applying reverse cast operation) when the first
9470/// value of the "select" is a cast operation and the second value is a
9471/// constant. It is implemented in lookThroughCastConst().
9472/// 3. As one operand is cast instruction and the other is not. The operands in
9473/// sel(cmp) are in different type integer.
9474/// NOTE: We return only the new second value because the first value could be
9475/// accessed as operand of cast instruction.
9477 Instruction::CastOps *CastOp) {
9478 auto *Cast1 = dyn_cast<CastInst>(V1);
9479 if (!Cast1)
9480 return nullptr;
9481
9482 *CastOp = Cast1->getOpcode();
9483 Type *SrcTy = Cast1->getSrcTy();
9484 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9485 // If V1 and V2 are both the same cast from the same type, look through V1.
9486 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9487 return Cast2->getOperand(0);
9488 return nullptr;
9489 }
9490
9491 auto *C = dyn_cast<Constant>(V2);
9492 if (C)
9493 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9494
9495 Value *CastedTo = nullptr;
9496 if (*CastOp == Instruction::Trunc) {
9497 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9498 // Here we have the following case:
9499 // %y_ext = sext iK %y to iN
9500 // %cond = cmp iN %x, %y_ext
9501 // %tr = trunc iN %x to iK
9502 // %narrowsel = select i1 %cond, iK %tr, iK %y
9503 //
9504 // We can always move trunc after select operation:
9505 // %y_ext = sext iK %y to iN
9506 // %cond = cmp iN %x, %y_ext
9507 // %widesel = select i1 %cond, iN %x, iN %y_ext
9508 // %tr = trunc iN %widesel to iK
9509 assert(V2->getType() == Cast1->getType() &&
9510 "V2 and Cast1 should be the same type.");
9511 CastedTo = CmpI->getOperand(1);
9512 }
9513 }
9514
9515 return CastedTo;
9516}
9518 Instruction::CastOps *CastOp) {
9520 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9521
9522 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9523 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9524
9525 Value *TrueVal = SI->getTrueValue();
9526 Value *FalseVal = SI->getFalseValue();
9527
9529 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
9530}
9531
9533 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9534 FastMathFlags FMF, Instruction::CastOps *CastOp) {
9535 CmpInst::Predicate Pred = CmpI->getPredicate();
9536 Value *CmpLHS = CmpI->getOperand(0);
9537 Value *CmpRHS = CmpI->getOperand(1);
9538 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9539 FMF.setNoNaNs();
9540
9541 // Bail out early.
9542 if (CmpI->isEquality())
9543 return {SPF_UNKNOWN, SPNB_NA, false};
9544
9545 // Deal with type mismatches.
9546 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9547 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9548 // If this is a potential fmin/fmax with a cast to integer, then ignore
9549 // -0.0 because there is no corresponding integer value.
9550 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9551 FMF.setNoSignedZeros();
9552 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9553 cast<CastInst>(TrueVal)->getOperand(0), C,
9554 LHS, RHS);
9555 }
9556 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9557 // If this is a potential fmin/fmax with a cast to integer, then ignore
9558 // -0.0 because there is no corresponding integer value.
9559 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9560 FMF.setNoSignedZeros();
9561 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
9562 cast<CastInst>(FalseVal)->getOperand(0), LHS,
9563 RHS);
9564 }
9565 }
9566 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
9567 RHS);
9568}
9569
9571 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9572 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9573 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9574 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9575 if (SPF == SPF_FMINNUM)
9576 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9577 if (SPF == SPF_FMAXNUM)
9578 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9579 llvm_unreachable("unhandled!");
9580}
9581
9583 switch (SPF) {
9585 return Intrinsic::umin;
9587 return Intrinsic::umax;
9589 return Intrinsic::smin;
9591 return Intrinsic::smax;
9592 default:
9593 llvm_unreachable("Unexpected SPF");
9594 }
9595}
9596
9598 if (SPF == SPF_SMIN) return SPF_SMAX;
9599 if (SPF == SPF_UMIN) return SPF_UMAX;
9600 if (SPF == SPF_SMAX) return SPF_SMIN;
9601 if (SPF == SPF_UMAX) return SPF_UMIN;
9602 llvm_unreachable("unhandled!");
9603}
9604
9606 switch (MinMaxID) {
9607 case Intrinsic::smax: return Intrinsic::smin;
9608 case Intrinsic::smin: return Intrinsic::smax;
9609 case Intrinsic::umax: return Intrinsic::umin;
9610 case Intrinsic::umin: return Intrinsic::umax;
9611 // Please note that next four intrinsics may produce the same result for
9612 // original and inverted case even if X != Y due to NaN is handled specially.
9613 case Intrinsic::maximum: return Intrinsic::minimum;
9614 case Intrinsic::minimum: return Intrinsic::maximum;
9615 case Intrinsic::maxnum: return Intrinsic::minnum;
9616 case Intrinsic::minnum: return Intrinsic::maxnum;
9617 case Intrinsic::maximumnum:
9618 return Intrinsic::minimumnum;
9619 case Intrinsic::minimumnum:
9620 return Intrinsic::maximumnum;
9621 default: llvm_unreachable("Unexpected intrinsic");
9622 }
9623}
9624
9626 switch (SPF) {
9629 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9630 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9631 default: llvm_unreachable("Unexpected flavor");
9632 }
9633}
9634
9635std::pair<Intrinsic::ID, bool>
9637 // Check if VL contains select instructions that can be folded into a min/max
9638 // vector intrinsic and return the intrinsic if it is possible.
9639 // TODO: Support floating point min/max.
9640 bool AllCmpSingleUse = true;
9641 SelectPatternResult SelectPattern;
9642 SelectPattern.Flavor = SPF_UNKNOWN;
9643 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9644 Value *LHS, *RHS;
9645 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9646 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9647 return false;
9648 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9649 SelectPattern.Flavor != CurrentPattern.Flavor)
9650 return false;
9651 SelectPattern = CurrentPattern;
9652 AllCmpSingleUse &=
9654 return true;
9655 })) {
9656 switch (SelectPattern.Flavor) {
9657 case SPF_SMIN:
9658 return {Intrinsic::smin, AllCmpSingleUse};
9659 case SPF_UMIN:
9660 return {Intrinsic::umin, AllCmpSingleUse};
9661 case SPF_SMAX:
9662 return {Intrinsic::smax, AllCmpSingleUse};
9663 case SPF_UMAX:
9664 return {Intrinsic::umax, AllCmpSingleUse};
9665 case SPF_FMAXNUM:
9666 return {Intrinsic::maxnum, AllCmpSingleUse};
9667 case SPF_FMINNUM:
9668 return {Intrinsic::minnum, AllCmpSingleUse};
9669 default:
9670 llvm_unreachable("unexpected select pattern flavor");
9671 }
9672 }
9673 return {Intrinsic::not_intrinsic, false};
9674}
9675
9676template <typename InstTy>
9677static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9678 Value *&Init, Value *&OtherOp) {
9679 // Handle the case of a simple two-predecessor recurrence PHI.
9680 // There's a lot more that could theoretically be done here, but
9681 // this is sufficient to catch some interesting cases.
9682 // TODO: Expand list -- gep, uadd.sat etc.
9683 if (PN->getNumIncomingValues() != 2)
9684 return false;
9685
9686 for (unsigned I = 0; I != 2; ++I) {
9687 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9688 Operation && Operation->getNumOperands() >= 2) {
9689 Value *LHS = Operation->getOperand(0);
9690 Value *RHS = Operation->getOperand(1);
9691 if (LHS != PN && RHS != PN)
9692 continue;
9693
9694 Inst = Operation;
9695 Init = PN->getIncomingValue(!I);
9696 OtherOp = (LHS == PN) ? RHS : LHS;
9697 return true;
9698 }
9699 }
9700 return false;
9701}
9702
9703template <typename InstTy>
9704static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9705 Value *&Init, Value *&OtherOp0,
9706 Value *&OtherOp1) {
9707 if (PN->getNumIncomingValues() != 2)
9708 return false;
9709
9710 for (unsigned I = 0; I != 2; ++I) {
9711 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9712 Operation && Operation->getNumOperands() >= 3) {
9713 Value *Op0 = Operation->getOperand(0);
9714 Value *Op1 = Operation->getOperand(1);
9715 Value *Op2 = Operation->getOperand(2);
9716
9717 if (Op0 != PN && Op1 != PN && Op2 != PN)
9718 continue;
9719
9720 Inst = Operation;
9721 Init = PN->getIncomingValue(!I);
9722 if (Op0 == PN) {
9723 OtherOp0 = Op1;
9724 OtherOp1 = Op2;
9725 } else if (Op1 == PN) {
9726 OtherOp0 = Op0;
9727 OtherOp1 = Op2;
9728 } else {
9729 OtherOp0 = Op0;
9730 OtherOp1 = Op1;
9731 }
9732 return true;
9733 }
9734 }
9735 return false;
9736}
9738 Value *&Start, Value *&Step) {
9739 // We try to match a recurrence of the form:
9740 // %iv = [Start, %entry], [%iv.next, %backedge]
9741 // %iv.next = binop %iv, Step
9742 // Or:
9743 // %iv = [Start, %entry], [%iv.next, %backedge]
9744 // %iv.next = binop Step, %iv
9745 return matchTwoInputRecurrence(P, BO, Start, Step);
9746}
9747
9749 Value *&Start, Value *&Step) {
9750 BinaryOperator *BO = nullptr;
9751 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9752 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9753}
9754
9756 PHINode *&P, Value *&Init,
9757 Value *&OtherOp) {
9758 // Binary intrinsics only supported for now.
9759 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9760 I->getType() != I->getArgOperand(1)->getType())
9761 return false;
9762
9763 IntrinsicInst *II = nullptr;
9764 P = dyn_cast<PHINode>(I->getArgOperand(0));
9765 if (!P)
9766 P = dyn_cast<PHINode>(I->getArgOperand(1));
9767
9768 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9769}
9770
9772 PHINode *&P, Value *&Init,
9773 Value *&OtherOp0,
9774 Value *&OtherOp1) {
9775 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9776 I->getType() != I->getArgOperand(1)->getType() ||
9777 I->getType() != I->getArgOperand(2)->getType())
9778 return false;
9779 IntrinsicInst *II = nullptr;
9780 P = dyn_cast<PHINode>(I->getArgOperand(0));
9781 if (!P) {
9782 P = dyn_cast<PHINode>(I->getArgOperand(1));
9783 if (!P)
9784 P = dyn_cast<PHINode>(I->getArgOperand(2));
9785 }
9786 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9787 II == I;
9788}
9789
9790/// Return true if "icmp Pred LHS RHS" is always true.
9792 const Value *RHS) {
9793 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9794 return true;
9795
9796 switch (Pred) {
9797 default:
9798 return false;
9799
9800 case CmpInst::ICMP_SLE: {
9801 const APInt *C;
9802
9803 // LHS s<= LHS +_{nsw} C if C >= 0
9804 // LHS s<= LHS | C if C >= 0
9805 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9807 return !C->isNegative();
9808
9809 // LHS s<= smax(LHS, V) for any V
9811 return true;
9812
9813 // smin(RHS, V) s<= RHS for any V
9815 return true;
9816
9817 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9818 const Value *X;
9819 const APInt *CLHS, *CRHS;
9820 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9822 return CLHS->sle(*CRHS);
9823
9824 return false;
9825 }
9826
9827 case CmpInst::ICMP_ULE: {
9828 // LHS u<= LHS +_{nuw} V for any V
9829 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9831 return true;
9832
9833 // LHS u<= LHS | V for any V
9834 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9835 return true;
9836
9837 // LHS u<= umax(LHS, V) for any V
9839 return true;
9840
9841 // RHS >> V u<= RHS for any V
9842 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9843 return true;
9844
9845 // RHS u/ C_ugt_1 u<= RHS
9846 const APInt *C;
9847 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9848 return true;
9849
9850 // RHS & V u<= RHS for any V
9852 return true;
9853
9854 // umin(RHS, V) u<= RHS for any V
9856 return true;
9857
9858 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9859 const Value *X;
9860 const APInt *CLHS, *CRHS;
9861 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9863 return CLHS->ule(*CRHS);
9864
9865 return false;
9866 }
9867 }
9868}
9869
9870/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9871/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9872static std::optional<bool>
9874 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9875 switch (Pred) {
9876 default:
9877 return std::nullopt;
9878
9879 case CmpInst::ICMP_SLT:
9880 case CmpInst::ICMP_SLE:
9881 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9883 return true;
9884 return std::nullopt;
9885
9886 case CmpInst::ICMP_SGT:
9887 case CmpInst::ICMP_SGE:
9888 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9890 return true;
9891 return std::nullopt;
9892
9893 case CmpInst::ICMP_ULT:
9894 case CmpInst::ICMP_ULE:
9895 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9897 return true;
9898 return std::nullopt;
9899
9900 case CmpInst::ICMP_UGT:
9901 case CmpInst::ICMP_UGE:
9902 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9904 return true;
9905 return std::nullopt;
9906 }
9907}
9908
9909/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9910/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9911/// Otherwise, return std::nullopt if we can't infer anything.
9912static std::optional<bool>
9914 CmpPredicate RPred, const ConstantRange &RCR) {
9915 auto CRImpliesPred = [&](ConstantRange CR,
9916 CmpInst::Predicate Pred) -> std::optional<bool> {
9917 // If all true values for lhs and true for rhs, lhs implies rhs
9918 if (CR.icmp(Pred, RCR))
9919 return true;
9920
9921 // If there is no overlap, lhs implies not rhs
9922 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9923 return false;
9924
9925 return std::nullopt;
9926 };
9927 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9928 RPred))
9929 return Res;
9930 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9932 : LPred.dropSameSign();
9934 : RPred.dropSameSign();
9935 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9936 RPred);
9937 }
9938 return std::nullopt;
9939}
9940
9941/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9942/// is true. Return false if LHS implies RHS is false. Otherwise, return
9943/// std::nullopt if we can't infer anything.
9944static std::optional<bool>
9945isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9946 CmpPredicate RPred, const Value *R0, const Value *R1,
9947 const DataLayout &DL, bool LHSIsTrue) {
9948 // The rest of the logic assumes the LHS condition is true. If that's not the
9949 // case, invert the predicate to make it so.
9950 if (!LHSIsTrue)
9951 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9952
9953 // We can have non-canonical operands, so try to normalize any common operand
9954 // to L0/R0.
9955 if (L0 == R1) {
9956 std::swap(R0, R1);
9957 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9958 }
9959 if (R0 == L1) {
9960 std::swap(L0, L1);
9961 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9962 }
9963 if (L1 == R1) {
9964 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9965 if (L0 != R0 || match(L0, m_ImmConstant())) {
9966 std::swap(L0, L1);
9967 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9968 std::swap(R0, R1);
9969 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9970 }
9971 }
9972
9973 // See if we can infer anything if operand-0 matches and we have at least one
9974 // constant.
9975 const APInt *Unused;
9976 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9977 // Potential TODO: We could also further use the constant range of L0/R0 to
9978 // further constraint the constant ranges. At the moment this leads to
9979 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9980 // C1` (see discussion: D58633).
9981 SimplifyQuery SQ(DL);
9986
9987 // Even if L1/R1 are not both constant, we can still sometimes deduce
9988 // relationship from a single constant. For example X u> Y implies X != 0.
9989 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9990 return R;
9991 // If both L1/R1 were exact constant ranges and we didn't get anything
9992 // here, we won't be able to deduce this.
9993 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9994 return std::nullopt;
9995 }
9996
9997 // Can we infer anything when the two compares have matching operands?
9998 if (L0 == R0 && L1 == R1)
9999 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10000
10001 // It only really makes sense in the context of signed comparison for "X - Y
10002 // must be positive if X >= Y and no overflow".
10003 // Take SGT as an example: L0:x > L1:y and C >= 0
10004 // ==> R0:(x -nsw y) < R1:(-C) is false
10005 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10006 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10007 SignedLPred == ICmpInst::ICMP_SGE) &&
10008 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10009 if (match(R1, m_NonPositive()) &&
10010 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10011 return false;
10012 }
10013
10014 // Take SLT as an example: L0:x < L1:y and C <= 0
10015 // ==> R0:(x -nsw y) < R1:(-C) is true
10016 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10017 SignedLPred == ICmpInst::ICMP_SLE) &&
10018 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10019 if (match(R1, m_NonNegative()) &&
10020 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10021 return true;
10022 }
10023
10024 // a - b == NonZero -> a != b
10025 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10026 const APInt *L1C;
10027 Value *A, *B;
10028 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10029 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10030 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10031 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10036 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10037 }
10038
10039 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10040 if (L0 == R0 &&
10041 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10042 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10043 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10044 return CmpPredicate::getMatching(LPred, RPred).has_value();
10045
10046 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10047 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10048
10049 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10050 // Example: L0 u< 13 => (L0 & 16) == 0
10051 const APInt *LC, *RC, *MaskC;
10052 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10053 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10055 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10056 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10057 return true;
10058 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10059 ConstantRange(*RC)))
10060 return false;
10061 }
10062
10063 return std::nullopt;
10064}
10065
10066/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10067/// is true. Return false if LHS implies RHS is false. Otherwise, return
10068/// std::nullopt if we can't infer anything.
10069static std::optional<bool>
10071 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10072 const DataLayout &DL, bool LHSIsTrue) {
10073 // The rest of the logic assumes the LHS condition is true. If that's not the
10074 // case, invert the predicate to make it so.
10075 if (!LHSIsTrue)
10076 LPred = FCmpInst::getInversePredicate(LPred);
10077
10078 // We can have non-canonical operands, so try to normalize any common operand
10079 // to L0/R0.
10080 if (L0 == R1) {
10081 std::swap(R0, R1);
10082 RPred = FCmpInst::getSwappedPredicate(RPred);
10083 }
10084 if (R0 == L1) {
10085 std::swap(L0, L1);
10086 LPred = FCmpInst::getSwappedPredicate(LPred);
10087 }
10088 if (L1 == R1) {
10089 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10090 if (L0 != R0 || match(L0, m_ImmConstant())) {
10091 std::swap(L0, L1);
10092 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10093 std::swap(R0, R1);
10094 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10095 }
10096 }
10097
10098 // Can we infer anything when the two compares have matching operands?
10099 if (L0 == R0 && L1 == R1) {
10100 if ((LPred & RPred) == LPred)
10101 return true;
10102 if ((LPred & ~RPred) == LPred)
10103 return false;
10104 }
10105
10106 // See if we can infer anything if operand-0 matches and we have at least one
10107 // constant.
10108 const APFloat *L1C, *R1C;
10109 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10110 if (std::optional<ConstantFPRange> DomCR =
10112 if (std::optional<ConstantFPRange> ImpliedCR =
10114 if (ImpliedCR->contains(*DomCR))
10115 return true;
10116 }
10117 if (std::optional<ConstantFPRange> ImpliedCR =
10119 FCmpInst::getInversePredicate(RPred), *R1C)) {
10120 if (ImpliedCR->contains(*DomCR))
10121 return false;
10122 }
10123 }
10124 }
10125
10126 return std::nullopt;
10127}
10128
10129/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10130/// false. Otherwise, return std::nullopt if we can't infer anything. We
10131/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10132/// instruction.
10133static std::optional<bool>
10135 const Value *RHSOp0, const Value *RHSOp1,
10136 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10137 // The LHS must be an 'or', 'and', or a 'select' instruction.
10138 assert((LHS->getOpcode() == Instruction::And ||
10139 LHS->getOpcode() == Instruction::Or ||
10140 LHS->getOpcode() == Instruction::Select) &&
10141 "Expected LHS to be 'and', 'or', or 'select'.");
10142
10143 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10144
10145 // If the result of an 'or' is false, then we know both legs of the 'or' are
10146 // false. Similarly, if the result of an 'and' is true, then we know both
10147 // legs of the 'and' are true.
10148 const Value *ALHS, *ARHS;
10149 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10150 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10151 // FIXME: Make this non-recursion.
10152 if (std::optional<bool> Implication = isImpliedCondition(
10153 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10154 return Implication;
10155 if (std::optional<bool> Implication = isImpliedCondition(
10156 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10157 return Implication;
10158 return std::nullopt;
10159 }
10160 return std::nullopt;
10161}
10162
10163std::optional<bool>
10165 const Value *RHSOp0, const Value *RHSOp1,
10166 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10167 // Bail out when we hit the limit.
10169 return std::nullopt;
10170
10171 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10172 // example.
10173 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10174 return std::nullopt;
10175
10176 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10177 "Expected integer type only!");
10178
10179 // Match not
10180 if (match(LHS, m_Not(m_Value(LHS))))
10181 LHSIsTrue = !LHSIsTrue;
10182
10183 // Both LHS and RHS are icmps.
10184 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10185 CmpPredicate LHSPred;
10186 Value *LHSOp0, *LHSOp1;
10187 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10188 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10189 RHSOp1, DL, LHSIsTrue);
10190 } else {
10191 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10192 "Expected floating point type only!");
10193 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10194 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10195 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10196 DL, LHSIsTrue);
10197 }
10198
10199 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10200 /// the RHS to be an icmp.
10201 /// FIXME: Add support for and/or/select on the RHS.
10202 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10203 if ((LHSI->getOpcode() == Instruction::And ||
10204 LHSI->getOpcode() == Instruction::Or ||
10205 LHSI->getOpcode() == Instruction::Select))
10206 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10207 Depth);
10208 }
10209 return std::nullopt;
10210}
10211
10212std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10213 const DataLayout &DL,
10214 bool LHSIsTrue, unsigned Depth) {
10215 // LHS ==> RHS by definition
10216 if (LHS == RHS)
10217 return LHSIsTrue;
10218
10219 // Match not
10220 bool InvertRHS = false;
10221 if (match(RHS, m_Not(m_Value(RHS)))) {
10222 if (LHS == RHS)
10223 return !LHSIsTrue;
10224 InvertRHS = true;
10225 }
10226
10227 CmpPredicate RHSPred;
10228 Value *RHSOp0, *RHSOp1;
10229 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10230 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10231 LHSIsTrue, Depth))
10232 return InvertRHS ? !*Implied : *Implied;
10233 return std::nullopt;
10234 }
10235 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10236 if (auto Implied = isImpliedCondition(
10237 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10238 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10239 return InvertRHS ? !*Implied : *Implied;
10240 return std::nullopt;
10241 }
10242
10244 return std::nullopt;
10245
10246 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10247 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10248 const Value *RHS1, *RHS2;
10249 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10250 if (std::optional<bool> Imp =
10251 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10252 if (*Imp == true)
10253 return !InvertRHS;
10254 if (std::optional<bool> Imp =
10255 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10256 if (*Imp == true)
10257 return !InvertRHS;
10258 }
10259 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10260 if (std::optional<bool> Imp =
10261 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10262 if (*Imp == false)
10263 return InvertRHS;
10264 if (std::optional<bool> Imp =
10265 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10266 if (*Imp == false)
10267 return InvertRHS;
10268 }
10269
10270 return std::nullopt;
10271}
10272
10273// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10274// condition dominating ContextI or nullptr, if no condition is found.
10275static std::pair<Value *, bool>
10277 if (!ContextI || !ContextI->getParent())
10278 return {nullptr, false};
10279
10280 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10281 // dominator tree (eg, from a SimplifyQuery) instead?
10282 const BasicBlock *ContextBB = ContextI->getParent();
10283 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10284 if (!PredBB)
10285 return {nullptr, false};
10286
10287 // We need a conditional branch in the predecessor.
10288 Value *PredCond;
10289 BasicBlock *TrueBB, *FalseBB;
10290 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10291 return {nullptr, false};
10292
10293 // The branch should get simplified. Don't bother simplifying this condition.
10294 if (TrueBB == FalseBB)
10295 return {nullptr, false};
10296
10297 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10298 "Predecessor block does not point to successor?");
10299
10300 // Is this condition implied by the predecessor condition?
10301 return {PredCond, TrueBB == ContextBB};
10302}
10303
10304std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10305 const Instruction *ContextI,
10306 const DataLayout &DL) {
10307 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10308 auto PredCond = getDomPredecessorCondition(ContextI);
10309 if (PredCond.first)
10310 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10311 return std::nullopt;
10312}
10313
10315 const Value *LHS,
10316 const Value *RHS,
10317 const Instruction *ContextI,
10318 const DataLayout &DL) {
10319 auto PredCond = getDomPredecessorCondition(ContextI);
10320 if (PredCond.first)
10321 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10322 PredCond.second);
10323 return std::nullopt;
10324}
10325
10327 APInt &Upper, const InstrInfoQuery &IIQ,
10328 bool PreferSignedRange) {
10329 unsigned Width = Lower.getBitWidth();
10330 const APInt *C;
10331 switch (BO.getOpcode()) {
10332 case Instruction::Sub:
10333 if (match(BO.getOperand(0), m_APInt(C))) {
10334 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10335 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10336
10337 // If the caller expects a signed compare, then try to use a signed range.
10338 // Otherwise if both no-wraps are set, use the unsigned range because it
10339 // is never larger than the signed range. Example:
10340 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10341 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10342 if (PreferSignedRange && HasNSW && HasNUW)
10343 HasNUW = false;
10344
10345 if (HasNUW) {
10346 // 'sub nuw c, x' produces [0, C].
10347 Upper = *C + 1;
10348 } else if (HasNSW) {
10349 if (C->isNegative()) {
10350 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10352 Upper = *C - APInt::getSignedMaxValue(Width);
10353 } else {
10354 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10355 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10356 Lower = *C - APInt::getSignedMaxValue(Width);
10358 }
10359 }
10360 }
10361 break;
10362 case Instruction::Add:
10363 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10364 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10365 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10366
10367 // If the caller expects a signed compare, then try to use a signed
10368 // range. Otherwise if both no-wraps are set, use the unsigned range
10369 // because it is never larger than the signed range. Example: "add nuw
10370 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10371 if (PreferSignedRange && HasNSW && HasNUW)
10372 HasNUW = false;
10373
10374 if (HasNUW) {
10375 // 'add nuw x, C' produces [C, UINT_MAX].
10376 Lower = *C;
10377 } else if (HasNSW) {
10378 if (C->isNegative()) {
10379 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10381 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10382 } else {
10383 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10384 Lower = APInt::getSignedMinValue(Width) + *C;
10385 Upper = APInt::getSignedMaxValue(Width) + 1;
10386 }
10387 }
10388 }
10389 break;
10390
10391 case Instruction::And:
10392 if (match(BO.getOperand(1), m_APInt(C)))
10393 // 'and x, C' produces [0, C].
10394 Upper = *C + 1;
10395 // X & -X is a power of two or zero. So we can cap the value at max power of
10396 // two.
10397 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10398 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10399 Upper = APInt::getSignedMinValue(Width) + 1;
10400 break;
10401
10402 case Instruction::Or:
10403 if (match(BO.getOperand(1), m_APInt(C)))
10404 // 'or x, C' produces [C, UINT_MAX].
10405 Lower = *C;
10406 break;
10407
10408 case Instruction::AShr:
10409 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10410 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10412 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10413 } else if (match(BO.getOperand(0), m_APInt(C))) {
10414 unsigned ShiftAmount = Width - 1;
10415 if (!C->isZero() && IIQ.isExact(&BO))
10416 ShiftAmount = C->countr_zero();
10417 if (C->isNegative()) {
10418 // 'ashr C, x' produces [C, C >> (Width-1)]
10419 Lower = *C;
10420 Upper = C->ashr(ShiftAmount) + 1;
10421 } else {
10422 // 'ashr C, x' produces [C >> (Width-1), C]
10423 Lower = C->ashr(ShiftAmount);
10424 Upper = *C + 1;
10425 }
10426 }
10427 break;
10428
10429 case Instruction::LShr:
10430 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10431 // 'lshr x, C' produces [0, UINT_MAX >> C].
10432 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10433 } else if (match(BO.getOperand(0), m_APInt(C))) {
10434 // 'lshr C, x' produces [C >> (Width-1), C].
10435 unsigned ShiftAmount = Width - 1;
10436 if (!C->isZero() && IIQ.isExact(&BO))
10437 ShiftAmount = C->countr_zero();
10438 Lower = C->lshr(ShiftAmount);
10439 Upper = *C + 1;
10440 }
10441 break;
10442
10443 case Instruction::Shl:
10444 if (match(BO.getOperand(0), m_APInt(C))) {
10445 if (IIQ.hasNoUnsignedWrap(&BO)) {
10446 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10447 Lower = *C;
10448 Upper = Lower.shl(Lower.countl_zero()) + 1;
10449 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10450 if (C->isNegative()) {
10451 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10452 unsigned ShiftAmount = C->countl_one() - 1;
10453 Lower = C->shl(ShiftAmount);
10454 Upper = *C + 1;
10455 } else {
10456 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10457 unsigned ShiftAmount = C->countl_zero() - 1;
10458 Lower = *C;
10459 Upper = C->shl(ShiftAmount) + 1;
10460 }
10461 } else {
10462 // If lowbit is set, value can never be zero.
10463 if ((*C)[0])
10464 Lower = APInt::getOneBitSet(Width, 0);
10465 // If we are shifting a constant the largest it can be is if the longest
10466 // sequence of consecutive ones is shifted to the highbits (breaking
10467 // ties for which sequence is higher). At the moment we take a liberal
10468 // upper bound on this by just popcounting the constant.
10469 // TODO: There may be a bitwise trick for it longest/highest
10470 // consecutative sequence of ones (naive method is O(Width) loop).
10471 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10472 }
10473 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10474 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10475 }
10476 break;
10477
10478 case Instruction::SDiv:
10479 if (match(BO.getOperand(1), m_APInt(C))) {
10480 APInt IntMin = APInt::getSignedMinValue(Width);
10481 APInt IntMax = APInt::getSignedMaxValue(Width);
10482 if (C->isAllOnes()) {
10483 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10484 // where C != -1 and C != 0 and C != 1
10485 Lower = IntMin + 1;
10486 Upper = IntMax + 1;
10487 } else if (C->countl_zero() < Width - 1) {
10488 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10489 // where C != -1 and C != 0 and C != 1
10490 Lower = IntMin.sdiv(*C);
10491 Upper = IntMax.sdiv(*C);
10492 if (Lower.sgt(Upper))
10494 Upper = Upper + 1;
10495 assert(Upper != Lower && "Upper part of range has wrapped!");
10496 }
10497 } else if (match(BO.getOperand(0), m_APInt(C))) {
10498 if (C->isMinSignedValue()) {
10499 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10500 Lower = *C;
10501 Upper = Lower.lshr(1) + 1;
10502 } else {
10503 // 'sdiv C, x' produces [-|C|, |C|].
10504 Upper = C->abs() + 1;
10505 Lower = (-Upper) + 1;
10506 }
10507 }
10508 break;
10509
10510 case Instruction::UDiv:
10511 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10512 // 'udiv x, C' produces [0, UINT_MAX / C].
10513 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10514 } else if (match(BO.getOperand(0), m_APInt(C))) {
10515 // 'udiv C, x' produces [0, C].
10516 Upper = *C + 1;
10517 }
10518 break;
10519
10520 case Instruction::SRem:
10521 if (match(BO.getOperand(1), m_APInt(C))) {
10522 // 'srem x, C' produces (-|C|, |C|).
10523 Upper = C->abs();
10524 Lower = (-Upper) + 1;
10525 } else if (match(BO.getOperand(0), m_APInt(C))) {
10526 if (C->isNegative()) {
10527 // 'srem -|C|, x' produces [-|C|, 0].
10528 Upper = 1;
10529 Lower = *C;
10530 } else {
10531 // 'srem |C|, x' produces [0, |C|].
10532 Upper = *C + 1;
10533 }
10534 }
10535 break;
10536
10537 case Instruction::URem:
10538 if (match(BO.getOperand(1), m_APInt(C)))
10539 // 'urem x, C' produces [0, C).
10540 Upper = *C;
10541 else if (match(BO.getOperand(0), m_APInt(C)))
10542 // 'urem C, x' produces [0, C].
10543 Upper = *C + 1;
10544 break;
10545
10546 default:
10547 break;
10548 }
10549}
10550
10552 bool UseInstrInfo) {
10553 unsigned Width = II.getType()->getScalarSizeInBits();
10554 const APInt *C;
10555 switch (II.getIntrinsicID()) {
10556 case Intrinsic::ctlz:
10557 case Intrinsic::cttz: {
10558 APInt Upper(Width, Width);
10559 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10560 Upper += 1;
10561 // Maximum of set/clear bits is the bit width.
10563 }
10564 case Intrinsic::ctpop:
10565 // Maximum of set/clear bits is the bit width.
10567 APInt(Width, Width) + 1);
10568 case Intrinsic::uadd_sat:
10569 // uadd.sat(x, C) produces [C, UINT_MAX].
10570 if (match(II.getOperand(0), m_APInt(C)) ||
10571 match(II.getOperand(1), m_APInt(C)))
10573 break;
10574 case Intrinsic::sadd_sat:
10575 if (match(II.getOperand(0), m_APInt(C)) ||
10576 match(II.getOperand(1), m_APInt(C))) {
10577 if (C->isNegative())
10578 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10580 APInt::getSignedMaxValue(Width) + *C +
10581 1);
10582
10583 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10585 APInt::getSignedMaxValue(Width) + 1);
10586 }
10587 break;
10588 case Intrinsic::usub_sat:
10589 // usub.sat(C, x) produces [0, C].
10590 if (match(II.getOperand(0), m_APInt(C)))
10591 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10592
10593 // usub.sat(x, C) produces [0, UINT_MAX - C].
10594 if (match(II.getOperand(1), m_APInt(C)))
10596 APInt::getMaxValue(Width) - *C + 1);
10597 break;
10598 case Intrinsic::ssub_sat:
10599 if (match(II.getOperand(0), m_APInt(C))) {
10600 if (C->isNegative())
10601 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10603 *C - APInt::getSignedMinValue(Width) +
10604 1);
10605
10606 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10608 APInt::getSignedMaxValue(Width) + 1);
10609 } else if (match(II.getOperand(1), m_APInt(C))) {
10610 if (C->isNegative())
10611 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10613 APInt::getSignedMaxValue(Width) + 1);
10614
10615 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10617 APInt::getSignedMaxValue(Width) - *C +
10618 1);
10619 }
10620 break;
10621 case Intrinsic::umin:
10622 case Intrinsic::umax:
10623 case Intrinsic::smin:
10624 case Intrinsic::smax:
10625 if (!match(II.getOperand(0), m_APInt(C)) &&
10626 !match(II.getOperand(1), m_APInt(C)))
10627 break;
10628
10629 switch (II.getIntrinsicID()) {
10630 case Intrinsic::umin:
10631 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10632 case Intrinsic::umax:
10634 case Intrinsic::smin:
10636 *C + 1);
10637 case Intrinsic::smax:
10639 APInt::getSignedMaxValue(Width) + 1);
10640 default:
10641 llvm_unreachable("Must be min/max intrinsic");
10642 }
10643 break;
10644 case Intrinsic::abs:
10645 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10646 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10647 if (match(II.getOperand(1), m_One()))
10649 APInt::getSignedMaxValue(Width) + 1);
10650
10652 APInt::getSignedMinValue(Width) + 1);
10653 case Intrinsic::vscale:
10654 if (!II.getParent() || !II.getFunction())
10655 break;
10656 return getVScaleRange(II.getFunction(), Width);
10657 case Intrinsic::read_register:
10658 case Intrinsic::read_volatile_register: {
10659 const Module *M = II.getModule();
10660 if (!M || !M->getTargetTriple().isRISCV())
10661 break;
10662 if (II.getFunction() && isReadVLENB(II))
10663 return getRISCVVLENBRange(II, Width);
10664 break;
10665 }
10666 default:
10667 break;
10668 }
10669
10670 return ConstantRange::getFull(Width);
10671}
10672
10674 const InstrInfoQuery &IIQ) {
10675 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10676 const Value *LHS = nullptr, *RHS = nullptr;
10678 if (R.Flavor == SPF_UNKNOWN)
10679 return ConstantRange::getFull(BitWidth);
10680
10681 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10682 // If the negation part of the abs (in RHS) has the NSW flag,
10683 // then the result of abs(X) is [0..SIGNED_MAX],
10684 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10685 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10689
10692 }
10693
10694 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10695 // The result of -abs(X) is <= 0.
10697 APInt(BitWidth, 1));
10698 }
10699
10700 const APInt *C;
10701 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10702 return ConstantRange::getFull(BitWidth);
10703
10704 switch (R.Flavor) {
10705 case SPF_UMIN:
10707 case SPF_UMAX:
10709 case SPF_SMIN:
10711 *C + 1);
10712 case SPF_SMAX:
10715 default:
10716 return ConstantRange::getFull(BitWidth);
10717 }
10718}
10719
10721 // The maximum representable value of a half is 65504. For floats the maximum
10722 // value is 3.4e38 which requires roughly 129 bits.
10723 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10724 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10725 return;
10726 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10727 Lower = APInt(BitWidth, -65504, true);
10728 Upper = APInt(BitWidth, 65505);
10729 }
10730
10731 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10732 // For a fptoui the lower limit is left as 0.
10733 Upper = APInt(BitWidth, 65505);
10734 }
10735}
10736
10738 const SimplifyQuery &SQ,
10739 unsigned Depth) {
10740 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10741
10743 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10744
10745 if (auto *C = dyn_cast<Constant>(V))
10746 return C->toConstantRange();
10747
10748 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10749 ConstantRange CR = ConstantRange::getFull(BitWidth);
10750 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10751 APInt Lower = APInt(BitWidth, 0);
10752 APInt Upper = APInt(BitWidth, 0);
10753 // TODO: Return ConstantRange.
10754 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10756 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10758 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10759 ConstantRange CRTrue =
10760 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10761 ConstantRange CRFalse =
10762 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10763 CR = CRTrue.unionWith(CRFalse);
10765 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10766 ConstantRange SrcCR =
10767 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10768 CR = SrcCR.truncate(BitWidth);
10769 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10770 ConstantRange SrcCR =
10771 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10772 CR = SrcCR.zeroExtend(BitWidth);
10773 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10774 ConstantRange SrcCR =
10775 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10776 CR = SrcCR.signExtend(BitWidth);
10777 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10778 APInt Lower = APInt(BitWidth, 0);
10779 APInt Upper = APInt(BitWidth, 0);
10780 // TODO: Return ConstantRange.
10783 } else if (const auto *A = dyn_cast<Argument>(V))
10784 if (std::optional<ConstantRange> Range = A->getRange())
10785 CR = *Range;
10786
10787 if (auto *I = dyn_cast<Instruction>(V)) {
10788 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10790
10791 Value *FrexpSrc;
10792 if (const auto *CB = dyn_cast<CallBase>(V)) {
10793 if (std::optional<ConstantRange> Range = CB->getRange())
10794 CR = CR.intersectWith(*Range);
10796 m_Value(FrexpSrc))))) {
10797 const fltSemantics &FltSem =
10798 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10799 // It should be possible to implement this for any type, but this logic
10800 // only computes the range assuming standard subnormal handling.
10801 if (APFloat::isIEEELikeFP(FltSem)) {
10803 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10804
10805 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10806 // constrain its range when the source can be neither.
10807 if (KnownSrc.isKnownNeverInfOrNaN()) {
10808 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10809
10810 // Offset to find the true minimum exponent value for a denormal.
10811 if (!KnownSrc.isKnownNeverSubnormal())
10812 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10813
10814 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10815
10816 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10818
10819 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10820 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10821
10822 MinExp = std::max(AdjustedMin, MinExp);
10823 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10824 MaxExp);
10825
10827 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10828 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10829 /*isSigned=*/true));
10830 }
10831 }
10832 }
10833 }
10834
10835 if (SQ.CtxI && SQ.AC) {
10836 // Try to restrict the range based on information from assumptions.
10837 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10838 if (!AssumeVH)
10839 continue;
10840 CallInst *I = cast<CallInst>(AssumeVH);
10841 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10842 "Got assumption for the wrong function!");
10843 assert(I->getIntrinsicID() == Intrinsic::assume &&
10844 "must be an assume intrinsic");
10845
10846 if (!isValidAssumeForContext(I, SQ))
10847 continue;
10848 Value *Arg = I->getArgOperand(0);
10849 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10850 // Currently we just use information from comparisons.
10851 if (!Cmp || Cmp->getOperand(0) != V)
10852 continue;
10853 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10854 ConstantRange RHS =
10855 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10856 SQ.getWithInstruction(I), Depth + 1);
10857 CR = CR.intersectWith(
10858 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10859 }
10860 }
10861
10862 return CR;
10863}
10864
10865static void
10867 function_ref<void(Value *)> InsertAffected) {
10868 assert(V != nullptr);
10869 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10870 InsertAffected(V);
10871 } else if (auto *I = dyn_cast<Instruction>(V)) {
10872 InsertAffected(V);
10873
10874 // Peek through unary operators to find the source of the condition.
10875 Value *Op;
10877 m_Trunc(m_Value(Op))))) {
10879 InsertAffected(Op);
10880 }
10881 }
10882}
10883
10885 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10886 auto AddAffected = [&InsertAffected](Value *V) {
10887 addValueAffectedByCondition(V, InsertAffected);
10888 };
10889
10890 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10891 if (IsAssume) {
10892 AddAffected(LHS);
10893 AddAffected(RHS);
10894 } else if (match(RHS, m_Constant()))
10895 AddAffected(LHS);
10896 };
10897
10898 SmallVector<Value *, 8> Worklist;
10900 Worklist.push_back(Cond);
10901 while (!Worklist.empty()) {
10902 Value *V = Worklist.pop_back_val();
10903 if (!Visited.insert(V).second)
10904 continue;
10905
10906 CmpPredicate Pred;
10907 Value *A, *B, *X;
10908
10909 if (IsAssume) {
10910 AddAffected(V);
10911 if (match(V, m_Not(m_Value(X))))
10912 AddAffected(X);
10913 }
10914
10915 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10916 // assume(A && B) is split to -> assume(A); assume(B);
10917 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10918 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10919 // enough information to be worth handling (intersection of information as
10920 // opposed to union).
10921 if (!IsAssume) {
10922 Worklist.push_back(A);
10923 Worklist.push_back(B);
10924 }
10925 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10926 bool HasRHSC = match(B, m_ConstantInt());
10927 if (ICmpInst::isEquality(Pred)) {
10928 AddAffected(A);
10929 if (IsAssume)
10930 AddAffected(B);
10931 if (HasRHSC) {
10932 Value *Y;
10933 // (X << C) or (X >>_s C) or (X >>_u C).
10934 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10935 AddAffected(X);
10936 // (X & C) or (X | C).
10937 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10938 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10939 AddAffected(X);
10940 AddAffected(Y);
10941 }
10942 // X - Y
10943 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10944 AddAffected(X);
10945 AddAffected(Y);
10946 }
10947 }
10948 } else {
10949 AddCmpOperands(A, B);
10950 if (HasRHSC) {
10951 // Handle (A + C1) u< C2, which is the canonical form of
10952 // A > C3 && A < C4.
10954 AddAffected(X);
10955
10956 if (ICmpInst::isUnsigned(Pred)) {
10957 Value *Y;
10958 // X & Y u> C -> X >u C && Y >u C
10959 // X | Y u< C -> X u< C && Y u< C
10960 // X nuw+ Y u< C -> X u< C && Y u< C
10961 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10962 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10963 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10964 AddAffected(X);
10965 AddAffected(Y);
10966 }
10967 // X nuw- Y u> C -> X u> C
10968 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10969 AddAffected(X);
10970 }
10971 }
10972
10973 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10974 // by computeKnownFPClass().
10976 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10977 InsertAffected(X);
10978 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10979 InsertAffected(X);
10980 }
10981 }
10982
10983 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10984 Value *SquareOp = nullptr;
10985 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10986 AddAffected(SquareOp);
10987 };
10988 AddNuwSquareOperand(A);
10989 AddNuwSquareOperand(B);
10990
10991 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10992 AddAffected(X);
10993 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10994 AddCmpOperands(A, B);
10995
10996 // fcmp fneg(x), y
10997 // fcmp fabs(x), y
10998 // fcmp fneg(fabs(x)), y
10999 if (match(A, m_FNeg(m_Value(A))))
11000 AddAffected(A);
11001 if (match(A, m_FAbs(m_Value(A))))
11002 AddAffected(A);
11003
11005 m_Value()))) {
11006 // Handle patterns that computeKnownFPClass() support.
11007 AddAffected(A);
11008 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11009 // Assume is checked here as X is already added above for assumes in
11010 // addValueAffectedByCondition
11011 AddAffected(X);
11012 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11013 // Assume is checked here to avoid issues with ephemeral values
11014 Worklist.push_back(X);
11015 }
11016 }
11017}
11018
11020 // (X >> C) or/add (X & mask(C) != 0)
11021 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11022 if (BO->getOpcode() == Instruction::Add ||
11023 BO->getOpcode() == Instruction::Or) {
11024 const Value *X;
11025 const APInt *C1, *C2;
11026 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11030 m_Zero())))) &&
11031 C2->popcount() == C1->getZExtValue())
11032 return X;
11033 }
11034 }
11035 return nullptr;
11036}
11037
11039 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11040}
11041
11044 unsigned MaxCount, bool AllowUndefOrPoison) {
11047 auto Push = [&](const Value *V) -> bool {
11048 Constant *C;
11049 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11050 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11051 return false;
11052 // Check existence first to avoid unnecessary allocations.
11053 if (Constants.contains(C))
11054 return true;
11055 if (Constants.size() == MaxCount)
11056 return false;
11057 Constants.insert(C);
11058 return true;
11059 }
11060
11061 if (auto *Inst = dyn_cast<Instruction>(V)) {
11062 if (Visited.insert(Inst).second)
11063 Worklist.push_back(Inst);
11064 return true;
11065 }
11066 return false;
11067 };
11068 if (!Push(V))
11069 return false;
11070 while (!Worklist.empty()) {
11071 const Instruction *CurInst = Worklist.pop_back_val();
11072 switch (CurInst->getOpcode()) {
11073 case Instruction::Select:
11074 if (!Push(CurInst->getOperand(1)))
11075 return false;
11076 if (!Push(CurInst->getOperand(2)))
11077 return false;
11078 break;
11079 case Instruction::PHI:
11080 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11081 // Fast path for recurrence PHI.
11082 if (IncomingValue == CurInst)
11083 continue;
11084 if (!Push(IncomingValue))
11085 return false;
11086 }
11087 break;
11088 default:
11089 return false;
11090 }
11091 }
11092 return true;
11093}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
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:857
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 RegName(no)
#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 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 const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
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 bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
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 ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
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 SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
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 void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
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 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 bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
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 void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
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 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 bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
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:368
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:364
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:372
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:360
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:385
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
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:6161
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1405
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
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:1253
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
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:106
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:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
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
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
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
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 ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
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.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
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 multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
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 ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
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 APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
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:794
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...
iterator_range< user_iterator > users()
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:71
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:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
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
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.
LibFunc getLibFunc(StringRef funcName) 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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
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
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
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:222
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:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
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:35
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:257
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:729
iterator_range< user_iterator > users()
Definition Value.h:428
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:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
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.
AllOnesConstantMatch m_AllOnes()
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_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
static constexpr unsigned RVVBytesPerBlock
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:679
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)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ 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:1755
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:1685
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 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
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 const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
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:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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:448
@ 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)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
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 unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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.
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.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
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 isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
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:1762
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:326
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....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
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 bool programUndefinedIfPoison(const Instruction *Inst)
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.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
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 const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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 Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
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 bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
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 isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
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 bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
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...
auto predecessors(const MachineBasicBlock *BB)
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...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
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)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
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:202
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.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
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 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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
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 ceil(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ceil.
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 atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
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.
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.
std::optional< bool > getSignBit() const
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 fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (rint, nearbyint, round, roundeven).
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.
static LLVM_ABI KnownFPClass trunc(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for trunc.
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 log(const KnownFPClass &Src, DenormalMode Mode, bool IsMultiUnitFPType)
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass floor(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for floor.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041