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 const bool IsTrunc = IID == Intrinsic::trunc;
5697 Known = KnownFPClass::roundToIntegral(KnownSrc, IsTrunc,
5698 IsMultiUnitFPType, Mode);
5699 break;
5700 }
5701 case Intrinsic::exp:
5702 case Intrinsic::exp2:
5703 case Intrinsic::exp10:
5704 case Intrinsic::amdgcn_exp2: {
5705 KnownFPClass KnownSrc;
5706 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5707 KnownSrc, Q, Depth + 1);
5708
5709 Known = KnownFPClass::exp(KnownSrc);
5710
5711 Type *EltTy = II->getType()->getScalarType();
5712 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5713 Known.knownNot(fcSubnormal);
5714
5715 break;
5716 }
5717 case Intrinsic::fptrunc_round: {
5718 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5719 Q, Depth);
5720 break;
5721 }
5722 case Intrinsic::log:
5723 case Intrinsic::log10:
5724 case Intrinsic::log2:
5725 case Intrinsic::experimental_constrained_log:
5726 case Intrinsic::experimental_constrained_log10:
5727 case Intrinsic::experimental_constrained_log2:
5728 case Intrinsic::amdgcn_log: {
5729 FPClassTest InterestedSrcs = fcNone;
5730
5731 // log(negative) produces NaN.
5732 if ((InterestedClasses & fcNan) != fcNone)
5733 InterestedSrcs |= fcNan | fcNegative;
5734
5735 // log(logical-zero) produces negative infinity.
5736 if ((InterestedClasses & fcNegInf) != fcNone)
5737 InterestedSrcs |= fcZero | fcSubnormal;
5738
5739 // log(x) < -0.0 if x < +1.0
5740 if ((InterestedClasses & fcNegNormal) != fcNone)
5741 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5742
5743 // log(x) >= +0.0 if x >= +1.0
5744 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5745 InterestedSrcs |= fcPosNormal;
5746
5747 // log(x) is positive infinity iff x is positive infinity.
5748 if ((InterestedClasses & fcPosInf) != fcNone)
5749 InterestedSrcs |= fcPosInf;
5750
5751 KnownFPClass KnownSrc;
5752 if (InterestedSrcs != fcNone)
5753 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5754 KnownSrc, Q, Depth + 1);
5755 const Function *F = II->getFunction();
5757 F ? F->getDenormalMode(
5758 II->getType()->getScalarType()->getFltSemantics())
5760 Known = KnownFPClass::log(KnownSrc, Mode);
5761 break;
5762 }
5763 case Intrinsic::pow: {
5764 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5765 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5766 if (!WantNaN && !WantNegative)
5767 break;
5768
5769 FPClassTest InterestedLHS = fcNone;
5770 FPClassTest InterestedRHS = fcNone;
5771 if (WantNaN) {
5772 // pow may return NaN if one of the arguments is NaN. NaN may also be
5773 // produced from a negative, non-zero finite base and a non-integer
5774 // exponent.
5775 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5776 InterestedRHS |= fcNan;
5777 }
5778 if (WantNegative) {
5779 // A negative value is returned when a negative base is raised to an odd
5780 // integer power. Only normal values can be odd integers.
5781 InterestedLHS |= fcNegative;
5782 InterestedRHS |= fcNormal;
5783 }
5784
5785 KnownFPClass KnownLHS;
5786 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5787 KnownLHS, Q, Depth + 1);
5788
5789 // If the LHS is unknown, then querying the RHS is only useful for rare
5790 // edge cases.
5791 if (KnownLHS.isUnknown())
5792 break;
5793
5794 KnownFPClass KnownRHS;
5795 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5796 KnownRHS, Q, Depth + 1);
5797 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5798 break;
5799 }
5800 case Intrinsic::powi: {
5801 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5802 break;
5803
5804 // The exponent is always a scalar, even when raising a vector to a power.
5805 const Value *Exp = II->getArgOperand(1);
5806 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5807 KnownBits ExponentKnownBits(BitWidth);
5808 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5809
5810 FPClassTest InterestedSrcs = fcNone;
5811 if (InterestedClasses & fcNan)
5812 InterestedSrcs |= fcNan;
5813 if (!ExponentKnownBits.isZero()) {
5814 if (InterestedClasses & fcInf)
5815 InterestedSrcs |= fcFinite | fcInf;
5816 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5817 InterestedSrcs |= fcNegative;
5818 }
5819
5820 KnownFPClass KnownSrc;
5821 if (InterestedSrcs != fcNone)
5822 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5823 KnownSrc, Q, Depth + 1);
5824
5825 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5826 break;
5827 }
5828 case Intrinsic::ldexp: {
5829 KnownFPClass KnownSrc;
5830 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5831 KnownSrc, Q, Depth + 1);
5832 // Can refine inf/zero handling based on the exponent operand.
5833 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5834
5835 const Value *ExpArg = II->getArgOperand(1);
5836 ConstantRange ExpKnownRange =
5837 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5838 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5839 : ConstantRange::getFull(
5840 ExpArg->getType()->getScalarSizeInBits());
5841
5842 const fltSemantics &Flt =
5843 II->getType()->getScalarType()->getFltSemantics();
5844
5845 const Function *F = II->getFunction();
5847 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5848
5849 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5850 ExpKnownRange.getSignedMax(), Flt, Mode);
5851 break;
5852 }
5853 case Intrinsic::arithmetic_fence: {
5854 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5855 Known, Q, Depth + 1);
5856 break;
5857 }
5858 case Intrinsic::experimental_constrained_sitofp:
5859 case Intrinsic::experimental_constrained_uitofp:
5860 // Cannot produce nan
5861 Known.knownNot(fcNan);
5862
5863 // sitofp and uitofp turn into +0.0 for zero.
5864 Known.knownNot(fcNegZero);
5865
5866 // Integers cannot be subnormal
5867 Known.knownNot(fcSubnormal);
5868
5869 if (IID == Intrinsic::experimental_constrained_uitofp)
5870 Known.signBitMustBeZero();
5871
5872 // TODO: Copy inf handling from instructions
5873 break;
5874
5875 case Intrinsic::amdgcn_fract: {
5876 Known.knownNot(fcInf);
5877
5878 if (InterestedClasses & fcNan) {
5879 KnownFPClass KnownSrc;
5880 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5881 InterestedClasses, KnownSrc, Q, Depth + 1);
5882
5883 if (KnownSrc.isKnownNeverInfOrNaN())
5884 Known.knownNot(fcNan);
5885 else if (KnownSrc.isKnownNever(fcSNan))
5886 Known.knownNot(fcSNan);
5887 }
5888
5889 break;
5890 }
5891 case Intrinsic::amdgcn_rcp: {
5892 KnownFPClass KnownSrc;
5893 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5894 KnownSrc, Q, Depth + 1);
5895
5896 Known.propagateNonNaN(KnownSrc);
5897
5898 Type *EltTy = II->getType()->getScalarType();
5899
5900 // f32 denormal always flushed.
5901 if (EltTy->isFloatTy()) {
5902 Known.knownNot(fcSubnormal);
5903 KnownSrc.knownNot(fcSubnormal);
5904 }
5905
5906 if (KnownSrc.isKnownNever(fcNegative))
5907 Known.knownNot(fcNegative);
5908 if (KnownSrc.isKnownNever(fcPositive))
5909 Known.knownNot(fcPositive);
5910
5911 if (const Function *F = II->getFunction()) {
5912 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5913 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5914 Known.knownNot(fcPosInf);
5915 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5916 Known.knownNot(fcNegInf);
5917 }
5918
5919 break;
5920 }
5921 case Intrinsic::amdgcn_rsq: {
5922 KnownFPClass KnownSrc;
5923 // The only negative value that can be returned is -inf for -0 inputs.
5925
5926 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5927 KnownSrc, Q, Depth + 1);
5928
5929 // Negative -> nan
5930 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5931 Known.knownNot(fcNan);
5932 else if (KnownSrc.isKnownNever(fcSNan))
5933 Known.knownNot(fcSNan);
5934
5935 // +inf -> +0
5936 if (KnownSrc.isKnownNeverPosInfinity())
5937 Known.knownNot(fcPosZero);
5938
5939 Type *EltTy = II->getType()->getScalarType();
5940
5941 // f32 denormal always flushed.
5942 if (EltTy->isFloatTy())
5943 Known.knownNot(fcPosSubnormal);
5944
5945 if (const Function *F = II->getFunction()) {
5946 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5947
5948 // -0 -> -inf
5949 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5950 Known.knownNot(fcNegInf);
5951
5952 // +0 -> +inf
5953 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5954 Known.knownNot(fcPosInf);
5955 }
5956
5957 break;
5958 }
5959 case Intrinsic::amdgcn_trig_preop: {
5960 // Always returns a value [0, 1)
5961 Known.knownNot(fcNan | fcInf | fcNegative);
5962 break;
5963 }
5964 case Intrinsic::convert_from_arbitrary_fp: {
5965 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5966 StringRef FormatStr = cast<MDString>(MD)->getString();
5967
5968 const fltSemantics *SrcSemantics =
5970 if (!SrcSemantics)
5971 break;
5972
5973 const fltSemantics DstSemantics =
5974 II->getType()->getScalarType()->getFltSemantics();
5975
5976 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5977 Known.knownNot(fcNan);
5978
5979 // fcInf can only be cleared if the source format has no Inf encoding
5980 // and the dst max exp can accommodate src max exp.
5981 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5982 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5983 APFloat::semanticsMaxExponent(DstSemantics))
5984 Known.knownNot(fcInf);
5985
5986 // Check and clear all neg flags for formats that do not have signed
5987 // representation.
5988 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5989 Known.knownNot(fcNegative);
5990
5991 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5992 // zero.
5993 if (!APFloat::semanticsHasZero(*SrcSemantics))
5994 Known.knownNot(fcZero);
5995 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5996 Known.knownNot(fcNegZero);
5997
5998 // If src lands normally in dest, the result can never be subnormal.
5999 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6000 Known.knownNot(fcSubnormal);
6001 break;
6002 }
6003 default:
6004 break;
6005 }
6006
6007 break;
6008 }
6009 case Instruction::FAdd:
6010 case Instruction::FSub: {
6011 KnownFPClass KnownLHS, KnownRHS;
6012 bool WantNegative =
6013 Op->getOpcode() == Instruction::FAdd &&
6014 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6015 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6016 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6017
6018 if (!WantNaN && !WantNegative && !WantNegZero)
6019 break;
6020
6021 FPClassTest InterestedSrcs = InterestedClasses;
6022 if (WantNegative)
6023 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6024 if (InterestedClasses & fcNan)
6025 InterestedSrcs |= fcInf;
6026 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6027 KnownRHS, Q, Depth + 1);
6028
6029 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6030 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6031 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6032 Depth + 1);
6033 if (Self)
6034 KnownLHS = KnownRHS;
6035
6036 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6037 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6038 WantNegZero || Opc == Instruction::FSub) {
6039
6040 // FIXME: Context function should always be passed in separately
6041 const Function *F = cast<Instruction>(Op)->getFunction();
6042 const fltSemantics &FltSem =
6043 Op->getType()->getScalarType()->getFltSemantics();
6045 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6046
6047 if (Self && Opc == Instruction::FAdd) {
6048 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6049 } else {
6050 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6051 // there's no point.
6052
6053 if (!Self) {
6054 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6055 KnownLHS, Q, Depth + 1);
6056 }
6057
6058 Known = Opc == Instruction::FAdd
6059 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6060 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6061 }
6062 }
6063
6064 break;
6065 }
6066 case Instruction::FMul: {
6067 const Function *F = cast<Instruction>(Op)->getFunction();
6069 F ? F->getDenormalMode(
6070 Op->getType()->getScalarType()->getFltSemantics())
6072
6073 Value *LHS = Op->getOperand(0);
6074 Value *RHS = Op->getOperand(1);
6075 // X * X is always non-negative or a NaN.
6076 // FIXME: Should check isGuaranteedNotToBeUndef
6077 if (LHS == RHS) {
6078 KnownFPClass KnownSrc;
6079 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6080 Depth + 1);
6081 Known = KnownFPClass::square(KnownSrc, Mode);
6082 break;
6083 }
6084
6085 KnownFPClass KnownLHS, KnownRHS;
6086
6087 const APFloat *CRHS;
6088 if (match(RHS, m_APFloat(CRHS))) {
6089 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6090 Depth + 1);
6091 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6092 } else {
6093 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6094 Depth + 1);
6095 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6096 // additional not-nan if the addend is known-not negative infinity if the
6097 // multiply is known-not infinity.
6098
6099 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6100 Depth + 1);
6101 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6102 }
6103
6104 /// Propgate no-infs if the other source is known smaller than one, such
6105 /// that this cannot introduce overflow.
6106 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6107 Known.knownNot(fcInf);
6108 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6109 Known.knownNot(fcInf);
6110
6111 break;
6112 }
6113 case Instruction::FDiv: {
6114 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6115
6116 const Function *F = cast<Instruction>(Op)->getFunction();
6117 const fltSemantics &FltSem =
6118 Op->getType()->getScalarType()->getFltSemantics();
6120 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6121
6122 if (Op->getOperand(0) == Op->getOperand(1) &&
6123 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6124 // X / X is always exactly 1.0 or a NaN.
6125 Known.setKnownFPClasses(fcNan | fcPosNormal);
6126
6127 if (!WantNan)
6128 break;
6129
6130 KnownFPClass KnownSrc;
6131 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6132 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6133 Depth + 1);
6134
6135 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6136 break;
6137 }
6138
6139 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6140 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6141 if (!WantNan && !WantNegative && !WantPositive)
6142 break;
6143
6144 KnownFPClass KnownLHS, KnownRHS;
6145 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6146 Q, Depth + 1);
6147
6148 bool KnowSomethingUseful =
6149 KnownRHS.isKnownNeverNaN() ||
6152
6153 if (KnowSomethingUseful)
6154 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6155 Q, Depth + 1);
6156
6157 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6158 break;
6159 }
6160 case Instruction::FRem: {
6161 FPClassTest InterestedLHS = fcNone;
6162 FPClassTest InterestedRHS = fcNone;
6163
6164 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6165 if (InterestedClasses & fcNan) {
6166 InterestedLHS |= fcNan | fcInf;
6167 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6168 }
6169
6170 // The sign for frem is the same as the first operand.
6171 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6172 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6173 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6174 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6175
6176 // A negative zero result requires a negative finite first operand.
6177 if (InterestedClasses & fcNegZero)
6178 InterestedLHS |= fcNegFinite;
6179
6180 // A positive zero result can additionally come from a negative finite
6181 // result being flushed to positive zero.
6182 if (InterestedClasses & fcPosZero)
6183 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6184
6185 const Function *F = cast<Instruction>(Op)->getFunction();
6187 F ? F->getDenormalMode(
6188 Op->getType()->getScalarType()->getFltSemantics())
6190
6191 if (Op->getOperand(0) == Op->getOperand(1) &&
6192 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6193 // X % X is always exactly [+-]0.0 or a NaN.
6194 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6195 KnownFPClass KnownSrc;
6196 if (InterestedSrcs != fcNone)
6197 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6198 KnownSrc, Q, Depth + 1);
6199 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6200 break;
6201 }
6202
6203 KnownFPClass KnownLHS;
6204 if (InterestedLHS != fcNone)
6205 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6206 KnownLHS, Q, Depth + 1);
6207
6208 KnownFPClass KnownRHS;
6209 // RHS is only useful for refining NaN classes.
6210 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6211 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6212 KnownRHS, Q, Depth + 1);
6213
6214 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6215
6216 break;
6217 }
6218 case Instruction::FPExt: {
6219 KnownFPClass KnownSrc;
6220 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6221 KnownSrc, Q, Depth + 1);
6222
6223 const fltSemantics &DstTy =
6224 Op->getType()->getScalarType()->getFltSemantics();
6225 const fltSemantics &SrcTy =
6226 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6227
6228 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6229 break;
6230 }
6231 case Instruction::FPTrunc: {
6232 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6233 Depth);
6234 break;
6235 }
6236 case Instruction::SIToFP:
6237 case Instruction::UIToFP: {
6238 // Cannot produce nan
6239 Known.knownNot(fcNan);
6240
6241 // Integers cannot be subnormal
6242 Known.knownNot(fcSubnormal);
6243
6244 // sitofp and uitofp turn into +0.0 for zero.
6245 Known.knownNot(fcNegZero);
6246
6247 // UIToFP is always non-negative regardless of known bits.
6248 if (Op->getOpcode() == Instruction::UIToFP)
6249 Known.signBitMustBeZero();
6250
6251 // Only compute known bits if we can learn something useful from them.
6252 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6253 break;
6254
6255 KnownBits IntKnown =
6256 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6257
6258 // If the integer is non-zero, the result cannot be +0.0
6259 if (IntKnown.isNonZero())
6260 Known.knownNot(fcPosZero);
6261
6262 if (Op->getOpcode() == Instruction::SIToFP) {
6263 // If the signed integer is known non-negative, the result is
6264 // non-negative. If the signed integer is known negative, the result is
6265 // negative.
6266 if (IntKnown.isNonNegative()) {
6267 Known.signBitMustBeZero();
6268 } else if (IntKnown.isNegative()) {
6269 Known.signBitMustBeOne();
6270 }
6271 }
6272
6273 // Guard kept for ilogb()
6274 if (InterestedClasses & fcInf) {
6275 // Get width of largest magnitude integer known.
6276 // This still works for a signed minimum value because the largest FP
6277 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6278 int IntSize = IntKnown.getBitWidth();
6279 if (Op->getOpcode() == Instruction::UIToFP)
6280 IntSize -= IntKnown.countMinLeadingZeros();
6281 else if (Op->getOpcode() == Instruction::SIToFP)
6282 IntSize -= IntKnown.countMinSignBits();
6283
6284 // If the exponent of the largest finite FP value can hold the largest
6285 // integer, the result of the cast must be finite.
6286 Type *FPTy = Op->getType()->getScalarType();
6287 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6288 Known.knownNot(fcInf);
6289 }
6290
6291 break;
6292 }
6293 case Instruction::ExtractElement: {
6294 // Look through extract element. If the index is non-constant or
6295 // out-of-range demand all elements, otherwise just the extracted element.
6296 const Value *Vec = Op->getOperand(0);
6297
6298 APInt DemandedVecElts;
6299 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6300 unsigned NumElts = VecTy->getNumElements();
6301 DemandedVecElts = APInt::getAllOnes(NumElts);
6302 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6303 if (CIdx && CIdx->getValue().ult(NumElts))
6304 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6305 } else {
6306 DemandedVecElts = APInt(1, 1);
6307 }
6308
6309 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6310 Q, Depth + 1);
6311 }
6312 case Instruction::InsertElement: {
6313 if (isa<ScalableVectorType>(Op->getType()))
6314 return;
6315
6316 const Value *Vec = Op->getOperand(0);
6317 const Value *Elt = Op->getOperand(1);
6318 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6319 unsigned NumElts = DemandedElts.getBitWidth();
6320 APInt DemandedVecElts = DemandedElts;
6321 bool NeedsElt = true;
6322 // If we know the index we are inserting to, clear it from Vec check.
6323 if (CIdx && CIdx->getValue().ult(NumElts)) {
6324 DemandedVecElts.clearBit(CIdx->getZExtValue());
6325 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6326 }
6327
6328 // Do we demand the inserted element?
6329 if (NeedsElt) {
6330 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6331 // If we don't know any bits, early out.
6332 if (Known.isUnknown())
6333 break;
6334 } else {
6335 Known.setKnownFPClasses(fcNone);
6336 }
6337
6338 // Do we need anymore elements from Vec?
6339 if (!DemandedVecElts.isZero()) {
6340 KnownFPClass Known2;
6341 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6342 Depth + 1);
6343 Known |= Known2;
6344 }
6345
6346 break;
6347 }
6348 case Instruction::ShuffleVector: {
6349 // Handle vector splat idiom
6350 if (Value *Splat = getSplatValue(V)) {
6351 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6352 break;
6353 }
6354
6355 // For undef elements, we don't know anything about the common state of
6356 // the shuffle result.
6357 APInt DemandedLHS, DemandedRHS;
6358 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6359 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6360 return;
6361
6362 if (!!DemandedLHS) {
6363 const Value *LHS = Shuf->getOperand(0);
6364 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6365 Depth + 1);
6366
6367 // If we don't know any bits, early out.
6368 if (Known.isUnknown())
6369 break;
6370 } else {
6371 Known.setKnownFPClasses(fcNone);
6372 }
6373
6374 if (!!DemandedRHS) {
6375 KnownFPClass Known2;
6376 const Value *RHS = Shuf->getOperand(1);
6377 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6378 Depth + 1);
6379 Known |= Known2;
6380 }
6381
6382 break;
6383 }
6384 case Instruction::ExtractValue: {
6385 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6386 ArrayRef<unsigned> Indices = Extract->getIndices();
6387 const Value *Src = Extract->getAggregateOperand();
6388 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6389 Indices[0] == 0) {
6390 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6391 switch (II->getIntrinsicID()) {
6392 case Intrinsic::frexp: {
6393 FPClassTest InterestedSrcs = InterestedClasses;
6394
6395 // Positive subnormals and negative subnormals could become positive
6396 // zero.
6397 if (InterestedClasses & fcPosZero)
6398 InterestedSrcs |= fcSubnormal;
6399
6400 // Negative subnormals could become negative zero.
6401 if (InterestedClasses & fcNegZero)
6402 InterestedSrcs |= fcNegSubnormal;
6403
6404 if (InterestedClasses & fcPosNormal)
6405 InterestedSrcs |= fcPosSubnormal;
6406
6407 if (InterestedClasses & fcNegNormal)
6408 InterestedSrcs |= fcNegSubnormal;
6409
6410 KnownFPClass KnownSrc;
6411 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6412 InterestedSrcs, KnownSrc, Q, Depth + 1);
6413
6414 const Function *F = cast<Instruction>(Op)->getFunction();
6415 const fltSemantics &FltSem =
6416 Op->getType()->getScalarType()->getFltSemantics();
6417
6419 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6420 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6421 return;
6422 }
6423 default:
6424 break;
6425 }
6426 }
6427 }
6428
6429 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6430 Depth + 1);
6431 break;
6432 }
6433 case Instruction::PHI: {
6434 const PHINode *P = cast<PHINode>(Op);
6435 // Unreachable blocks may have zero-operand PHI nodes.
6436 if (P->getNumIncomingValues() == 0)
6437 break;
6438
6439 // Otherwise take the unions of the known bit sets of the operands,
6440 // taking conservative care to avoid excessive recursion.
6441 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6442
6443 if (Depth < PhiRecursionLimit) {
6444 // Skip if every incoming value references to ourself.
6445 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6446 break;
6447
6448 bool First = true;
6449
6450 for (const Use &U : P->operands()) {
6451 Value *IncValue;
6452 Instruction *CtxI;
6453 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6454 // Skip direct self references.
6455 if (IncValue == P)
6456 continue;
6457
6458 KnownFPClass KnownSrc;
6459 // Recurse, but cap the recursion to two levels, because we don't want
6460 // to waste time spinning around in loops. We need at least depth 2 to
6461 // detect known sign bits.
6462 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6464 PhiRecursionLimit);
6465
6466 if (First) {
6467 Known = KnownSrc;
6468 First = false;
6469 } else {
6470 Known |= KnownSrc;
6471 }
6472
6473 if (Known.getKnownFPClasses() == fcAllFlags)
6474 break;
6475 }
6476 }
6477
6478 // Look for the case of a for loop which has a positive
6479 // initial value and is incremented by a squared value.
6480 // This will propagate sign information out of such loops.
6481 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6482 break;
6483 for (unsigned I = 0; I < 2; I++) {
6484 Value *RecurValue = P->getIncomingValue(1 - I);
6486 if (!II)
6487 continue;
6488 Value *R, *L, *Init;
6489 PHINode *PN;
6491 PN == P) {
6492 switch (II->getIntrinsicID()) {
6493 case Intrinsic::fma:
6494 case Intrinsic::fmuladd: {
6495 KnownFPClass KnownStart;
6496 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6497 Q, Depth + 1);
6498 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6499 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6501 break;
6502 }
6503 }
6504 }
6505 }
6506 break;
6507 }
6508 case Instruction::BitCast: {
6509 const Value *Src;
6510 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6511 !Src->getType()->isIntOrIntVectorTy())
6512 break;
6513
6514 const Type *Ty = Op->getType();
6515
6516 Value *CastLHS, *CastRHS;
6517
6518 // Match bitcast(umax(bitcast(a), bitcast(b)))
6519 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6520 m_BitCast(m_Value(CastRHS)))) &&
6521 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6522 KnownFPClass KnownLHS, KnownRHS;
6523 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6524 Depth + 1);
6525 if (!KnownRHS.isUnknown()) {
6526 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6527 Q, Depth + 1);
6528 Known = KnownLHS | KnownRHS;
6529 }
6530
6531 return;
6532 }
6533
6534 const Type *EltTy = Ty->getScalarType();
6535 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6536 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6537
6539 break;
6540 }
6541 default:
6542 break;
6543 }
6544}
6545
6547 const APInt &DemandedElts,
6548 FPClassTest InterestedClasses,
6549 const SimplifyQuery &SQ,
6550 unsigned Depth) {
6551 KnownFPClass KnownClasses;
6552 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6553 Depth);
6554 return KnownClasses;
6555}
6556
6558 FPClassTest InterestedClasses,
6559 const SimplifyQuery &SQ,
6560 unsigned Depth) {
6562 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6563 return Known;
6564}
6565
6567 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6568 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6569 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6570 return computeKnownFPClass(V, InterestedClasses,
6571 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6572 Depth);
6573}
6574
6576llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6577 FastMathFlags FMF, FPClassTest InterestedClasses,
6578 const SimplifyQuery &SQ, unsigned Depth) {
6579 if (FMF.noNaNs())
6580 InterestedClasses &= ~fcNan;
6581 if (FMF.noInfs())
6582 InterestedClasses &= ~fcInf;
6583
6584 KnownFPClass Result =
6585 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6586
6587 if (FMF.noNaNs())
6588 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6589 if (FMF.noInfs())
6590 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6591 return Result;
6592}
6593
6595 FPClassTest InterestedClasses,
6596 const SimplifyQuery &SQ,
6597 unsigned Depth) {
6598 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6599 APInt DemandedElts =
6600 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6601 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6602 Depth);
6603}
6604
6606 unsigned Depth) {
6608 return Known.isKnownNeverNegZero();
6609}
6610
6612 unsigned Depth) {
6615 return Known.cannotBeOrderedLessThanZero();
6616}
6617
6619 unsigned Depth) {
6621 return Known.isKnownNeverInfinity();
6622}
6623
6624/// Return true if the floating-point value can never contain a NaN or infinity.
6626 unsigned Depth) {
6628 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6629}
6630
6631/// Return true if the floating-point scalar value is not a NaN or if the
6632/// floating-point vector value has no NaN elements. Return false if a value
6633/// could ever be NaN.
6635 unsigned Depth) {
6637 return Known.isKnownNeverNaN();
6638}
6639
6640/// Return false if we can prove that the specified FP value's sign bit is 0.
6641/// Return true if we can prove that the specified FP value's sign bit is 1.
6642/// Otherwise return std::nullopt.
6643std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6644 const SimplifyQuery &SQ,
6645 unsigned Depth) {
6647 return Known.getSignBit();
6648}
6649
6651 auto *User = cast<Instruction>(U.getUser());
6652 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6653 if (FPOp->hasNoSignedZeros())
6654 return true;
6655 }
6656
6657 switch (User->getOpcode()) {
6658 case Instruction::FPToSI:
6659 case Instruction::FPToUI:
6660 return true;
6661 case Instruction::FCmp:
6662 // fcmp treats both positive and negative zero as equal.
6663 return true;
6664 case Instruction::Call:
6665 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6666 switch (II->getIntrinsicID()) {
6667 case Intrinsic::fabs:
6668 return true;
6669 case Intrinsic::copysign:
6670 return U.getOperandNo() == 0;
6671 case Intrinsic::is_fpclass: {
6672 auto Test =
6673 static_cast<FPClassTest>(
6674 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6677 }
6678 default:
6679 return false;
6680 }
6681 }
6682 return false;
6683 default:
6684 return false;
6685 }
6686}
6687
6689 auto *User = cast<Instruction>(U.getUser());
6690 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6691 if (FPOp->hasNoNaNs())
6692 return true;
6693 }
6694
6695 switch (User->getOpcode()) {
6696 case Instruction::FPToSI:
6697 case Instruction::FPToUI:
6698 return true;
6699 // Proper FP math operations ignore the sign bit of NaN.
6700 case Instruction::FAdd:
6701 case Instruction::FSub:
6702 case Instruction::FMul:
6703 case Instruction::FDiv:
6704 case Instruction::FRem:
6705 case Instruction::FPTrunc:
6706 case Instruction::FPExt:
6707 case Instruction::FCmp:
6708 return true;
6709 // Bitwise FP operations should preserve the sign bit of NaN.
6710 case Instruction::FNeg:
6711 case Instruction::Select:
6712 case Instruction::PHI:
6713 return false;
6714 case Instruction::Ret:
6715 return User->getFunction()->getAttributes().getRetNoFPClass() &
6717 case Instruction::Call:
6718 case Instruction::Invoke: {
6719 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6720 switch (II->getIntrinsicID()) {
6721 case Intrinsic::fabs:
6722 return true;
6723 case Intrinsic::copysign:
6724 return U.getOperandNo() == 0;
6725 // Other proper FP math intrinsics ignore the sign bit of NaN.
6726 case Intrinsic::maxnum:
6727 case Intrinsic::minnum:
6728 case Intrinsic::maximum:
6729 case Intrinsic::minimum:
6730 case Intrinsic::maximumnum:
6731 case Intrinsic::minimumnum:
6732 case Intrinsic::canonicalize:
6733 case Intrinsic::fma:
6734 case Intrinsic::fmuladd:
6735 case Intrinsic::sqrt:
6736 case Intrinsic::pow:
6737 case Intrinsic::powi:
6738 case Intrinsic::fptoui_sat:
6739 case Intrinsic::fptosi_sat:
6740 case Intrinsic::is_fpclass:
6741 return true;
6742 default:
6743 return false;
6744 }
6745 }
6746
6747 FPClassTest NoFPClass =
6748 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6749 return NoFPClass & FPClassTest::fcNan;
6750 }
6751 default:
6752 return false;
6753 }
6754}
6755
6757 FastMathFlags FMF) {
6758 if (isa<PoisonValue>(V))
6759 return true;
6760 if (isa<UndefValue>(V))
6761 return false;
6762
6763 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6764 return true;
6765
6767 if (!I)
6768 return false;
6769
6770 switch (I->getOpcode()) {
6771 case Instruction::SIToFP:
6772 case Instruction::UIToFP:
6773 // TODO: Could check nofpclass(inf) on incoming argument
6774 if (FMF.noInfs())
6775 return true;
6776
6777 // Need to check int size cannot produce infinity, which computeKnownFPClass
6778 // knows how to do already.
6779 return isKnownNeverInfinity(I, SQ);
6780 case Instruction::Call: {
6781 const CallInst *CI = cast<CallInst>(I);
6782 switch (CI->getIntrinsicID()) {
6783 case Intrinsic::trunc:
6784 case Intrinsic::floor:
6785 case Intrinsic::ceil:
6786 case Intrinsic::rint:
6787 case Intrinsic::nearbyint:
6788 case Intrinsic::round:
6789 case Intrinsic::roundeven:
6790 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6791 default:
6792 break;
6793 }
6794
6795 break;
6796 }
6797 default:
6798 break;
6799 }
6800
6801 return false;
6802}
6803
6805
6806 // All byte-wide stores are splatable, even of arbitrary variables.
6807 if (V->getType()->isIntegerTy(8))
6808 return V;
6809
6810 LLVMContext &Ctx = V->getContext();
6811
6812 // Undef don't care.
6813 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6814 if (isa<UndefValue>(V))
6815 return UndefInt8;
6816
6817 // Return poison for zero-sized type.
6818 if (DL.getTypeStoreSize(V->getType()).isZero())
6819 return PoisonValue::get(Type::getInt8Ty(Ctx));
6820
6822 if (!C) {
6823 // Conceptually, we could handle things like:
6824 // %a = zext i8 %X to i16
6825 // %b = shl i16 %a, 8
6826 // %c = or i16 %a, %b
6827 // but until there is an example that actually needs this, it doesn't seem
6828 // worth worrying about.
6829 return nullptr;
6830 }
6831
6832 // Handle 'null' ConstantArrayZero etc.
6833 if (C->isNullValue())
6835
6836 // Constant floating-point values can be handled as integer values if the
6837 // corresponding integer value is "byteable". An important case is 0.0.
6838 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6839 Type *ScalarTy = CFP->getType()->getScalarType();
6840 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6841 return isBytewiseValue(
6842 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6843
6844 // Don't handle long double formats, which have strange constraints.
6845 return nullptr;
6846 }
6847
6848 // We can handle constant integers that are multiple of 8 bits.
6849 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6850 if (CI->getBitWidth() % 8 == 0) {
6851 if (!CI->getValue().isSplat(8))
6852 return nullptr;
6853 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6854 }
6855 }
6856
6857 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6858 if (CE->getOpcode() == Instruction::IntToPtr) {
6859 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6860 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6862 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6863 return isBytewiseValue(Op, DL);
6864 }
6865 }
6866 }
6867
6868 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6869 if (LHS == RHS)
6870 return LHS;
6871 if (!LHS || !RHS)
6872 return nullptr;
6873 if (LHS == UndefInt8)
6874 return RHS;
6875 if (RHS == UndefInt8)
6876 return LHS;
6877 return nullptr;
6878 };
6879
6881 Value *Val = UndefInt8;
6882 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6883 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6884 return nullptr;
6885 return Val;
6886 }
6887
6889 Value *Val = UndefInt8;
6890 for (Value *Op : C->operands())
6891 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6892 return nullptr;
6893 return Val;
6894 }
6895
6896 // Don't try to handle the handful of other constants.
6897 return nullptr;
6898}
6899
6900// This is the recursive version of BuildSubAggregate. It takes a few different
6901// arguments. Idxs is the index within the nested struct From that we are
6902// looking at now (which is of type IndexedType). IdxSkip is the number of
6903// indices from Idxs that should be left out when inserting into the resulting
6904// struct. To is the result struct built so far, new insertvalue instructions
6905// build on that.
6906static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6908 unsigned IdxSkip,
6909 BasicBlock::iterator InsertBefore) {
6910 StructType *STy = dyn_cast<StructType>(IndexedType);
6911 if (STy) {
6912 // Save the original To argument so we can modify it
6913 Value *OrigTo = To;
6914 // General case, the type indexed by Idxs is a struct
6915 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6916 // Process each struct element recursively
6917 Idxs.push_back(i);
6918 Value *PrevTo = To;
6919 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6920 InsertBefore);
6921 Idxs.pop_back();
6922 if (!To) {
6923 // Couldn't find any inserted value for this index? Cleanup
6924 while (PrevTo != OrigTo) {
6926 PrevTo = Del->getAggregateOperand();
6927 Del->eraseFromParent();
6928 }
6929 // Stop processing elements
6930 break;
6931 }
6932 }
6933 // If we successfully found a value for each of our subaggregates
6934 if (To)
6935 return To;
6936 }
6937 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6938 // the struct's elements had a value that was inserted directly. In the latter
6939 // case, perhaps we can't determine each of the subelements individually, but
6940 // we might be able to find the complete struct somewhere.
6941
6942 // Find the value that is at that particular spot
6943 Value *V = FindInsertedValue(From, Idxs);
6944
6945 if (!V)
6946 return nullptr;
6947
6948 // Insert the value in the new (sub) aggregate
6949 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6950 InsertBefore);
6951}
6952
6953// This helper takes a nested struct and extracts a part of it (which is again a
6954// struct) into a new value. For example, given the struct:
6955// { a, { b, { c, d }, e } }
6956// and the indices "1, 1" this returns
6957// { c, d }.
6958//
6959// It does this by inserting an insertvalue for each element in the resulting
6960// struct, as opposed to just inserting a single struct. This will only work if
6961// each of the elements of the substruct are known (ie, inserted into From by an
6962// insertvalue instruction somewhere).
6963//
6964// All inserted insertvalue instructions are inserted before InsertBefore
6966 BasicBlock::iterator InsertBefore) {
6967 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6968 idx_range);
6969 Value *To = PoisonValue::get(IndexedType);
6970 SmallVector<unsigned, 10> Idxs(idx_range);
6971 unsigned IdxSkip = Idxs.size();
6972
6973 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6974}
6975
6976/// Given an aggregate and a sequence of indices, see if the scalar value
6977/// indexed is already around as a register, for example if it was inserted
6978/// directly into the aggregate.
6979///
6980/// If InsertBefore is not null, this function will duplicate (modified)
6981/// insertvalues when a part of a nested struct is extracted.
6982Value *
6984 std::optional<BasicBlock::iterator> InsertBefore) {
6985 // Nothing to index? Just return V then (this is useful at the end of our
6986 // recursion).
6987 if (idx_range.empty())
6988 return V;
6989 // We have indices, so V should have an indexable type.
6990 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6991 "Not looking at a struct or array?");
6992 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6993 "Invalid indices for type?");
6994
6995 if (Constant *C = dyn_cast<Constant>(V)) {
6996 C = C->getAggregateElement(idx_range[0]);
6997 if (!C) return nullptr;
6998 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6999 }
7000
7002 // Loop the indices for the insertvalue instruction in parallel with the
7003 // requested indices
7004 const unsigned *req_idx = idx_range.begin();
7005 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7006 i != e; ++i, ++req_idx) {
7007 if (req_idx == idx_range.end()) {
7008 // We can't handle this without inserting insertvalues
7009 if (!InsertBefore)
7010 return nullptr;
7011
7012 // The requested index identifies a part of a nested aggregate. Handle
7013 // this specially. For example,
7014 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7015 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7016 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7017 // This can be changed into
7018 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7019 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7020 // which allows the unused 0,0 element from the nested struct to be
7021 // removed.
7022 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7023 *InsertBefore);
7024 }
7025
7026 // This insert value inserts something else than what we are looking for.
7027 // See if the (aggregate) value inserted into has the value we are
7028 // looking for, then.
7029 if (*req_idx != *i)
7030 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7031 InsertBefore);
7032 }
7033 // If we end up here, the indices of the insertvalue match with those
7034 // requested (though possibly only partially). Now we recursively look at
7035 // the inserted value, passing any remaining indices.
7036 return FindInsertedValue(I->getInsertedValueOperand(),
7037 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7038 }
7039
7041 // If we're extracting a value from an aggregate that was extracted from
7042 // something else, we can extract from that something else directly instead.
7043 // However, we will need to chain I's indices with the requested indices.
7044
7045 // Calculate the number of indices required
7046 unsigned size = I->getNumIndices() + idx_range.size();
7047 // Allocate some space to put the new indices in
7049 Idxs.reserve(size);
7050 // Add indices from the extract value instruction
7051 Idxs.append(I->idx_begin(), I->idx_end());
7052
7053 // Add requested indices
7054 Idxs.append(idx_range.begin(), idx_range.end());
7055
7056 assert(Idxs.size() == size
7057 && "Number of indices added not correct?");
7058
7059 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7060 }
7061 // Otherwise, we don't know (such as, extracting from a function return value
7062 // or load instruction)
7063 return nullptr;
7064}
7065
7066// If V refers to an initialized global constant, set Slice either to
7067// its initializer if the size of its elements equals ElementSize, or,
7068// for ElementSize == 8, to its representation as an array of unsiged
7069// char. Return true on success.
7070// Offset is in the unit "nr of ElementSize sized elements".
7073 unsigned ElementSize, uint64_t Offset) {
7074 assert(V && "V should not be null.");
7075 assert((ElementSize % 8) == 0 &&
7076 "ElementSize expected to be a multiple of the size of a byte.");
7077 unsigned ElementSizeInBytes = ElementSize / 8;
7078
7079 // Drill down into the pointer expression V, ignoring any intervening
7080 // casts, and determine the identity of the object it references along
7081 // with the cumulative byte offset into it.
7082 const GlobalVariable *GV =
7084 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7085 // Fail if V is not based on constant global object.
7086 return false;
7087
7088 const DataLayout &DL = GV->getDataLayout();
7089 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7090
7092 /*AllowNonInbounds*/ true))
7093 // Fail if a constant offset could not be determined.
7094 return false;
7095
7096 uint64_t StartIdx = Off.getLimitedValue();
7097 if (StartIdx == UINT64_MAX)
7098 // Fail if the constant offset is excessive.
7099 return false;
7100
7101 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7102 // elements. Simply bail out if that isn't possible.
7103 if ((StartIdx % ElementSizeInBytes) != 0)
7104 return false;
7105
7106 Offset += StartIdx / ElementSizeInBytes;
7107 ConstantDataArray *Array = nullptr;
7108 ArrayType *ArrayTy = nullptr;
7109
7110 if (GV->getInitializer()->isNullValue()) {
7111 Type *GVTy = GV->getValueType();
7112 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7113 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7114
7115 Slice.Array = nullptr;
7116 Slice.Offset = 0;
7117 // Return an empty Slice for undersized constants to let callers
7118 // transform even undefined library calls into simpler, well-defined
7119 // expressions. This is preferable to making the calls although it
7120 // prevents sanitizers from detecting such calls.
7121 Slice.Length = Length < Offset ? 0 : Length - Offset;
7122 return true;
7123 }
7124
7125 auto *Init = const_cast<Constant *>(GV->getInitializer());
7126 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7127 Type *InitElTy = ArrayInit->getElementType();
7128 if (InitElTy->isIntegerTy(ElementSize)) {
7129 // If Init is an initializer for an array of the expected type
7130 // and size, use it as is.
7131 Array = ArrayInit;
7132 ArrayTy = ArrayInit->getType();
7133 }
7134 }
7135
7136 if (!Array) {
7137 if (ElementSize != 8)
7138 // TODO: Handle conversions to larger integral types.
7139 return false;
7140
7141 // Otherwise extract the portion of the initializer starting
7142 // at Offset as an array of bytes, and reset Offset.
7144 if (!Init)
7145 return false;
7146
7147 Offset = 0;
7149 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7150 }
7151
7152 uint64_t NumElts = ArrayTy->getArrayNumElements();
7153 if (Offset > NumElts)
7154 return false;
7155
7156 Slice.Array = Array;
7157 Slice.Offset = Offset;
7158 Slice.Length = NumElts - Offset;
7159 return true;
7160}
7161
7162/// Extract bytes from the initializer of the constant array V, which need
7163/// not be a nul-terminated string. On success, store the bytes in Str and
7164/// return true. When TrimAtNul is set, Str will contain only the bytes up
7165/// to but not including the first nul. Return false on failure.
7167 bool TrimAtNul) {
7169 if (!getConstantDataArrayInfo(V, Slice, 8))
7170 return false;
7171
7172 if (Slice.Array == nullptr) {
7173 if (TrimAtNul) {
7174 // Return a nul-terminated string even for an empty Slice. This is
7175 // safe because all existing SimplifyLibcalls callers require string
7176 // arguments and the behavior of the functions they fold is undefined
7177 // otherwise. Folding the calls this way is preferable to making
7178 // the undefined library calls, even though it prevents sanitizers
7179 // from reporting such calls.
7180 Str = StringRef();
7181 return true;
7182 }
7183 if (Slice.Length == 1) {
7184 Str = StringRef("", 1);
7185 return true;
7186 }
7187 // We cannot instantiate a StringRef as we do not have an appropriate string
7188 // of 0s at hand.
7189 return false;
7190 }
7191
7192 // Start out with the entire array in the StringRef.
7193 Str = Slice.Array->getAsString();
7194 // Skip over 'offset' bytes.
7195 Str = Str.substr(Slice.Offset);
7196
7197 if (TrimAtNul) {
7198 // Trim off the \0 and anything after it. If the array is not nul
7199 // terminated, we just return the whole end of string. The client may know
7200 // some other way that the string is length-bound.
7201 Str = Str.substr(0, Str.find('\0'));
7202 }
7203 return true;
7204}
7205
7206// These next two are very similar to the above, but also look through PHI
7207// nodes.
7208// TODO: See if we can integrate these two together.
7209
7210/// If we can compute the length of the string pointed to by
7211/// the specified pointer, return 'len+1'. If we can't, return 0.
7214 unsigned CharSize) {
7215 // Look through noop bitcast instructions.
7216 V = V->stripPointerCasts();
7217
7218 // If this is a PHI node, there are two cases: either we have already seen it
7219 // or we haven't.
7220 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7221 if (!PHIs.insert(PN).second)
7222 return ~0ULL; // already in the set.
7223
7224 // If it was new, see if all the input strings are the same length.
7225 uint64_t LenSoFar = ~0ULL;
7226 for (Value *IncValue : PN->incoming_values()) {
7227 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7228 if (Len == 0) return 0; // Unknown length -> unknown.
7229
7230 if (Len == ~0ULL) continue;
7231
7232 if (Len != LenSoFar && LenSoFar != ~0ULL)
7233 return 0; // Disagree -> unknown.
7234 LenSoFar = Len;
7235 }
7236
7237 // Success, all agree.
7238 return LenSoFar;
7239 }
7240
7241 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7242 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7243 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7244 if (Len1 == 0) return 0;
7245 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7246 if (Len2 == 0) return 0;
7247 if (Len1 == ~0ULL) return Len2;
7248 if (Len2 == ~0ULL) return Len1;
7249 if (Len1 != Len2) return 0;
7250 return Len1;
7251 }
7252
7253 // Otherwise, see if we can read the string.
7255 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7256 return 0;
7257
7258 if (Slice.Array == nullptr)
7259 // Zeroinitializer (including an empty one).
7260 return 1;
7261
7262 // Search for the first nul character. Return a conservative result even
7263 // when there is no nul. This is safe since otherwise the string function
7264 // being folded such as strlen is undefined, and can be preferable to
7265 // making the undefined library call.
7266 unsigned NullIndex = 0;
7267 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7268 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7269 break;
7270 }
7271
7272 return NullIndex + 1;
7273}
7274
7275/// If we can compute the length of the string pointed to by
7276/// the specified pointer, return 'len+1'. If we can't, return 0.
7277uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7278 if (!V->getType()->isPointerTy())
7279 return 0;
7280
7282 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7283 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7284 // an empty string as a length.
7285 return Len == ~0ULL ? 1 : Len;
7286}
7287
7288const Value *
7290 bool MustPreserveOffset,
7291 bool MustPreserveProvenance) {
7292 assert(Call &&
7293 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7294 if (const Value *RV = Call->getReturnedArgOperand())
7295 return RV;
7296 // This can be used only as a aliasing property.
7298 Call, MustPreserveOffset, MustPreserveProvenance))
7299 return Call->getArgOperand(0);
7300 return nullptr;
7301}
7302
7304 const CallBase *Call, bool MustPreserveOffset,
7305 bool MustPreserveProvenance) {
7306 switch (Call->getIntrinsicID()) {
7307 case Intrinsic::launder_invariant_group:
7308 case Intrinsic::aarch64_irg:
7309 case Intrinsic::aarch64_tagp:
7310 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7311 // input pointer (and thus preserves the byte offset, which is the property
7312 // the MustPreserveOffset flag selects). However, it will not necessarily
7313 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7314 // descriptor", which has "all loads return 0, all stores are dropped"
7315 // semantics. Given the context of this intrinsic list, no one should be
7316 // relying on such a strict bit-exact null mapping (and, at time of
7317 // writing, they are not), but we document this fact out of an abundance
7318 // of caution.
7319 case Intrinsic::amdgcn_make_buffer_rsrc:
7320 return !MustPreserveProvenance;
7321 case Intrinsic::ptrmask:
7322 return !MustPreserveOffset;
7323 case Intrinsic::threadlocal_address:
7324 // The underlying variable changes with thread ID. The Thread ID may change
7325 // at coroutine suspend points.
7326 return !Call->getParent()->getParent()->isPresplitCoroutine();
7327 default:
7328 return false;
7329 }
7330}
7331
7332/// \p PN defines a loop-variant pointer to an object. Check if the
7333/// previous iteration of the loop was referring to the same object as \p PN.
7335 const LoopInfo *LI) {
7336 // Find the loop-defined value.
7337 Loop *L = LI->getLoopFor(PN->getParent());
7338 if (PN->getNumIncomingValues() != 2)
7339 return true;
7340
7341 // Find the value from previous iteration.
7342 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7343 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7344 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7345 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7346 return true;
7347
7348 // If a new pointer is loaded in the loop, the pointer references a different
7349 // object in every iteration. E.g.:
7350 // for (i)
7351 // int *p = a[i];
7352 // ...
7353 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7354 if (!L->isLoopInvariant(Load->getPointerOperand()))
7355 return false;
7356 return true;
7357}
7358
7359const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7360 bool MustPreserveProvenance) {
7361 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7362 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7363 const Value *PtrOp = GEP->getPointerOperand();
7364 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7365 return V;
7366 V = PtrOp;
7367 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7368 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7369 Value *NewV = cast<Operator>(V)->getOperand(0);
7370 if (!NewV->getType()->isPointerTy())
7371 return V;
7372 V = NewV;
7373 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7374 if (GA->isInterposable())
7375 return V;
7376 V = GA->getAliasee();
7377 } else {
7378 if (auto *PHI = dyn_cast<PHINode>(V)) {
7379 // Look through single-arg phi nodes created by LCSSA.
7380 if (PHI->getNumIncomingValues() == 1) {
7381 V = PHI->getIncomingValue(0);
7382 continue;
7383 }
7384 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7385 // CaptureTracking can know about special capturing properties of some
7386 // intrinsics like launder.invariant.group, that can't be expressed with
7387 // the attributes, but have properties like returning aliasing pointer.
7388 // Because some analysis may assume that nocaptured pointer is not
7389 // returned from some special intrinsic (because function would have to
7390 // be marked with returns attribute), it is crucial to use this function
7391 // because it should be in sync with CaptureTracking. Not using it may
7392 // cause weird miscompilations where 2 aliasing pointers are assumed to
7393 // noalias.
7395 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7396 V = RP;
7397 continue;
7398 }
7399 }
7400
7401 return V;
7402 }
7403 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7404 }
7405 return V;
7406}
7407
7410 const LoopInfo *LI, unsigned MaxLookup) {
7413 Worklist.push_back(V);
7414 do {
7415 const Value *P = Worklist.pop_back_val();
7416 P = getUnderlyingObject(P, MaxLookup);
7417
7418 if (!Visited.insert(P).second)
7419 continue;
7420
7421 if (auto *SI = dyn_cast<SelectInst>(P)) {
7422 Worklist.push_back(SI->getTrueValue());
7423 Worklist.push_back(SI->getFalseValue());
7424 continue;
7425 }
7426
7427 if (auto *PN = dyn_cast<PHINode>(P)) {
7428 // If this PHI changes the underlying object in every iteration of the
7429 // loop, don't look through it. Consider:
7430 // int **A;
7431 // for (i) {
7432 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7433 // Curr = A[i];
7434 // *Prev, *Curr;
7435 //
7436 // Prev is tracking Curr one iteration behind so they refer to different
7437 // underlying objects.
7438 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7440 append_range(Worklist, PN->incoming_values());
7441 else
7442 Objects.push_back(P);
7443 continue;
7444 }
7445
7446 Objects.push_back(P);
7447 } while (!Worklist.empty());
7448}
7449
7451 bool MustPreserveProvenance) {
7452 const unsigned MaxVisited = 8;
7453
7456 Worklist.push_back(V);
7457 const Value *Object = nullptr;
7458 // Used as fallback if we can't find a common underlying object through
7459 // recursion.
7460 bool First = true;
7461 const Value *FirstObject =
7462 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7463 do {
7464 const Value *P = Worklist.pop_back_val();
7465 P = First ? FirstObject
7467 MustPreserveProvenance);
7468 First = false;
7469
7470 if (!Visited.insert(P).second)
7471 continue;
7472
7473 if (Visited.size() == MaxVisited)
7474 return FirstObject;
7475
7476 if (auto *SI = dyn_cast<SelectInst>(P)) {
7477 Worklist.push_back(SI->getTrueValue());
7478 Worklist.push_back(SI->getFalseValue());
7479 continue;
7480 }
7481
7482 if (auto *PN = dyn_cast<PHINode>(P)) {
7483 append_range(Worklist, PN->incoming_values());
7484 continue;
7485 }
7486
7487 if (!Object)
7488 Object = P;
7489 else if (Object != P)
7490 return FirstObject;
7491 } while (!Worklist.empty());
7492
7493 return Object ? Object : FirstObject;
7494}
7495
7496/// This is the function that does the work of looking through basic
7497/// ptrtoint+arithmetic+inttoptr sequences.
7498static const Value *getUnderlyingObjectFromInt(const Value *V) {
7499 do {
7500 if (const Operator *U = dyn_cast<Operator>(V)) {
7501 // If we find a ptrtoint, we can transfer control back to the
7502 // regular getUnderlyingObjectFromInt.
7503 if (U->getOpcode() == Instruction::PtrToInt)
7504 return U->getOperand(0);
7505 // If we find an add of a constant, a multiplied value, or a phi, it's
7506 // likely that the other operand will lead us to the base
7507 // object. We don't have to worry about the case where the
7508 // object address is somehow being computed by the multiply,
7509 // because our callers only care when the result is an
7510 // identifiable object.
7511 if (U->getOpcode() != Instruction::Add ||
7512 (!isa<ConstantInt>(U->getOperand(1)) &&
7513 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7514 !isa<PHINode>(U->getOperand(1))))
7515 return V;
7516 V = U->getOperand(0);
7517 } else {
7518 return V;
7519 }
7520 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7521 } while (true);
7522}
7523
7524/// This is a wrapper around getUnderlyingObjects and adds support for basic
7525/// ptrtoint+arithmetic+inttoptr sequences.
7526/// It returns false if unidentified object is found in getUnderlyingObjects.
7528 SmallVectorImpl<Value *> &Objects) {
7530 SmallVector<const Value *, 4> Working(1, V);
7531 bool AllObjectsIdentified = true;
7532 do {
7533 V = Working.pop_back_val();
7534
7536 getUnderlyingObjects(V, Objs);
7537
7538 for (const Value *V : Objs) {
7539 if (!Visited.insert(V).second)
7540 continue;
7541 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7542 const Value *O =
7543 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7544 if (O->getType()->isPointerTy()) {
7545 Working.push_back(O);
7546 continue;
7547 }
7548 }
7549 AllObjectsIdentified &= isIdentifiedObject(V);
7550 Objects.push_back(const_cast<Value *>(V));
7551 }
7552 } while (!Working.empty());
7553 return AllObjectsIdentified;
7554}
7555
7557 AllocaInst *Result = nullptr;
7559 SmallVector<Value *, 4> Worklist;
7560
7561 auto AddWork = [&](Value *V) {
7562 if (Visited.insert(V).second)
7563 Worklist.push_back(V);
7564 };
7565
7566 AddWork(V);
7567 do {
7568 V = Worklist.pop_back_val();
7569 assert(Visited.count(V));
7570
7571 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7572 if (Result && Result != AI)
7573 return nullptr;
7574 Result = AI;
7575 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7576 AddWork(CI->getOperand(0));
7577 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7578 for (Value *IncValue : PN->incoming_values())
7579 AddWork(IncValue);
7580 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7581 AddWork(SI->getTrueValue());
7582 AddWork(SI->getFalseValue());
7584 if (OffsetZero && !GEP->hasAllZeroIndices())
7585 return nullptr;
7586 AddWork(GEP->getPointerOperand());
7587 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7588 Value *Returned = CB->getReturnedArgOperand();
7589 if (Returned)
7590 AddWork(Returned);
7591 else
7592 return nullptr;
7593 } else {
7594 return nullptr;
7595 }
7596 } while (!Worklist.empty());
7597
7598 return Result;
7599}
7600
7602 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7603 for (const User *U : V->users()) {
7605 if (!II)
7606 return false;
7607
7608 if (AllowLifetime && II->isLifetimeStartOrEnd())
7609 continue;
7610
7611 if (AllowDroppable && II->isDroppable())
7612 continue;
7613
7614 return false;
7615 }
7616 return true;
7617}
7618
7621 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7622}
7625 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7626}
7627
7629 if (auto *II = dyn_cast<IntrinsicInst>(I))
7630 return isTriviallyVectorizable(II->getIntrinsicID());
7631 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7632 return (!Shuffle || Shuffle->isSelect()) &&
7634}
7635
7637 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7638 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7639 bool IgnoreUBImplyingAttrs) {
7640 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7641 AC, DT, TLI, UseVariableInfo,
7642 IgnoreUBImplyingAttrs);
7643}
7644
7646 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7647 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7648 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7649#ifndef NDEBUG
7650 if (Inst->getOpcode() != Opcode) {
7651 // Check that the operands are actually compatible with the Opcode override.
7652 auto hasEqualReturnAndLeadingOperandTypes =
7653 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7654 if (Inst->getNumOperands() < NumLeadingOperands)
7655 return false;
7656 const Type *ExpectedType = Inst->getType();
7657 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7658 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7659 return false;
7660 return true;
7661 };
7663 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7664 assert(!Instruction::isUnaryOp(Opcode) ||
7665 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7666 }
7667#endif
7668
7669 switch (Opcode) {
7670 default:
7671 return true;
7672 case Instruction::UDiv:
7673 case Instruction::URem: {
7674 // x / y is undefined if y == 0.
7675 const APInt *V;
7676 if (match(Inst->getOperand(1), m_APInt(V)))
7677 return *V != 0;
7678 return false;
7679 }
7680 case Instruction::SDiv:
7681 case Instruction::SRem: {
7682 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7683 const APInt *Numerator, *Denominator;
7684 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7685 return false;
7686 // We cannot hoist this division if the denominator is 0.
7687 if (*Denominator == 0)
7688 return false;
7689 // It's safe to hoist if the denominator is not 0 or -1.
7690 if (!Denominator->isAllOnes())
7691 return true;
7692 // At this point we know that the denominator is -1. It is safe to hoist as
7693 // long we know that the numerator is not INT_MIN.
7694 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7695 return !Numerator->isMinSignedValue();
7696 // The numerator *might* be MinSignedValue.
7697 return false;
7698 }
7699 case Instruction::Load: {
7700 if (!UseVariableInfo)
7701 return false;
7702
7703 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7704 if (!LI)
7705 return false;
7706 if (mustSuppressSpeculation(*LI))
7707 return false;
7708 const DataLayout &DL = LI->getDataLayout();
7710 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7711 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7712 }
7713 case Instruction::Call: {
7714 auto *CI = dyn_cast<const CallInst>(Inst);
7715 if (!CI)
7716 return false;
7717 const Function *Callee = CI->getCalledFunction();
7718
7719 // The called function could have undefined behavior or side-effects, even
7720 // if marked readnone nounwind.
7721 if (!Callee || !Callee->isSpeculatable())
7722 return false;
7723 // Since the operands may be changed after hoisting, undefined behavior may
7724 // be triggered by some UB-implying attributes.
7725 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7726 }
7727 case Instruction::VAArg:
7728 case Instruction::Alloca:
7729 case Instruction::Invoke:
7730 case Instruction::CallBr:
7731 case Instruction::PHI:
7732 case Instruction::Store:
7733 case Instruction::Ret:
7734 case Instruction::UncondBr:
7735 case Instruction::CondBr:
7736 case Instruction::IndirectBr:
7737 case Instruction::Switch:
7738 case Instruction::Unreachable:
7739 case Instruction::Fence:
7740 case Instruction::AtomicRMW:
7741 case Instruction::AtomicCmpXchg:
7742 case Instruction::LandingPad:
7743 case Instruction::Resume:
7744 case Instruction::CatchSwitch:
7745 case Instruction::CatchPad:
7746 case Instruction::CatchRet:
7747 case Instruction::CleanupPad:
7748 case Instruction::CleanupRet:
7749 return false; // Misc instructions which have effects
7750 }
7751}
7752
7754 if (I.mayReadOrWriteMemory())
7755 // Memory dependency possible
7756 return true;
7758 // Can't move above a maythrow call or infinite loop. Or if an
7759 // inalloca alloca, above a stacksave call.
7760 return true;
7762 // 1) Can't reorder two inf-loop calls, even if readonly
7763 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7764 // safe to speculative execute. (Inverse of above)
7765 return true;
7766 return false;
7767}
7768
7769/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7783
7784/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7787 bool ForSigned,
7788 const SimplifyQuery &SQ) {
7789 ConstantRange CR1 =
7790 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7791 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7794 return CR1.intersectWith(CR2, RangeType);
7795}
7796
7798 const Value *RHS,
7799 const SimplifyQuery &SQ,
7800 bool IsNSW) {
7801 ConstantRange LHSRange =
7802 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7803 ConstantRange RHSRange =
7804 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7805
7806 // mul nsw of two non-negative numbers is also nuw.
7807 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7809
7810 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7811}
7812
7814 const Value *RHS,
7815 const SimplifyQuery &SQ) {
7816 // Multiplying n * m significant bits yields a result of n + m significant
7817 // bits. If the total number of significant bits does not exceed the
7818 // result bit width (minus 1), there is no overflow.
7819 // This means if we have enough leading sign bits in the operands
7820 // we can guarantee that the result does not overflow.
7821 // Ref: "Hacker's Delight" by Henry Warren
7822 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7823
7824 // Note that underestimating the number of sign bits gives a more
7825 // conservative answer.
7826 unsigned SignBits =
7827 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7828
7829 // First handle the easy case: if we have enough sign bits there's
7830 // definitely no overflow.
7831 if (SignBits > BitWidth + 1)
7833
7834 // There are two ambiguous cases where there can be no overflow:
7835 // SignBits == BitWidth + 1 and
7836 // SignBits == BitWidth
7837 // The second case is difficult to check, therefore we only handle the
7838 // first case.
7839 if (SignBits == BitWidth + 1) {
7840 // It overflows only when both arguments are negative and the true
7841 // product is exactly the minimum negative number.
7842 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7843 // For simplicity we just check if at least one side is not negative.
7844 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7845 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7846 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7848 }
7850}
7851
7854 const WithCache<const Value *> &RHS,
7855 const SimplifyQuery &SQ) {
7856 ConstantRange LHSRange =
7857 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7858 ConstantRange RHSRange =
7859 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7860 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7861}
7862
7863static OverflowResult
7866 const AddOperator *Add, const SimplifyQuery &SQ) {
7867 if (Add && Add->hasNoSignedWrap()) {
7869 }
7870
7871 // If LHS and RHS each have at least two sign bits, the addition will look
7872 // like
7873 //
7874 // XX..... +
7875 // YY.....
7876 //
7877 // If the carry into the most significant position is 0, X and Y can't both
7878 // be 1 and therefore the carry out of the addition is also 0.
7879 //
7880 // If the carry into the most significant position is 1, X and Y can't both
7881 // be 0 and therefore the carry out of the addition is also 1.
7882 //
7883 // Since the carry into the most significant position is always equal to
7884 // the carry out of the addition, there is no signed overflow.
7885 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7887
7888 ConstantRange LHSRange =
7889 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7890 ConstantRange RHSRange =
7891 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7892 OverflowResult OR =
7893 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7895 return OR;
7896
7897 // The remaining code needs Add to be available. Early returns if not so.
7898 if (!Add)
7900
7901 // If the sign of Add is the same as at least one of the operands, this add
7902 // CANNOT overflow. If this can be determined from the known bits of the
7903 // operands the above signedAddMayOverflow() check will have already done so.
7904 // The only other way to improve on the known bits is from an assumption, so
7905 // call computeKnownBitsFromContext() directly.
7906 bool LHSOrRHSKnownNonNegative =
7907 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7908 bool LHSOrRHSKnownNegative =
7909 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7910 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7911 KnownBits AddKnown(LHSRange.getBitWidth());
7912 computeKnownBitsFromContext(Add, AddKnown, SQ);
7913 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7914 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7916 }
7917
7919}
7920
7922 const Value *RHS,
7923 const SimplifyQuery &SQ) {
7924 // X - (X % ?)
7925 // The remainder of a value can't have greater magnitude than itself,
7926 // so the subtraction can't overflow.
7927
7928 // X - (X -nuw ?)
7929 // In the minimal case, this would simplify to "?", so there's no subtract
7930 // at all. But if this analysis is used to peek through casts, for example,
7931 // then determining no-overflow may allow other transforms.
7932
7933 // TODO: There are other patterns like this.
7934 // See simplifyICmpWithBinOpOnLHS() for candidates.
7935 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7936 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7937 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7939
7940 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
7941 SQ.DL)) {
7942 if (*C)
7945 }
7946
7947 ConstantRange LHSRange =
7948 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7949 ConstantRange RHSRange =
7950 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7951 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7952}
7953
7955 const Value *RHS,
7956 const SimplifyQuery &SQ) {
7957 // X - (X % ?)
7958 // The remainder of a value can't have greater magnitude than itself,
7959 // so the subtraction can't overflow.
7960
7961 // X - (X -nsw ?)
7962 // In the minimal case, this would simplify to "?", so there's no subtract
7963 // at all. But if this analysis is used to peek through casts, for example,
7964 // then determining no-overflow may allow other transforms.
7965 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7966 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7967 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7969
7970 // If LHS and RHS each have at least two sign bits, the subtraction
7971 // cannot overflow.
7972 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7974
7975 ConstantRange LHSRange =
7976 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7977 ConstantRange RHSRange =
7978 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7979 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7980}
7981
7983 const DominatorTree &DT) {
7984 SmallVector<const CondBrInst *, 2> GuardingBranches;
7986
7987 for (const User *U : WO->users()) {
7988 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7989 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7990
7991 if (EVI->getIndices()[0] == 0)
7992 Results.push_back(EVI);
7993 else {
7994 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7995
7996 for (const auto *U : EVI->users())
7997 if (const auto *B = dyn_cast<CondBrInst>(U))
7998 GuardingBranches.push_back(B);
7999 }
8000 } else {
8001 // We are using the aggregate directly in a way we don't want to analyze
8002 // here (storing it to a global, say).
8003 return false;
8004 }
8005 }
8006
8007 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8008 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8009
8010 // Check if all users of the add are provably no-wrap.
8011 for (const auto *Result : Results) {
8012 // If the extractvalue itself is not executed on overflow, the we don't
8013 // need to check each use separately, since domination is transitive.
8014 if (DT.dominates(NoWrapEdge, Result->getParent()))
8015 continue;
8016
8017 for (const auto &RU : Result->uses())
8018 if (!DT.dominates(NoWrapEdge, RU))
8019 return false;
8020 }
8021
8022 return true;
8023 };
8024
8025 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8026}
8027
8028/// Shifts return poison if shiftwidth is larger than the bitwidth.
8029static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8030 auto *C = dyn_cast<Constant>(ShiftAmount);
8031 if (!C)
8032 return false;
8033
8034 // Shifts return poison if shiftwidth is larger than the bitwidth.
8036 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8037 unsigned NumElts = FVTy->getNumElements();
8038 for (unsigned i = 0; i < NumElts; ++i)
8039 ShiftAmounts.push_back(C->getAggregateElement(i));
8040 } else if (isa<ScalableVectorType>(C->getType()))
8041 return false; // Can't tell, just return false to be safe
8042 else
8043 ShiftAmounts.push_back(C);
8044
8045 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8046 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8047 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8048 });
8049
8050 return Safe;
8051}
8052
8054 bool ConsiderFlagsAndMetadata) {
8055
8056 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8057 Op->hasPoisonGeneratingAnnotations())
8058 return true;
8059
8060 unsigned Opcode = Op->getOpcode();
8061
8062 // Check whether opcode is a poison/undef-generating operation
8063 switch (Opcode) {
8064 case Instruction::Shl:
8065 case Instruction::AShr:
8066 case Instruction::LShr:
8067 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8068 case Instruction::FPToSI:
8069 case Instruction::FPToUI:
8070 // fptosi/ui yields poison if the resulting value does not fit in the
8071 // destination type.
8072 return true;
8073 case Instruction::Call:
8074 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8075 switch (II->getIntrinsicID()) {
8076 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8077 case Intrinsic::ctlz:
8078 case Intrinsic::cttz:
8079 case Intrinsic::abs:
8080 // We're not considering flags so it is safe to just return false.
8081 return false;
8082 case Intrinsic::sshl_sat:
8083 case Intrinsic::ushl_sat:
8084 if (!includesPoison(Kind) ||
8085 shiftAmountKnownInRange(II->getArgOperand(1)))
8086 return false;
8087 break;
8088 }
8089 }
8090 [[fallthrough]];
8091 case Instruction::CallBr:
8092 case Instruction::Invoke: {
8093 const auto *CB = cast<CallBase>(Op);
8094 return !CB->hasRetAttr(Attribute::NoUndef) &&
8095 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8096 }
8097 case Instruction::InsertElement:
8098 case Instruction::ExtractElement: {
8099 // If index exceeds the length of the vector, it returns poison
8100 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8101 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8102 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8103 if (includesPoison(Kind))
8104 return !Idx ||
8105 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8106 return false;
8107 }
8108 case Instruction::ShuffleVector: {
8110 ? cast<ConstantExpr>(Op)->getShuffleMask()
8111 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8112 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8113 }
8114 case Instruction::FNeg:
8115 case Instruction::PHI:
8116 case Instruction::Select:
8117 case Instruction::ExtractValue:
8118 case Instruction::InsertValue:
8119 case Instruction::Freeze:
8120 case Instruction::ICmp:
8121 case Instruction::FCmp:
8122 case Instruction::GetElementPtr:
8123 return false;
8124 case Instruction::AddrSpaceCast:
8125 return true;
8126 default: {
8127 const auto *CE = dyn_cast<ConstantExpr>(Op);
8128 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8129 return false;
8130 else if (Instruction::isBinaryOp(Opcode))
8131 return false;
8132 // Be conservative and return true.
8133 return true;
8134 }
8135 }
8136}
8137
8139 bool ConsiderFlagsAndMetadata) {
8140 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8141 ConsiderFlagsAndMetadata);
8142}
8143
8144bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8145 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8146 ConsiderFlagsAndMetadata);
8147}
8148
8149static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8150 unsigned Depth) {
8151 if (ValAssumedPoison == V)
8152 return true;
8153
8154 const unsigned MaxDepth = 2;
8155 if (Depth >= MaxDepth)
8156 return false;
8157
8158 if (const auto *I = dyn_cast<Instruction>(V)) {
8159 if (any_of(I->operands(), [=](const Use &Op) {
8160 return propagatesPoison(Op) &&
8161 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8162 }))
8163 return true;
8164
8165 // V = extractvalue V0, idx
8166 // V2 = extractvalue V0, idx2
8167 // V0's elements are all poison or not. (e.g., add_with_overflow)
8168 const WithOverflowInst *II;
8170 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8171 llvm::is_contained(II->args(), ValAssumedPoison)))
8172 return true;
8173 }
8174 return false;
8175}
8176
8177static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8178 unsigned Depth) {
8179 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8180 return true;
8181
8182 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8183 return true;
8184
8185 const unsigned MaxDepth = 2;
8186 if (Depth >= MaxDepth)
8187 return false;
8188
8189 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8190 if (I && !canCreatePoison(cast<Operator>(I))) {
8191 return all_of(I->operands(), [=](const Value *Op) {
8192 return impliesPoison(Op, V, Depth + 1);
8193 });
8194 }
8195 return false;
8196}
8197
8198bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8199 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8200}
8201
8202static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8203
8205 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8206 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8208 return false;
8209
8210 if (isa<MetadataAsValue>(V))
8211 return false;
8212
8213 if (const auto *A = dyn_cast<Argument>(V)) {
8214 if (A->hasAttribute(Attribute::NoUndef) ||
8215 A->hasAttribute(Attribute::Dereferenceable) ||
8216 A->hasAttribute(Attribute::DereferenceableOrNull))
8217 return true;
8218 }
8219
8220 if (auto *C = dyn_cast<Constant>(V)) {
8221 if (isa<PoisonValue>(C))
8222 return !includesPoison(Kind);
8223
8224 if (isa<UndefValue>(C))
8225 return !includesUndef(Kind);
8226
8229 return true;
8230
8231 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8232 if (isa<ConstantExpr>(C)) {
8233 // Scalable vectors can use a ConstantExpr to build a splat.
8234 if (Constant *SplatC = C->getSplatValue())
8235 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8236 return true;
8237 } else {
8238 if (includesUndef(Kind) && C->containsUndefElement())
8239 return false;
8240 if (includesPoison(Kind) && C->containsPoisonElement())
8241 return false;
8242 return !C->containsConstantExpression();
8243 }
8244 }
8245 }
8246
8247 // Strip cast operations from a pointer value.
8248 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8249 // inbounds with zero offset. To guarantee that the result isn't poison, the
8250 // stripped pointer is checked as it has to be pointing into an allocated
8251 // object or be null `null` to ensure `inbounds` getelement pointers with a
8252 // zero offset could not produce poison.
8253 // It can strip off addrspacecast that do not change bit representation as
8254 // well. We believe that such addrspacecast is equivalent to no-op.
8255 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8256 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8257 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8258 return true;
8259
8260 auto OpCheck = [&](const Value *V) {
8261 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8262 };
8263
8264 if (auto *Opr = dyn_cast<Operator>(V)) {
8265 // If the value is a freeze instruction, then it can never
8266 // be undef or poison.
8267 if (isa<FreezeInst>(V))
8268 return true;
8269
8270 if (const auto *CB = dyn_cast<CallBase>(V)) {
8271 if (CB->hasRetAttr(Attribute::NoUndef) ||
8272 CB->hasRetAttr(Attribute::Dereferenceable) ||
8273 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8274 return true;
8275 }
8276
8277 if (!::canCreateUndefOrPoison(Opr, Kind,
8278 /*ConsiderFlagsAndMetadata=*/true)) {
8279 if (const auto *PN = dyn_cast<PHINode>(V)) {
8280 unsigned Num = PN->getNumIncomingValues();
8281 bool IsWellDefined = true;
8282 for (unsigned i = 0; i < Num; ++i) {
8283 if (PN == PN->getIncomingValue(i))
8284 continue;
8285 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8286 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8287 DT, Depth + 1, Kind)) {
8288 IsWellDefined = false;
8289 break;
8290 }
8291 }
8292 if (IsWellDefined)
8293 return true;
8294 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8295 : nullptr) {
8296 // For splats we only need to check the value being splatted.
8297 if (OpCheck(Splat))
8298 return true;
8299 } else if (all_of(Opr->operands(), OpCheck))
8300 return true;
8301 }
8302 }
8303
8304 if (auto *I = dyn_cast<LoadInst>(V))
8305 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8306 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8307 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8308 return true;
8309
8311 return true;
8312
8313 // CtxI may be null or a cloned instruction.
8314 if (!CtxI || !CtxI->getParent() || !DT)
8315 return false;
8316
8317 auto *DNode = DT->getNode(CtxI->getParent());
8318 if (!DNode)
8319 // Unreachable block
8320 return false;
8321
8322 // If V is used as a branch condition before reaching CtxI, V cannot be
8323 // undef or poison.
8324 // br V, BB1, BB2
8325 // BB1:
8326 // CtxI ; V cannot be undef or poison here
8327 auto *Dominator = DNode->getIDom();
8328 // This check is purely for compile time reasons: we can skip the IDom walk
8329 // if what we are checking for includes undef and the value is not an integer.
8330 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8331 while (Dominator) {
8332 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8333
8334 Value *Cond = nullptr;
8335 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8336 Cond = BI->getCondition();
8337 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8338 Cond = SI->getCondition();
8339 }
8340
8341 if (Cond) {
8342 if (Cond == V)
8343 return true;
8344 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8345 // For poison, we can analyze further
8346 auto *Opr = cast<Operator>(Cond);
8347 if (any_of(Opr->operands(), [V](const Use &U) {
8348 return V == U && propagatesPoison(U);
8349 }))
8350 return true;
8351 }
8352 }
8353
8354 Dominator = Dominator->getIDom();
8355 }
8356
8357 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8358 return true;
8359
8360 return false;
8361}
8362
8364 const Instruction *CtxI,
8365 const DominatorTree *DT,
8366 unsigned Depth) {
8367 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8369}
8370
8372 const Instruction *CtxI,
8373 const DominatorTree *DT, unsigned Depth) {
8374 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8376}
8377
8379 const Instruction *CtxI,
8380 const DominatorTree *DT, unsigned Depth) {
8381 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8383}
8384
8385/// Return true if undefined behavior would provably be executed on the path to
8386/// OnPathTo if Root produced a posion result. Note that this doesn't say
8387/// anything about whether OnPathTo is actually executed or whether Root is
8388/// actually poison. This can be used to assess whether a new use of Root can
8389/// be added at a location which is control equivalent with OnPathTo (such as
8390/// immediately before it) without introducing UB which didn't previously
8391/// exist. Note that a false result conveys no information.
8393 Instruction *OnPathTo,
8394 DominatorTree *DT) {
8395 // Basic approach is to assume Root is poison, propagate poison forward
8396 // through all users we can easily track, and then check whether any of those
8397 // users are provable UB and must execute before out exiting block might
8398 // exit.
8399
8400 // The set of all recursive users we've visited (which are assumed to all be
8401 // poison because of said visit)
8404 Worklist.push_back(Root);
8405 while (!Worklist.empty()) {
8406 const Instruction *I = Worklist.pop_back_val();
8407
8408 // If we know this must trigger UB on a path leading our target.
8409 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8410 return true;
8411
8412 // If we can't analyze propagation through this instruction, just skip it
8413 // and transitive users. Safe as false is a conservative result.
8414 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8415 return KnownPoison.contains(U) && propagatesPoison(U);
8416 }))
8417 continue;
8418
8419 if (KnownPoison.insert(I).second)
8420 for (const User *User : I->users())
8421 Worklist.push_back(cast<Instruction>(User));
8422 }
8423
8424 // Might be non-UB, or might have a path we couldn't prove must execute on
8425 // way to exiting bb.
8426 return false;
8427}
8428
8430 const SimplifyQuery &SQ) {
8431 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8432 Add, SQ);
8433}
8434
8437 const WithCache<const Value *> &RHS,
8438 const SimplifyQuery &SQ) {
8439 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8440}
8441
8443 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8444 // of time because it's possible for another thread to interfere with it for an
8445 // arbitrary length of time, but programs aren't allowed to rely on that.
8446
8447 // If there is no successor, then execution can't transfer to it.
8448 if (isa<ReturnInst>(I))
8449 return false;
8451 return false;
8452
8453 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8454 // Instruction::willReturn.
8455 //
8456 // FIXME: Move this check into Instruction::willReturn.
8457 if (isa<CatchPadInst>(I)) {
8458 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8459 default:
8460 // A catchpad may invoke exception object constructors and such, which
8461 // in some languages can be arbitrary code, so be conservative by default.
8462 return false;
8464 // For CoreCLR, it just involves a type test.
8465 return true;
8466 }
8467 }
8468
8469 // An instruction that returns without throwing must transfer control flow
8470 // to a successor.
8471 return !I->mayThrow() && I->willReturn();
8472}
8473
8475 // TODO: This is slightly conservative for invoke instruction since exiting
8476 // via an exception *is* normal control for them.
8477 for (const Instruction &I : *BB)
8479 return false;
8480 return true;
8481}
8482
8489
8492 assert(ScanLimit && "scan limit must be non-zero");
8493 for (const Instruction &I : Range) {
8494 if (--ScanLimit == 0)
8495 return false;
8497 return false;
8498 }
8499 return true;
8500}
8501
8503 const Loop *L) {
8504 // The loop header is guaranteed to be executed for every iteration.
8505 //
8506 // FIXME: Relax this constraint to cover all basic blocks that are
8507 // guaranteed to be executed at every iteration.
8508 if (I->getParent() != L->getHeader()) return false;
8509
8510 for (const Instruction &LI : *L->getHeader()) {
8511 if (&LI == I) return true;
8512 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8513 }
8514 llvm_unreachable("Instruction not contained in its own parent basic block.");
8515}
8516
8518 switch (IID) {
8519 // TODO: Add more intrinsics.
8520 case Intrinsic::sadd_with_overflow:
8521 case Intrinsic::ssub_with_overflow:
8522 case Intrinsic::smul_with_overflow:
8523 case Intrinsic::uadd_with_overflow:
8524 case Intrinsic::usub_with_overflow:
8525 case Intrinsic::umul_with_overflow:
8526 // If an input is a vector containing a poison element, the
8527 // two output vectors (calculated results, overflow bits)'
8528 // corresponding lanes are poison.
8529 return true;
8530 case Intrinsic::ctpop:
8531 case Intrinsic::ctlz:
8532 case Intrinsic::cttz:
8533 case Intrinsic::abs:
8534 case Intrinsic::smax:
8535 case Intrinsic::smin:
8536 case Intrinsic::umax:
8537 case Intrinsic::umin:
8538 case Intrinsic::scmp:
8539 case Intrinsic::smulh:
8540 case Intrinsic::umulh:
8541 case Intrinsic::is_fpclass:
8542 case Intrinsic::ptrmask:
8543 case Intrinsic::ucmp:
8544 case Intrinsic::bitreverse:
8545 case Intrinsic::bswap:
8546 case Intrinsic::sadd_sat:
8547 case Intrinsic::ssub_sat:
8548 case Intrinsic::sshl_sat:
8549 case Intrinsic::uadd_sat:
8550 case Intrinsic::usub_sat:
8551 case Intrinsic::ushl_sat:
8552 case Intrinsic::smul_fix:
8553 case Intrinsic::smul_fix_sat:
8554 case Intrinsic::umul_fix:
8555 case Intrinsic::umul_fix_sat:
8556 case Intrinsic::pow:
8557 case Intrinsic::powi:
8558 case Intrinsic::sin:
8559 case Intrinsic::sinh:
8560 case Intrinsic::cos:
8561 case Intrinsic::cosh:
8562 case Intrinsic::sincos:
8563 case Intrinsic::sincospi:
8564 case Intrinsic::tan:
8565 case Intrinsic::tanh:
8566 case Intrinsic::asin:
8567 case Intrinsic::acos:
8568 case Intrinsic::atan:
8569 case Intrinsic::atan2:
8570 case Intrinsic::canonicalize:
8571 case Intrinsic::sqrt:
8572 case Intrinsic::fma:
8573 case Intrinsic::fmuladd:
8574 case Intrinsic::exp:
8575 case Intrinsic::exp2:
8576 case Intrinsic::exp10:
8577 case Intrinsic::log:
8578 case Intrinsic::log2:
8579 case Intrinsic::log10:
8580 case Intrinsic::modf:
8581 case Intrinsic::floor:
8582 case Intrinsic::ceil:
8583 case Intrinsic::trunc:
8584 case Intrinsic::rint:
8585 case Intrinsic::nearbyint:
8586 case Intrinsic::round:
8587 case Intrinsic::roundeven:
8588 case Intrinsic::lrint:
8589 case Intrinsic::llrint:
8590 case Intrinsic::fshl:
8591 case Intrinsic::fshr:
8592 case Intrinsic::frexp:
8593 case Intrinsic::get_active_lane_mask:
8594 return true;
8595 default:
8596 return false;
8597 }
8598}
8599
8600bool llvm::propagatesPoison(const Use &PoisonOp) {
8601 const Operator *I = cast<Operator>(PoisonOp.getUser());
8602 switch (I->getOpcode()) {
8603 case Instruction::Freeze:
8604 case Instruction::PHI:
8605 case Instruction::Invoke:
8606 return false;
8607 case Instruction::Select:
8608 return PoisonOp.getOperandNo() == 0;
8609 case Instruction::Call:
8610 if (auto *II = dyn_cast<IntrinsicInst>(I))
8611 return intrinsicPropagatesPoison(II->getIntrinsicID());
8612 return false;
8613 case Instruction::ICmp:
8614 case Instruction::FCmp:
8615 case Instruction::GetElementPtr:
8616 return true;
8617 default:
8619 return true;
8620
8621 // Be conservative and return false.
8622 return false;
8623 }
8624}
8625
8626/// Enumerates all operands of \p I that are guaranteed to not be undef or
8627/// poison. If the callback \p Handle returns true, stop processing and return
8628/// true. Otherwise, return false.
8629template <typename CallableT>
8631 const CallableT &Handle) {
8632 switch (I->getOpcode()) {
8633 case Instruction::Store:
8634 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8635 return true;
8636 break;
8637
8638 case Instruction::Load:
8639 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8640 return true;
8641 break;
8642
8643 // Since dereferenceable attribute imply noundef, atomic operations
8644 // also implicitly have noundef pointers too
8645 case Instruction::AtomicCmpXchg:
8647 return true;
8648 break;
8649
8650 case Instruction::AtomicRMW:
8651 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8652 return true;
8653 break;
8654
8655 case Instruction::Call:
8656 case Instruction::Invoke: {
8657 const CallBase *CB = cast<CallBase>(I);
8658 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8659 return true;
8660 for (unsigned i = 0; i < CB->arg_size(); ++i)
8661 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8662 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8663 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8664 Handle(CB->getArgOperand(i)))
8665 return true;
8666 break;
8667 }
8668 case Instruction::Ret:
8669 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8670 Handle(I->getOperand(0)))
8671 return true;
8672 break;
8673 case Instruction::Switch:
8674 if (Handle(cast<SwitchInst>(I)->getCondition()))
8675 return true;
8676 break;
8677 case Instruction::CondBr:
8678 if (Handle(cast<CondBrInst>(I)->getCondition()))
8679 return true;
8680 break;
8681 default:
8682 break;
8683 }
8684
8685 return false;
8686}
8687
8688/// Enumerates all operands of \p I that are guaranteed to not be poison.
8689template <typename CallableT>
8691 const CallableT &Handle) {
8692 if (handleGuaranteedWellDefinedOps(I, Handle))
8693 return true;
8694 switch (I->getOpcode()) {
8695 // Divisors of these operations are allowed to be partially undef.
8696 case Instruction::UDiv:
8697 case Instruction::SDiv:
8698 case Instruction::URem:
8699 case Instruction::SRem:
8700 return Handle(I->getOperand(1));
8701 default:
8702 return false;
8703 }
8704}
8705
8707 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8709 I, [&](const Value *V) { return KnownPoison.count(V); });
8710}
8711
8713 bool PoisonOnly) {
8714 // We currently only look for uses of values within the same basic
8715 // block, as that makes it easier to guarantee that the uses will be
8716 // executed given that Inst is executed.
8717 //
8718 // FIXME: Expand this to consider uses beyond the same basic block. To do
8719 // this, look out for the distinction between post-dominance and strong
8720 // post-dominance.
8721 const BasicBlock *BB = nullptr;
8723 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8724 BB = Inst->getParent();
8725 Begin = Inst->getIterator();
8726 Begin++;
8727 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8728 if (Arg->getParent()->isDeclaration())
8729 return false;
8730 BB = &Arg->getParent()->getEntryBlock();
8731 Begin = BB->begin();
8732 } else {
8733 return false;
8734 }
8735
8736 // Limit number of instructions we look at, to avoid scanning through large
8737 // blocks. The current limit is chosen arbitrarily.
8738 unsigned ScanLimit = 32;
8739 BasicBlock::const_iterator End = BB->end();
8740
8741 if (!PoisonOnly) {
8742 // Since undef does not propagate eagerly, be conservative & just check
8743 // whether a value is directly passed to an instruction that must take
8744 // well-defined operands.
8745
8746 for (const auto &I : make_range(Begin, End)) {
8747 if (--ScanLimit == 0)
8748 break;
8749
8750 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8751 return WellDefinedOp == V;
8752 }))
8753 return true;
8754
8756 break;
8757 }
8758 return false;
8759 }
8760
8761 // Set of instructions that we have proved will yield poison if Inst
8762 // does.
8763 SmallPtrSet<const Value *, 16> YieldsPoison;
8765
8766 YieldsPoison.insert(V);
8767 Visited.insert(BB);
8768
8769 while (true) {
8770 for (const auto &I : make_range(Begin, End)) {
8771 if (--ScanLimit == 0)
8772 return false;
8773 if (mustTriggerUB(&I, YieldsPoison))
8774 return true;
8776 return false;
8777
8778 // If an operand is poison and propagates it, mark I as yielding poison.
8779 for (const Use &Op : I.operands()) {
8780 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8781 YieldsPoison.insert(&I);
8782 break;
8783 }
8784 }
8785
8786 // Special handling for select, which returns poison if its operand 0 is
8787 // poison (handled in the loop above) *or* if both its true/false operands
8788 // are poison (handled here).
8789 if (I.getOpcode() == Instruction::Select &&
8790 YieldsPoison.count(I.getOperand(1)) &&
8791 YieldsPoison.count(I.getOperand(2))) {
8792 YieldsPoison.insert(&I);
8793 }
8794 }
8795
8796 BB = BB->getSingleSuccessor();
8797 if (!BB || !Visited.insert(BB).second)
8798 break;
8799
8800 Begin = BB->getFirstNonPHIIt();
8801 End = BB->end();
8802 }
8803 return false;
8804}
8805
8807 return ::programUndefinedIfUndefOrPoison(Inst, false);
8808}
8809
8811 return ::programUndefinedIfUndefOrPoison(Inst, true);
8812}
8813
8814static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8815 if (FMF.noNaNs())
8816 return true;
8817
8818 if (auto *C = dyn_cast<ConstantFP>(V))
8819 return !C->isNaN();
8820
8821 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8822 if (!C->getElementType()->isFloatingPointTy())
8823 return false;
8824 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8825 if (C->getElementAsAPFloat(I).isNaN())
8826 return false;
8827 }
8828 return true;
8829 }
8830
8832 return true;
8833
8834 return false;
8835}
8836
8837static bool isKnownNonZero(const Value *V) {
8838 if (auto *C = dyn_cast<ConstantFP>(V))
8839 return !C->isZero();
8840
8841 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8842 if (!C->getElementType()->isFloatingPointTy())
8843 return false;
8844 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8845 if (C->getElementAsAPFloat(I).isZero())
8846 return false;
8847 }
8848 return true;
8849 }
8850
8851 return false;
8852}
8853
8854/// Match clamp pattern for float types without care about NaNs or signed zeros.
8855/// Given non-min/max outer cmp/select from the clamp pattern this
8856/// function recognizes if it can be substitued by a "canonical" min/max
8857/// pattern.
8859 Value *CmpLHS, Value *CmpRHS,
8860 Value *TrueVal, Value *FalseVal,
8861 Value *&LHS, Value *&RHS) {
8862 // Try to match
8863 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8864 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8865 // and return description of the outer Max/Min.
8866
8867 // First, check if select has inverse order:
8868 if (CmpRHS == FalseVal) {
8869 std::swap(TrueVal, FalseVal);
8870 Pred = CmpInst::getInversePredicate(Pred);
8871 }
8872
8873 // Assume success now. If there's no match, callers should not use these anyway.
8874 LHS = TrueVal;
8875 RHS = FalseVal;
8876
8877 const APFloat *FC1;
8878 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8879 return {SPF_UNKNOWN, SPNB_NA, false};
8880
8881 const APFloat *FC2;
8882 switch (Pred) {
8883 case CmpInst::FCMP_OLT:
8884 case CmpInst::FCMP_OLE:
8885 case CmpInst::FCMP_ULT:
8886 case CmpInst::FCMP_ULE:
8887 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8888 *FC1 < *FC2)
8889 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8890 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8891 *FC1 < *FC2)
8892 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8893 break;
8894 case CmpInst::FCMP_OGT:
8895 case CmpInst::FCMP_OGE:
8896 case CmpInst::FCMP_UGT:
8897 case CmpInst::FCMP_UGE:
8898 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8899 *FC1 > *FC2)
8900 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8901 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8902 *FC1 > *FC2)
8903 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8904 break;
8905 default:
8906 break;
8907 }
8908
8909 return {SPF_UNKNOWN, SPNB_NA, false};
8910}
8911
8912/// Recognize variations of:
8913/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8915 Value *CmpLHS, Value *CmpRHS,
8916 Value *TrueVal, Value *FalseVal) {
8917 // Swap the select operands and predicate to match the patterns below.
8918 if (CmpRHS != TrueVal) {
8919 Pred = ICmpInst::getSwappedPredicate(Pred);
8920 std::swap(TrueVal, FalseVal);
8921 }
8922 const APInt *C1;
8923 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8924 const APInt *C2;
8925 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8926 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8927 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8928 return {SPF_SMAX, SPNB_NA, false};
8929
8930 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8931 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8932 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8933 return {SPF_SMIN, SPNB_NA, false};
8934
8935 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8936 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8937 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8938 return {SPF_UMAX, SPNB_NA, false};
8939
8940 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8941 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8942 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8943 return {SPF_UMIN, SPNB_NA, false};
8944 }
8945 return {SPF_UNKNOWN, SPNB_NA, false};
8946}
8947
8948/// Recognize variations of:
8949/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8951 Value *CmpLHS, Value *CmpRHS,
8952 Value *TVal, Value *FVal,
8953 unsigned Depth) {
8954 // TODO: Allow FP min/max with nnan/nsz.
8955 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8956
8957 Value *A = nullptr, *B = nullptr;
8958 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8959 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8960 return {SPF_UNKNOWN, SPNB_NA, false};
8961
8962 Value *C = nullptr, *D = nullptr;
8963 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8964 if (L.Flavor != R.Flavor)
8965 return {SPF_UNKNOWN, SPNB_NA, false};
8966
8967 // We have something like: x Pred y ? min(a, b) : min(c, d).
8968 // Try to match the compare to the min/max operations of the select operands.
8969 // First, make sure we have the right compare predicate.
8970 switch (L.Flavor) {
8971 case SPF_SMIN:
8972 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8973 Pred = ICmpInst::getSwappedPredicate(Pred);
8974 std::swap(CmpLHS, CmpRHS);
8975 }
8976 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8977 break;
8978 return {SPF_UNKNOWN, SPNB_NA, false};
8979 case SPF_SMAX:
8980 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8981 Pred = ICmpInst::getSwappedPredicate(Pred);
8982 std::swap(CmpLHS, CmpRHS);
8983 }
8984 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8985 break;
8986 return {SPF_UNKNOWN, SPNB_NA, false};
8987 case SPF_UMIN:
8988 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8989 Pred = ICmpInst::getSwappedPredicate(Pred);
8990 std::swap(CmpLHS, CmpRHS);
8991 }
8992 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8993 break;
8994 return {SPF_UNKNOWN, SPNB_NA, false};
8995 case SPF_UMAX:
8996 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8997 Pred = ICmpInst::getSwappedPredicate(Pred);
8998 std::swap(CmpLHS, CmpRHS);
8999 }
9000 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
9001 break;
9002 return {SPF_UNKNOWN, SPNB_NA, false};
9003 default:
9004 return {SPF_UNKNOWN, SPNB_NA, false};
9005 }
9006
9007 // If there is a common operand in the already matched min/max and the other
9008 // min/max operands match the compare operands (either directly or inverted),
9009 // then this is min/max of the same flavor.
9010
9011 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
9012 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
9013 if (D == B) {
9014 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
9015 match(A, m_Not(m_Specific(CmpRHS)))))
9016 return {L.Flavor, SPNB_NA, false};
9017 }
9018 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
9019 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
9020 if (C == B) {
9021 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
9022 match(A, m_Not(m_Specific(CmpRHS)))))
9023 return {L.Flavor, SPNB_NA, false};
9024 }
9025 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
9026 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
9027 if (D == A) {
9028 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
9029 match(B, m_Not(m_Specific(CmpRHS)))))
9030 return {L.Flavor, SPNB_NA, false};
9031 }
9032 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
9033 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
9034 if (C == A) {
9035 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
9036 match(B, m_Not(m_Specific(CmpRHS)))))
9037 return {L.Flavor, SPNB_NA, false};
9038 }
9039
9040 return {SPF_UNKNOWN, SPNB_NA, false};
9041}
9042
9043/// If the input value is the result of a 'not' op, constant integer, or vector
9044/// splat of a constant integer, return the bitwise-not source value.
9045/// TODO: This could be extended to handle non-splat vector integer constants.
9047 Value *NotV;
9048 if (match(V, m_Not(m_Value(NotV))))
9049 return NotV;
9050
9051 const APInt *C;
9052 if (match(V, m_APInt(C)))
9053 return ConstantInt::get(V->getType(), ~(*C));
9054
9055 return nullptr;
9056}
9057
9058/// Match non-obvious integer minimum and maximum sequences.
9060 Value *CmpLHS, Value *CmpRHS,
9061 Value *TrueVal, Value *FalseVal,
9062 Value *&LHS, Value *&RHS,
9063 unsigned Depth) {
9064 // Assume success. If there's no match, callers should not use these anyway.
9065 LHS = TrueVal;
9066 RHS = FalseVal;
9067
9068 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9070 return SPR;
9071
9072 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
9074 return SPR;
9075
9076 // Look through 'not' ops to find disguised min/max.
9077 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9078 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9079 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9080 switch (Pred) {
9081 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9082 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9083 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9084 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9085 default: break;
9086 }
9087 }
9088
9089 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9090 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9091 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9092 switch (Pred) {
9093 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9094 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9095 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9096 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9097 default: break;
9098 }
9099 }
9100
9101 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9102 return {SPF_UNKNOWN, SPNB_NA, false};
9103
9104 const APInt *C1;
9105 if (!match(CmpRHS, m_APInt(C1)))
9106 return {SPF_UNKNOWN, SPNB_NA, false};
9107
9108 // An unsigned min/max can be written with a signed compare.
9109 const APInt *C2;
9110 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9111 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9112 // Is the sign bit set?
9113 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9114 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9115 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9116 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9117
9118 // Is the sign bit clear?
9119 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9120 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9121 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9122 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9123 }
9124
9125 return {SPF_UNKNOWN, SPNB_NA, false};
9126}
9127
9128bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9129 bool AllowPoison) {
9130 assert(X && Y && "Invalid operand");
9131
9132 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9133 if (!match(X, m_Neg(m_Specific(Y))))
9134 return false;
9135
9136 auto *BO = cast<BinaryOperator>(X);
9137 if (NeedNSW && !BO->hasNoSignedWrap())
9138 return false;
9139
9140 auto *Zero = cast<Constant>(BO->getOperand(0));
9141 if (!AllowPoison && !Zero->isNullValue())
9142 return false;
9143
9144 return true;
9145 };
9146
9147 // X = -Y or Y = -X
9148 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9149 return true;
9150
9151 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9152 Value *A, *B;
9153 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9154 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9155 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9157}
9158
9159bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9160 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9161 Value *A, *B, *C;
9162 CmpPredicate Pred1, Pred2;
9163 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9164 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9165 return false;
9166
9167 // They must both have samesign flag or not.
9168 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9169 return false;
9170
9171 if (B == C)
9172 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9173
9174 // Try to infer the relationship from constant ranges.
9175 const APInt *RHSC1, *RHSC2;
9176 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9177 return false;
9178
9179 // Sign bits of two RHSCs should match.
9180 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9181 return false;
9182
9183 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9184 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9185
9186 return CR1.inverse() == CR2;
9187}
9188
9190 SelectPatternNaNBehavior NaNBehavior,
9191 bool Ordered) {
9192 switch (Pred) {
9193 default:
9194 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9195 case ICmpInst::ICMP_UGT:
9196 case ICmpInst::ICMP_UGE:
9197 return {SPF_UMAX, SPNB_NA, false};
9198 case ICmpInst::ICMP_SGT:
9199 case ICmpInst::ICMP_SGE:
9200 return {SPF_SMAX, SPNB_NA, false};
9201 case ICmpInst::ICMP_ULT:
9202 case ICmpInst::ICMP_ULE:
9203 return {SPF_UMIN, SPNB_NA, false};
9204 case ICmpInst::ICMP_SLT:
9205 case ICmpInst::ICMP_SLE:
9206 return {SPF_SMIN, SPNB_NA, false};
9207 case FCmpInst::FCMP_UGT:
9208 case FCmpInst::FCMP_UGE:
9209 case FCmpInst::FCMP_OGT:
9210 case FCmpInst::FCMP_OGE:
9211 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9212 case FCmpInst::FCMP_ULT:
9213 case FCmpInst::FCMP_ULE:
9214 case FCmpInst::FCMP_OLT:
9215 case FCmpInst::FCMP_OLE:
9216 return {SPF_FMINNUM, NaNBehavior, Ordered};
9217 }
9218}
9219
9220std::optional<std::pair<CmpPredicate, Constant *>>
9223 "Only for relational integer predicates.");
9224 if (isa<UndefValue>(C))
9225 return std::nullopt;
9226
9227 Type *Type = C->getType();
9228 bool IsSigned = ICmpInst::isSigned(Pred);
9229
9231 bool WillIncrement =
9232 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9233
9234 // Check if the constant operand can be safely incremented/decremented
9235 // without overflowing/underflowing.
9236 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9237 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9238 return false;
9239
9240 if (!Pred.hasSameSign())
9241 return true;
9242
9243 // Crossing the corresponding boundary in the other ordering changes the
9244 // sign bit, and therefore changes the poison domain.
9245 return WillIncrement ? !C->isMaxValue(!IsSigned)
9246 : !C->isMinValue(!IsSigned);
9247 };
9248
9249 Constant *SafeReplacementConstant = nullptr;
9250 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9251 // Bail out if the constant can't be safely incremented/decremented.
9252 if (!ConstantIsOk(CI))
9253 return std::nullopt;
9254 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9255 unsigned NumElts = FVTy->getNumElements();
9256 for (unsigned i = 0; i != NumElts; ++i) {
9257 Constant *Elt = C->getAggregateElement(i);
9258 if (!Elt)
9259 return std::nullopt;
9260
9261 if (isa<UndefValue>(Elt))
9262 continue;
9263
9264 // Bail out if we can't determine if this constant is min/max or if we
9265 // know that this constant is min/max.
9266 auto *CI = dyn_cast<ConstantInt>(Elt);
9267 if (!CI || !ConstantIsOk(CI))
9268 return std::nullopt;
9269
9270 if (!SafeReplacementConstant)
9271 SafeReplacementConstant = CI;
9272 }
9273 } else if (isa<VectorType>(C->getType())) {
9274 // Handle scalable splat
9275 Value *SplatC = C->getSplatValue();
9276 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9277 // Bail out if the constant can't be safely incremented/decremented.
9278 if (!CI || !ConstantIsOk(CI))
9279 return std::nullopt;
9280 } else {
9281 // ConstantExpr?
9282 return std::nullopt;
9283 }
9284
9285 // It may not be safe to change a compare predicate in the presence of
9286 // undefined elements, so replace those elements with the first safe constant
9287 // that we found.
9288 // TODO: in case of poison, it is safe; let's replace undefs only.
9289 if (C->containsUndefOrPoisonElement()) {
9290 assert(SafeReplacementConstant && "Replacement constant not set");
9291 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9292 }
9293
9295 Pred.hasSameSign());
9296
9297 // Increment or decrement the constant.
9298 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9299 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9300
9301 return std::make_pair(NewPred, NewC);
9302}
9303
9305 FastMathFlags FMF,
9306 Value *CmpLHS, Value *CmpRHS,
9307 Value *TrueVal, Value *FalseVal,
9308 Value *&LHS, Value *&RHS,
9309 unsigned Depth) {
9310 if (CmpInst::isFPPredicate(Pred)) {
9311 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9312 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9313 // purpose of identifying min/max. Disregard vector constants with undefined
9314 // elements because those can not be back-propagated for analysis.
9315 Value *OutputZeroVal = nullptr;
9316 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9317 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9318 OutputZeroVal = TrueVal;
9319 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9320 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9321 OutputZeroVal = FalseVal;
9322
9323 if (OutputZeroVal) {
9324 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9325 CmpLHS = OutputZeroVal;
9326 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9327 CmpRHS = OutputZeroVal;
9328 }
9329 }
9330
9331 LHS = CmpLHS;
9332 RHS = CmpRHS;
9333
9334 // Signed zero may return inconsistent results between implementations.
9335 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9336 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9337 // Therefore, we behave conservatively and only proceed if at least one of the
9338 // operands is known to not be zero or if we don't care about signed zero.
9339 if (CmpInst::isFPPredicate(Pred)) {
9340 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9341 !isKnownNonZero(CmpRHS))
9342 return {SPF_UNKNOWN, SPNB_NA, false};
9343 }
9344
9345 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9346 bool Ordered = false;
9347
9348 // When given one NaN and one non-NaN input:
9349 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9350 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9351 // ordered comparison fails), which could be NaN or non-NaN.
9352 // so here we discover exactly what NaN behavior is required/accepted.
9353 if (CmpInst::isFPPredicate(Pred)) {
9354 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9355 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9356
9357 if (LHSSafe && RHSSafe) {
9358 // Both operands are known non-NaN.
9359 NaNBehavior = SPNB_RETURNS_ANY;
9360 Ordered = CmpInst::isOrdered(Pred);
9361 } else if (CmpInst::isOrdered(Pred)) {
9362 // An ordered comparison will return false when given a NaN, so it
9363 // returns the RHS.
9364 Ordered = true;
9365 if (LHSSafe)
9366 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9367 NaNBehavior = SPNB_RETURNS_NAN;
9368 else if (RHSSafe)
9369 NaNBehavior = SPNB_RETURNS_OTHER;
9370 else
9371 // Completely unsafe.
9372 return {SPF_UNKNOWN, SPNB_NA, false};
9373 } else {
9374 Ordered = false;
9375 // An unordered comparison will return true when given a NaN, so it
9376 // returns the LHS.
9377 if (LHSSafe)
9378 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9379 NaNBehavior = SPNB_RETURNS_OTHER;
9380 else if (RHSSafe)
9381 NaNBehavior = SPNB_RETURNS_NAN;
9382 else
9383 // Completely unsafe.
9384 return {SPF_UNKNOWN, SPNB_NA, false};
9385 }
9386 }
9387
9388 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9389 std::swap(CmpLHS, CmpRHS);
9390 Pred = CmpInst::getSwappedPredicate(Pred);
9391 if (NaNBehavior == SPNB_RETURNS_NAN)
9392 NaNBehavior = SPNB_RETURNS_OTHER;
9393 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9394 NaNBehavior = SPNB_RETURNS_NAN;
9395 Ordered = !Ordered;
9396 }
9397
9398 // ([if]cmp X, Y) ? X : Y
9399 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9400 return getSelectPattern(Pred, NaNBehavior, Ordered);
9401
9402 if (isKnownNegation(TrueVal, FalseVal)) {
9403 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9404 // match against either LHS or sign-preserving operations on LHS, like
9405 // sext(LHS), or binary ops that do not wrap in signed sense.
9406 auto CmpLHSOrSExt =
9407 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9408 auto MaybeSExtOrMulCmpLHS =
9409 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9410 m_NSWShl(CmpLHSOrSExt, m_Value()));
9411 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9412 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9413 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9414 // Set the return values. If the compare uses the negated value (-X >s 0),
9415 // swap the return values because the negated value is always 'RHS'.
9416 LHS = TrueVal;
9417 RHS = FalseVal;
9418 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9419 std::swap(LHS, RHS);
9420
9421 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9422 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9423 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9424 return {SPF_ABS, SPNB_NA, false};
9425
9426 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9427 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9428 return {SPF_ABS, SPNB_NA, false};
9429
9430 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9431 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9432 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9433 return {SPF_NABS, SPNB_NA, false};
9434 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9435 // Set the return values. If the compare uses the negated value (-X >s 0),
9436 // swap the return values because the negated value is always 'RHS'.
9437 LHS = FalseVal;
9438 RHS = TrueVal;
9439 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9440 std::swap(LHS, RHS);
9441
9442 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9443 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9444 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9445 return {SPF_NABS, SPNB_NA, false};
9446
9447 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9448 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9449 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9450 return {SPF_ABS, SPNB_NA, false};
9451 }
9452 }
9453
9454 if (CmpInst::isIntPredicate(Pred))
9455 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9456
9457 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9458 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9459 // semantics than minNum. Be conservative in such case.
9460 if (NaNBehavior != SPNB_RETURNS_ANY ||
9461 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9462 !isKnownNonZero(CmpRHS)))
9463 return {SPF_UNKNOWN, SPNB_NA, false};
9464
9465 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9466}
9467
9469 Instruction::CastOps *CastOp) {
9470 const DataLayout &DL = CmpI->getDataLayout();
9471
9472 Constant *CastedTo = nullptr;
9473 switch (*CastOp) {
9474 case Instruction::ZExt:
9475 if (CmpI->isUnsigned())
9476 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9477 break;
9478 case Instruction::SExt:
9479 if (CmpI->isSigned())
9480 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9481 break;
9482 case Instruction::Trunc:
9483 Constant *CmpConst;
9484 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9485 CmpConst->getType() == SrcTy) {
9486 // Here we have the following case:
9487 //
9488 // %cond = cmp iN %x, CmpConst
9489 // %tr = trunc iN %x to iK
9490 // %narrowsel = select i1 %cond, iK %t, iK C
9491 //
9492 // We can always move trunc after select operation:
9493 //
9494 // %cond = cmp iN %x, CmpConst
9495 // %widesel = select i1 %cond, iN %x, iN CmpConst
9496 // %tr = trunc iN %widesel to iK
9497 //
9498 // Note that C could be extended in any way because we don't care about
9499 // upper bits after truncation. It can't be abs pattern, because it would
9500 // look like:
9501 //
9502 // select i1 %cond, x, -x.
9503 //
9504 // So only min/max pattern could be matched. Such match requires widened C
9505 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9506 // CmpConst == C is checked below.
9507 CastedTo = CmpConst;
9508 } else {
9509 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9510 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9511 }
9512 break;
9513 case Instruction::FPTrunc:
9514 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9515 break;
9516 case Instruction::FPExt:
9517 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9518 break;
9519 case Instruction::FPToUI:
9520 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9521 break;
9522 case Instruction::FPToSI:
9523 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9524 break;
9525 case Instruction::UIToFP:
9526 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9527 break;
9528 case Instruction::SIToFP:
9529 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9530 break;
9531 default:
9532 break;
9533 }
9534
9535 if (!CastedTo)
9536 return nullptr;
9537
9538 // Make sure the cast doesn't lose any information.
9539 Constant *CastedBack =
9540 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9541 if (CastedBack && CastedBack != C)
9542 return nullptr;
9543
9544 return CastedTo;
9545}
9546
9547/// Helps to match a select pattern in case of a type mismatch.
9548///
9549/// The function processes the case when type of true and false values of a
9550/// select instruction differs from type of the cmp instruction operands because
9551/// of a cast instruction. The function checks if it is legal to move the cast
9552/// operation after "select". If yes, it returns the new second value of
9553/// "select" (with the assumption that cast is moved):
9554/// 1. As operand of cast instruction when both values of "select" are same cast
9555/// instructions.
9556/// 2. As restored constant (by applying reverse cast operation) when the first
9557/// value of the "select" is a cast operation and the second value is a
9558/// constant. It is implemented in lookThroughCastConst().
9559/// 3. As one operand is cast instruction and the other is not. The operands in
9560/// sel(cmp) are in different type integer.
9561/// NOTE: We return only the new second value because the first value could be
9562/// accessed as operand of cast instruction.
9564 Instruction::CastOps *CastOp) {
9565 auto *Cast1 = dyn_cast<CastInst>(V1);
9566 if (!Cast1)
9567 return nullptr;
9568
9569 *CastOp = Cast1->getOpcode();
9570 Type *SrcTy = Cast1->getSrcTy();
9571 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9572 // If V1 and V2 are both the same cast from the same type, look through V1.
9573 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9574 return Cast2->getOperand(0);
9575 return nullptr;
9576 }
9577
9578 auto *C = dyn_cast<Constant>(V2);
9579 if (C)
9580 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9581
9582 Value *CastedTo = nullptr;
9583 if (*CastOp == Instruction::Trunc) {
9584 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9585 // Here we have the following case:
9586 // %y_ext = sext iK %y to iN
9587 // %cond = cmp iN %x, %y_ext
9588 // %tr = trunc iN %x to iK
9589 // %narrowsel = select i1 %cond, iK %tr, iK %y
9590 //
9591 // We can always move trunc after select operation:
9592 // %y_ext = sext iK %y to iN
9593 // %cond = cmp iN %x, %y_ext
9594 // %widesel = select i1 %cond, iN %x, iN %y_ext
9595 // %tr = trunc iN %widesel to iK
9596 assert(V2->getType() == Cast1->getType() &&
9597 "V2 and Cast1 should be the same type.");
9598 CastedTo = CmpI->getOperand(1);
9599 }
9600 }
9601
9602 return CastedTo;
9603}
9605 Instruction::CastOps *CastOp,
9606 unsigned Depth) {
9608 return {SPF_UNKNOWN, SPNB_NA, false};
9609
9611 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9612
9613 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9614 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9615
9616 Value *TrueVal = SI->getTrueValue();
9617 Value *FalseVal = SI->getFalseValue();
9618
9619 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9620 SI->getFastMathFlagsOrNone(),
9621 CastOp, Depth);
9622}
9623
9625 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9626 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9627 CmpInst::Predicate Pred = CmpI->getPredicate();
9628 Value *CmpLHS = CmpI->getOperand(0);
9629 Value *CmpRHS = CmpI->getOperand(1);
9630 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9631 FMF.setNoNaNs();
9632
9633 // Bail out early.
9634 if (CmpI->isEquality())
9635 return {SPF_UNKNOWN, SPNB_NA, false};
9636
9637 // Deal with type mismatches.
9638 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9639 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9640 // If this is a potential fmin/fmax with a cast to integer, then ignore
9641 // -0.0 because there is no corresponding integer value.
9642 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9643 FMF.setNoSignedZeros();
9644 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9645 cast<CastInst>(TrueVal)->getOperand(0), C,
9646 LHS, RHS, Depth);
9647 }
9648 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9649 // If this is a potential fmin/fmax with a cast to integer, then ignore
9650 // -0.0 because there is no corresponding integer value.
9651 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9652 FMF.setNoSignedZeros();
9653 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9654 C, cast<CastInst>(FalseVal)->getOperand(0),
9655 LHS, RHS, Depth);
9656 }
9657 }
9658 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9659 LHS, RHS, Depth);
9660}
9661
9663 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9664 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9665 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9666 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9667 if (SPF == SPF_FMINNUM)
9668 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9669 if (SPF == SPF_FMAXNUM)
9670 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9671 llvm_unreachable("unhandled!");
9672}
9673
9675 switch (SPF) {
9677 return Intrinsic::umin;
9679 return Intrinsic::umax;
9681 return Intrinsic::smin;
9683 return Intrinsic::smax;
9684 default:
9685 llvm_unreachable("Unexpected SPF");
9686 }
9687}
9688
9690 if (SPF == SPF_SMIN) return SPF_SMAX;
9691 if (SPF == SPF_UMIN) return SPF_UMAX;
9692 if (SPF == SPF_SMAX) return SPF_SMIN;
9693 if (SPF == SPF_UMAX) return SPF_UMIN;
9694 llvm_unreachable("unhandled!");
9695}
9696
9698 switch (MinMaxID) {
9699 case Intrinsic::smax: return Intrinsic::smin;
9700 case Intrinsic::smin: return Intrinsic::smax;
9701 case Intrinsic::umax: return Intrinsic::umin;
9702 case Intrinsic::umin: return Intrinsic::umax;
9703 // Please note that next four intrinsics may produce the same result for
9704 // original and inverted case even if X != Y due to NaN is handled specially.
9705 case Intrinsic::maximum: return Intrinsic::minimum;
9706 case Intrinsic::minimum: return Intrinsic::maximum;
9707 case Intrinsic::maxnum: return Intrinsic::minnum;
9708 case Intrinsic::minnum: return Intrinsic::maxnum;
9709 case Intrinsic::maximumnum:
9710 return Intrinsic::minimumnum;
9711 case Intrinsic::minimumnum:
9712 return Intrinsic::maximumnum;
9713 default: llvm_unreachable("Unexpected intrinsic");
9714 }
9715}
9716
9718 switch (SPF) {
9721 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9722 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9723 default: llvm_unreachable("Unexpected flavor");
9724 }
9725}
9726
9727std::pair<Intrinsic::ID, bool>
9729 // Check if VL contains select instructions that can be folded into a min/max
9730 // vector intrinsic and return the intrinsic if it is possible.
9731 // TODO: Support floating point min/max.
9732 bool AllCmpSingleUse = true;
9733 SelectPatternResult SelectPattern;
9734 SelectPattern.Flavor = SPF_UNKNOWN;
9735 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9736 Value *LHS, *RHS;
9737 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9738 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9739 return false;
9740 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9741 SelectPattern.Flavor != CurrentPattern.Flavor)
9742 return false;
9743 SelectPattern = CurrentPattern;
9744 AllCmpSingleUse &=
9746 return true;
9747 })) {
9748 switch (SelectPattern.Flavor) {
9749 case SPF_SMIN:
9750 return {Intrinsic::smin, AllCmpSingleUse};
9751 case SPF_UMIN:
9752 return {Intrinsic::umin, AllCmpSingleUse};
9753 case SPF_SMAX:
9754 return {Intrinsic::smax, AllCmpSingleUse};
9755 case SPF_UMAX:
9756 return {Intrinsic::umax, AllCmpSingleUse};
9757 case SPF_FMAXNUM:
9758 return {Intrinsic::maxnum, AllCmpSingleUse};
9759 case SPF_FMINNUM:
9760 return {Intrinsic::minnum, AllCmpSingleUse};
9761 default:
9762 llvm_unreachable("unexpected select pattern flavor");
9763 }
9764 }
9765 return {Intrinsic::not_intrinsic, false};
9766}
9767
9768template <typename InstTy>
9769static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9770 Value *&Init, Value *&OtherOp) {
9771 // Handle the case of a simple two-predecessor recurrence PHI.
9772 // There's a lot more that could theoretically be done here, but
9773 // this is sufficient to catch some interesting cases.
9774 // TODO: Expand list -- gep, uadd.sat etc.
9775 if (PN->getNumIncomingValues() != 2)
9776 return false;
9777
9778 for (unsigned I = 0; I != 2; ++I) {
9779 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9780 Operation && Operation->getNumOperands() >= 2) {
9781 Value *LHS = Operation->getOperand(0);
9782 Value *RHS = Operation->getOperand(1);
9783 if (LHS != PN && RHS != PN)
9784 continue;
9785
9786 Inst = Operation;
9787 Init = PN->getIncomingValue(!I);
9788 OtherOp = (LHS == PN) ? RHS : LHS;
9789 return true;
9790 }
9791 }
9792 return false;
9793}
9794
9795template <typename InstTy>
9796static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9797 Value *&Init, Value *&OtherOp0,
9798 Value *&OtherOp1) {
9799 if (PN->getNumIncomingValues() != 2)
9800 return false;
9801
9802 for (unsigned I = 0; I != 2; ++I) {
9803 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9804 Operation && Operation->getNumOperands() >= 3) {
9805 Value *Op0 = Operation->getOperand(0);
9806 Value *Op1 = Operation->getOperand(1);
9807 Value *Op2 = Operation->getOperand(2);
9808
9809 if (Op0 != PN && Op1 != PN && Op2 != PN)
9810 continue;
9811
9812 Inst = Operation;
9813 Init = PN->getIncomingValue(!I);
9814 if (Op0 == PN) {
9815 OtherOp0 = Op1;
9816 OtherOp1 = Op2;
9817 } else if (Op1 == PN) {
9818 OtherOp0 = Op0;
9819 OtherOp1 = Op2;
9820 } else {
9821 OtherOp0 = Op0;
9822 OtherOp1 = Op1;
9823 }
9824 return true;
9825 }
9826 }
9827 return false;
9828}
9830 Value *&Start, Value *&Step) {
9831 // We try to match a recurrence of the form:
9832 // %iv = [Start, %entry], [%iv.next, %backedge]
9833 // %iv.next = binop %iv, Step
9834 // Or:
9835 // %iv = [Start, %entry], [%iv.next, %backedge]
9836 // %iv.next = binop Step, %iv
9837 return matchTwoInputRecurrence(P, BO, Start, Step);
9838}
9839
9841 Value *&Start, Value *&Step) {
9842 BinaryOperator *BO = nullptr;
9843 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9844 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9845}
9846
9848 PHINode *&P, Value *&Init,
9849 Value *&OtherOp) {
9850 // Binary intrinsics only supported for now.
9851 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9852 I->getType() != I->getArgOperand(1)->getType())
9853 return false;
9854
9855 IntrinsicInst *II = nullptr;
9856 P = dyn_cast<PHINode>(I->getArgOperand(0));
9857 if (!P)
9858 P = dyn_cast<PHINode>(I->getArgOperand(1));
9859
9860 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9861}
9862
9864 PHINode *&P, Value *&Init,
9865 Value *&OtherOp0,
9866 Value *&OtherOp1) {
9867 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9868 I->getType() != I->getArgOperand(1)->getType() ||
9869 I->getType() != I->getArgOperand(2)->getType())
9870 return false;
9871 IntrinsicInst *II = nullptr;
9872 P = dyn_cast<PHINode>(I->getArgOperand(0));
9873 if (!P) {
9874 P = dyn_cast<PHINode>(I->getArgOperand(1));
9875 if (!P)
9876 P = dyn_cast<PHINode>(I->getArgOperand(2));
9877 }
9878 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9879 II == I;
9880}
9881
9882/// Return true if "icmp Pred LHS RHS" is always true.
9884 const Value *RHS) {
9885 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9886 return true;
9887
9888 switch (Pred) {
9889 default:
9890 return false;
9891
9892 case CmpInst::ICMP_SLE: {
9893 const APInt *C;
9894
9895 // LHS s<= LHS +_{nsw} C if C >= 0
9896 // LHS s<= LHS | C if C >= 0
9897 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9899 return !C->isNegative();
9900
9901 // LHS s<= smax(LHS, V) for any V
9903 return true;
9904
9905 // smin(RHS, V) s<= RHS for any V
9907 return true;
9908
9909 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9910 const Value *X;
9911 const APInt *CLHS, *CRHS;
9912 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9914 return CLHS->sle(*CRHS);
9915
9916 return false;
9917 }
9918
9919 case CmpInst::ICMP_ULE: {
9920 // LHS u<= LHS +_{nuw} V for any V
9921 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9923 return true;
9924
9925 // LHS u<= LHS | V for any V
9926 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9927 return true;
9928
9929 // LHS u<= umax(LHS, V) for any V
9931 return true;
9932
9933 // RHS >> V u<= RHS for any V
9934 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9935 return true;
9936
9937 // RHS u/ C_ugt_1 u<= RHS
9938 const APInt *C;
9939 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9940 return true;
9941
9942 // RHS & V u<= RHS for any V
9944 return true;
9945
9946 // umin(RHS, V) u<= RHS for any V
9948 return true;
9949
9950 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9951 const Value *X;
9952 const APInt *CLHS, *CRHS;
9953 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9955 return CLHS->ule(*CRHS);
9956
9957 return false;
9958 }
9959 }
9960}
9961
9962/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9963/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9964static std::optional<bool>
9966 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9967 switch (Pred) {
9968 default:
9969 return std::nullopt;
9970
9971 case CmpInst::ICMP_SLT:
9972 case CmpInst::ICMP_SLE:
9973 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9975 return true;
9976 return std::nullopt;
9977
9978 case CmpInst::ICMP_SGT:
9979 case CmpInst::ICMP_SGE:
9980 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9982 return true;
9983 return std::nullopt;
9984
9985 case CmpInst::ICMP_ULT:
9986 case CmpInst::ICMP_ULE:
9987 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9989 return true;
9990 return std::nullopt;
9991
9992 case CmpInst::ICMP_UGT:
9993 case CmpInst::ICMP_UGE:
9994 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9996 return true;
9997 return std::nullopt;
9998 }
9999}
10000
10001/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
10002/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
10003/// Otherwise, return std::nullopt if we can't infer anything.
10004static std::optional<bool>
10006 CmpPredicate RPred, const ConstantRange &RCR) {
10007 auto CRImpliesPred = [&](ConstantRange CR,
10008 CmpInst::Predicate Pred) -> std::optional<bool> {
10009 // If all true values for lhs and true for rhs, lhs implies rhs
10010 if (CR.icmp(Pred, RCR))
10011 return true;
10012
10013 // If there is no overlap, lhs implies not rhs
10014 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
10015 return false;
10016
10017 return std::nullopt;
10018 };
10019 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10020 RPred))
10021 return Res;
10022 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
10024 : LPred.dropSameSign();
10026 : RPred.dropSameSign();
10027 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10028 RPred);
10029 }
10030 return std::nullopt;
10031}
10032
10033/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10034/// is true. Return false if LHS implies RHS is false. Otherwise, return
10035/// std::nullopt if we can't infer anything.
10036static std::optional<bool>
10037isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
10038 CmpPredicate RPred, const Value *R0, const Value *R1,
10039 const DataLayout &DL, bool LHSIsTrue) {
10040 // The rest of the logic assumes the LHS condition is true. If that's not the
10041 // case, invert the predicate to make it so.
10042 if (!LHSIsTrue)
10043 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10044
10045 // We can have non-canonical operands, so try to normalize any common operand
10046 // to L0/R0.
10047 if (L0 == R1) {
10048 std::swap(R0, R1);
10049 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10050 }
10051 if (R0 == L1) {
10052 std::swap(L0, L1);
10053 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10054 }
10055 if (L1 == R1) {
10056 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10057 if (L0 != R0 || match(L0, m_ImmConstant())) {
10058 std::swap(L0, L1);
10059 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10060 std::swap(R0, R1);
10061 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10062 }
10063 }
10064
10065 // See if we can infer anything if operand-0 matches and we have at least one
10066 // constant.
10067 const APInt *Unused;
10068 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10069 // Potential TODO: We could also further use the constant range of L0/R0 to
10070 // further constraint the constant ranges. At the moment this leads to
10071 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10072 // C1` (see discussion: D58633).
10073 SimplifyQuery SQ(DL);
10078
10079 // Even if L1/R1 are not both constant, we can still sometimes deduce
10080 // relationship from a single constant. For example X u> Y implies X != 0.
10081 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10082 return R;
10083 // If both L1/R1 were exact constant ranges and we didn't get anything
10084 // here, we won't be able to deduce this.
10085 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10086 return std::nullopt;
10087 }
10088
10089 // Can we infer anything when the two compares have matching operands?
10090 if (L0 == R0 && L1 == R1)
10091 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10092
10093 // It only really makes sense in the context of signed comparison for "X - Y
10094 // must be positive if X >= Y and no overflow".
10095 // Take SGT as an example: L0:x > L1:y and C >= 0
10096 // ==> R0:(x -nsw y) < R1:(-C) is false
10097 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10098 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10099 SignedLPred == ICmpInst::ICMP_SGE) &&
10100 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10101 if (match(R1, m_NonPositive()) &&
10102 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10103 return false;
10104 }
10105
10106 // Take SLT as an example: L0:x < L1:y and C <= 0
10107 // ==> R0:(x -nsw y) < R1:(-C) is true
10108 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10109 SignedLPred == ICmpInst::ICMP_SLE) &&
10110 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10111 if (match(R1, m_NonNegative()) &&
10112 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10113 return true;
10114 }
10115
10116 // a - b == NonZero -> a != b
10117 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10118 const APInt *L1C;
10119 Value *A, *B;
10120 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10121 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10122 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10123 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10128 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10129 }
10130
10131 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10132 if (L0 == R0 &&
10133 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10134 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10135 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10136 return CmpPredicate::getMatching(LPred, RPred).has_value();
10137
10138 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10139 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10140
10141 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10142 // Example: L0 u< 13 => (L0 & 16) == 0
10143 const APInt *LC, *RC, *MaskC;
10144 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10145 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10147 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10148 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10149 return true;
10150 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10151 ConstantRange(*RC)))
10152 return false;
10153 }
10154
10155 return std::nullopt;
10156}
10157
10158/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10159/// is true. Return false if LHS implies RHS is false. Otherwise, return
10160/// std::nullopt if we can't infer anything.
10161static std::optional<bool>
10163 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10164 const DataLayout &DL, bool LHSIsTrue) {
10165 // The rest of the logic assumes the LHS condition is true. If that's not the
10166 // case, invert the predicate to make it so.
10167 if (!LHSIsTrue)
10168 LPred = FCmpInst::getInversePredicate(LPred);
10169
10170 // We can have non-canonical operands, so try to normalize any common operand
10171 // to L0/R0.
10172 if (L0 == R1) {
10173 std::swap(R0, R1);
10174 RPred = FCmpInst::getSwappedPredicate(RPred);
10175 }
10176 if (R0 == L1) {
10177 std::swap(L0, L1);
10178 LPred = FCmpInst::getSwappedPredicate(LPred);
10179 }
10180 if (L1 == R1) {
10181 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10182 if (L0 != R0 || match(L0, m_ImmConstant())) {
10183 std::swap(L0, L1);
10184 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10185 std::swap(R0, R1);
10186 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10187 }
10188 }
10189
10190 // Can we infer anything when the two compares have matching operands?
10191 if (L0 == R0 && L1 == R1) {
10192 if ((LPred & RPred) == LPred)
10193 return true;
10194 if ((LPred & ~RPred) == LPred)
10195 return false;
10196 }
10197
10198 // See if we can infer anything if operand-0 matches and we have at least one
10199 // constant.
10200 const APFloat *L1C, *R1C;
10201 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10202 if (std::optional<ConstantFPRange> DomCR =
10204 if (std::optional<ConstantFPRange> ImpliedCR =
10206 if (ImpliedCR->contains(*DomCR))
10207 return true;
10208 }
10209 if (std::optional<ConstantFPRange> ImpliedCR =
10211 FCmpInst::getInversePredicate(RPred), *R1C)) {
10212 if (ImpliedCR->contains(*DomCR))
10213 return false;
10214 }
10215 }
10216 }
10217
10218 return std::nullopt;
10219}
10220
10221/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10222/// false. Otherwise, return std::nullopt if we can't infer anything. We
10223/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10224/// instruction.
10225static std::optional<bool>
10227 const Value *RHSOp0, const Value *RHSOp1,
10228 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10229 // The LHS must be an 'or', 'and', or a 'select' instruction.
10230 assert((LHS->getOpcode() == Instruction::And ||
10231 LHS->getOpcode() == Instruction::Or ||
10232 LHS->getOpcode() == Instruction::Select) &&
10233 "Expected LHS to be 'and', 'or', or 'select'.");
10234
10235 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10236
10237 // If the result of an 'or' is false, then we know both legs of the 'or' are
10238 // false. Similarly, if the result of an 'and' is true, then we know both
10239 // legs of the 'and' are true.
10240 const Value *ALHS, *ARHS;
10241 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10242 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10243 // FIXME: Make this non-recursion.
10244 if (std::optional<bool> Implication = isImpliedCondition(
10245 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10246 return Implication;
10247 if (std::optional<bool> Implication = isImpliedCondition(
10248 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10249 return Implication;
10250 return std::nullopt;
10251 }
10252 return std::nullopt;
10253}
10254
10255std::optional<bool>
10257 const Value *RHSOp0, const Value *RHSOp1,
10258 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10259 // Bail out when we hit the limit.
10261 return std::nullopt;
10262
10263 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10264 // example.
10265 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10266 return std::nullopt;
10267
10268 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10269 "Expected integer type only!");
10270
10271 // Match not
10272 if (match(LHS, m_Not(m_Value(LHS))))
10273 LHSIsTrue = !LHSIsTrue;
10274
10275 // Both LHS and RHS are icmps.
10276 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10277 CmpPredicate LHSPred;
10278 Value *LHSOp0, *LHSOp1;
10279 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10280 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10281 RHSOp1, DL, LHSIsTrue);
10282 } else {
10283 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10284 "Expected floating point type only!");
10285 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10286 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10287 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10288 DL, LHSIsTrue);
10289 }
10290
10291 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10292 /// the RHS to be an icmp.
10293 /// FIXME: Add support for and/or/select on the RHS.
10294 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10295 if ((LHSI->getOpcode() == Instruction::And ||
10296 LHSI->getOpcode() == Instruction::Or ||
10297 LHSI->getOpcode() == Instruction::Select))
10298 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10299 Depth);
10300 }
10301 return std::nullopt;
10302}
10303
10304std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10305 const DataLayout &DL,
10306 bool LHSIsTrue, unsigned Depth) {
10307 // LHS ==> RHS by definition
10308 if (LHS == RHS)
10309 return LHSIsTrue;
10310
10311 // Match not
10312 bool InvertRHS = false;
10313 if (match(RHS, m_Not(m_Value(RHS)))) {
10314 if (LHS == RHS)
10315 return !LHSIsTrue;
10316 InvertRHS = true;
10317 }
10318
10319 CmpPredicate RHSPred;
10320 Value *RHSOp0, *RHSOp1;
10321 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10322 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10323 LHSIsTrue, Depth))
10324 return InvertRHS ? !*Implied : *Implied;
10325 return std::nullopt;
10326 }
10327 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10328 if (auto Implied = isImpliedCondition(
10329 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10330 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10331 return InvertRHS ? !*Implied : *Implied;
10332 return std::nullopt;
10333 }
10334
10336 return std::nullopt;
10337
10338 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10339 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10340 const Value *RHS1, *RHS2;
10341 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10342 if (std::optional<bool> Imp =
10343 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10344 if (*Imp == true)
10345 return !InvertRHS;
10346 if (std::optional<bool> Imp =
10347 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10348 if (*Imp == true)
10349 return !InvertRHS;
10350 }
10351 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10352 if (std::optional<bool> Imp =
10353 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10354 if (*Imp == false)
10355 return InvertRHS;
10356 if (std::optional<bool> Imp =
10357 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10358 if (*Imp == false)
10359 return InvertRHS;
10360 }
10361
10362 return std::nullopt;
10363}
10364
10365// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10366// condition dominating ContextI or nullptr, if no condition is found.
10367static std::pair<Value *, bool>
10369 if (!ContextI || !ContextI->getParent())
10370 return {nullptr, false};
10371
10372 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10373 // dominator tree (eg, from a SimplifyQuery) instead?
10374 const BasicBlock *ContextBB = ContextI->getParent();
10375 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10376 if (!PredBB)
10377 return {nullptr, false};
10378
10379 // We need a conditional branch in the predecessor.
10380 Value *PredCond;
10381 BasicBlock *TrueBB, *FalseBB;
10382 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10383 return {nullptr, false};
10384
10385 // The branch should get simplified. Don't bother simplifying this condition.
10386 if (TrueBB == FalseBB)
10387 return {nullptr, false};
10388
10389 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10390 "Predecessor block does not point to successor?");
10391
10392 // Is this condition implied by the predecessor condition?
10393 return {PredCond, TrueBB == ContextBB};
10394}
10395
10396std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10397 const Instruction *ContextI,
10398 const DataLayout &DL) {
10399 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10400 auto PredCond = getDomPredecessorCondition(ContextI);
10401 if (PredCond.first)
10402 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10403 return std::nullopt;
10404}
10405
10407 const Value *LHS,
10408 const Value *RHS,
10409 const Instruction *ContextI,
10410 const DataLayout &DL) {
10411 auto PredCond = getDomPredecessorCondition(ContextI);
10412 if (PredCond.first)
10413 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10414 PredCond.second);
10415 return std::nullopt;
10416}
10417
10419 APInt &Upper, const InstrInfoQuery &IIQ,
10420 bool PreferSignedRange) {
10421 unsigned Width = Lower.getBitWidth();
10422 const APInt *C;
10423 switch (BO.getOpcode()) {
10424 case Instruction::Sub:
10425 if (match(BO.getOperand(0), m_APInt(C))) {
10426 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10427 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10428
10429 // If the caller expects a signed compare, then try to use a signed range.
10430 // Otherwise if both no-wraps are set, use the unsigned range because it
10431 // is never larger than the signed range. Example:
10432 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10433 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10434 if (PreferSignedRange && HasNSW && HasNUW)
10435 HasNUW = false;
10436
10437 if (HasNUW) {
10438 // 'sub nuw c, x' produces [0, C].
10439 Upper = *C + 1;
10440 } else if (HasNSW) {
10441 if (C->isNegative()) {
10442 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10444 Upper = *C - APInt::getSignedMaxValue(Width);
10445 } else {
10446 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10447 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10448 Lower = *C - APInt::getSignedMaxValue(Width);
10450 }
10451 }
10452 }
10453 break;
10454 case Instruction::Add:
10455 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10456 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10457 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10458
10459 // If the caller expects a signed compare, then try to use a signed
10460 // range. Otherwise if both no-wraps are set, use the unsigned range
10461 // because it is never larger than the signed range. Example: "add nuw
10462 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10463 if (PreferSignedRange && HasNSW && HasNUW)
10464 HasNUW = false;
10465
10466 if (HasNUW) {
10467 // 'add nuw x, C' produces [C, UINT_MAX].
10468 Lower = *C;
10469 } else if (HasNSW) {
10470 if (C->isNegative()) {
10471 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10473 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10474 } else {
10475 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10476 Lower = APInt::getSignedMinValue(Width) + *C;
10477 Upper = APInt::getSignedMaxValue(Width) + 1;
10478 }
10479 }
10480 }
10481 break;
10482
10483 case Instruction::And:
10484 if (match(BO.getOperand(1), m_APInt(C)))
10485 // 'and x, C' produces [0, C].
10486 Upper = *C + 1;
10487 // X & -X is a power of two or zero. So we can cap the value at max power of
10488 // two.
10489 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10490 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10491 Upper = APInt::getSignedMinValue(Width) + 1;
10492 break;
10493
10494 case Instruction::Or:
10495 if (match(BO.getOperand(1), m_APInt(C)))
10496 // 'or x, C' produces [C, UINT_MAX].
10497 Lower = *C;
10498 break;
10499
10500 case Instruction::AShr:
10501 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10502 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10504 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10505 } else if (match(BO.getOperand(0), m_APInt(C))) {
10506 unsigned ShiftAmount = Width - 1;
10507 if (!C->isZero() && IIQ.isExact(&BO))
10508 ShiftAmount = C->countr_zero();
10509 if (C->isNegative()) {
10510 // 'ashr C, x' produces [C, C >> (Width-1)]
10511 Lower = *C;
10512 Upper = C->ashr(ShiftAmount) + 1;
10513 } else {
10514 // 'ashr C, x' produces [C >> (Width-1), C]
10515 Lower = C->ashr(ShiftAmount);
10516 Upper = *C + 1;
10517 }
10518 }
10519 break;
10520
10521 case Instruction::LShr:
10522 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10523 // 'lshr x, C' produces [0, UINT_MAX >> C].
10524 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10525 } else if (match(BO.getOperand(0), m_APInt(C))) {
10526 // 'lshr C, x' produces [C >> (Width-1), C].
10527 unsigned ShiftAmount = Width - 1;
10528 if (!C->isZero() && IIQ.isExact(&BO))
10529 ShiftAmount = C->countr_zero();
10530 Lower = C->lshr(ShiftAmount);
10531 Upper = *C + 1;
10532 }
10533 break;
10534
10535 case Instruction::Shl:
10536 if (match(BO.getOperand(0), m_APInt(C))) {
10537 if (IIQ.hasNoUnsignedWrap(&BO)) {
10538 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10539 Lower = *C;
10540 Upper = Lower.shl(Lower.countl_zero()) + 1;
10541 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10542 if (C->isNegative()) {
10543 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10544 unsigned ShiftAmount = C->countl_one() - 1;
10545 Lower = C->shl(ShiftAmount);
10546 Upper = *C + 1;
10547 } else {
10548 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10549 unsigned ShiftAmount = C->countl_zero() - 1;
10550 Lower = *C;
10551 Upper = C->shl(ShiftAmount) + 1;
10552 }
10553 } else {
10554 // If lowbit is set, value can never be zero.
10555 if ((*C)[0])
10556 Lower = APInt::getOneBitSet(Width, 0);
10557 // If we are shifting a constant the largest it can be is if the longest
10558 // sequence of consecutive ones is shifted to the highbits (breaking
10559 // ties for which sequence is higher). At the moment we take a liberal
10560 // upper bound on this by just popcounting the constant.
10561 // TODO: There may be a bitwise trick for it longest/highest
10562 // consecutative sequence of ones (naive method is O(Width) loop).
10563 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10564 }
10565 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10566 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10567 }
10568 break;
10569
10570 case Instruction::SDiv:
10571 if (match(BO.getOperand(1), m_APInt(C))) {
10572 APInt IntMin = APInt::getSignedMinValue(Width);
10573 APInt IntMax = APInt::getSignedMaxValue(Width);
10574 if (C->isAllOnes()) {
10575 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10576 // where C != -1 and C != 0 and C != 1
10577 Lower = IntMin + 1;
10578 Upper = IntMax + 1;
10579 } else if (C->countl_zero() < Width - 1) {
10580 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10581 // where C != -1 and C != 0 and C != 1
10582 Lower = IntMin.sdiv(*C);
10583 Upper = IntMax.sdiv(*C);
10584 if (Lower.sgt(Upper))
10586 Upper = Upper + 1;
10587 assert(Upper != Lower && "Upper part of range has wrapped!");
10588 }
10589 } else if (match(BO.getOperand(0), m_APInt(C))) {
10590 if (C->isMinSignedValue()) {
10591 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10592 Lower = *C;
10593 Upper = Lower.lshr(1) + 1;
10594 } else {
10595 // 'sdiv C, x' produces [-|C|, |C|].
10596 Upper = C->abs() + 1;
10597 Lower = (-Upper) + 1;
10598 }
10599 }
10600 break;
10601
10602 case Instruction::UDiv:
10603 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10604 // 'udiv x, C' produces [0, UINT_MAX / C].
10605 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10606 } else if (match(BO.getOperand(0), m_APInt(C))) {
10607 // 'udiv C, x' produces [0, C].
10608 Upper = *C + 1;
10609 }
10610 break;
10611
10612 case Instruction::SRem:
10613 if (match(BO.getOperand(1), m_APInt(C))) {
10614 // 'srem x, C' produces (-|C|, |C|).
10615 Upper = C->abs();
10616 Lower = (-Upper) + 1;
10617 } else if (match(BO.getOperand(0), m_APInt(C))) {
10618 if (C->isNegative()) {
10619 // 'srem -|C|, x' produces [-|C|, 0].
10620 Upper = 1;
10621 Lower = *C;
10622 } else {
10623 // 'srem |C|, x' produces [0, |C|].
10624 Upper = *C + 1;
10625 }
10626 }
10627 break;
10628
10629 case Instruction::URem:
10630 if (match(BO.getOperand(1), m_APInt(C)))
10631 // 'urem x, C' produces [0, C).
10632 Upper = *C;
10633 else if (match(BO.getOperand(0), m_APInt(C)))
10634 // 'urem C, x' produces [0, C].
10635 Upper = *C + 1;
10636 break;
10637
10638 default:
10639 break;
10640 }
10641}
10642
10644 bool UseInstrInfo) {
10645 unsigned Width = II.getType()->getScalarSizeInBits();
10646 const APInt *C;
10647 switch (II.getIntrinsicID()) {
10648 case Intrinsic::ctlz:
10649 case Intrinsic::cttz: {
10650 APInt Upper(Width, Width);
10651 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10652 Upper += 1;
10653 // Maximum of set/clear bits is the bit width.
10655 }
10656 case Intrinsic::ctpop:
10657 // Maximum of set/clear bits is the bit width.
10659 APInt(Width, Width) + 1);
10660 case Intrinsic::uadd_sat:
10661 // uadd.sat(x, C) produces [C, UINT_MAX].
10662 if (match(II.getOperand(0), m_APInt(C)) ||
10663 match(II.getOperand(1), m_APInt(C)))
10665 break;
10666 case Intrinsic::sadd_sat:
10667 if (match(II.getOperand(0), m_APInt(C)) ||
10668 match(II.getOperand(1), m_APInt(C))) {
10669 if (C->isNegative())
10670 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10672 APInt::getSignedMaxValue(Width) + *C +
10673 1);
10674
10675 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10677 APInt::getSignedMaxValue(Width) + 1);
10678 }
10679 break;
10680 case Intrinsic::usub_sat:
10681 // usub.sat(C, x) produces [0, C].
10682 if (match(II.getOperand(0), m_APInt(C)))
10683 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10684
10685 // usub.sat(x, C) produces [0, UINT_MAX - C].
10686 if (match(II.getOperand(1), m_APInt(C)))
10688 APInt::getMaxValue(Width) - *C + 1);
10689 break;
10690 case Intrinsic::ssub_sat:
10691 if (match(II.getOperand(0), m_APInt(C))) {
10692 if (C->isNegative())
10693 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10695 *C - APInt::getSignedMinValue(Width) +
10696 1);
10697
10698 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10700 APInt::getSignedMaxValue(Width) + 1);
10701 } else if (match(II.getOperand(1), m_APInt(C))) {
10702 if (C->isNegative())
10703 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10705 APInt::getSignedMaxValue(Width) + 1);
10706
10707 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10709 APInt::getSignedMaxValue(Width) - *C +
10710 1);
10711 }
10712 break;
10713 case Intrinsic::umin:
10714 case Intrinsic::umax:
10715 case Intrinsic::smin:
10716 case Intrinsic::smax:
10717 if (!match(II.getOperand(0), m_APInt(C)) &&
10718 !match(II.getOperand(1), m_APInt(C)))
10719 break;
10720
10721 switch (II.getIntrinsicID()) {
10722 case Intrinsic::umin:
10723 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10724 case Intrinsic::umax:
10726 case Intrinsic::smin:
10728 *C + 1);
10729 case Intrinsic::smax:
10731 APInt::getSignedMaxValue(Width) + 1);
10732 default:
10733 llvm_unreachable("Must be min/max intrinsic");
10734 }
10735 break;
10736 case Intrinsic::abs:
10737 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10738 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10739 if (match(II.getOperand(1), m_One()))
10741 APInt::getSignedMaxValue(Width) + 1);
10742
10744 APInt::getSignedMinValue(Width) + 1);
10745 case Intrinsic::vscale:
10746 if (!II.getParent() || !II.getFunction())
10747 break;
10748 return getVScaleRange(II.getFunction(), Width);
10749 case Intrinsic::read_register:
10750 case Intrinsic::read_volatile_register: {
10751 const Module *M = II.getModule();
10752 if (!M || !M->getTargetTriple().isRISCV())
10753 break;
10754 if (II.getFunction() && isReadVLENB(II))
10755 return getRISCVVLENBRange(II, Width);
10756 break;
10757 }
10758 default:
10759 break;
10760 }
10761
10762 return ConstantRange::getFull(Width);
10763}
10764
10766 const InstrInfoQuery &IIQ) {
10767 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10768 const Value *LHS = nullptr, *RHS = nullptr;
10770 if (R.Flavor == SPF_UNKNOWN)
10771 return ConstantRange::getFull(BitWidth);
10772
10773 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10774 // If the negation part of the abs (in RHS) has the NSW flag,
10775 // then the result of abs(X) is [0..SIGNED_MAX],
10776 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10777 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10781
10784 }
10785
10786 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10787 // The result of -abs(X) is <= 0.
10789 APInt(BitWidth, 1));
10790 }
10791
10792 const APInt *C;
10793 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10794 return ConstantRange::getFull(BitWidth);
10795
10796 switch (R.Flavor) {
10797 case SPF_UMIN:
10799 case SPF_UMAX:
10801 case SPF_SMIN:
10803 *C + 1);
10804 case SPF_SMAX:
10807 default:
10808 return ConstantRange::getFull(BitWidth);
10809 }
10810}
10811
10813 // The maximum representable value of a half is 65504. For floats the maximum
10814 // value is 3.4e38 which requires roughly 129 bits.
10815 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10816 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10817 return;
10818 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10819 Lower = APInt(BitWidth, -65504, true);
10820 Upper = APInt(BitWidth, 65505);
10821 }
10822
10823 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10824 // For a fptoui the lower limit is left as 0.
10825 Upper = APInt(BitWidth, 65505);
10826 }
10827}
10828
10830 const SimplifyQuery &SQ,
10831 unsigned Depth) {
10832 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10833
10835 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10836
10837 if (auto *C = dyn_cast<Constant>(V))
10838 return C->toConstantRange();
10839
10840 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10841 ConstantRange CR = ConstantRange::getFull(BitWidth);
10842 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10843 APInt Lower = APInt(BitWidth, 0);
10844 APInt Upper = APInt(BitWidth, 0);
10845 // TODO: Return ConstantRange.
10846 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10848 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10850 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10851 ConstantRange CRTrue =
10852 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10853 ConstantRange CRFalse =
10854 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10855 CR = CRTrue.unionWith(CRFalse);
10857 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10858 ConstantRange SrcCR =
10859 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10860 CR = SrcCR.truncate(BitWidth);
10861 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10862 ConstantRange SrcCR =
10863 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10864 CR = SrcCR.zeroExtend(BitWidth);
10865 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10866 ConstantRange SrcCR =
10867 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10868 CR = SrcCR.signExtend(BitWidth);
10869 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10870 APInt Lower = APInt(BitWidth, 0);
10871 APInt Upper = APInt(BitWidth, 0);
10872 // TODO: Return ConstantRange.
10875 } else if (const auto *A = dyn_cast<Argument>(V))
10876 if (std::optional<ConstantRange> Range = A->getRange())
10877 CR = *Range;
10878
10879 if (auto *I = dyn_cast<Instruction>(V)) {
10880 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10882
10883 Value *FrexpSrc;
10884 if (const auto *CB = dyn_cast<CallBase>(V)) {
10885 if (std::optional<ConstantRange> Range = CB->getRange())
10886 CR = CR.intersectWith(*Range);
10888 m_Value(FrexpSrc))))) {
10889 const fltSemantics &FltSem =
10890 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10891 // It should be possible to implement this for any type, but this logic
10892 // only computes the range assuming standard subnormal handling.
10893 if (APFloat::isIEEELikeFP(FltSem)) {
10895 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10896
10897 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10898 // constrain its range when the source can be neither.
10899 if (KnownSrc.isKnownNeverInfOrNaN()) {
10900 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10901
10902 // Offset to find the true minimum exponent value for a denormal.
10903 if (!KnownSrc.isKnownNeverSubnormal())
10904 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10905
10906 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10907
10908 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10910
10911 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10912 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10913
10914 MinExp = std::max(AdjustedMin, MinExp);
10915 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10916 MaxExp);
10917
10919 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10920 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10921 /*isSigned=*/true));
10922 }
10923 }
10924 }
10925 }
10926
10927 if (SQ.CtxI && SQ.AC) {
10928 // Try to restrict the range based on information from assumptions.
10929 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10930 if (!AssumeVH)
10931 continue;
10932 CallInst *I = cast<CallInst>(AssumeVH);
10933 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10934 "Got assumption for the wrong function!");
10935 assert(I->getIntrinsicID() == Intrinsic::assume &&
10936 "must be an assume intrinsic");
10937
10938 if (!isValidAssumeForContext(I, SQ))
10939 continue;
10940 Value *Arg = I->getArgOperand(0);
10941 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10942 // Currently we just use information from comparisons.
10943 if (!Cmp || Cmp->getOperand(0) != V)
10944 continue;
10945 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10946 ConstantRange RHS =
10947 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10948 SQ.getWithInstruction(I), Depth + 1);
10949 CR = CR.intersectWith(
10950 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10951 }
10952 }
10953
10954 return CR;
10955}
10956
10957static void
10959 function_ref<void(Value *)> InsertAffected) {
10960 assert(V != nullptr);
10961 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10962 InsertAffected(V);
10963 } else if (auto *I = dyn_cast<Instruction>(V)) {
10964 InsertAffected(V);
10965
10966 // Peek through unary operators to find the source of the condition.
10967 Value *Op;
10969 m_Trunc(m_Value(Op))))) {
10971 InsertAffected(Op);
10972 }
10973 }
10974}
10975
10977 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10978 auto AddAffected = [&InsertAffected](Value *V) {
10979 addValueAffectedByCondition(V, InsertAffected);
10980 };
10981
10982 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10983 if (IsAssume) {
10984 AddAffected(LHS);
10985 AddAffected(RHS);
10986 } else if (match(RHS, m_Constant()))
10987 AddAffected(LHS);
10988 };
10989
10990 SmallVector<Value *, 8> Worklist;
10992 Worklist.push_back(Cond);
10993 while (!Worklist.empty()) {
10994 Value *V = Worklist.pop_back_val();
10995 if (!Visited.insert(V).second)
10996 continue;
10997
10998 CmpPredicate Pred;
10999 Value *A, *B, *X;
11000
11001 if (IsAssume) {
11002 AddAffected(V);
11003 if (match(V, m_Not(m_Value(X))))
11004 AddAffected(X);
11005 }
11006
11007 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
11008 // assume(A && B) is split to -> assume(A); assume(B);
11009 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
11010 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
11011 // enough information to be worth handling (intersection of information as
11012 // opposed to union).
11013 if (!IsAssume) {
11014 Worklist.push_back(A);
11015 Worklist.push_back(B);
11016 }
11017 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
11018 bool HasRHSC = match(B, m_ConstantInt());
11019 if (ICmpInst::isEquality(Pred)) {
11020 AddAffected(A);
11021 if (IsAssume)
11022 AddAffected(B);
11023 if (HasRHSC) {
11024 Value *Y;
11025 // (X << C) or (X >>_s C) or (X >>_u C).
11026 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
11027 AddAffected(X);
11028 // (X & C) or (X | C).
11029 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11030 match(A, m_Or(m_Value(X), m_Value(Y)))) {
11031 AddAffected(X);
11032 AddAffected(Y);
11033 }
11034 // X - Y
11035 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11036 AddAffected(X);
11037 AddAffected(Y);
11038 }
11039 }
11040 } else {
11041 AddCmpOperands(A, B);
11042 if (HasRHSC) {
11043 // Handle (A + C1) u< C2, which is the canonical form of
11044 // A > C3 && A < C4.
11046 AddAffected(X);
11047
11048 if (ICmpInst::isUnsigned(Pred)) {
11049 Value *Y;
11050 // X & Y u> C -> X >u C && Y >u C
11051 // X | Y u< C -> X u< C && Y u< C
11052 // X nuw+ Y u< C -> X u< C && Y u< C
11053 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11054 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11055 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11056 AddAffected(X);
11057 AddAffected(Y);
11058 }
11059 // X nuw- Y u> C -> X u> C
11060 if (match(A, m_NUWSub(m_Value(X), m_Value())))
11061 AddAffected(X);
11062 }
11063 }
11064
11065 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11066 // by computeKnownFPClass().
11068 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11069 InsertAffected(X);
11070 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11071 InsertAffected(X);
11072 }
11073 }
11074
11075 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11076 Value *SquareOp = nullptr;
11077 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11078 AddAffected(SquareOp);
11079 };
11080 AddNuwSquareOperand(A);
11081 AddNuwSquareOperand(B);
11082
11083 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11084 AddAffected(X);
11085 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11086 AddCmpOperands(A, B);
11087
11088 // fcmp fneg(x), y
11089 // fcmp fabs(x), y
11090 // fcmp fneg(fabs(x)), y
11091 if (match(A, m_FNeg(m_Value(A))))
11092 AddAffected(A);
11093 if (match(A, m_FAbs(m_Value(A))))
11094 AddAffected(A);
11095
11097 m_Value()))) {
11098 // Handle patterns that computeKnownFPClass() support.
11099 AddAffected(A);
11100 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11101 // Assume is checked here as X is already added above for assumes in
11102 // addValueAffectedByCondition
11103 AddAffected(X);
11104 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11105 // Assume is checked here to avoid issues with ephemeral values
11106 Worklist.push_back(X);
11107 }
11108 }
11109}
11110
11112 // (X >> C) or/add (X & mask(C) != 0)
11113 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11114 if (BO->getOpcode() == Instruction::Add ||
11115 BO->getOpcode() == Instruction::Or) {
11116 const Value *X;
11117 const APInt *C1, *C2;
11118 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11122 m_Zero())))) &&
11123 C2->popcount() == C1->getZExtValue())
11124 return X;
11125 }
11126 }
11127 return nullptr;
11128}
11129
11131 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11132}
11133
11136 unsigned MaxCount, bool AllowUndefOrPoison) {
11139 auto Push = [&](const Value *V) -> bool {
11140 Constant *C;
11141 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11142 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11143 return false;
11144 // Check existence first to avoid unnecessary allocations.
11145 if (Constants.contains(C))
11146 return true;
11147 if (Constants.size() == MaxCount)
11148 return false;
11149 Constants.insert(C);
11150 return true;
11151 }
11152
11153 if (auto *Inst = dyn_cast<Instruction>(V)) {
11154 if (Visited.insert(Inst).second)
11155 Worklist.push_back(Inst);
11156 return true;
11157 }
11158 return false;
11159 };
11160 if (!Push(V))
11161 return false;
11162 while (!Worklist.empty()) {
11163 const Instruction *CurInst = Worklist.pop_back_val();
11164 switch (CurInst->getOpcode()) {
11165 case Instruction::Select:
11166 if (!Push(CurInst->getOperand(1)))
11167 return false;
11168 if (!Push(CurInst->getOperand(2)))
11169 return false;
11170 break;
11171 case Instruction::PHI:
11172 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11173 // Fast path for recurrence PHI.
11174 if (IncomingValue == CurInst)
11175 continue;
11176 if (!Push(IncomingValue))
11177 return false;
11178 }
11179 break;
11180 default:
11181 return false;
11182 }
11183 }
11184 return true;
11185}
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 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 SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static 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 SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static 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:362
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:366
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:354
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:379
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
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:6155
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:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h: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:452
@ 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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
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.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI 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:197
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
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 fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass 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 fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
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 roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
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