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 *safeCxtI(const Value *V, const Instruction *CxtI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CxtI && CxtI->getParent())
117 return CxtI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CxtI = dyn_cast<Instruction>(V);
121 if (CxtI && CxtI->getParent())
122 return CxtI;
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 *CxtI, const DominatorTree *DT,
160 bool UseInstrInfo, unsigned Depth) {
162 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
163 Depth);
164}
165
167 AssumptionCache *AC, const Instruction *CxtI,
168 const DominatorTree *DT, bool UseInstrInfo,
169 unsigned Depth) {
170 return computeKnownBits(
171 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), 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.CxtI, SQ.DT)
185 }
186
187 // X op (Y & ~X)
189 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, 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.CxtI, SQ.DT) &&
199 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, 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.CxtI, 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.CxtI, SQ.DT) &&
218 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, 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 *CxtI,
295 const DominatorTree *DT, bool UseInstrInfo,
296 unsigned Depth) {
297 return ::isKnownToBeAPowerOfTwo(
298 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), 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 *CxtI,
365 const DominatorTree *DT, bool UseInstrInfo,
366 unsigned Depth) {
367 return ::ComputeNumSignBits(
368 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
369}
370
372 AssumptionCache *AC,
373 const Instruction *CxtI,
374 const DominatorTree *DT,
375 unsigned Depth) {
376 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, 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.CxtI, 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 *CxtI,
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() == CxtI->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(CxtI))
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 == CxtI)
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 CxtI 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(CxtI->getIterator(), Inv->getIterator());
712 return false;
713
714 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
715 }
716
717 // Inv and CxtI are in different blocks.
718 if (DT) {
719 if (DT->dominates(Inv, CxtI))
720 return true;
721 } else if (Inv->getParent() == CxtI->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
731 const Instruction *CtxI) {
732 // Helper to check if there are any calls in the range that may free memory.
733 unsigned NumChecked = 0;
734 auto hasNoFreeInRange = [&NumChecked](auto Range) {
735 for (const Instruction &I : Range) {
736 if (NumChecked++ > MaxInstrsToCheckForFree)
737 return false;
738
739 if (auto *CB = dyn_cast<CallBase>(&I)) {
740 if (!CB->hasFnAttr(Attribute::NoFree))
741 return false;
742 } else if (I.maySynchronize())
743 return false;
744 }
745 return true;
746 };
747
748 const BasicBlock *CtxBB = CtxI->getParent();
749 const BasicBlock *AssumeBB = Assume->getParent();
750 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
751 if (CtxBB == AssumeBB) {
752 // Same block case: check that Assume comes before CtxI.
753 if (Assume != CtxI && !Assume->comesBefore(CtxI))
754 return false;
755 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
756 }
757
758 // Handle chain of single-predecessor blocks.
759 const BasicBlock *CurBB = CtxBB;
760 while (true) {
761 if (CurBB == AssumeBB)
762 return hasNoFreeInRange(
763 make_range(Assume->getIterator(), AssumeBB->end()));
764
765 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
766 if (!PredBB)
767 return false;
768
769 if (!hasNoFreeInRange(make_range(CurBB->begin(),
770 CurBB == CtxBB ? CtxIter : CurBB->end())))
771 return false;
772 CurBB = PredBB;
773 }
774}
775
776// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
777// we still have enough information about `RHS` to conclude non-zero. For
778// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
779// so the extra compile time may not be worth it, but possibly a second API
780// should be created for use outside of loops.
781static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
782 // v u> y implies v != 0.
783 if (Pred == ICmpInst::ICMP_UGT)
784 return true;
785
786 // Special-case v != 0 to also handle v != null.
787 if (Pred == ICmpInst::ICMP_NE)
788 return match(RHS, m_Zero());
789
790 // All other predicates - rely on generic ConstantRange handling.
791 const APInt *C;
792 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
793 if (match(RHS, m_APInt(C))) {
795 return !TrueValues.contains(Zero);
796 }
797
799 if (VC == nullptr)
800 return false;
801
802 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
803 ++ElemIdx) {
805 Pred, VC->getElementAsAPInt(ElemIdx));
806 if (TrueValues.contains(Zero))
807 return false;
808 }
809 return true;
810}
811
812static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
813 Value *&ValOut, Instruction *&CtxIOut,
814 const PHINode **PhiOut = nullptr) {
815 ValOut = U->get();
816 if (ValOut == PHI)
817 return;
818 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
819 if (PhiOut)
820 *PhiOut = PHI;
821 Value *V;
822 // If the Use is a select of this phi, compute analysis on other arm to break
823 // recursion.
824 // TODO: Min/Max
825 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
826 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
827 ValOut = V;
828
829 // Same for select, if this phi is 2-operand phi, compute analysis on other
830 // incoming value to break recursion.
831 // TODO: We could handle any number of incoming edges as long as we only have
832 // two unique values.
833 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
834 IncPhi && IncPhi->getNumIncomingValues() == 2) {
835 for (int Idx = 0; Idx < 2; ++Idx) {
836 if (IncPhi->getIncomingValue(Idx) == PHI) {
837 ValOut = IncPhi->getIncomingValue(1 - Idx);
838 if (PhiOut)
839 *PhiOut = IncPhi;
840 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
841 break;
842 }
843 }
844 }
845}
846
847static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
848 // Use of assumptions is context-sensitive. If we don't have a context, we
849 // cannot use them!
850 if (!Q.AC || !Q.CxtI)
851 return false;
852
853 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
854 if (!Elem.Assume)
855 continue;
856
857 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
858 assert(I->getFunction() == Q.CxtI->getFunction() &&
859 "Got assumption for the wrong function!");
860
861 if (Elem.Index != AssumptionCache::ExprResultIdx) {
863 I->getOperandBundleAt(Elem.Index)) &&
865 return true;
866 continue;
867 }
868
869 // Warning: This loop can end up being somewhat performance sensitive.
870 // We're running this loop for once for each value queried resulting in a
871 // runtime of ~O(#assumes * #values).
872
873 Value *RHS;
874 CmpPredicate Pred;
875 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
876 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
877 continue;
878
880 return true;
881 }
882
883 return false;
884}
885
888 const SimplifyQuery &Q) {
889 if (RHS->getType()->isPointerTy()) {
890 // Handle comparison of pointer to null explicitly, as it will not be
891 // covered by the m_APInt() logic below.
892 if (LHS == V && match(RHS, m_Zero())) {
893 switch (Pred) {
895 Known.setAllZero();
896 break;
899 Known.makeNonNegative();
900 break;
902 Known.makeNegative();
903 break;
904 default:
905 break;
906 }
907 }
908 return;
909 }
910
911 unsigned BitWidth = Known.getBitWidth();
912 auto m_V =
914
915 Value *Y;
916 const APInt *Mask, *C;
917 if (!match(RHS, m_APInt(C)))
918 return;
919
920 uint64_t ShAmt;
921 switch (Pred) {
923 // assume(V = C)
924 if (match(LHS, m_V)) {
925 Known = Known.unionWith(KnownBits::makeConstant(*C));
926 // assume(V & Mask = C)
927 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
928 // For one bits in Mask, we can propagate bits from C to V.
929 Known.One |= *C;
930 if (match(Y, m_APInt(Mask)))
931 Known.Zero |= ~*C & *Mask;
932 // assume(V | Mask = C)
933 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
934 // For zero bits in Mask, we can propagate bits from C to V.
935 Known.Zero |= ~*C;
936 if (match(Y, m_APInt(Mask)))
937 Known.One |= *C & ~*Mask;
938 // assume(V << ShAmt = C)
939 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
940 ShAmt < BitWidth) {
941 // For those bits in C that are known, we can propagate them to known
942 // bits in V shifted to the right by ShAmt.
944 RHSKnown >>= ShAmt;
945 Known = Known.unionWith(RHSKnown);
946 // assume(V >> ShAmt = C)
947 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
948 ShAmt < BitWidth) {
949 // For those bits in RHS that are known, we can propagate them to known
950 // bits in V shifted to the right by C.
952 RHSKnown <<= ShAmt;
953 Known = Known.unionWith(RHSKnown);
954 }
955 break;
956 case ICmpInst::ICMP_NE: {
957 // assume (V & B != 0) where B is a power of 2
958 const APInt *BPow2;
959 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
960 Known.One |= *BPow2;
961 break;
962 }
963 default: {
964 const APInt *Offset = nullptr;
965 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
967 if (Offset)
968 LHSRange = LHSRange.sub(*Offset);
969 Known = Known.unionWith(LHSRange.toKnownBits());
970 }
971 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
972 // X & Y u> C -> X u> C && Y u> C
973 // X nuw- Y u> C -> X u> C
974 if (match(LHS, m_c_And(m_V, m_Value())) ||
975 match(LHS, m_NUWSub(m_V, m_Value())))
976 Known.One.setHighBits(
977 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
978 }
979 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
980 // X | Y u< C -> X u< C && Y u< C
981 // X nuw+ Y u< C -> X u< C && Y u< C
982 if (match(LHS, m_c_Or(m_V, m_Value())) ||
983 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
984 Known.Zero.setHighBits(
985 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
986 }
987 }
988 } break;
989 }
990}
991
992static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
994 const SimplifyQuery &SQ, bool Invert) {
996 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
997 Value *LHS = Cmp->getOperand(0);
998 Value *RHS = Cmp->getOperand(1);
999
1000 // Handle icmp pred (trunc V), C
1001 if (match(LHS, m_Trunc(m_Specific(V)))) {
1002 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1003 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1005 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1006 else
1007 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1008 return;
1009 }
1010
1011 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1012}
1013
1015 KnownBits &Known, const SimplifyQuery &SQ,
1016 bool Invert, unsigned Depth) {
1017 Value *A, *B;
1020 KnownBits Known2(Known.getBitWidth());
1021 KnownBits Known3(Known.getBitWidth());
1022 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1023 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1024 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1026 Known2 = Known2.unionWith(Known3);
1027 else
1028 Known2 = Known2.intersectWith(Known3);
1029 Known = Known.unionWith(Known2);
1030 return;
1031 }
1032
1033 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1034 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1035 return;
1036 }
1037
1038 if (match(Cond, m_Trunc(m_Specific(V)))) {
1039 KnownBits DstKnown(1);
1040 if (Invert) {
1041 DstKnown.setAllZero();
1042 } else {
1043 DstKnown.setAllOnes();
1044 }
1046 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1047 return;
1048 }
1049 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1050 return;
1051 }
1052
1054 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1055}
1056
1058 const SimplifyQuery &Q, unsigned Depth) {
1059 // Handle injected condition.
1060 if (Q.CC && Q.CC->AffectedValues.contains(V))
1062
1063 if (!Q.CxtI)
1064 return;
1065
1066 if (Q.DC && Q.DT) {
1067 // Handle dominating conditions.
1068 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1069 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1070 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1071 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1072 /*Invert*/ false, Depth);
1073
1074 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1075 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1076 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1077 /*Invert*/ true, Depth);
1078 }
1079
1080 if (Known.hasConflict())
1081 Known.resetAll();
1082 }
1083
1084 if (!Q.AC)
1085 return;
1086
1087 unsigned BitWidth = Known.getBitWidth();
1088
1089 // Note that the patterns below need to be kept in sync with the code
1090 // in AssumptionCache::updateAffectedValues.
1091
1092 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1093 if (!Elem.Assume)
1094 continue;
1095
1096 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1097 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1098 "Got assumption for the wrong function!");
1099
1100 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1101 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1102 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1103 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1104 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1106 Known.Zero |= (*Alignment - 1) & ~*Offset;
1107 Known.One |= (*Alignment - 1) & *Offset;
1108 }
1109 }
1110 continue;
1111 }
1112
1113 // Warning: This loop can end up being somewhat performance sensitive.
1114 // We're running this loop for once for each value queried resulting in a
1115 // runtime of ~O(#assumes * #values).
1116
1117 Value *Arg = I->getArgOperand(0);
1118
1119 if (Arg == V && isValidAssumeForContext(I, Q)) {
1120 assert(BitWidth == 1 && "assume operand is not i1?");
1121 (void)BitWidth;
1122 Known.setAllOnes();
1123 return;
1124 }
1125 if (match(Arg, m_Not(m_Specific(V))) &&
1127 assert(BitWidth == 1 && "assume operand is not i1?");
1128 (void)BitWidth;
1129 Known.setAllZero();
1130 return;
1131 }
1132 auto *Trunc = dyn_cast<TruncInst>(Arg);
1133 if (Trunc && Trunc->getOperand(0) == V &&
1135 if (Trunc->hasNoUnsignedWrap()) {
1137 return;
1138 }
1139 Known.One.setBit(0);
1140 return;
1141 }
1142
1143 // The remaining tests are all recursive, so bail out if we hit the limit.
1145 continue;
1146
1147 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1148 if (!Cmp)
1149 continue;
1150
1151 if (!isValidAssumeForContext(I, Q))
1152 continue;
1153
1154 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1155 }
1156
1157 // Conflicting assumption: Undefined behavior will occur on this execution
1158 // path.
1159 if (Known.hasConflict())
1160 Known.resetAll();
1161}
1162
1163/// Compute known bits from a shift operator, including those with a
1164/// non-constant shift amount. Known is the output of this function. Known2 is a
1165/// pre-allocated temporary with the same bit width as Known and on return
1166/// contains the known bit of the shift value source. KF is an
1167/// operator-specific function that, given the known-bits and a shift amount,
1168/// compute the implied known-bits of the shift operator's result respectively
1169/// for that shift amount. The results from calling KF are conservatively
1170/// combined for all permitted shift amounts.
1172 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1173 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1174 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1175 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1176 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1177 // To limit compile-time impact, only query isKnownNonZero() if we know at
1178 // least something about the shift amount.
1179 bool ShAmtNonZero =
1180 Known.isNonZero() ||
1181 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1182 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1183 Known = KF(Known2, Known, ShAmtNonZero);
1184}
1185
1186static KnownBits
1187getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1188 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1189 const SimplifyQuery &Q, unsigned Depth) {
1190 unsigned BitWidth = KnownLHS.getBitWidth();
1191 KnownBits KnownOut(BitWidth);
1192 bool IsAnd = false;
1193 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1194 Value *X = nullptr, *Y = nullptr;
1195
1196 switch (I->getOpcode()) {
1197 case Instruction::And:
1198 KnownOut = KnownLHS & KnownRHS;
1199 IsAnd = true;
1200 // and(x, -x) is common idioms that will clear all but lowest set
1201 // bit. If we have a single known bit in x, we can clear all bits
1202 // above it.
1203 // TODO: instcombine often reassociates independent `and` which can hide
1204 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1205 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1206 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1207 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1208 KnownOut = KnownLHS.blsi();
1209 else
1210 KnownOut = KnownRHS.blsi();
1211 }
1212 break;
1213 case Instruction::Or:
1214 KnownOut = KnownLHS | KnownRHS;
1215 break;
1216 case Instruction::Xor:
1217 KnownOut = KnownLHS ^ KnownRHS;
1218 // xor(x, x-1) is common idioms that will clear all but lowest set
1219 // bit. If we have a single known bit in x, we can clear all bits
1220 // above it.
1221 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1222 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1223 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1224 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1225 if (HasKnownOne &&
1227 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1228 KnownOut = XBits.blsmsk();
1229 }
1230 break;
1231 default:
1232 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1233 }
1234
1235 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1236 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1237 // here we handle the more general case of adding any odd number by
1238 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1239 // TODO: This could be generalized to clearing any bit set in y where the
1240 // following bit is known to be unset in y.
1241 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1245 KnownBits KnownY(BitWidth);
1246 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1247 if (KnownY.countMinTrailingOnes() > 0) {
1248 if (IsAnd)
1249 KnownOut.Zero.setBit(0);
1250 else
1251 KnownOut.One.setBit(0);
1252 }
1253 }
1254 return KnownOut;
1255}
1256
1258 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1259 unsigned Depth,
1260 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1261 KnownBitsFunc) {
1262 APInt DemandedEltsLHS, DemandedEltsRHS;
1264 DemandedElts, DemandedEltsLHS,
1265 DemandedEltsRHS);
1266
1267 const auto ComputeForSingleOpFunc =
1268 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1269 return KnownBitsFunc(
1270 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1271 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1272 };
1273
1274 if (DemandedEltsRHS.isZero())
1275 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1276 if (DemandedEltsLHS.isZero())
1277 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1278
1279 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1280 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1281}
1282
1283// Public so this can be used in `SimplifyDemandedUseBits`.
1285 const KnownBits &KnownLHS,
1286 const KnownBits &KnownRHS,
1287 const SimplifyQuery &SQ,
1288 unsigned Depth) {
1289 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1290 APInt DemandedElts =
1291 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1292
1293 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1294 Depth);
1295}
1296
1298 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1299 // Without vscale_range, we only know that vscale is non-zero.
1300 if (!Attr.isValid())
1302
1303 unsigned AttrMin = Attr.getVScaleRangeMin();
1304 // Minimum is larger than vscale width, result is always poison.
1305 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1306 return ConstantRange::getEmpty(BitWidth);
1307
1308 APInt Min(BitWidth, AttrMin);
1309 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1310 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1312
1313 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1314}
1315
1316/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1317/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1318/// target's VLEN range. Callers must ensure the target is RISC-V.
1319static bool isReadVLENB(const IntrinsicInst &II) {
1320 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1321 if (!MAV)
1322 return false;
1323 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1324 if (!MD || MD->getNumOperands() != 1)
1325 return false;
1326 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1327 return RegName && RegName->getString() == "vlenb";
1328}
1329
1330/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1331/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1332/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1333/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1334/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1335/// attribute, when present, pins the subtarget's VLEN in units of
1336/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1337/// RVVBytesPerBlock.
1339 unsigned Width) {
1340 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1341 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1342
1343 const Function *F = II.getFunction();
1344 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1345 ConstantRange VScale = getVScaleRange(F, Width);
1346 Range = Range.intersectWith(
1348 }
1349 return Range;
1350}
1351
1353 Value *Arm, bool Invert,
1354 const SimplifyQuery &Q, unsigned Depth) {
1355 // If we have a constant arm, we are done.
1356 if (Known.isConstant())
1357 return;
1358
1359 // See what condition implies about the bits of the select arm.
1360 KnownBits CondRes(Known.getBitWidth());
1361 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1362 // If we don't get any information from the condition, no reason to
1363 // proceed.
1364 if (CondRes.isUnknown())
1365 return;
1366
1367 // We can have conflict if the condition is dead. I.e if we have
1368 // (x | 64) < 32 ? (x | 64) : y
1369 // we will have conflict at bit 6 from the condition/the `or`.
1370 // In that case just return. Its not particularly important
1371 // what we do, as this select is going to be simplified soon.
1372 CondRes = CondRes.unionWith(Known);
1373 if (CondRes.hasConflict())
1374 return;
1375
1376 // Finally make sure the information we found is valid. This is relatively
1377 // expensive so it's left for the very end.
1378 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1379 return;
1380
1381 // Finally, we know we get information from the condition and its valid,
1382 // so return it.
1383 Known = std::move(CondRes);
1384}
1385
1386// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1387// Returns the input and lower/upper bounds.
1388static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1389 const APInt *&CLow, const APInt *&CHigh) {
1391 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1392 "Input should be a Select!");
1393
1394 const Value *LHS = nullptr, *RHS = nullptr;
1396 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1397 return false;
1398
1399 if (!match(RHS, m_APInt(CLow)))
1400 return false;
1401
1402 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1404 if (getInverseMinMaxFlavor(SPF) != SPF2)
1405 return false;
1406
1407 if (!match(RHS2, m_APInt(CHigh)))
1408 return false;
1409
1410 if (SPF == SPF_SMIN)
1411 std::swap(CLow, CHigh);
1412
1413 In = LHS2;
1414 return CLow->sle(*CHigh);
1415}
1416
1418 const APInt *&CLow,
1419 const APInt *&CHigh) {
1420 assert((II->getIntrinsicID() == Intrinsic::smin ||
1421 II->getIntrinsicID() == Intrinsic::smax) &&
1422 "Must be smin/smax");
1423
1424 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1425 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1426 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1427 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1428 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1429 return false;
1430
1431 if (II->getIntrinsicID() == Intrinsic::smin)
1432 std::swap(CLow, CHigh);
1433 return CLow->sle(*CHigh);
1434}
1435
1437 KnownBits &Known) {
1438 const APInt *CLow, *CHigh;
1439 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1440 Known = Known.unionWith(
1441 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1442}
1443
1445 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1446 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1447 unsigned Depth) {
1448 // Change the context instruction to the "edge" that flows into the phi. This
1449 // is important because that is where the value is actually "evaluated" even
1450 // though it is used later somewhere else. (see also D69571).
1452 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1453
1454 RecQ.CxtI = P->getIncomingBlock(OpNum)->getTerminator();
1455 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1456
1457 RecQ.CxtI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1458 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1459}
1460
1462 const APInt &DemandedElts,
1464 const SimplifyQuery &Q,
1465 unsigned Depth) {
1466 unsigned BitWidth = Known.getBitWidth();
1467
1468 KnownBits Known2(BitWidth);
1469 switch (I->getOpcode()) {
1470 default: break;
1471 case Instruction::Load:
1472 if (MDNode *MD =
1473 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1475 break;
1476 case Instruction::And:
1477 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1478 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1479
1480 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1481 break;
1482 case Instruction::Or:
1483 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1484 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1485
1486 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1487 break;
1488 case Instruction::Xor:
1489 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1490 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1491
1492 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1493 break;
1494 case Instruction::Mul: {
1497 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1498 DemandedElts, Known, Known2, Q, Depth);
1499 break;
1500 }
1501 case Instruction::UDiv: {
1502 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1503 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1504 Known =
1506 break;
1507 }
1508 case Instruction::SDiv: {
1509 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1510 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1511 Known =
1513 break;
1514 }
1515 case Instruction::Select: {
1516 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1517 KnownBits Res(Known.getBitWidth());
1518 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1519 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1520 return Res;
1521 };
1522 // Only known if known in both the LHS and RHS.
1523 Known =
1524 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1525 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1526 break;
1527 }
1528 case Instruction::FPToSI: {
1529 // fptosi is poison if the rounded value doesn't fit in the result type,
1530 // so we can assume the conversion is well-defined and rounds towards
1531 // zero. +-Inf can never fit in an integer type, so it is always poison,
1532 // like NaN. Negative subnormals and negative zero round to 0. That
1533 // leaves negative normals as the only class that can produce a defined
1534 // negative result.
1535 KnownFPClass SrcFPClass = computeKnownFPClass(
1536 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1537 if (SrcFPClass.isKnownNever(fcNegNormal))
1538 Known.makeNonNegative();
1539 break;
1540 }
1541 case Instruction::FPTrunc:
1542 case Instruction::FPExt:
1543 case Instruction::FPToUI:
1544 case Instruction::SIToFP:
1545 case Instruction::UIToFP:
1546 break; // Can't work with floating point.
1547 case Instruction::PtrToInt:
1548 case Instruction::PtrToAddr:
1549 case Instruction::IntToPtr:
1550 // Fall through and handle them the same as zext/trunc.
1551 [[fallthrough]];
1552 case Instruction::ZExt:
1553 case Instruction::Trunc: {
1554 Type *SrcTy = I->getOperand(0)->getType();
1555
1556 unsigned SrcBitWidth;
1557 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1558 // which fall through here.
1559 Type *ScalarTy = SrcTy->getScalarType();
1560 SrcBitWidth = ScalarTy->isPointerTy() ?
1561 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1562 Q.DL.getTypeSizeInBits(ScalarTy);
1563
1564 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1565 Known = Known.anyextOrTrunc(SrcBitWidth);
1566 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1567 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1568 Inst && Inst->hasNonNeg() && !Known.isNegative())
1569 Known.makeNonNegative();
1570 Known = Known.zextOrTrunc(BitWidth);
1571 break;
1572 }
1573 case Instruction::BitCast: {
1574 Type *SrcTy = I->getOperand(0)->getType();
1575 if (SrcTy->isIntOrPtrTy() &&
1576 // TODO: For now, not handling conversions like:
1577 // (bitcast i64 %x to <2 x i32>)
1578 !I->getType()->isVectorTy()) {
1579 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1580 break;
1581 }
1582
1583 const Value *V;
1584 // Handle bitcast from floating point to integer.
1585 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1586 V->getType()->isFPOrFPVectorTy()) {
1587 Type *FPType = V->getType()->getScalarType();
1588 KnownFPClass Result =
1589 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1590
1591 Known = Result.toKnownBits(FPType->getFltSemantics());
1592
1593 break;
1594 }
1595
1596 // Handle cast from vector integer type to scalar or vector integer.
1597 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1598 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1599 !I->getType()->isIntOrIntVectorTy() ||
1600 isa<ScalableVectorType>(I->getType()))
1601 break;
1602
1603 unsigned NumElts = DemandedElts.getBitWidth();
1604 bool IsLE = Q.DL.isLittleEndian();
1605 // Look through a cast from narrow vector elements to wider type.
1606 // Examples: v4i32 -> v2i64, v3i8 -> v24
1607 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1608 if (BitWidth % SubBitWidth == 0) {
1609 // Known bits are automatically intersected across demanded elements of a
1610 // vector. So for example, if a bit is computed as known zero, it must be
1611 // zero across all demanded elements of the vector.
1612 //
1613 // For this bitcast, each demanded element of the output is sub-divided
1614 // across a set of smaller vector elements in the source vector. To get
1615 // the known bits for an entire element of the output, compute the known
1616 // bits for each sub-element sequentially. This is done by shifting the
1617 // one-set-bit demanded elements parameter across the sub-elements for
1618 // consecutive calls to computeKnownBits. We are using the demanded
1619 // elements parameter as a mask operator.
1620 //
1621 // The known bits of each sub-element are then inserted into place
1622 // (dependent on endian) to form the full result of known bits.
1623 unsigned SubScale = BitWidth / SubBitWidth;
1624 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1625 for (unsigned i = 0; i != NumElts; ++i) {
1626 if (DemandedElts[i])
1627 SubDemandedElts.setBit(i * SubScale);
1628 }
1629
1630 KnownBits KnownSrc(SubBitWidth);
1631 for (unsigned i = 0; i != SubScale; ++i) {
1632 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1633 Depth + 1);
1634 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1635 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1636 }
1637 }
1638 // Look through a cast from wider vector elements to narrow type.
1639 // Examples: v2i64 -> v4i32
1640 if (SubBitWidth % BitWidth == 0) {
1641 unsigned SubScale = SubBitWidth / BitWidth;
1642 KnownBits KnownSrc(SubBitWidth);
1643 APInt SubDemandedElts =
1644 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1645 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1646 Depth + 1);
1647
1648 Known.setAllConflict();
1649 for (unsigned i = 0; i != NumElts; ++i) {
1650 if (DemandedElts[i]) {
1651 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1652 unsigned Offset = (Shifts % SubScale) * BitWidth;
1653 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1654 if (Known.isUnknown())
1655 break;
1656 }
1657 }
1658 }
1659 break;
1660 }
1661 case Instruction::SExt: {
1662 // Compute the bits in the result that are not present in the input.
1663 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1664
1665 Known = Known.trunc(SrcBitWidth);
1666 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1667 // If the sign bit of the input is known set or clear, then we know the
1668 // top bits of the result.
1669 Known = Known.sext(BitWidth);
1670 break;
1671 }
1672 case Instruction::Shl: {
1675 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1676 bool ShAmtNonZero) {
1677 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1678 };
1679 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1680 KF);
1681 // Trailing zeros of a right-shifted constant never decrease.
1682 const APInt *C;
1683 if (match(I->getOperand(0), m_APInt(C)))
1684 Known.Zero.setLowBits(C->countr_zero());
1685
1686 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1687 // lands at bit Y, when BitWidth is a power of 2.
1688 const APInt *YC;
1689 Value *X = I->getOperand(0);
1690 if (isPowerOf2_32(BitWidth) &&
1691 match(I->getOperand(1),
1693 m_SpecificInt(BitWidth - 1)))) &&
1694 YC->ult(BitWidth - 1)) {
1695 unsigned Y = YC->getZExtValue();
1696 Known.One.setBit(Y);
1697 Known.Zero.setBitsFrom(Y + 1);
1698 }
1699 break;
1700 }
1701 case Instruction::LShr: {
1702 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1703 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1704 bool ShAmtNonZero) {
1705 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1706 };
1707 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1708 KF);
1709 // Leading zeros of a left-shifted constant never decrease.
1710 const APInt *C;
1711 if (match(I->getOperand(0), m_APInt(C)))
1712 Known.Zero.setHighBits(C->countl_zero());
1713 break;
1714 }
1715 case Instruction::AShr: {
1716 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1717 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1718 bool ShAmtNonZero) {
1719 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1720 };
1721 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1722 KF);
1723 break;
1724 }
1725 case Instruction::Sub: {
1728 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1729 DemandedElts, Known, Known2, Q, Depth);
1730 break;
1731 }
1732 case Instruction::Add: {
1735 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1736 DemandedElts, Known, Known2, Q, Depth);
1737 break;
1738 }
1739 case Instruction::SRem:
1740 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1741 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1742 Known = KnownBits::srem(Known, Known2);
1743 break;
1744
1745 case Instruction::URem:
1746 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1747 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1748 Known = KnownBits::urem(Known, Known2);
1749 break;
1750 case Instruction::Alloca:
1751 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1752 break;
1753 case Instruction::GetElementPtr: {
1754 // Analyze all of the subscripts of this getelementptr instruction
1755 // to determine if we can prove known low zero bits.
1756 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1757 // Accumulate the constant indices in a separate variable
1758 // to minimize the number of calls to computeForAddSub.
1759 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1760 APInt AccConstIndices(IndexWidth, 0);
1761
1762 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1763 if (IndexWidth == BitWidth) {
1764 // Note that inbounds does *not* guarantee nsw for the addition, as only
1765 // the offset is signed, while the base address is unsigned.
1766 Known = KnownBits::add(Known, IndexBits);
1767 } else {
1768 // If the index width is smaller than the pointer width, only add the
1769 // value to the low bits.
1770 assert(IndexWidth < BitWidth &&
1771 "Index width can't be larger than pointer width");
1772 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1773 }
1774 };
1775
1777 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1778 // TrailZ can only become smaller, short-circuit if we hit zero.
1779 if (Known.isUnknown())
1780 break;
1781
1782 Value *Index = I->getOperand(i);
1783
1784 // Handle case when index is zero.
1785 Constant *CIndex = dyn_cast<Constant>(Index);
1786 if (CIndex && CIndex->isNullValue())
1787 continue;
1788
1789 if (StructType *STy = GTI.getStructTypeOrNull()) {
1790 // Handle struct member offset arithmetic.
1791
1792 assert(CIndex &&
1793 "Access to structure field must be known at compile time");
1794
1795 if (CIndex->getType()->isVectorTy())
1796 Index = CIndex->getSplatValue();
1797
1798 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1799 const StructLayout *SL = Q.DL.getStructLayout(STy);
1800 uint64_t Offset = SL->getElementOffset(Idx);
1801 AccConstIndices += Offset;
1802 continue;
1803 }
1804
1805 // Handle array index arithmetic.
1806 Type *IndexedTy = GTI.getIndexedType();
1807 if (!IndexedTy->isSized()) {
1808 Known.resetAll();
1809 break;
1810 }
1811
1812 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1813 uint64_t StrideInBytes = Stride.getKnownMinValue();
1814 if (!Stride.isScalable()) {
1815 // Fast path for constant offset.
1816 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1817 AccConstIndices +=
1818 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1819 continue;
1820 }
1821 }
1822
1823 KnownBits IndexBits =
1824 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1825 KnownBits ScalingFactor(IndexWidth);
1826 // Multiply by current sizeof type.
1827 // &A[i] == A + i * sizeof(*A[i]).
1828 if (Stride.isScalable()) {
1829 // For scalable types the only thing we know about sizeof is
1830 // that this is a multiple of the minimum size.
1831 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1832 } else {
1833 ScalingFactor =
1834 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1835 }
1836 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1837 }
1838 if (!Known.isUnknown() && !AccConstIndices.isZero())
1839 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1840 break;
1841 }
1842 case Instruction::PHI: {
1843 const PHINode *P = cast<PHINode>(I);
1844 BinaryOperator *BO = nullptr;
1845 Value *Start = nullptr, *Step = nullptr;
1846 KnownBits &KnownStart = Known2;
1847 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1848 // Handle the case of a simple two-predecessor recurrence PHI.
1849 // There's a lot more that could theoretically be done here, but
1850 // this is sufficient to catch some interesting cases.
1851 unsigned Opcode = BO->getOpcode();
1852
1853 switch (Opcode) {
1854 // If this is a shift recurrence, we know the bits being shifted in. We
1855 // can combine that with information about the start value of the
1856 // recurrence to conclude facts about the result. If this is a udiv
1857 // recurrence, we know that the result can never exceed either the
1858 // numerator or the start value, whichever is greater.
1859 case Instruction::LShr:
1860 case Instruction::AShr:
1861 case Instruction::Shl:
1862 case Instruction::UDiv:
1863 if (BO->getOperand(0) != I)
1864 break;
1865 [[fallthrough]];
1866
1867 // For a urem recurrence, the result can never exceed the start value. The
1868 // phi could either be the numerator or the denominator.
1869 case Instruction::URem: {
1870 // We have matched a recurrence of the form:
1871 // %iv = [R, %entry], [%iv.next, %backedge]
1872 // %iv.next = shift_op %iv, L
1873
1874 // Recurse with the phi context to avoid concern about whether facts
1875 // inferred hold at original context instruction. TODO: It may be
1876 // correct to use the original context. IF warranted, explore and
1877 // add sufficient tests to cover.
1879 RecQ.CxtI = P;
1880 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1881 switch (Opcode) {
1882 case Instruction::Shl:
1883 // A shl recurrence will only increase the tailing zeros
1884 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1885 break;
1886 case Instruction::LShr:
1887 case Instruction::UDiv:
1888 case Instruction::URem:
1889 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1890 // the start value.
1891 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1892 break;
1893 case Instruction::AShr:
1894 // An ashr recurrence will extend the initial sign bit
1895 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1896 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1897 break;
1898 }
1899 break;
1900 }
1901
1902 // Check for operations that have the property that if
1903 // both their operands have low zero bits, the result
1904 // will have low zero bits.
1905 case Instruction::Add:
1906 case Instruction::Sub:
1907 case Instruction::And:
1908 case Instruction::Or:
1909 case Instruction::Mul: {
1910 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1911 // zero bits.
1912 KnownBits KnownStep(BitWidth);
1913 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1914 KnownStart, KnownStep, Q, Depth);
1915
1916 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1917 KnownStep.countMinTrailingZeros()));
1918
1919 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1920 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1921 break;
1922
1923 switch (Opcode) {
1924 // If initial value of recurrence is nonnegative, and we are adding
1925 // a nonnegative number with nsw, the result can only be nonnegative
1926 // or poison value regardless of the number of times we execute the
1927 // add in phi recurrence. If initial value is negative and we are
1928 // adding a negative number with nsw, the result can only be
1929 // negative or poison value. Similar arguments apply to sub and mul.
1930 //
1931 // (add non-negative, non-negative) --> non-negative
1932 // (add negative, negative) --> negative
1933 case Instruction::Add: {
1934 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1935 Known.makeNonNegative();
1936 else if (KnownStart.isNegative() && KnownStep.isNegative())
1937 Known.makeNegative();
1938 break;
1939 }
1940
1941 // (sub nsw non-negative, negative) --> non-negative
1942 // (sub nsw negative, non-negative) --> negative
1943 case Instruction::Sub: {
1944 if (BO->getOperand(0) != I)
1945 break;
1946 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1947 Known.makeNonNegative();
1948 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1949 Known.makeNegative();
1950 break;
1951 }
1952
1953 // (mul nsw non-negative, non-negative) --> non-negative
1954 case Instruction::Mul:
1955 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1956 Known.makeNonNegative();
1957 break;
1958
1959 default:
1960 break;
1961 }
1962 break;
1963 }
1964
1965 default:
1966 break;
1967 }
1968 } else {
1969 IntrinsicInst *II = nullptr;
1970 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
1971 // %iv = [<Start>, %entry], [%iv.next, %backedge]
1972 //
1973 // %iv.next = <II>(%iv, <Step>)
1974 // or
1975 // %iv.next = <II>(<Step>, %iv)
1976 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
1977 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
1978 KnownBits KnownStep(BitWidth);
1980 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
1981
1982 if (IntrinsicID == Intrinsic::umin) {
1983 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1984 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
1985 KnownStep.countMinLeadingOnes()));
1986 } else {
1987 // umax
1988 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
1989 KnownStep.countMinLeadingZeros()));
1990 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1991 }
1992 }
1993 }
1994 }
1995
1996 // Unreachable blocks may have zero-operand PHI nodes.
1997 if (P->getNumIncomingValues() == 0)
1998 break;
1999
2000 // Otherwise take the unions of the known bit sets of the operands,
2001 // taking conservative care to avoid excessive recursion.
2002 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2003 // Skip if every incoming value references to ourself.
2004 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2005 break;
2006
2007 Known.setAllConflict();
2008 for (const Use &U : P->operands()) {
2009 Value *IncValue;
2010 const PHINode *CxtPhi;
2011 Instruction *CxtI;
2012 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
2013 // Skip direct self references.
2014 if (IncValue == P)
2015 continue;
2016
2017 // Change the context instruction to the "edge" that flows into the
2018 // phi. This is important because that is where the value is actually
2019 // "evaluated" even though it is used later somewhere else. (see also
2020 // D69571).
2022
2023 Known2 = KnownBits(BitWidth);
2024
2025 // Recurse, but cap the recursion to one level, because we don't
2026 // want to waste time spinning around in loops.
2027 // TODO: See if we can base recursion limiter on number of incoming phi
2028 // edges so we don't overly clamp analysis.
2029 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2031
2032 // See if we can further use a conditional branch into the phi
2033 // to help us determine the range of the value.
2034 if (!Known2.isConstant()) {
2035 CmpPredicate Pred;
2036 const APInt *RHSC;
2037 BasicBlock *TrueSucc, *FalseSucc;
2038 // TODO: Use RHS Value and compute range from its known bits.
2039 if (match(RecQ.CxtI,
2040 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2041 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2042 // Check for cases of duplicate successors.
2043 if ((TrueSucc == CxtPhi->getParent()) !=
2044 (FalseSucc == CxtPhi->getParent())) {
2045 // If we're using the false successor, invert the predicate.
2046 if (FalseSucc == CxtPhi->getParent())
2047 Pred = CmpInst::getInversePredicate(Pred);
2048 // Get the knownbits implied by the incoming phi condition.
2049 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2050 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2051 // We can have conflicts here if we are analyzing deadcode (its
2052 // impossible for us reach this BB based the icmp).
2053 if (KnownUnion.hasConflict()) {
2054 // No reason to continue analyzing in a known dead region, so
2055 // just resetAll and break. This will cause us to also exit the
2056 // outer loop.
2057 Known.resetAll();
2058 break;
2059 }
2060 Known2 = KnownUnion;
2061 }
2062 }
2063 }
2064
2065 Known = Known.intersectWith(Known2);
2066 // If all bits have been ruled out, there's no need to check
2067 // more operands.
2068 if (Known.isUnknown())
2069 break;
2070 }
2071 }
2072 break;
2073 }
2074 case Instruction::Call:
2075 case Instruction::Invoke: {
2076 // If range metadata is attached to this call, set known bits from that,
2077 // and then intersect with known bits based on other properties of the
2078 // function.
2079 if (MDNode *MD =
2080 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2082
2083 const auto *CB = cast<CallBase>(I);
2084
2085 if (std::optional<ConstantRange> Range = CB->getRange())
2086 Known = Known.unionWith(Range->toKnownBits());
2087
2088 if (const Value *RV = CB->getReturnedArgOperand()) {
2089 if (RV->getType() == I->getType()) {
2090 computeKnownBits(RV, Known2, Q, Depth + 1);
2091 Known = Known.unionWith(Known2);
2092 // If the function doesn't return properly for all input values
2093 // (e.g. unreachable exits) then there might be conflicts between the
2094 // argument value and the range metadata. Simply discard the known bits
2095 // in case of conflicts.
2096 if (Known.hasConflict())
2097 Known.resetAll();
2098 }
2099 }
2100 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2101 switch (II->getIntrinsicID()) {
2102 default:
2103 break;
2104 case Intrinsic::abs: {
2105 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2106 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2107 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2108 break;
2109 }
2110 case Intrinsic::bitreverse:
2111 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2112 Known = Known.unionWith(Known2.reverseBits());
2113 break;
2114 case Intrinsic::bswap:
2115 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2116 Known = Known.unionWith(Known2.byteSwap());
2117 break;
2118 case Intrinsic::ctlz: {
2119 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2120 // If we have a known 1, its position is our upper bound.
2121 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2122 // If this call is poison for 0 input, the result will be less than 2^n.
2123 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2124 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2125 unsigned LowBits = llvm::bit_width(PossibleLZ);
2126 Known.Zero.setBitsFrom(LowBits);
2127 break;
2128 }
2129 case Intrinsic::cttz: {
2130 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2131 // If we have a known 1, its position is our upper bound.
2132 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2133 // If this call is poison for 0 input, the result will be less than 2^n.
2134 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2135 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2136 unsigned LowBits = llvm::bit_width(PossibleTZ);
2137 Known.Zero.setBitsFrom(LowBits);
2138 break;
2139 }
2140 case Intrinsic::ctpop: {
2141 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2142 // We can bound the space the count needs. Also, bits known to be zero
2143 // can't contribute to the population.
2144 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2145 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2146 Known.Zero.setBitsFrom(LowBits);
2147 // TODO: we could bound KnownOne using the lower bound on the number
2148 // of bits which might be set provided by popcnt KnownOne2.
2149 break;
2150 }
2151 case Intrinsic::fshr:
2152 case Intrinsic::fshl: {
2153 const APInt *SA;
2154 if (!match(I->getOperand(2), m_APInt(SA)))
2155 break;
2156
2157 KnownBits Known3(BitWidth);
2158 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2159 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2160 Known = II->getIntrinsicID() == Intrinsic::fshl
2161 ? KnownBits::fshl(Known2, Known3, *SA)
2162 : KnownBits::fshr(Known2, Known3, *SA);
2163 break;
2164 }
2165 case Intrinsic::clmul:
2166 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2167 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2168 Known = KnownBits::clmul(Known, Known2);
2169 break;
2170 case Intrinsic::pext:
2171 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2172 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2173 Known = KnownBits::pext(Known, Known2);
2174 break;
2175 case Intrinsic::pdep:
2176 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2177 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2178 Known = KnownBits::pdep(Known, Known2);
2179 break;
2180 case Intrinsic::smulh:
2181 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2182 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2183 Known = KnownBits::mulhs(Known, Known2);
2184 break;
2185 case Intrinsic::umulh:
2186 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2187 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2188 Known = KnownBits::mulhu(Known, Known2);
2189 break;
2190 case Intrinsic::uadd_sat:
2191 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2192 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2193 Known = KnownBits::uadd_sat(Known, Known2);
2194 break;
2195 case Intrinsic::usub_sat:
2196 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2197 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2198 Known = KnownBits::usub_sat(Known, Known2);
2199 break;
2200 case Intrinsic::sadd_sat:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::sadd_sat(Known, Known2);
2204 break;
2205 case Intrinsic::ssub_sat:
2206 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2207 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2208 Known = KnownBits::ssub_sat(Known, Known2);
2209 break;
2210 // Vec reverse preserves bits from input vec.
2211 case Intrinsic::vector_reverse:
2212 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2213 Depth + 1);
2214 break;
2215 // for min/max/and/or reduce, any bit common to each element in the
2216 // input vec is set in the output.
2217 case Intrinsic::vector_reduce_and:
2218 case Intrinsic::vector_reduce_or:
2219 case Intrinsic::vector_reduce_umax:
2220 case Intrinsic::vector_reduce_umin:
2221 case Intrinsic::vector_reduce_smax:
2222 case Intrinsic::vector_reduce_smin:
2223 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2224 break;
2225 case Intrinsic::vector_reduce_xor: {
2226 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2227 // The zeros common to all vecs are zero in the output.
2228 // If the number of elements is odd, then the common ones remain. If the
2229 // number of elements is even, then the common ones becomes zeros.
2230 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2231 // Even, so the ones become zeros.
2232 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2233 if (EvenCnt)
2234 Known.Zero |= Known.One;
2235 // Maybe even element count so need to clear ones.
2236 if (VecTy->isScalableTy() || EvenCnt)
2237 Known.One.clearAllBits();
2238 break;
2239 }
2240 case Intrinsic::vector_reduce_add: {
2241 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2242 if (!VecTy)
2243 break;
2244 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2245 Known = Known.reduceAdd(VecTy->getNumElements());
2246 break;
2247 }
2248 case Intrinsic::umin:
2249 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2250 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2251 Known = KnownBits::umin(Known, Known2);
2252 break;
2253 case Intrinsic::umax:
2254 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2255 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2256 Known = KnownBits::umax(Known, Known2);
2257 break;
2258 case Intrinsic::smin:
2259 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2260 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2261 Known = KnownBits::smin(Known, Known2);
2263 break;
2264 case Intrinsic::smax:
2265 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2266 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2267 Known = KnownBits::smax(Known, Known2);
2269 break;
2270 case Intrinsic::ptrmask: {
2271 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2272
2273 const Value *Mask = I->getOperand(1);
2274 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2275 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2276 // TODO: 1-extend would be more precise.
2277 Known &= Known2.anyextOrTrunc(BitWidth);
2278 break;
2279 }
2280 case Intrinsic::x86_sse2_pmulh_w:
2281 case Intrinsic::x86_avx2_pmulh_w:
2282 case Intrinsic::x86_avx512_pmulh_w_512:
2283 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2284 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2285 Known = KnownBits::mulhs(Known, Known2);
2286 break;
2287 case Intrinsic::x86_sse2_pmulhu_w:
2288 case Intrinsic::x86_avx2_pmulhu_w:
2289 case Intrinsic::x86_avx512_pmulhu_w_512:
2290 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2291 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2292 Known = KnownBits::mulhu(Known, Known2);
2293 break;
2294 case Intrinsic::x86_sse42_crc32_64_64:
2295 Known.Zero.setBitsFrom(32);
2296 break;
2297 case Intrinsic::x86_ssse3_phadd_d_128:
2298 case Intrinsic::x86_ssse3_phadd_w_128:
2299 case Intrinsic::x86_avx2_phadd_d:
2300 case Intrinsic::x86_avx2_phadd_w: {
2302 I, DemandedElts, Q, Depth,
2303 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2304 return KnownBits::add(KnownLHS, KnownRHS);
2305 });
2306 break;
2307 }
2308 case Intrinsic::x86_ssse3_phadd_sw_128:
2309 case Intrinsic::x86_avx2_phadd_sw: {
2311 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2312 break;
2313 }
2314 case Intrinsic::x86_ssse3_phsub_d_128:
2315 case Intrinsic::x86_ssse3_phsub_w_128:
2316 case Intrinsic::x86_avx2_phsub_d:
2317 case Intrinsic::x86_avx2_phsub_w: {
2319 I, DemandedElts, Q, Depth,
2320 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2321 return KnownBits::sub(KnownLHS, KnownRHS);
2322 });
2323 break;
2324 }
2325 case Intrinsic::x86_ssse3_phsub_sw_128:
2326 case Intrinsic::x86_avx2_phsub_sw: {
2328 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2329 break;
2330 }
2331 case Intrinsic::riscv_vsetvli:
2332 case Intrinsic::riscv_vsetvlimax: {
2333 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2334 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2336 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2337 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2338 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2339 uint64_t MaxVLEN =
2340 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2341 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2342
2343 // Result of vsetvli must be not larger than AVL.
2344 if (HasAVL)
2345 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2346 MaxVL = std::min(MaxVL, CI->getZExtValue());
2347
2348 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2349 if (BitWidth > KnownZeroFirstBit)
2350 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2351 break;
2352 }
2353 case Intrinsic::amdgcn_mbcnt_hi:
2354 case Intrinsic::amdgcn_mbcnt_lo: {
2355 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2356 // most 31 + src1.
2357 Known.Zero.setBitsFrom(
2358 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2359 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2360 Known = KnownBits::add(Known, Known2);
2361 break;
2362 }
2363 case Intrinsic::vscale: {
2364 if (!II->getParent() || !II->getFunction())
2365 break;
2366
2367 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2368 break;
2369 }
2370 case Intrinsic::stepvector: {
2371 auto *VecTy = cast<VectorType>(II->getType());
2372 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2373 if (!isUIntN(BitWidth, MinNumElts))
2374 break;
2375
2376 bool Overflow = false;
2377 APInt MaxNumElts(BitWidth, MinNumElts);
2378 if (VecTy->isScalableTy()) {
2379 if (!II->getParent() || !II->getFunction())
2380 break;
2381 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2383 .umul_ov(MaxNumElts, Overflow);
2384 }
2385
2386 // Give up if the lane count could wrap. Stepvector truncates lane
2387 // indices that do not fit in the element type.
2388 if (Overflow)
2389 break;
2390
2391 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2392 break;
2393 }
2394 }
2395 }
2396 break;
2397 }
2398 case Instruction::ShuffleVector: {
2399 if (auto *Splat = getSplatValue(I)) {
2401 break;
2402 }
2403
2404 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2405 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2406 if (!Shuf) {
2407 Known.resetAll();
2408 return;
2409 }
2410 // For undef elements, we don't know anything about the common state of
2411 // the shuffle result.
2412 APInt DemandedLHS, DemandedRHS;
2413 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2414 Known.resetAll();
2415 return;
2416 }
2417 Known.setAllConflict();
2418 if (!!DemandedLHS) {
2419 const Value *LHS = Shuf->getOperand(0);
2420 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2421 // If we don't know any bits, early out.
2422 if (Known.isUnknown())
2423 break;
2424 }
2425 if (!!DemandedRHS) {
2426 const Value *RHS = Shuf->getOperand(1);
2427 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2428 Known = Known.intersectWith(Known2);
2429 }
2430 break;
2431 }
2432 case Instruction::InsertElement: {
2433 if (isa<ScalableVectorType>(I->getType())) {
2434 Known.resetAll();
2435 return;
2436 }
2437 const Value *Vec = I->getOperand(0);
2438 const Value *Elt = I->getOperand(1);
2439 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2440 unsigned NumElts = DemandedElts.getBitWidth();
2441 APInt DemandedVecElts = DemandedElts;
2442 bool NeedsElt = true;
2443 // If we know the index we are inserting too, clear it from Vec check.
2444 if (CIdx && CIdx->getValue().ult(NumElts)) {
2445 DemandedVecElts.clearBit(CIdx->getZExtValue());
2446 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2447 }
2448
2449 Known.setAllConflict();
2450 if (NeedsElt) {
2451 computeKnownBits(Elt, Known, Q, Depth + 1);
2452 // If we don't know any bits, early out.
2453 if (Known.isUnknown())
2454 break;
2455 }
2456
2457 if (!DemandedVecElts.isZero()) {
2458 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2459 Known = Known.intersectWith(Known2);
2460 }
2461 break;
2462 }
2463 case Instruction::ExtractElement: {
2464 // Look through extract element. If the index is non-constant or
2465 // out-of-range demand all elements, otherwise just the extracted element.
2466 const Value *Vec = I->getOperand(0);
2467 const Value *Idx = I->getOperand(1);
2468 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2469 if (isa<ScalableVectorType>(Vec->getType())) {
2470 // FIXME: there's probably *something* we can do with scalable vectors
2471 Known.resetAll();
2472 break;
2473 }
2474 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2475 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2476 if (CIdx && CIdx->getValue().ult(NumElts))
2477 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2478 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2479 break;
2480 }
2481 case Instruction::ExtractValue:
2482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2484 if (EVI->getNumIndices() != 1) break;
2485 if (EVI->getIndices()[0] == 0) {
2486 switch (II->getIntrinsicID()) {
2487 default: break;
2488 case Intrinsic::uadd_with_overflow:
2489 case Intrinsic::sadd_with_overflow:
2491 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2492 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2493 break;
2494 case Intrinsic::usub_with_overflow:
2495 case Intrinsic::ssub_with_overflow:
2497 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2498 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2499 break;
2500 case Intrinsic::umul_with_overflow:
2501 case Intrinsic::smul_with_overflow:
2502 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2503 false, DemandedElts, Known, Known2, Q, Depth);
2504 break;
2505 }
2506 }
2507 }
2508 break;
2509 case Instruction::Freeze:
2510 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2511 Depth + 1))
2512 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2513 break;
2514 }
2515}
2516
2517/// Determine which bits of V are known to be either zero or one and return
2518/// them.
2519KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2520 const SimplifyQuery &Q, unsigned Depth) {
2521 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2522 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2523 return Known;
2524}
2525
2526/// Determine which bits of V are known to be either zero or one and return
2527/// them.
2529 unsigned Depth) {
2530 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2532 return Known;
2533}
2534
2535/// Determine which bits of V are known to be either zero or one and return
2536/// them in the Known bit set.
2537///
2538/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2539/// we cannot optimize based on the assumption that it is zero without changing
2540/// it to be an explicit zero. If we don't change it to zero, other code could
2541/// optimized based on the contradictory assumption that it is non-zero.
2542/// Because instcombine aggressively folds operations with undef args anyway,
2543/// this won't lose us code quality.
2544///
2545/// This function is defined on values with integer type, values with pointer
2546/// type, and vectors of integers. In the case
2547/// where V is a vector, known zero, and known one values are the
2548/// same width as the vector element, and the bit is set only if it is true
2549/// for all of the demanded elements in the vector specified by DemandedElts.
2550void computeKnownBits(const Value *V, const APInt &DemandedElts,
2551 KnownBits &Known, const SimplifyQuery &Q,
2552 unsigned Depth) {
2553 if (!DemandedElts) {
2554 // No demanded elts, better to assume we don't know anything.
2555 Known.resetAll();
2556 return;
2557 }
2558
2559 assert(V && "No Value?");
2560 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2561
2562#ifndef NDEBUG
2563 Type *Ty = V->getType();
2564 unsigned BitWidth = Known.getBitWidth();
2565
2566 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2567 "Not integer or pointer type!");
2568
2569 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2570 assert(
2571 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2572 "DemandedElt width should equal the fixed vector number of elements");
2573 } else {
2574 assert(DemandedElts == APInt(1, 1) &&
2575 "DemandedElt width should be 1 for scalars or scalable vectors");
2576 }
2577
2578 Type *ScalarTy = Ty->getScalarType();
2579 if (ScalarTy->isPointerTy()) {
2580 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2581 "V and Known should have same BitWidth");
2582 } else {
2583 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2584 "V and Known should have same BitWidth");
2585 }
2586#endif
2587
2588 const APInt *C;
2589 if (match(V, m_APInt(C))) {
2590 // We know all of the bits for a scalar constant or a splat vector constant!
2592 return;
2593 }
2594 // Null and aggregate-zero are all-zeros.
2596 Known.setAllZero();
2597 return;
2598 }
2599 // Handle a constant vector by taking the intersection of the known bits of
2600 // each element.
2602 assert(!isa<ScalableVectorType>(V->getType()));
2603 // We know that CDV must be a vector of integers. Take the intersection of
2604 // each element.
2605 Known.setAllConflict();
2606 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2607 if (!DemandedElts[i])
2608 continue;
2609 APInt Elt = CDV->getElementAsAPInt(i);
2610 Known.Zero &= ~Elt;
2611 Known.One &= Elt;
2612 }
2613 if (Known.hasConflict())
2614 Known.resetAll();
2615 return;
2616 }
2617
2618 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2619 assert(!isa<ScalableVectorType>(V->getType()));
2620 // We know that CV must be a vector of integers. Take the intersection of
2621 // each element.
2622 Known.setAllConflict();
2623 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2624 if (!DemandedElts[i])
2625 continue;
2626 Constant *Element = CV->getAggregateElement(i);
2627 if (isa<PoisonValue>(Element))
2628 continue;
2629 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2630 if (!ElementCI) {
2631 Known.resetAll();
2632 return;
2633 }
2634 const APInt &Elt = ElementCI->getValue();
2635 Known.Zero &= ~Elt;
2636 Known.One &= Elt;
2637 }
2638 if (Known.hasConflict())
2639 Known.resetAll();
2640 return;
2641 }
2642
2643 // Start out not knowing anything.
2644 Known.resetAll();
2645
2646 // We can't imply anything about undefs.
2647 if (isa<UndefValue>(V))
2648 return;
2649
2650 // There's no point in looking through other users of ConstantData for
2651 // assumptions. Confirm that we've handled them all.
2652 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2653
2654 if (const auto *A = dyn_cast<Argument>(V))
2655 if (std::optional<ConstantRange> Range = A->getRange())
2656 Known = Range->toKnownBits();
2657
2658 // All recursive calls that increase depth must come after this.
2660 return;
2661
2662 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2663 // the bits of its aliasee.
2664 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2665 if (!GA->isInterposable())
2666 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2667 return;
2668 }
2669
2670 if (const Operator *I = dyn_cast<Operator>(V))
2671 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2672 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2673 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2674 Known = CR->toKnownBits();
2675 }
2676
2677 // Aligned pointers have trailing zeros - refine Known.Zero set
2678 if (isa<PointerType>(V->getType())) {
2679 Align Alignment = V->getPointerAlignment(Q.DL);
2680 Known.Zero.setLowBits(Log2(Alignment));
2681 }
2682
2683 // computeKnownBitsFromContext strictly refines Known.
2684 // Therefore, we run them after computeKnownBitsFromOperator.
2685
2686 // Check whether we can determine known bits from context such as assumes.
2688}
2689
2690/// Try to detect a recurrence that the value of the induction variable is
2691/// always a power of two (or zero).
2692static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2693 SimplifyQuery &Q, unsigned Depth) {
2694 BinaryOperator *BO = nullptr;
2695 Value *Start = nullptr, *Step = nullptr;
2696 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2697 return false;
2698
2699 // Initial value must be a power of two.
2700 for (const Use &U : PN->operands()) {
2701 if (U.get() == Start) {
2702 // Initial value comes from a different BB, need to adjust context
2703 // instruction for analysis.
2704 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2705 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2706 return false;
2707 }
2708 }
2709
2710 // Except for Mul, the induction variable must be on the left side of the
2711 // increment expression, otherwise its value can be arbitrary.
2712 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2713 return false;
2714
2715 Q.CxtI = BO->getParent()->getTerminator();
2716 switch (BO->getOpcode()) {
2717 case Instruction::Mul:
2718 // Power of two is closed under multiplication.
2719 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2720 Q.IIQ.hasNoSignedWrap(BO)) &&
2721 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2722 case Instruction::SDiv:
2723 // Start value must not be signmask for signed division, so simply being a
2724 // power of two is not sufficient, and it has to be a constant.
2725 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2726 return false;
2727 [[fallthrough]];
2728 case Instruction::UDiv:
2729 // Divisor must be a power of two.
2730 // If OrZero is false, cannot guarantee induction variable is non-zero after
2731 // division, same for Shr, unless it is exact division.
2732 return (OrZero || Q.IIQ.isExact(BO)) &&
2733 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2734 case Instruction::Shl:
2735 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2736 case Instruction::AShr:
2737 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2738 return false;
2739 [[fallthrough]];
2740 case Instruction::LShr:
2741 return OrZero || Q.IIQ.isExact(BO);
2742 default:
2743 return false;
2744 }
2745}
2746
2747/// Return true if we can infer that \p V is known to be a power of 2 from
2748/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2749static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2750 const Value *Cond,
2751 bool CondIsTrue) {
2752 CmpPredicate Pred;
2753 const APInt *RHSC;
2754 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2755 return false;
2756 if (!CondIsTrue)
2757 Pred = ICmpInst::getInversePredicate(Pred);
2758 // ctpop(V) u< 2
2759 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2760 return true;
2761 // ctpop(V) == 1
2762 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2763}
2764
2765/// Return true if the given value is known to have exactly one
2766/// bit set when defined. For vectors return true if every element is known to
2767/// be a power of two when defined. Supports values with integer or pointer
2768/// types and vectors of integers.
2769bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2770 const SimplifyQuery &Q, unsigned Depth) {
2771 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2772
2773 if (isa<Constant>(V))
2774 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2775
2776 // i1 is by definition a power of 2 or zero.
2777 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2778 return true;
2779
2780 // Try to infer from assumptions.
2781 if (Q.AC && Q.CxtI) {
2782 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2783 if (!AssumeVH)
2784 continue;
2785 CallInst *I = cast<CallInst>(AssumeVH);
2786 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2787 /*CondIsTrue=*/true) &&
2789 return true;
2790 }
2791 }
2792
2793 // Handle dominating conditions.
2794 if (Q.DC && Q.CxtI && Q.DT) {
2795 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2796 Value *Cond = BI->getCondition();
2797
2798 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2800 /*CondIsTrue=*/true) &&
2801 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2802 return true;
2803
2804 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2806 /*CondIsTrue=*/false) &&
2807 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2808 return true;
2809 }
2810 }
2811
2812 auto *I = dyn_cast<Instruction>(V);
2813 if (!I)
2814 return false;
2815
2816 if (Q.CxtI && match(V, m_VScale())) {
2817 const Function *F = Q.CxtI->getFunction();
2818 // The vscale_range indicates vscale is a power-of-two.
2819 return F->hasFnAttribute(Attribute::VScaleRange);
2820 }
2821
2822 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2823 // it is shifted off the end then the result is undefined.
2824 if (match(I, m_Shl(m_One(), m_Value())))
2825 return true;
2826
2827 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2828 // the bottom. If it is shifted off the bottom then the result is undefined.
2829 if (match(I, m_LShr(m_SignMask(), m_Value())))
2830 return true;
2831
2832 // The remaining tests are all recursive, so bail out if we hit the limit.
2834 return false;
2835
2836 switch (I->getOpcode()) {
2837 case Instruction::ZExt:
2838 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2839 case Instruction::Trunc:
2840 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2841 case Instruction::Shl:
2842 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2843 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2844 return false;
2845 case Instruction::LShr:
2846 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2847 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2848 return false;
2849 case Instruction::UDiv:
2851 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2852 return false;
2853 case Instruction::Mul:
2854 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2855 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2856 (OrZero || isKnownNonZero(I, Q, Depth));
2857 case Instruction::And:
2858 // A power of two and'd with anything is a power of two or zero.
2859 if (OrZero &&
2860 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2861 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2862 return true;
2863 // X & (-X) is always a power of two or zero.
2864 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2865 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2866 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2867 return false;
2868 case Instruction::Add: {
2869 // Adding a power-of-two or zero to the same power-of-two or zero yields
2870 // either the original power-of-two, a larger power-of-two or zero.
2872 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2873 Q.IIQ.hasNoSignedWrap(VOBO)) {
2874 if (match(I->getOperand(0),
2875 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2876 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2877 return true;
2878 if (match(I->getOperand(1),
2879 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2880 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2881 return true;
2882
2883 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2884 KnownBits LHSBits(BitWidth);
2885 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2886
2887 KnownBits RHSBits(BitWidth);
2888 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2889 // If i8 V is a power of two or zero:
2890 // ZeroBits: 1 1 1 0 1 1 1 1
2891 // ~ZeroBits: 0 0 0 1 0 0 0 0
2892 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2893 // If OrZero isn't set, we cannot give back a zero result.
2894 // Make sure either the LHS or RHS has a bit set.
2895 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2896 return true;
2897 }
2898
2899 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2900 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2901 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2902 return true;
2903 return false;
2904 }
2905 case Instruction::Select:
2906 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2907 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2908 case Instruction::PHI: {
2909 // A PHI node is power of two if all incoming values are power of two, or if
2910 // it is an induction variable where in each step its value is a power of
2911 // two.
2912 auto *PN = cast<PHINode>(I);
2914
2915 // Check if it is an induction variable and always power of two.
2916 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2917 return true;
2918
2919 // Recursively check all incoming values. Limit recursion to 2 levels, so
2920 // that search complexity is limited to number of operands^2.
2921 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2922 return llvm::all_of(PN->operands(), [&](const Use &U) {
2923 // Value is power of 2 if it is coming from PHI node itself by induction.
2924 if (U.get() == PN)
2925 return true;
2926
2927 // Change the context instruction to the incoming block where it is
2928 // evaluated.
2929 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2930 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2931 });
2932 }
2933 case Instruction::Invoke:
2934 case Instruction::Call: {
2935 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2936 switch (II->getIntrinsicID()) {
2937 case Intrinsic::umax:
2938 case Intrinsic::smax:
2939 case Intrinsic::umin:
2940 case Intrinsic::smin:
2941 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2942 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2943 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2944 // thus dont change pow2/non-pow2 status.
2945 case Intrinsic::bitreverse:
2946 case Intrinsic::bswap:
2947 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2948 case Intrinsic::fshr:
2949 case Intrinsic::fshl:
2950 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2951 if (II->getArgOperand(0) == II->getArgOperand(1))
2952 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2953 break;
2954 case Intrinsic::riscv_vsetvlimax:
2955 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2956 // for any valid vtype, so it is a power of two regardless of OrZero.
2957 return true;
2958 case Intrinsic::read_register:
2959 case Intrinsic::read_volatile_register: {
2960 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2961 // of two, so it is a power of two regardless of OrZero.
2962 const Module *M = II->getModule();
2963 if (!M || !M->getTargetTriple().isRISCV())
2964 break;
2965 return isReadVLENB(*II);
2966 }
2967 default:
2968 break;
2969 }
2970 }
2971 return false;
2972 }
2973 default:
2974 return false;
2975 }
2976}
2977
2978/// Test whether a GEP's result is known to be non-null.
2979///
2980/// Uses properties inherent in a GEP to try to determine whether it is known
2981/// to be non-null.
2982///
2983/// Currently this routine does not support vector GEPs.
2984static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2985 unsigned Depth) {
2986 const Function *F = nullptr;
2987 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2988 F = I->getFunction();
2989
2990 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2991 // may be null iff the base pointer is null and the offset is zero.
2992 if (!GEP->hasNoUnsignedWrap() &&
2993 !(GEP->isInBounds() &&
2994 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2995 return false;
2996
2997 // FIXME: Support vector-GEPs.
2998 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2999
3000 // If the base pointer is non-null, we cannot walk to a null address with an
3001 // inbounds GEP in address space zero.
3002 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3003 return true;
3004
3005 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3006 // If so, then the GEP cannot produce a null pointer, as doing so would
3007 // inherently violate the inbounds contract within address space zero.
3009 GTI != GTE; ++GTI) {
3010 // Struct types are easy -- they must always be indexed by a constant.
3011 if (StructType *STy = GTI.getStructTypeOrNull()) {
3012 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3013 unsigned ElementIdx = OpC->getZExtValue();
3014 const StructLayout *SL = Q.DL.getStructLayout(STy);
3015 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3016 if (ElementOffset > 0)
3017 return true;
3018 continue;
3019 }
3020
3021 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3022 if (GTI.getSequentialElementStride(Q.DL).isZero())
3023 continue;
3024
3025 // Fast path the constant operand case both for efficiency and so we don't
3026 // increment Depth when just zipping down an all-constant GEP.
3027 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3028 if (!OpC->isZero())
3029 return true;
3030 continue;
3031 }
3032
3033 // We post-increment Depth here because while isKnownNonZero increments it
3034 // as well, when we pop back up that increment won't persist. We don't want
3035 // to recurse 10k times just because we have 10k GEP operands. We don't
3036 // bail completely out because we want to handle constant GEPs regardless
3037 // of depth.
3039 continue;
3040
3041 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3042 return true;
3043 }
3044
3045 return false;
3046}
3047
3049 const Instruction *CtxI,
3050 const DominatorTree *DT) {
3051 assert(!isa<Constant>(V) && "Called for constant?");
3052
3053 if (!CtxI || !DT)
3054 return false;
3055
3056 unsigned NumUsesExplored = 0;
3057 for (auto &U : V->uses()) {
3058 // Avoid massive lists
3059 if (NumUsesExplored >= DomConditionsMaxUses)
3060 break;
3061 NumUsesExplored++;
3062
3063 const Instruction *UI = cast<Instruction>(U.getUser());
3064 // If the value is used as an argument to a call or invoke, then argument
3065 // attributes may provide an answer about null-ness.
3066 if (V->getType()->isPointerTy()) {
3067 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3068 if (CB->isArgOperand(&U) &&
3069 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3070 /*AllowUndefOrPoison=*/false) &&
3071 DT->dominates(CB, CtxI))
3072 return true;
3073 }
3074 }
3075
3076 // If the value is used as a load/store, then the pointer must be non null.
3077 if (V == getLoadStorePointerOperand(UI)) {
3080 DT->dominates(UI, CtxI))
3081 return true;
3082 }
3083
3084 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3085 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3086 isValidAssumeForContext(UI, CtxI, DT))
3087 return true;
3088
3089 // Consider only compare instructions uniquely controlling a branch
3090 Value *RHS;
3091 CmpPredicate Pred;
3092 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3093 continue;
3094
3095 bool NonNullIfTrue;
3096 if (cmpExcludesZero(Pred, RHS))
3097 NonNullIfTrue = true;
3099 NonNullIfTrue = false;
3100 else
3101 continue;
3102
3105 for (const auto *CmpU : UI->users()) {
3106 assert(WorkList.empty() && "Should be!");
3107 if (Visited.insert(CmpU).second)
3108 WorkList.push_back(CmpU);
3109
3110 while (!WorkList.empty()) {
3111 auto *Curr = WorkList.pop_back_val();
3112
3113 // If a user is an AND, add all its users to the work list. We only
3114 // propagate "pred != null" condition through AND because it is only
3115 // correct to assume that all conditions of AND are met in true branch.
3116 // TODO: Support similar logic of OR and EQ predicate?
3117 if (NonNullIfTrue)
3118 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3119 for (const auto *CurrU : Curr->users())
3120 if (Visited.insert(CurrU).second)
3121 WorkList.push_back(CurrU);
3122 continue;
3123 }
3124
3125 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3126 BasicBlock *NonNullSuccessor =
3127 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3128 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3129 if (DT->dominates(Edge, CtxI->getParent()))
3130 return true;
3131 } else if (NonNullIfTrue && isGuard(Curr) &&
3132 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3133 return true;
3134 }
3135 }
3136 }
3137 }
3138
3139 return false;
3140}
3141
3142/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3143/// ensure that the value it's attached to is never Value? 'RangeType' is
3144/// is the type of the value described by the range.
3145static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3146 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3147 assert(NumRanges >= 1);
3148 for (unsigned i = 0; i < NumRanges; ++i) {
3150 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3152 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3153 ConstantRange Range(Lower->getValue(), Upper->getValue());
3154 if (Range.contains(Value))
3155 return false;
3156 }
3157 return true;
3158}
3159
3160/// Try to detect a recurrence that monotonically increases/decreases from a
3161/// non-zero starting value. These are common as induction variables.
3162static bool isNonZeroRecurrence(const PHINode *PN) {
3163 BinaryOperator *BO = nullptr;
3164 Value *Start = nullptr, *Step = nullptr;
3165 const APInt *StartC, *StepC;
3166 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3167 !match(Start, m_APInt(StartC)) || StartC->isZero())
3168 return false;
3169
3170 switch (BO->getOpcode()) {
3171 case Instruction::Add:
3172 // Starting from non-zero and stepping away from zero can never wrap back
3173 // to zero.
3174 return BO->hasNoUnsignedWrap() ||
3175 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3176 StartC->isNegative() == StepC->isNegative());
3177 case Instruction::Mul:
3178 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3179 match(Step, m_APInt(StepC)) && !StepC->isZero();
3180 case Instruction::Shl:
3181 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3182 case Instruction::AShr:
3183 case Instruction::LShr:
3184 return BO->isExact();
3185 case Instruction::Or:
3186 return true;
3187 default:
3188 return false;
3189 }
3190}
3191
3192static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3194 m_Specific(Op1), m_Zero()))) ||
3196 m_Specific(Op0), m_Zero())));
3197}
3198
3199static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3200 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3201 bool NUW, unsigned Depth) {
3202 // (X + (X != 0)) is non zero
3203 if (matchOpWithOpEqZero(X, Y))
3204 return true;
3205
3206 if (NUW)
3207 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3208 isKnownNonZero(X, DemandedElts, Q, Depth);
3209
3210 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3211 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3212
3213 // If X and Y are both non-negative (as signed values) then their sum is not
3214 // zero unless both X and Y are zero.
3215 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3216 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3217 isKnownNonZero(X, DemandedElts, Q, Depth))
3218 return true;
3219
3220 // If X and Y are both negative (as signed values) then their sum is not
3221 // zero unless both X and Y equal INT_MIN.
3222 if (XKnown.isNegative() && YKnown.isNegative()) {
3224 // The sign bit of X is set. If some other bit is set then X is not equal
3225 // to INT_MIN.
3226 if (XKnown.One.intersects(Mask))
3227 return true;
3228 // The sign bit of Y is set. If some other bit is set then Y is not equal
3229 // to INT_MIN.
3230 if (YKnown.One.intersects(Mask))
3231 return true;
3232 }
3233
3234 // The sum of a non-negative number and a power of two is not zero.
3235 if (XKnown.isNonNegative() &&
3236 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3237 return true;
3238 if (YKnown.isNonNegative() &&
3239 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3240 return true;
3241
3242 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3243}
3244
3245static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3246 unsigned BitWidth, Value *X, Value *Y,
3247 unsigned Depth) {
3248 // (X - (X != 0)) is non zero
3249 // ((X != 0) - X) is non zero
3250 if (matchOpWithOpEqZero(X, Y))
3251 return true;
3252
3253 // TODO: Move this case into isKnownNonEqual().
3254 if (auto *C = dyn_cast<Constant>(X))
3255 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3256 return true;
3257
3258 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3259}
3260
3261static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3262 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3263 bool NUW, unsigned Depth) {
3264 // If X and Y are non-zero then so is X * Y as long as the multiplication
3265 // does not overflow.
3266 if (NSW || NUW)
3267 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3268 isKnownNonZero(Y, DemandedElts, Q, Depth);
3269
3270 // If either X or Y is odd, then if the other is non-zero the result can't
3271 // be zero.
3272 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3273 if (XKnown.One[0])
3274 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3275
3276 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3277 if (YKnown.One[0])
3278 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3279
3280 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3281 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3282 // the lowest known One of X and Y. If they are non-zero, the result
3283 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3284 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3285 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3286 BitWidth;
3287}
3288
3289static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3290 const SimplifyQuery &Q, const KnownBits &KnownVal,
3291 unsigned Depth) {
3292 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3293 switch (I->getOpcode()) {
3294 case Instruction::Shl:
3295 return Lhs.shl(Rhs);
3296 case Instruction::LShr:
3297 return Lhs.lshr(Rhs);
3298 case Instruction::AShr:
3299 return Lhs.ashr(Rhs);
3300 default:
3301 llvm_unreachable("Unknown Shift Opcode");
3302 }
3303 };
3304
3305 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3306 switch (I->getOpcode()) {
3307 case Instruction::Shl:
3308 return Lhs.lshr(Rhs);
3309 case Instruction::LShr:
3310 case Instruction::AShr:
3311 return Lhs.shl(Rhs);
3312 default:
3313 llvm_unreachable("Unknown Shift Opcode");
3314 }
3315 };
3316
3317 if (KnownVal.isUnknown())
3318 return false;
3319
3320 KnownBits KnownCnt =
3321 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3322 APInt MaxShift = KnownCnt.getMaxValue();
3323 unsigned NumBits = KnownVal.getBitWidth();
3324 if (MaxShift.uge(NumBits))
3325 return false;
3326
3327 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3328 return true;
3329
3330 // If all of the bits shifted out are known to be zero, and Val is known
3331 // non-zero then at least one non-zero bit must remain.
3332 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3333 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3334 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3335 return true;
3336
3337 return false;
3338}
3339
3341 const APInt &DemandedElts,
3342 const SimplifyQuery &Q, unsigned Depth) {
3343 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3344 switch (I->getOpcode()) {
3345 case Instruction::Alloca:
3346 // Alloca never returns null, malloc might.
3347 return I->getType()->getPointerAddressSpace() == 0;
3348 case Instruction::GetElementPtr:
3349 if (I->getType()->isPointerTy())
3351 break;
3352 case Instruction::BitCast: {
3353 // We need to be a bit careful here. We can only peek through the bitcast
3354 // if the scalar size of elements in the operand are smaller than and a
3355 // multiple of the size they are casting too. Take three cases:
3356 //
3357 // 1) Unsafe:
3358 // bitcast <2 x i16> %NonZero to <4 x i8>
3359 //
3360 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3361 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3362 // guranteed (imagine just sign bit set in the 2 i16 elements).
3363 //
3364 // 2) Unsafe:
3365 // bitcast <4 x i3> %NonZero to <3 x i4>
3366 //
3367 // Even though the scalar size of the src (`i3`) is smaller than the
3368 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3369 // its possible for the `3 x i4` elements to be zero because there are
3370 // some elements in the destination that don't contain any full src
3371 // element.
3372 //
3373 // 3) Safe:
3374 // bitcast <4 x i8> %NonZero to <2 x i16>
3375 //
3376 // This is always safe as non-zero in the 4 i8 elements implies
3377 // non-zero in the combination of any two adjacent ones. Since i8 is a
3378 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3379 // This all implies the 2 i16 elements are non-zero.
3380 Type *FromTy = I->getOperand(0)->getType();
3381 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3382 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3383 return isKnownNonZero(I->getOperand(0), Q, Depth);
3384 } break;
3385 case Instruction::IntToPtr:
3386 // Note that we have to take special care to avoid looking through
3387 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3388 // as casts that can alter the value, e.g., AddrSpaceCasts.
3389 if (!isa<ScalableVectorType>(I->getType()) &&
3390 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3391 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3392 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3393 break;
3394 case Instruction::PtrToAddr:
3395 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3396 // so we can directly forward.
3397 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3398 case Instruction::PtrToInt:
3399 // For inttoptr, make sure the result size is >= the address size. If the
3400 // address is non-zero, any larger value is also non-zero.
3401 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3402 I->getType()->getScalarSizeInBits())
3403 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3404 break;
3405 case Instruction::Trunc:
3406 // nuw/nsw trunc preserves zero/non-zero status of input.
3407 if (auto *TI = dyn_cast<TruncInst>(I))
3408 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3409 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3410 break;
3411
3412 // Iff x - y != 0, then x ^ y != 0
3413 // Therefore we can do the same exact checks
3414 case Instruction::Xor:
3415 case Instruction::Sub:
3416 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3417 I->getOperand(1), Depth);
3418 case Instruction::Or:
3419 // (X | (X != 0)) is non zero
3420 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3421 return true;
3422 // X | Y != 0 if X != Y.
3423 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3424 Depth))
3425 return true;
3426 // X | Y != 0 if X != 0 or Y != 0.
3427 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3428 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3429 case Instruction::SExt:
3430 case Instruction::ZExt:
3431 // ext X != 0 if X != 0.
3432 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3433
3434 case Instruction::Shl: {
3435 // shl nsw/nuw can't remove any non-zero bits.
3437 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3438 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3439
3440 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3441 // if the lowest bit is shifted off the end.
3443 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3444 if (Known.One[0])
3445 return true;
3446
3447 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3448 }
3449 case Instruction::LShr:
3450 case Instruction::AShr: {
3451 // shr exact can only shift out zero bits.
3453 if (BO->isExact())
3454 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3455
3456 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3457 // defined if the sign bit is shifted off the end.
3459 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3460 if (Known.isNegative())
3461 return true;
3462
3463 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3464 // position >= C, because the sum >= max(A, B).
3465 Value *A, *B;
3466 const APInt *C;
3467 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3468 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3469 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3470 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3471 if (!KnownA.One.lshr(*C).isZero())
3472 return true;
3473 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3474 if (!KnownB.One.lshr(*C).isZero())
3475 return true;
3476 }
3477
3478 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3479 }
3480 case Instruction::UDiv:
3481 case Instruction::SDiv: {
3482 // X / Y
3483 // div exact can only produce a zero if the dividend is zero.
3484 if (cast<PossiblyExactOperator>(I)->isExact())
3485 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3486
3487 KnownBits XKnown =
3488 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3489 // If X is fully unknown we won't be able to figure anything out so don't
3490 // both computing knownbits for Y.
3491 if (XKnown.isUnknown())
3492 return false;
3493
3494 KnownBits YKnown =
3495 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3496 if (I->getOpcode() == Instruction::SDiv) {
3497 // For signed division need to compare abs value of the operands.
3498 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3499 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3500 }
3501 // If X u>= Y then div is non zero (0/0 is UB).
3502 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3503 // If X is total unknown or X u< Y we won't be able to prove non-zero
3504 // with compute known bits so just return early.
3505 return XUgeY && *XUgeY;
3506 }
3507 case Instruction::Add: {
3508 // X + Y.
3509
3510 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3511 // non-zero.
3513 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3514 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3515 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3516 }
3517 case Instruction::Mul: {
3519 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3520 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3521 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3522 }
3523 case Instruction::Select: {
3524 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3525
3526 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3527 // then see if the select condition implies the arm is non-zero. For example
3528 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3529 // dominated by `X != 0`.
3530 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3531 Value *Op;
3532 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3533 // Op is trivially non-zero.
3534 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3535 return true;
3536
3537 // The condition of the select dominates the true/false arm. Check if the
3538 // condition implies that a given arm is non-zero.
3539 Value *X;
3540 CmpPredicate Pred;
3541 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3542 return false;
3543
3544 if (!IsTrueArm)
3545 Pred = ICmpInst::getInversePredicate(Pred);
3546
3547 return cmpExcludesZero(Pred, X);
3548 };
3549
3550 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3551 SelectArmIsNonZero(/* IsTrueArm */ false))
3552 return true;
3553 break;
3554 }
3555 case Instruction::PHI: {
3556 auto *PN = cast<PHINode>(I);
3558 return true;
3559
3560 // Check if all incoming values are non-zero using recursion.
3562 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3563 return llvm::all_of(PN->operands(), [&](const Use &U) {
3564 if (U.get() == PN)
3565 return true;
3566 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3567 // Check if the branch on the phi excludes zero.
3568 CmpPredicate Pred;
3569 Value *X;
3570 BasicBlock *TrueSucc, *FalseSucc;
3571 if (match(RecQ.CxtI,
3572 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3573 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3574 // Check for cases of duplicate successors.
3575 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3576 // If we're using the false successor, invert the predicate.
3577 if (FalseSucc == PN->getParent())
3578 Pred = CmpInst::getInversePredicate(Pred);
3579 if (cmpExcludesZero(Pred, X))
3580 return true;
3581 }
3582 }
3583 // Finally recurse on the edge and check it directly.
3584 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3585 });
3586 }
3587 case Instruction::InsertElement: {
3588 if (isa<ScalableVectorType>(I->getType()))
3589 break;
3590
3591 const Value *Vec = I->getOperand(0);
3592 const Value *Elt = I->getOperand(1);
3593 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3594
3595 unsigned NumElts = DemandedElts.getBitWidth();
3596 APInt DemandedVecElts = DemandedElts;
3597 bool SkipElt = false;
3598 // If we know the index we are inserting too, clear it from Vec check.
3599 if (CIdx && CIdx->getValue().ult(NumElts)) {
3600 DemandedVecElts.clearBit(CIdx->getZExtValue());
3601 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3602 }
3603
3604 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3605 // are non-zero.
3606 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3607 (DemandedVecElts.isZero() ||
3608 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3609 }
3610 case Instruction::ExtractElement:
3611 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3612 const Value *Vec = EEI->getVectorOperand();
3613 const Value *Idx = EEI->getIndexOperand();
3614 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3615 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3616 unsigned NumElts = VecTy->getNumElements();
3617 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3618 if (CIdx && CIdx->getValue().ult(NumElts))
3619 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3620 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3621 }
3622 }
3623 break;
3624 case Instruction::ShuffleVector: {
3625 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3626 if (!Shuf)
3627 break;
3628 APInt DemandedLHS, DemandedRHS;
3629 // For undef elements, we don't know anything about the common state of
3630 // the shuffle result.
3631 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3632 break;
3633 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3634 return (DemandedRHS.isZero() ||
3635 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3636 (DemandedLHS.isZero() ||
3637 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3638 }
3639 case Instruction::Freeze:
3640 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3641 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3642 Depth);
3643 case Instruction::Load: {
3644 auto *LI = cast<LoadInst>(I);
3645 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3646 // is never null.
3647 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3648 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3649 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3650 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3651 return true;
3652 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3654 }
3655
3656 // No need to fall through to computeKnownBits as range metadata is already
3657 // handled in isKnownNonZero.
3658 return false;
3659 }
3660 case Instruction::ExtractValue: {
3661 const WithOverflowInst *WO;
3663 switch (WO->getBinaryOp()) {
3664 default:
3665 break;
3666 case Instruction::Add:
3667 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3668 WO->getArgOperand(1),
3669 /*NSW=*/false,
3670 /*NUW=*/false, Depth);
3671 case Instruction::Sub:
3672 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3673 WO->getArgOperand(1), Depth);
3674 case Instruction::Mul:
3675 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3676 WO->getArgOperand(1),
3677 /*NSW=*/false, /*NUW=*/false, Depth);
3678 break;
3679 }
3680 }
3681 break;
3682 }
3683 case Instruction::Call:
3684 case Instruction::Invoke: {
3685 const auto *Call = cast<CallBase>(I);
3686 if (I->getType()->isPointerTy()) {
3687 if (Call->isReturnNonNull())
3688 return true;
3689 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3690 Call, /*MustPreserveOffset=*/true))
3691 return isKnownNonZero(RP, Q, Depth);
3692 } else {
3693 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3695 if (std::optional<ConstantRange> Range = Call->getRange()) {
3696 const APInt ZeroValue(Range->getBitWidth(), 0);
3697 if (!Range->contains(ZeroValue))
3698 return true;
3699 }
3700 if (const Value *RV = Call->getReturnedArgOperand())
3701 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3702 return true;
3703 }
3704
3705 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3706 switch (II->getIntrinsicID()) {
3707 case Intrinsic::sshl_sat:
3708 case Intrinsic::ushl_sat:
3709 case Intrinsic::abs:
3710 case Intrinsic::bitreverse:
3711 case Intrinsic::bswap:
3712 case Intrinsic::ctpop:
3713 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3714 // NB: We don't do usub_sat here as in any case we can prove its
3715 // non-zero, we will fold it to `sub nuw` in InstCombine.
3716 case Intrinsic::ssub_sat:
3717 // For most types, if x != y then ssub.sat x, y != 0. But
3718 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3719 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3720 if (BitWidth == 1)
3721 return false;
3722 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3723 II->getArgOperand(1), Depth);
3724 case Intrinsic::sadd_sat:
3725 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3726 II->getArgOperand(1),
3727 /*NSW=*/true, /* NUW=*/false, Depth);
3728 // Vec reverse preserves zero/non-zero status from input vec.
3729 case Intrinsic::vector_reverse:
3730 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3731 Q, Depth);
3732 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3733 case Intrinsic::vector_reduce_or:
3734 case Intrinsic::vector_reduce_umax:
3735 case Intrinsic::vector_reduce_umin:
3736 case Intrinsic::vector_reduce_smax:
3737 case Intrinsic::vector_reduce_smin:
3738 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3739 case Intrinsic::umax:
3740 case Intrinsic::uadd_sat:
3741 // umax(X, (X != 0)) is non zero
3742 // X +usat (X != 0) is non zero
3743 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3744 return true;
3745
3746 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3747 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3748 case Intrinsic::smax: {
3749 // If either arg is strictly positive the result is non-zero. Otherwise
3750 // the result is non-zero if both ops are non-zero.
3751 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3752 const KnownBits &OpKnown) {
3753 if (!OpNonZero.has_value())
3754 OpNonZero = OpKnown.isNonZero() ||
3755 isKnownNonZero(Op, DemandedElts, Q, Depth);
3756 return *OpNonZero;
3757 };
3758 // Avoid re-computing isKnownNonZero.
3759 std::optional<bool> Op0NonZero, Op1NonZero;
3760 KnownBits Op1Known =
3761 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3762 if (Op1Known.isNonNegative() &&
3763 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3764 return true;
3765 KnownBits Op0Known =
3766 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3767 if (Op0Known.isNonNegative() &&
3768 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3769 return true;
3770 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3771 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3772 }
3773 case Intrinsic::smin: {
3774 // If either arg is negative the result is non-zero. Otherwise
3775 // the result is non-zero if both ops are non-zero.
3776 KnownBits Op1Known =
3777 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3778 if (Op1Known.isNegative())
3779 return true;
3780 KnownBits Op0Known =
3781 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3782 if (Op0Known.isNegative())
3783 return true;
3784
3785 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3786 return true;
3787 }
3788 [[fallthrough]];
3789 case Intrinsic::umin:
3790 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3791 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3792 case Intrinsic::cttz:
3793 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3794 .Zero[0];
3795 case Intrinsic::ctlz:
3796 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3797 .isNonNegative();
3798 case Intrinsic::fshr:
3799 case Intrinsic::fshl:
3800 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3801 if (II->getArgOperand(0) == II->getArgOperand(1))
3802 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3803 break;
3804 case Intrinsic::vscale:
3805 return true;
3806 case Intrinsic::experimental_get_vector_length:
3807 return isKnownNonZero(I->getOperand(0), Q, Depth);
3808 default:
3809 break;
3810 }
3811 break;
3812 }
3813
3814 return false;
3815 }
3816 }
3817
3819 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3820 return Known.One != 0;
3821}
3822
3823/// Return true if the given value is known to be non-zero when defined. For
3824/// vectors, return true if every demanded element is known to be non-zero when
3825/// defined. For pointers, if the context instruction and dominator tree are
3826/// specified, perform context-sensitive analysis and return true if the
3827/// pointer couldn't possibly be null at the specified instruction.
3828/// Supports values with integer or pointer type and vectors of integers.
3829bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3830 const SimplifyQuery &Q, unsigned Depth) {
3831 Type *Ty = V->getType();
3832
3833#ifndef NDEBUG
3834 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3835
3836 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3837 assert(
3838 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3839 "DemandedElt width should equal the fixed vector number of elements");
3840 } else {
3841 assert(DemandedElts == APInt(1, 1) &&
3842 "DemandedElt width should be 1 for scalars");
3843 }
3844#endif
3845
3846 if (auto *C = dyn_cast<Constant>(V)) {
3847 if (C->isNullValue())
3848 return false;
3849 if (isa<ConstantInt>(C))
3850 // Must be non-zero due to null test above.
3851 return true;
3852
3853 // For constant vectors, check that all elements are poison or known
3854 // non-zero to determine that the whole vector is known non-zero.
3855 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3856 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3857 if (!DemandedElts[i])
3858 continue;
3859 Constant *Elt = C->getAggregateElement(i);
3860 if (!Elt || Elt->isNullValue())
3861 return false;
3862 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3863 return false;
3864 }
3865 return true;
3866 }
3867
3868 // Constant ptrauth can be null, iff the base pointer can be.
3869 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3870 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3871
3872 // A global variable in address space 0 is non null unless extern weak
3873 // or an absolute symbol reference. Other address spaces may have null as a
3874 // valid address for a global, so we can't assume anything.
3875 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3876 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3877 GV->getType()->getAddressSpace() == 0)
3878 return true;
3879 }
3880
3881 // For constant expressions, fall through to the Operator code below.
3882 if (!isa<ConstantExpr>(V))
3883 return false;
3884 }
3885
3886 if (const auto *A = dyn_cast<Argument>(V))
3887 if (std::optional<ConstantRange> Range = A->getRange()) {
3888 const APInt ZeroValue(Range->getBitWidth(), 0);
3889 if (!Range->contains(ZeroValue))
3890 return true;
3891 }
3892
3893 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3894 return true;
3895
3896 // Some of the tests below are recursive, so bail out if we hit the limit.
3898 return false;
3899
3900 // Check for pointer simplifications.
3901
3902 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3903 // A byval, inalloca may not be null in a non-default addres space. A
3904 // nonnull argument is assumed never 0.
3905 if (const Argument *A = dyn_cast<Argument>(V)) {
3906 if (((A->hasPassPointeeByValueCopyAttr() &&
3907 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3908 A->hasNonNullAttr()))
3909 return true;
3910 }
3911 }
3912
3913 if (const auto *I = dyn_cast<Operator>(V))
3914 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3915 return true;
3916
3917 if (!isa<Constant>(V) &&
3919 return true;
3920
3921 if (const Value *Stripped = stripNullTest(V))
3922 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3923
3924 return false;
3925}
3926
3928 unsigned Depth) {
3929 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3930 APInt DemandedElts =
3931 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3932 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3933}
3934
3935/// If the pair of operators are the same invertible function, return the
3936/// the operands of the function corresponding to each input. Otherwise,
3937/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3938/// every input value to exactly one output value. This is equivalent to
3939/// saying that Op1 and Op2 are equal exactly when the specified pair of
3940/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3941static std::optional<std::pair<Value*, Value*>>
3943 const Operator *Op2) {
3944 if (Op1->getOpcode() != Op2->getOpcode())
3945 return std::nullopt;
3946
3947 auto getOperands = [&](unsigned OpNum) -> auto {
3948 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3949 };
3950
3951 switch (Op1->getOpcode()) {
3952 default:
3953 break;
3954 case Instruction::Or:
3955 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3956 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3957 break;
3958 [[fallthrough]];
3959 case Instruction::Xor:
3960 case Instruction::Add: {
3961 Value *Other;
3962 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3963 return std::make_pair(Op1->getOperand(1), Other);
3964 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3965 return std::make_pair(Op1->getOperand(0), Other);
3966 break;
3967 }
3968 case Instruction::Sub:
3969 if (Op1->getOperand(0) == Op2->getOperand(0))
3970 return getOperands(1);
3971 if (Op1->getOperand(1) == Op2->getOperand(1))
3972 return getOperands(0);
3973 break;
3974 case Instruction::Mul: {
3975 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3976 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3977 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3978 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3979 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3980 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3981 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3982 break;
3983
3984 // Assume operand order has been canonicalized
3985 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3986 isa<ConstantInt>(Op1->getOperand(1)) &&
3987 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3988 return getOperands(0);
3989 break;
3990 }
3991 case Instruction::Shl: {
3992 // Same as multiplies, with the difference that we don't need to check
3993 // for a non-zero multiply. Shifts always multiply by non-zero.
3994 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3995 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3996 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3997 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3998 break;
3999
4000 if (Op1->getOperand(1) == Op2->getOperand(1))
4001 return getOperands(0);
4002 break;
4003 }
4004 case Instruction::AShr:
4005 case Instruction::LShr: {
4006 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4007 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4008 if (!PEO1->isExact() || !PEO2->isExact())
4009 break;
4010
4011 if (Op1->getOperand(1) == Op2->getOperand(1))
4012 return getOperands(0);
4013 break;
4014 }
4015 case Instruction::SExt:
4016 case Instruction::ZExt:
4017 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4018 return getOperands(0);
4019 break;
4020 case Instruction::PHI: {
4021 const PHINode *PN1 = cast<PHINode>(Op1);
4022 const PHINode *PN2 = cast<PHINode>(Op2);
4023
4024 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4025 // are a single invertible function of the start values? Note that repeated
4026 // application of an invertible function is also invertible
4027 BinaryOperator *BO1 = nullptr;
4028 Value *Start1 = nullptr, *Step1 = nullptr;
4029 BinaryOperator *BO2 = nullptr;
4030 Value *Start2 = nullptr, *Step2 = nullptr;
4031 if (PN1->getParent() != PN2->getParent() ||
4032 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4033 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4034 break;
4035
4037 cast<Operator>(BO2));
4038 if (!Values)
4039 break;
4040
4041 // We have to be careful of mutually defined recurrences here. Ex:
4042 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4043 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4044 // The invertibility of these is complicated, and not worth reasoning
4045 // about (yet?).
4046 if (Values->first != PN1 || Values->second != PN2)
4047 break;
4048
4049 return std::make_pair(Start1, Start2);
4050 }
4051 }
4052 return std::nullopt;
4053}
4054
4055/// Return true if V1 == (binop V2, X), where X is known non-zero.
4056/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4057/// implies V2 != V1.
4058static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4059 const APInt &DemandedElts,
4060 const SimplifyQuery &Q, unsigned Depth) {
4062 if (!BO)
4063 return false;
4064 switch (BO->getOpcode()) {
4065 default:
4066 break;
4067 case Instruction::Or:
4068 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4069 break;
4070 [[fallthrough]];
4071 case Instruction::Xor:
4072 case Instruction::Add:
4073 Value *Op = nullptr;
4074 if (V2 == BO->getOperand(0))
4075 Op = BO->getOperand(1);
4076 else if (V2 == BO->getOperand(1))
4077 Op = BO->getOperand(0);
4078 else
4079 return false;
4080 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4081 }
4082 return false;
4083}
4084
4085/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4086/// the multiplication is nuw or nsw.
4087static bool isNonEqualMul(const Value *V1, const Value *V2,
4088 const APInt &DemandedElts, const SimplifyQuery &Q,
4089 unsigned Depth) {
4090 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4091 const APInt *C;
4092 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4093 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4094 !C->isZero() && !C->isOne() &&
4095 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4096 }
4097 return false;
4098}
4099
4100/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4101/// the shift is nuw or nsw.
4102static bool isNonEqualShl(const Value *V1, const Value *V2,
4103 const APInt &DemandedElts, const SimplifyQuery &Q,
4104 unsigned Depth) {
4105 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4106 const APInt *C;
4107 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4108 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4109 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4110 }
4111 return false;
4112}
4113
4114static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4115 const APInt &DemandedElts, const SimplifyQuery &Q,
4116 unsigned Depth) {
4117 // Check two PHIs are in same block.
4118 if (PN1->getParent() != PN2->getParent())
4119 return false;
4120
4122 bool UsedFullRecursion = false;
4123 for (const BasicBlock *IncomBB : PN1->blocks()) {
4124 if (!VisitedBBs.insert(IncomBB).second)
4125 continue; // Don't reprocess blocks that we have dealt with already.
4126 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4127 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4128 const APInt *C1, *C2;
4129 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4130 continue;
4131
4132 // Only one pair of phi operands is allowed for full recursion.
4133 if (UsedFullRecursion)
4134 return false;
4135
4137 RecQ.CxtI = IncomBB->getTerminator();
4138 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4139 return false;
4140 UsedFullRecursion = true;
4141 }
4142 return true;
4143}
4144
4145static bool isNonEqualSelect(const Value *V1, const Value *V2,
4146 const APInt &DemandedElts, const SimplifyQuery &Q,
4147 unsigned Depth) {
4148 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4149 if (!SI1)
4150 return false;
4151
4152 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4153 const Value *Cond1 = SI1->getCondition();
4154 const Value *Cond2 = SI2->getCondition();
4155 if (Cond1 == Cond2)
4156 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4157 DemandedElts, Q, Depth + 1) &&
4158 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4159 DemandedElts, Q, Depth + 1);
4160 }
4161 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4162 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4163}
4164
4165// Check to see if A is both a GEP and is the incoming value for a PHI in the
4166// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4167// one of them being the recursive GEP A and the other a ptr at same base and at
4168// the same/higher offset than B we are only incrementing the pointer further in
4169// loop if offset of recursive GEP is greater than 0.
4171 const SimplifyQuery &Q) {
4172 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4173 return false;
4174
4175 auto *GEPA = dyn_cast<GEPOperator>(A);
4176 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4177 return false;
4178
4179 // Handle 2 incoming PHI values with one being a recursive GEP.
4180 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4181 if (!PN || PN->getNumIncomingValues() != 2)
4182 return false;
4183
4184 // Search for the recursive GEP as an incoming operand, and record that as
4185 // Step.
4186 Value *Start = nullptr;
4187 Value *Step = const_cast<Value *>(A);
4188 if (PN->getIncomingValue(0) == Step)
4189 Start = PN->getIncomingValue(1);
4190 else if (PN->getIncomingValue(1) == Step)
4191 Start = PN->getIncomingValue(0);
4192 else
4193 return false;
4194
4195 // Other incoming node base should match the B base.
4196 // StartOffset >= OffsetB && StepOffset > 0?
4197 // StartOffset <= OffsetB && StepOffset < 0?
4198 // Is non-equal if above are true.
4199 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4200 // optimisation to inbounds GEPs only.
4201 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4202 APInt StartOffset(IndexWidth, 0);
4203 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4204 APInt StepOffset(IndexWidth, 0);
4205 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4206
4207 // Check if Base Pointer of Step matches the PHI.
4208 if (Step != PN)
4209 return false;
4210 APInt OffsetB(IndexWidth, 0);
4211 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4212 return Start == B &&
4213 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4214 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4215}
4216
4217static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4218 const SimplifyQuery &Q, unsigned Depth) {
4219 if (!Q.CxtI)
4220 return false;
4221
4222 // Try to infer NonEqual based on information from dominating conditions.
4223 if (Q.DC && Q.DT) {
4224 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4225 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4226 Value *Cond = BI->getCondition();
4227 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4228 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4230 /*LHSIsTrue=*/true, Depth)
4231 .value_or(false))
4232 return true;
4233
4234 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4235 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4237 /*LHSIsTrue=*/false, Depth)
4238 .value_or(false))
4239 return true;
4240 }
4241
4242 return false;
4243 };
4244
4245 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4246 IsKnownNonEqualFromDominatingCondition(V2))
4247 return true;
4248 }
4249
4250 if (!Q.AC)
4251 return false;
4252
4253 // Try to infer NonEqual based on information from assumptions.
4254 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4255 if (!AssumeVH)
4256 continue;
4257 CallInst *I = cast<CallInst>(AssumeVH);
4258
4259 assert(I->getFunction() == Q.CxtI->getFunction() &&
4260 "Got assumption for the wrong function!");
4261 assert(I->getIntrinsicID() == Intrinsic::assume &&
4262 "must be an assume intrinsic");
4263
4264 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4265 /*LHSIsTrue=*/true, Depth)
4266 .value_or(false) &&
4268 return true;
4269 }
4270
4271 return false;
4272}
4273
4274static bool isNonEqualURem(const Value *X, const Value *Rem,
4275 const SimplifyQuery &Q) {
4276 const Value *Y;
4277 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4278 return false;
4279
4280 // For a defined urem, X != X urem Y exactly when X u>= Y.
4281 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4283 return true;
4284
4285 std::optional<bool> Implied =
4287 return Implied && *Implied;
4288}
4289
4290/// Return true if it is known that V1 != V2.
4291static bool isKnownNonEqual(const Value *V1, const Value *V2,
4292 const APInt &DemandedElts, const SimplifyQuery &Q,
4293 unsigned Depth) {
4294 if (V1 == V2)
4295 return false;
4296 if (V1->getType() != V2->getType())
4297 // We can't look through casts yet.
4298 return false;
4299
4301 return false;
4302
4303 // See if we can recurse through (exactly one of) our operands. This
4304 // requires our operation be 1-to-1 and map every input value to exactly
4305 // one output value. Such an operation is invertible.
4306 auto *O1 = dyn_cast<Operator>(V1);
4307 auto *O2 = dyn_cast<Operator>(V2);
4308 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4309 if (auto Values = getInvertibleOperands(O1, O2))
4310 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4311 Depth + 1);
4312
4313 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4314 const PHINode *PN2 = cast<PHINode>(V2);
4315 // FIXME: This is missing a generalization to handle the case where one is
4316 // a PHI and another one isn't.
4317 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4318 return true;
4319 };
4320 }
4321
4322 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4323 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4324 return true;
4325
4326 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4327 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4328 return true;
4329
4330 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4331 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4332 return true;
4333
4334 if (V1->getType()->isIntOrIntVectorTy()) {
4335 // Are any known bits in V1 contradictory to known bits in V2? If V1
4336 // has a known zero where V2 has a known one, they must not be equal.
4337 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4338 if (!Known1.isUnknown()) {
4339 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4340 if (Known1.Zero.intersects(Known2.One) ||
4341 Known2.Zero.intersects(Known1.One))
4342 return true;
4343 }
4344 }
4345
4346 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4347 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4348 return true;
4349
4352 return true;
4353
4354 Value *A, *B;
4355 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4356 // Check PtrToInt type matches the pointer size.
4357 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4359 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4360
4361 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4362 return true;
4363
4364 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4365 return true;
4366
4367 return false;
4368}
4369
4370/// For vector constants, loop over the elements and find the constant with the
4371/// minimum number of sign bits. Return 0 if the value is not a vector constant
4372/// or if any element was not analyzed; otherwise, return the count for the
4373/// element with the minimum number of sign bits.
4375 const APInt &DemandedElts,
4376 unsigned TyBits) {
4377 const auto *CV = dyn_cast<Constant>(V);
4378 if (!CV || !isa<FixedVectorType>(CV->getType()))
4379 return 0;
4380
4381 unsigned MinSignBits = TyBits;
4382 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4383 for (unsigned i = 0; i != NumElts; ++i) {
4384 if (!DemandedElts[i])
4385 continue;
4386 // If we find a non-ConstantInt, bail out.
4387 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4388 if (!Elt)
4389 return 0;
4390
4391 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4392 }
4393
4394 return MinSignBits;
4395}
4396
4397static unsigned ComputeNumSignBitsImpl(const Value *V,
4398 const APInt &DemandedElts,
4399 const SimplifyQuery &Q, unsigned Depth);
4400
4401static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4402 const SimplifyQuery &Q, unsigned Depth) {
4403 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4404 assert(Result > 0 && "At least one sign bit needs to be present!");
4405 return Result;
4406}
4407
4408/// Return the number of times the sign bit of the register is replicated into
4409/// the other bits. We know that at least 1 bit is always equal to the sign bit
4410/// (itself), but other cases can give us information. For example, immediately
4411/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4412/// other, so we return 3. For vectors, return the number of sign bits for the
4413/// vector element with the minimum number of known sign bits of the demanded
4414/// elements in the vector specified by DemandedElts.
4415static unsigned ComputeNumSignBitsImpl(const Value *V,
4416 const APInt &DemandedElts,
4417 const SimplifyQuery &Q, unsigned Depth) {
4418 Type *Ty = V->getType();
4419#ifndef NDEBUG
4420 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4421
4422 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4423 assert(
4424 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4425 "DemandedElt width should equal the fixed vector number of elements");
4426 } else {
4427 assert(DemandedElts == APInt(1, 1) &&
4428 "DemandedElt width should be 1 for scalars");
4429 }
4430#endif
4431
4432 // We return the minimum number of sign bits that are guaranteed to be present
4433 // in V, so for undef we have to conservatively return 1. We don't have the
4434 // same behavior for poison though -- that's a FIXME today.
4435
4436 Type *ScalarTy = Ty->getScalarType();
4437 unsigned TyBits = ScalarTy->isPointerTy() ?
4438 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4439 Q.DL.getTypeSizeInBits(ScalarTy);
4440
4441 unsigned Tmp, Tmp2;
4442 unsigned FirstAnswer = 1;
4443
4444 // Note that ConstantInt is handled by the general computeKnownBits case
4445 // below.
4446
4448 return 1;
4449
4450 if (auto *U = dyn_cast<Operator>(V)) {
4451 switch (Operator::getOpcode(V)) {
4452 default: break;
4453 case Instruction::BitCast: {
4454 Value *Src = U->getOperand(0);
4455 Type *SrcTy = Src->getType();
4456
4457 // Skip if the source type is not an integer or integer vector type
4458 // This ensures we only process integer-like types
4459 if (!SrcTy->isIntOrIntVectorTy())
4460 break;
4461
4462 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4463
4464 // Bitcast 'large element' scalar/vector to 'small element' vector.
4465 if ((SrcBits % TyBits) != 0)
4466 break;
4467
4468 // Only proceed if the destination type is a fixed-size vector
4469 if (isa<FixedVectorType>(Ty)) {
4470 // Fast case - sign splat can be simply split across the small elements.
4471 // This works for both vector and scalar sources
4472 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4473 if (Tmp == SrcBits)
4474 return TyBits;
4475 }
4476 break;
4477 }
4478 case Instruction::SExt:
4479 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4480 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4481 Tmp;
4482
4483 case Instruction::SDiv: {
4484 const APInt *Denominator;
4485 // sdiv X, C -> adds log(C) sign bits.
4486 if (match(U->getOperand(1), m_APInt(Denominator))) {
4487
4488 // Ignore non-positive denominator.
4489 if (!Denominator->isStrictlyPositive())
4490 break;
4491
4492 // Calculate the incoming numerator bits.
4493 unsigned NumBits =
4494 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4495
4496 // Add floor(log(C)) bits to the numerator bits.
4497 return std::min(TyBits, NumBits + Denominator->logBase2());
4498 }
4499 break;
4500 }
4501
4502 case Instruction::SRem: {
4503 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4504
4505 const APInt *Denominator;
4506 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4507 // positive constant. This let us put a lower bound on the number of sign
4508 // bits.
4509 if (match(U->getOperand(1), m_APInt(Denominator))) {
4510
4511 // Ignore non-positive denominator.
4512 if (Denominator->isStrictlyPositive()) {
4513 // Calculate the leading sign bit constraints by examining the
4514 // denominator. Given that the denominator is positive, there are two
4515 // cases:
4516 //
4517 // 1. The numerator is positive. The result range is [0,C) and
4518 // [0,C) u< (1 << ceilLogBase2(C)).
4519 //
4520 // 2. The numerator is negative. Then the result range is (-C,0] and
4521 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4522 //
4523 // Thus a lower bound on the number of sign bits is `TyBits -
4524 // ceilLogBase2(C)`.
4525
4526 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4527 Tmp = std::max(Tmp, ResBits);
4528 }
4529 }
4530 return Tmp;
4531 }
4532
4533 case Instruction::AShr: {
4534 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4535 // ashr X, C -> adds C sign bits. Vectors too.
4536 const APInt *ShAmt;
4537 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4538 if (ShAmt->uge(TyBits))
4539 break; // Bad shift.
4540 unsigned ShAmtLimited = ShAmt->getZExtValue();
4541 Tmp += ShAmtLimited;
4542 if (Tmp > TyBits) Tmp = TyBits;
4543 }
4544 return Tmp;
4545 }
4546 case Instruction::Shl: {
4547 const APInt *ShAmt;
4548 Value *X = nullptr;
4549 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4550 // shl destroys sign bits.
4551 if (ShAmt->uge(TyBits))
4552 break; // Bad shift.
4553 // We can look through a zext (more or less treating it as a sext) if
4554 // all extended bits are shifted out.
4555 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4556 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4557 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4558 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4559 } else
4560 Tmp =
4561 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4562 if (ShAmt->uge(Tmp))
4563 break; // Shifted all sign bits out.
4564 Tmp2 = ShAmt->getZExtValue();
4565 return Tmp - Tmp2;
4566 }
4567 break;
4568 }
4569 case Instruction::And:
4570 case Instruction::Or:
4571 case Instruction::Xor: // NOT is handled here.
4572 // Logical binary ops preserve the number of sign bits at the worst.
4573 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4574 if (Tmp != 1) {
4575 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4576 FirstAnswer = std::min(Tmp, Tmp2);
4577 // We computed what we know about the sign bits as our first
4578 // answer. Now proceed to the generic code that uses
4579 // computeKnownBits, and pick whichever answer is better.
4580 }
4581 break;
4582
4583 case Instruction::Select: {
4584 // If we have a clamp pattern, we know that the number of sign bits will
4585 // be the minimum of the clamp min/max range.
4586 const Value *X;
4587 const APInt *CLow, *CHigh;
4588 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4589 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4590
4591 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4592 if (Tmp == 1)
4593 break;
4594 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4595 return std::min(Tmp, Tmp2);
4596 }
4597
4598 case Instruction::Add:
4599 // Add can have at most one carry bit. Thus we know that the output
4600 // is, at worst, one more bit than the inputs.
4601 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4602 if (Tmp == 1) break;
4603
4604 // Special case decrementing a value (ADD X, -1):
4605 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4606 if (CRHS->isAllOnesValue()) {
4607 KnownBits Known(TyBits);
4608 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4609
4610 // If the input is known to be 0 or 1, the output is 0/-1, which is
4611 // all sign bits set.
4612 if ((Known.Zero | 1).isAllOnes())
4613 return TyBits;
4614
4615 // If we are subtracting one from a positive number, there is no carry
4616 // out of the result.
4617 if (Known.isNonNegative())
4618 return Tmp;
4619 }
4620
4621 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4622 if (Tmp2 == 1)
4623 break;
4624 return std::min(Tmp, Tmp2) - 1;
4625
4626 case Instruction::Sub:
4627 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4628 if (Tmp2 == 1)
4629 break;
4630
4631 // Handle NEG.
4632 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4633 if (CLHS->isNullValue()) {
4634 KnownBits Known(TyBits);
4635 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4636 // If the input is known to be 0 or 1, the output is 0/-1, which is
4637 // all sign bits set.
4638 if ((Known.Zero | 1).isAllOnes())
4639 return TyBits;
4640
4641 // If the input is known to be positive (the sign bit is known clear),
4642 // the output of the NEG has the same number of sign bits as the
4643 // input.
4644 if (Known.isNonNegative())
4645 return Tmp2;
4646
4647 // Otherwise, we treat this like a SUB.
4648 }
4649
4650 // Sub can have at most one carry bit. Thus we know that the output
4651 // is, at worst, one more bit than the inputs.
4652 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4653 if (Tmp == 1)
4654 break;
4655 return std::min(Tmp, Tmp2) - 1;
4656
4657 case Instruction::Mul: {
4658 // The output of the Mul can be at most twice the valid bits in the
4659 // inputs.
4660 unsigned SignBitsOp0 =
4661 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4662 if (SignBitsOp0 == 1)
4663 break;
4664 unsigned SignBitsOp1 =
4665 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4666 if (SignBitsOp1 == 1)
4667 break;
4668 unsigned OutValidBits =
4669 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4670 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4671 }
4672
4673 case Instruction::PHI: {
4674 const PHINode *PN = cast<PHINode>(U);
4675 unsigned NumIncomingValues = PN->getNumIncomingValues();
4676 // Don't analyze large in-degree PHIs.
4677 if (NumIncomingValues > 4) break;
4678 // Unreachable blocks may have zero-operand PHI nodes.
4679 if (NumIncomingValues == 0) break;
4680
4681 // Take the minimum of all incoming values. This can't infinitely loop
4682 // because of our depth threshold.
4684 Tmp = TyBits;
4685 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4686 if (Tmp == 1) return Tmp;
4687 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4688 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4689 DemandedElts, RecQ, Depth + 1));
4690 }
4691 return Tmp;
4692 }
4693
4694 case Instruction::Trunc: {
4695 // If the input contained enough sign bits that some remain after the
4696 // truncation, then we can make use of that. Otherwise we don't know
4697 // anything.
4698 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4699 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4700 if (Tmp > (OperandTyBits - TyBits))
4701 return Tmp - (OperandTyBits - TyBits);
4702
4703 return 1;
4704 }
4705
4706 case Instruction::ExtractElement:
4707 // Look through extract element. At the moment we keep this simple and
4708 // skip tracking the specific element. But at least we might find
4709 // information valid for all elements of the vector (for example if vector
4710 // is sign extended, shifted, etc).
4711 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4712
4713 case Instruction::ShuffleVector: {
4714 // Collect the minimum number of sign bits that are shared by every vector
4715 // element referenced by the shuffle.
4716 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4717 if (!Shuf) {
4718 // FIXME: Add support for shufflevector constant expressions.
4719 return 1;
4720 }
4721 APInt DemandedLHS, DemandedRHS;
4722 // For undef elements, we don't know anything about the common state of
4723 // the shuffle result.
4724 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4725 return 1;
4726 Tmp = std::numeric_limits<unsigned>::max();
4727 if (!!DemandedLHS) {
4728 const Value *LHS = Shuf->getOperand(0);
4729 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4730 }
4731 // If we don't know anything, early out and try computeKnownBits
4732 // fall-back.
4733 if (Tmp == 1)
4734 break;
4735 if (!!DemandedRHS) {
4736 const Value *RHS = Shuf->getOperand(1);
4737 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4738 Tmp = std::min(Tmp, Tmp2);
4739 }
4740 // If we don't know anything, early out and try computeKnownBits
4741 // fall-back.
4742 if (Tmp == 1)
4743 break;
4744 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4745 return Tmp;
4746 }
4747 case Instruction::Call: {
4748 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4749 switch (II->getIntrinsicID()) {
4750 default:
4751 break;
4752 case Intrinsic::abs:
4753 Tmp =
4754 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4755 if (Tmp == 1)
4756 break;
4757
4758 // Absolute value reduces number of sign bits by at most 1.
4759 return Tmp - 1;
4760 case Intrinsic::smin:
4761 case Intrinsic::smax: {
4762 const APInt *CLow, *CHigh;
4763 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4764 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4765 }
4766 }
4767 }
4768 }
4769 }
4770 }
4771
4772 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4773 // use this information.
4774
4775 // If we can examine all elements of a vector constant successfully, we're
4776 // done (we can't do any better than that). If not, keep trying.
4777 if (unsigned VecSignBits =
4778 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4779 return VecSignBits;
4780
4781 KnownBits Known(TyBits);
4782 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4783
4784 // If we know that the sign bit is either zero or one, determine the number of
4785 // identical bits in the top of the input value.
4786 return std::max(FirstAnswer, Known.countMinSignBits());
4787}
4788
4790 const TargetLibraryInfo *TLI) {
4791 const Function *F = CB.getCalledFunction();
4792 if (!F)
4794
4795 if (F->isIntrinsic())
4796 return F->getIntrinsicID();
4797
4798 // We are going to infer semantics of a library function based on mapping it
4799 // to an LLVM intrinsic. Check that the library function is available from
4800 // this callbase and in this environment.
4801 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4803
4804 LibFunc Func = TLI->getLibFunc(CB);
4805 if (Func == NotLibFunc)
4807
4808 switch (Func) {
4809 default:
4810 break;
4811 case LibFunc_sin:
4812 case LibFunc_sinf:
4813 case LibFunc_sinl:
4814 return Intrinsic::sin;
4815 case LibFunc_cos:
4816 case LibFunc_cosf:
4817 case LibFunc_cosl:
4818 return Intrinsic::cos;
4819 case LibFunc_tan:
4820 case LibFunc_tanf:
4821 case LibFunc_tanl:
4822 return Intrinsic::tan;
4823 case LibFunc_asin:
4824 case LibFunc_asinf:
4825 case LibFunc_asinl:
4826 return Intrinsic::asin;
4827 case LibFunc_acos:
4828 case LibFunc_acosf:
4829 case LibFunc_acosl:
4830 return Intrinsic::acos;
4831 case LibFunc_atan:
4832 case LibFunc_atanf:
4833 case LibFunc_atanl:
4834 return Intrinsic::atan;
4835 case LibFunc_atan2:
4836 case LibFunc_atan2f:
4837 case LibFunc_atan2l:
4838 return Intrinsic::atan2;
4839 case LibFunc_sinh:
4840 case LibFunc_sinhf:
4841 case LibFunc_sinhl:
4842 return Intrinsic::sinh;
4843 case LibFunc_cosh:
4844 case LibFunc_coshf:
4845 case LibFunc_coshl:
4846 return Intrinsic::cosh;
4847 case LibFunc_tanh:
4848 case LibFunc_tanhf:
4849 case LibFunc_tanhl:
4850 return Intrinsic::tanh;
4851 case LibFunc_exp:
4852 case LibFunc_expf:
4853 case LibFunc_expl:
4854 return Intrinsic::exp;
4855 case LibFunc_exp2:
4856 case LibFunc_exp2f:
4857 case LibFunc_exp2l:
4858 return Intrinsic::exp2;
4859 case LibFunc_exp10:
4860 case LibFunc_exp10f:
4861 case LibFunc_exp10l:
4862 return Intrinsic::exp10;
4863 case LibFunc_log:
4864 case LibFunc_logf:
4865 case LibFunc_logl:
4866 return Intrinsic::log;
4867 case LibFunc_log10:
4868 case LibFunc_log10f:
4869 case LibFunc_log10l:
4870 return Intrinsic::log10;
4871 case LibFunc_log2:
4872 case LibFunc_log2f:
4873 case LibFunc_log2l:
4874 return Intrinsic::log2;
4875 case LibFunc_fabs:
4876 case LibFunc_fabsf:
4877 case LibFunc_fabsl:
4878 return Intrinsic::fabs;
4879 case LibFunc_fmin:
4880 case LibFunc_fminf:
4881 case LibFunc_fminl:
4882 return Intrinsic::minnum;
4883 case LibFunc_fmax:
4884 case LibFunc_fmaxf:
4885 case LibFunc_fmaxl:
4886 return Intrinsic::maxnum;
4887 case LibFunc_copysign:
4888 case LibFunc_copysignf:
4889 case LibFunc_copysignl:
4890 return Intrinsic::copysign;
4891 case LibFunc_floor:
4892 case LibFunc_floorf:
4893 case LibFunc_floorl:
4894 return Intrinsic::floor;
4895 case LibFunc_ceil:
4896 case LibFunc_ceilf:
4897 case LibFunc_ceill:
4898 return Intrinsic::ceil;
4899 case LibFunc_trunc:
4900 case LibFunc_truncf:
4901 case LibFunc_truncl:
4902 return Intrinsic::trunc;
4903 case LibFunc_rint:
4904 case LibFunc_rintf:
4905 case LibFunc_rintl:
4906 return Intrinsic::rint;
4907 case LibFunc_nearbyint:
4908 case LibFunc_nearbyintf:
4909 case LibFunc_nearbyintl:
4910 return Intrinsic::nearbyint;
4911 case LibFunc_round:
4912 case LibFunc_roundf:
4913 case LibFunc_roundl:
4914 return Intrinsic::round;
4915 case LibFunc_roundeven:
4916 case LibFunc_roundevenf:
4917 case LibFunc_roundevenl:
4918 return Intrinsic::roundeven;
4919 case LibFunc_pow:
4920 case LibFunc_powf:
4921 case LibFunc_powl:
4922 return Intrinsic::pow;
4923 case LibFunc_sqrt:
4924 case LibFunc_sqrtf:
4925 case LibFunc_sqrtl:
4926 return Intrinsic::sqrt;
4927 }
4928
4930}
4931
4932/// Given an exploded icmp instruction, return true if the comparison only
4933/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4934/// the result of the comparison is true when the input value is signed.
4936 bool &TrueIfSigned) {
4937 switch (Pred) {
4938 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4939 TrueIfSigned = true;
4940 return RHS.isZero();
4941 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4942 TrueIfSigned = true;
4943 return RHS.isAllOnes();
4944 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4945 TrueIfSigned = false;
4946 return RHS.isAllOnes();
4947 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4948 TrueIfSigned = false;
4949 return RHS.isZero();
4950 case ICmpInst::ICMP_UGT:
4951 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4952 TrueIfSigned = true;
4953 return RHS.isMaxSignedValue();
4954 case ICmpInst::ICMP_UGE:
4955 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4956 TrueIfSigned = true;
4957 return RHS.isMinSignedValue();
4958 case ICmpInst::ICMP_ULT:
4959 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4960 TrueIfSigned = false;
4961 return RHS.isMinSignedValue();
4962 case ICmpInst::ICMP_ULE:
4963 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4964 TrueIfSigned = false;
4965 return RHS.isMaxSignedValue();
4966 default:
4967 return false;
4968 }
4969}
4970
4972 bool CondIsTrue,
4973 const Instruction *CxtI,
4974 KnownFPClass &KnownFromContext,
4975 unsigned Depth = 0) {
4976 Value *A, *B;
4978 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4979 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4980 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4981 Depth + 1);
4982 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4983 Depth + 1);
4984 return;
4985 }
4987 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4988 Depth + 1);
4989 return;
4990 }
4991 CmpPredicate Pred;
4992 Value *LHS;
4993 uint64_t ClassVal = 0;
4994 const APFloat *CRHS;
4995 const APInt *RHS;
4996 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4997 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4998 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4999 LHS != V);
5000 if (CmpVal == V)
5001 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5003 m_Specific(V), m_ConstantInt(ClassVal)))) {
5004 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5005 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5006 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5007 m_APInt(RHS)))) {
5008 bool TrueIfSigned;
5009 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5010 return;
5011 if (TrueIfSigned == CondIsTrue)
5012 KnownFromContext.signBitMustBeOne();
5013 else
5014 KnownFromContext.signBitMustBeZero();
5015 }
5016}
5017
5018/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5019/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5020/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5021/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5022/// exponent range is [-149, -2], but the 0 edge case is above this range).
5023static std::tuple<int, int, int>
5025 if (!Q.CxtI || !Q.DC || !Q.DT)
5027
5028 // Intersect the bounds implied by every dominating condition, keeping the
5029 // tightest maximum. A value may participate in multiple compares
5030 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5031 int MaxExp = APFloat::IEK_Inf;
5032 int MaxExpNonZero = APFloat::IEK_Inf;
5033
5034 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5035 CmpPredicate Pred;
5036 const APFloat *LimitC;
5037 if (!match(BI->getCondition(),
5038 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5039 continue;
5040
5041 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5042 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5043 continue;
5044
5045 // If fabs(x) <= K, implies the exponent min exp range.
5046 // if fabs(x) >= K, swap the successor
5047 bool IsLessEqual =
5048 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5049 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5050 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5051
5052 bool KnownStrictlyLess =
5053 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5054 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5055
5056 BasicBlockEdge Edge1(BI->getParent(),
5057 BI->getSuccessor(IsLessEqual ? 0 : 1));
5058 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
5059 // frexp returns an exponent one greater than ilogb.
5060 int Exp = ilogb(*LimitC) + 1;
5061
5062 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5063 // exponent drops by one when K is exact power of two.
5064 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5065 --Exp;
5066
5067 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5068 // may exclude.
5069
5070 // TODO: Figure out lower bound to detect no-underflow.
5071 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5072 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5073 }
5074 }
5075
5076 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5077}
5078
5080 const SimplifyQuery &Q) {
5081 KnownFPClass KnownFromContext;
5082
5083 if (Q.CC && Q.CC->AffectedValues.contains(V))
5085 KnownFromContext);
5086
5087 if (!Q.CxtI)
5088 return KnownFromContext;
5089
5090 if (Q.DC && Q.DT) {
5091 // Handle dominating conditions.
5092 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5093 Value *Cond = BI->getCondition();
5094
5095 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5096 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5097 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5098 KnownFromContext);
5099
5100 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5101 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5102 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5103 KnownFromContext);
5104 }
5105 }
5106
5107 if (!Q.AC)
5108 return KnownFromContext;
5109
5110 // Try to restrict the floating-point classes based on information from
5111 // assumptions.
5112 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5113 if (!AssumeVH)
5114 continue;
5115 CallInst *I = cast<CallInst>(AssumeVH);
5116
5117 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5118 "Got assumption for the wrong function!");
5119 assert(I->getIntrinsicID() == Intrinsic::assume &&
5120 "must be an assume intrinsic");
5121
5122 if (!isValidAssumeForContext(I, Q))
5123 continue;
5124
5125 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5126 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5127 }
5128
5129 return KnownFromContext;
5130}
5131
5133 Value *Arm, bool Invert,
5134 const SimplifyQuery &SQ,
5135 unsigned Depth) {
5136
5137 KnownFPClass KnownSrc;
5139 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5140 Depth + 1);
5141 KnownSrc = KnownSrc.unionWith(Known);
5142 if (KnownSrc.isUnknown())
5143 return;
5144
5145 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5146 Known = KnownSrc;
5147}
5148
5149void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5150 FPClassTest InterestedClasses, KnownFPClass &Known,
5151 const SimplifyQuery &Q, unsigned Depth);
5152
5154 FPClassTest InterestedClasses,
5155 const SimplifyQuery &Q, unsigned Depth) {
5156 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5157 APInt DemandedElts =
5158 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5159 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5160}
5161
5163 const APInt &DemandedElts,
5164 FPClassTest InterestedClasses,
5166 const SimplifyQuery &Q,
5167 unsigned Depth) {
5168 if ((InterestedClasses &
5170 return;
5171
5172 KnownFPClass KnownSrc;
5173 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5174 KnownSrc, Q, Depth + 1);
5175 Known = KnownFPClass::fptrunc(KnownSrc);
5176}
5177
5179 switch (IID) {
5180 case Intrinsic::minimum:
5182 case Intrinsic::maximum:
5184 case Intrinsic::minimumnum:
5186 case Intrinsic::maximumnum:
5188 case Intrinsic::minnum:
5190 case Intrinsic::maxnum:
5192 default:
5193 llvm_unreachable("not a floating-point min-max intrinsic");
5194 }
5195}
5196
5197/// \return true if this is a floating point value that is known to have a
5198/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5199static bool isAbsoluteValueULEOne(const Value *V) {
5200 // TODO: Handle frexp
5201 // TODO: Other rounding intrinsics?
5202 // TODO: Try computeKnownExponentRangeFromContext
5203
5204 // fabs(x - floor(x)) <= 1
5205 const Value *SubFloorX;
5206 if (match(V, m_FSub(m_Value(SubFloorX),
5208 return true;
5209
5212}
5213
5214void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5215 FPClassTest InterestedClasses, KnownFPClass &Known,
5216 const SimplifyQuery &Q, unsigned Depth) {
5217 assert(Known.isUnknown() && "should not be called with known information");
5218
5219 if (!DemandedElts) {
5220 // No demanded elts, better to assume we don't know anything.
5221 Known.resetAll();
5222 return;
5223 }
5224
5225 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5226
5227 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5228 Known = KnownFPClass(CFP->getValueAPF());
5229 return;
5230 }
5231
5233 Known.setKnownFPClasses(fcPosZero);
5234 Known.setSignBit(false);
5235 return;
5236 }
5237
5238 if (isa<PoisonValue>(V)) {
5239 Known.setKnownFPClasses(fcNone);
5240 Known.setSignBit(false);
5241 return;
5242 }
5243
5244 // Try to handle fixed width vector constants
5245 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5246 const Constant *CV = dyn_cast<Constant>(V);
5247 if (VFVTy && CV) {
5248 Known.setKnownFPClasses(fcNone);
5249 bool SignBitAllZero = true;
5250 bool SignBitAllOne = true;
5251
5252 // For vectors, verify that each element is not NaN.
5253 unsigned NumElts = VFVTy->getNumElements();
5254 for (unsigned i = 0; i != NumElts; ++i) {
5255 if (!DemandedElts[i])
5256 continue;
5257
5258 Constant *Elt = CV->getAggregateElement(i);
5259 if (!Elt) {
5260 Known = KnownFPClass();
5261 return;
5262 }
5263 if (isa<PoisonValue>(Elt))
5264 continue;
5265 auto *CElt = dyn_cast<ConstantFP>(Elt);
5266 if (!CElt) {
5267 Known = KnownFPClass();
5268 return;
5269 }
5270
5271 const APFloat &C = CElt->getValueAPF();
5272 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5273 if (C.isNegative())
5274 SignBitAllZero = false;
5275 else
5276 SignBitAllOne = false;
5277 }
5278 if (SignBitAllOne != SignBitAllZero)
5279 Known.setSignBit(SignBitAllOne);
5280 return;
5281 }
5282
5283 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5284 Known.setKnownFPClasses(fcNone);
5285 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5286 Known |= CDS->getElementAsAPFloat(I).classify();
5287 return;
5288 }
5289
5290 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5291 // TODO: Handle complex aggregates
5292 Known.setKnownFPClasses(fcNone);
5293 for (const Use &Op : CA->operands()) {
5294 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5295 if (!CFP) {
5296 Known = KnownFPClass();
5297 return;
5298 }
5299
5300 Known |= CFP->getValueAPF().classify();
5301 }
5302
5303 return;
5304 }
5305
5306 FPClassTest KnownNotFromFlags = fcNone;
5307 if (const auto *CB = dyn_cast<CallBase>(V))
5308 KnownNotFromFlags |= CB->getRetNoFPClass();
5309 else if (const auto *Arg = dyn_cast<Argument>(V))
5310 KnownNotFromFlags |= Arg->getNoFPClass();
5311
5312 const Operator *Op = dyn_cast<Operator>(V);
5314 if (FPOp->hasNoNaNs())
5315 KnownNotFromFlags |= fcNan;
5316 if (FPOp->hasNoInfs())
5317 KnownNotFromFlags |= fcInf;
5318 }
5319
5320 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5321 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5322
5323 // We no longer need to find out about these bits from inputs if we can
5324 // assume this from flags/attributes.
5325 InterestedClasses &= ~KnownNotFromFlags;
5326
5327 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5328 Known.knownNot(KnownNotFromFlags);
5329 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5330 if (*AssumedClasses.getSignBit())
5331 Known.signBitMustBeOne();
5332 else
5333 Known.signBitMustBeZero();
5334 }
5335 });
5336
5337 if (!Op)
5338 return;
5339
5340 // All recursive calls that increase depth must come after this.
5342 return;
5343
5344 const unsigned Opc = Op->getOpcode();
5345 switch (Opc) {
5346 case Instruction::FNeg: {
5347 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5348 Known, Q, Depth + 1);
5349 Known.fneg();
5350 break;
5351 }
5352 case Instruction::Select: {
5353 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5354 KnownFPClass Res;
5355 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5356 Depth + 1);
5357 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5358 Depth);
5359 return Res;
5360 };
5361 // Only known if known in both the LHS and RHS.
5362 Known =
5363 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5364 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5365 break;
5366 }
5367 case Instruction::Load: {
5368 const MDNode *NoFPClass =
5369 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5370 if (!NoFPClass)
5371 break;
5372
5373 ConstantInt *MaskVal =
5375 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5376 break;
5377 }
5378 case Instruction::Call: {
5379 const CallInst *II = cast<CallInst>(Op);
5380 const Intrinsic::ID IID = II->getIntrinsicID();
5381 switch (IID) {
5382 case Intrinsic::fabs: {
5383 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5384 // If we only care about the sign bit we don't need to inspect the
5385 // operand.
5386 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5387 InterestedClasses, Known, Q, Depth + 1);
5388 }
5389
5390 Known.fabs();
5391 break;
5392 }
5393 case Intrinsic::copysign: {
5394 KnownFPClass KnownSign;
5395
5396 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5397 Known, Q, Depth + 1);
5398 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5399 KnownSign, Q, Depth + 1);
5400 Known.copysign(KnownSign);
5401 break;
5402 }
5403 case Intrinsic::fma:
5404 case Intrinsic::fmuladd: {
5405 if ((InterestedClasses & fcNegative) == fcNone)
5406 break;
5407
5408 // FIXME: This should check isGuaranteedNotToBeUndef
5409 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5410 KnownFPClass KnownSrc, KnownAddend;
5411 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5412 InterestedClasses, KnownAddend, Q, Depth + 1);
5413 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5414 InterestedClasses, KnownSrc, Q, Depth + 1);
5415
5416 const Function *F = II->getFunction();
5417 const fltSemantics &FltSem =
5418 II->getType()->getScalarType()->getFltSemantics();
5420 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5421
5422 if (KnownNotFromFlags & fcNan) {
5423 KnownSrc.knownNot(fcNan);
5424 KnownAddend.knownNot(fcNan);
5425 }
5426
5427 if (KnownNotFromFlags & fcInf) {
5428 KnownSrc.knownNot(fcInf);
5429 KnownAddend.knownNot(fcInf);
5430 }
5431
5432 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5433 break;
5434 }
5435
5436 KnownFPClass KnownSrc[3];
5437 for (int I = 0; I != 3; ++I) {
5438 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5439 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5440 if (KnownSrc[I].isUnknown())
5441 return;
5442
5443 if (KnownNotFromFlags & fcNan)
5444 KnownSrc[I].knownNot(fcNan);
5445 if (KnownNotFromFlags & fcInf)
5446 KnownSrc[I].knownNot(fcInf);
5447 }
5448
5449 const Function *F = II->getFunction();
5450 const fltSemantics &FltSem =
5451 II->getType()->getScalarType()->getFltSemantics();
5453 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5454 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5455 break;
5456 }
5457 case Intrinsic::sqrt:
5458 case Intrinsic::experimental_constrained_sqrt: {
5459 KnownFPClass KnownSrc;
5460 FPClassTest InterestedSrcs = InterestedClasses;
5461 if (InterestedClasses & fcNan)
5462 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5463
5464 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5465 KnownSrc, Q, Depth + 1);
5466
5468
5469 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5470 if (!HasNSZ) {
5471 const Function *F = II->getFunction();
5472 const fltSemantics &FltSem =
5473 II->getType()->getScalarType()->getFltSemantics();
5474 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5475 }
5476
5477 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5478 if (HasNSZ)
5479 Known.knownNot(fcNegZero);
5480
5481 break;
5482 }
5483 case Intrinsic::sin: {
5484 KnownFPClass KnownSrc;
5485 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5486 KnownSrc, Q, Depth + 1);
5487 Known = KnownFPClass::sin(KnownSrc);
5488 break;
5489 }
5490 case Intrinsic::cos: {
5491 KnownFPClass KnownSrc;
5492 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5493 KnownSrc, Q, Depth + 1);
5494 Known = KnownFPClass::cos(KnownSrc);
5495 break;
5496 }
5497 case Intrinsic::tan: {
5498 KnownFPClass KnownSrc;
5499 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5500 KnownSrc, Q, Depth + 1);
5501 Known = KnownFPClass::tan(KnownSrc);
5502 break;
5503 }
5504 case Intrinsic::sinh: {
5505 KnownFPClass KnownSrc;
5506 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5507 KnownSrc, Q, Depth + 1);
5508 Known = KnownFPClass::sinh(KnownSrc);
5509 break;
5510 }
5511 case Intrinsic::cosh: {
5512 KnownFPClass KnownSrc;
5513 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5514 KnownSrc, Q, Depth + 1);
5515 Known = KnownFPClass::cosh(KnownSrc);
5516 break;
5517 }
5518 case Intrinsic::tanh: {
5519 KnownFPClass KnownSrc;
5520 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5521 KnownSrc, Q, Depth + 1);
5522 Known = KnownFPClass::tanh(KnownSrc);
5523 break;
5524 }
5525 case Intrinsic::asin: {
5526 KnownFPClass KnownSrc;
5527 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5528 KnownSrc, Q, Depth + 1);
5529 Known = KnownFPClass::asin(KnownSrc);
5530 break;
5531 }
5532 case Intrinsic::acos: {
5533 KnownFPClass KnownSrc;
5534 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5535 KnownSrc, Q, Depth + 1);
5536 Known = KnownFPClass::acos(KnownSrc);
5537 break;
5538 }
5539 case Intrinsic::atan: {
5540 KnownFPClass KnownSrc;
5541 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5542 KnownSrc, Q, Depth + 1);
5543 Known = KnownFPClass::atan(KnownSrc);
5544 break;
5545 }
5546 case Intrinsic::atan2: {
5547 FPClassTest InterestedY = InterestedClasses;
5548 FPClassTest InterestedX = InterestedClasses;
5549
5550 // We can rule out negative values if y cannot have a negative value.
5551 if ((InterestedClasses & fcNegFinite) != fcNone)
5552 InterestedY |= fcNegative;
5553
5554 // We can rule out positive values if y cannot have a positive value.
5555 if ((InterestedClasses & fcPosFinite) != fcNone)
5556 InterestedY |= fcPositive | fcNegSubnormal;
5557
5558 // We can rule out zero and subnormal if x cannot have a positive value.
5559 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5560 InterestedX |= fcPositive | fcNegSubnormal;
5561
5562 KnownFPClass KnownY, KnownX;
5563 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5564 KnownY, Q, Depth + 1);
5565 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5566 KnownX, Q, Depth + 1);
5567
5568 const Function *F = II->getFunction();
5570 F ? F->getDenormalMode(
5571 II->getType()->getScalarType()->getFltSemantics())
5573 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5574 break;
5575 }
5576 case Intrinsic::maxnum:
5577 case Intrinsic::minnum:
5578 case Intrinsic::minimum:
5579 case Intrinsic::maximum:
5580 case Intrinsic::minimumnum:
5581 case Intrinsic::maximumnum: {
5582 KnownFPClass KnownLHS, KnownRHS;
5583 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5584 KnownLHS, Q, Depth + 1);
5585 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5586 KnownRHS, Q, Depth + 1);
5587
5588 const Function *F = II->getFunction();
5589
5591 F ? F->getDenormalMode(
5592 II->getType()->getScalarType()->getFltSemantics())
5594
5595 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5596 Mode);
5597 break;
5598 }
5599 case Intrinsic::canonicalize: {
5600 KnownFPClass KnownSrc;
5601 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5602 KnownSrc, Q, Depth + 1);
5603
5604 const Function *F = II->getFunction();
5605 DenormalMode DenormMode =
5606 F ? F->getDenormalMode(
5607 II->getType()->getScalarType()->getFltSemantics())
5609 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5610 break;
5611 }
5612 case Intrinsic::vector_reduce_fmax:
5613 case Intrinsic::vector_reduce_fmin:
5614 case Intrinsic::vector_reduce_fmaximum:
5615 case Intrinsic::vector_reduce_fminimum:
5616 case Intrinsic::vector_reduce_fmaximumnum:
5617 case Intrinsic::vector_reduce_fminimumnum: {
5618 // reduce min/max will choose an element from one of the vector elements,
5619 // so we can infer and class information that is common to all elements.
5620 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5621 InterestedClasses, Q, Depth + 1);
5622 // Can only propagate sign if output is never NaN.
5623 if (!Known.isKnownNeverNaN())
5624 Known.setSignBit(std::nullopt);
5625 break;
5626 }
5627 // reverse preserves all characteristics of the input vec's element.
5628 case Intrinsic::vector_reverse:
5630 II->getArgOperand(0), DemandedElts.reverseBits(),
5631 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5632 break;
5633 case Intrinsic::trunc:
5634 case Intrinsic::floor:
5635 case Intrinsic::ceil:
5636 case Intrinsic::rint:
5637 case Intrinsic::nearbyint:
5638 case Intrinsic::round:
5639 case Intrinsic::roundeven: {
5640 KnownFPClass KnownSrc;
5641 FPClassTest InterestedSrcs = InterestedClasses;
5642 if (InterestedSrcs & fcPosFinite)
5643 InterestedSrcs |= fcPosFinite;
5644 if (InterestedSrcs & fcNegFinite)
5645 InterestedSrcs |= fcNegFinite;
5646 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5647 KnownSrc, Q, Depth + 1);
5648
5650 KnownSrc, IID == Intrinsic::trunc,
5651 V->getType()->getScalarType()->isMultiUnitFPType());
5652 break;
5653 }
5654 case Intrinsic::exp:
5655 case Intrinsic::exp2:
5656 case Intrinsic::exp10:
5657 case Intrinsic::amdgcn_exp2: {
5658 KnownFPClass KnownSrc;
5659 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5660 KnownSrc, Q, Depth + 1);
5661
5662 Known = KnownFPClass::exp(KnownSrc);
5663
5664 Type *EltTy = II->getType()->getScalarType();
5665 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5666 Known.knownNot(fcSubnormal);
5667
5668 break;
5669 }
5670 case Intrinsic::fptrunc_round: {
5671 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5672 Q, Depth);
5673 break;
5674 }
5675 case Intrinsic::log:
5676 case Intrinsic::log10:
5677 case Intrinsic::log2:
5678 case Intrinsic::experimental_constrained_log:
5679 case Intrinsic::experimental_constrained_log10:
5680 case Intrinsic::experimental_constrained_log2:
5681 case Intrinsic::amdgcn_log: {
5682 FPClassTest InterestedSrcs = fcNone;
5683
5684 // log(negative) produces NaN.
5685 if ((InterestedClasses & fcNan) != fcNone)
5686 InterestedSrcs |= fcNan | fcNegative;
5687
5688 // log(logical-zero) produces negative infinity.
5689 if ((InterestedClasses & fcNegInf) != fcNone)
5690 InterestedSrcs |= fcZero | fcSubnormal;
5691
5692 // log(x) < -0.0 if x < +1.0
5693 if ((InterestedClasses & fcNegNormal) != fcNone)
5694 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5695
5696 // log(x) >= +0.0 if x >= +1.0
5697 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5698 InterestedSrcs |= fcPosNormal;
5699
5700 // log(x) is positive infinity iff x is positive infinity.
5701 if ((InterestedClasses & fcPosInf) != fcNone)
5702 InterestedSrcs |= fcPosInf;
5703
5704 KnownFPClass KnownSrc;
5705 if (InterestedSrcs != fcNone)
5706 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5707 KnownSrc, Q, Depth + 1);
5708 const Function *F = II->getFunction();
5710 F ? F->getDenormalMode(
5711 II->getType()->getScalarType()->getFltSemantics())
5713 Known = KnownFPClass::log(KnownSrc, Mode);
5714 break;
5715 }
5716 case Intrinsic::pow: {
5717 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5718 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5719 if (!WantNaN && !WantNegative)
5720 break;
5721
5722 FPClassTest InterestedLHS = fcNone;
5723 FPClassTest InterestedRHS = fcNone;
5724 if (WantNaN) {
5725 // pow may return NaN if one of the arguments is NaN. NaN may also be
5726 // produced from a negative, non-zero finite base and a non-integer
5727 // exponent.
5728 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5729 InterestedRHS |= fcNan;
5730 }
5731 if (WantNegative) {
5732 // A negative value is returned when a negative base is raised to an odd
5733 // integer power. Only normal values can be odd integers.
5734 InterestedLHS |= fcNegative;
5735 InterestedRHS |= fcNormal;
5736 }
5737
5738 KnownFPClass KnownLHS;
5739 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5740 KnownLHS, Q, Depth + 1);
5741
5742 // If the LHS is unknown, then querying the RHS is only useful for rare
5743 // edge cases.
5744 if (KnownLHS.isUnknown())
5745 break;
5746
5747 KnownFPClass KnownRHS;
5748 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5749 KnownRHS, Q, Depth + 1);
5750 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5751 break;
5752 }
5753 case Intrinsic::powi: {
5754 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5755 break;
5756
5757 // The exponent is always a scalar, even when raising a vector to a power.
5758 const Value *Exp = II->getArgOperand(1);
5759 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5760 KnownBits ExponentKnownBits(BitWidth);
5761 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5762
5763 FPClassTest InterestedSrcs = fcNone;
5764 if (InterestedClasses & fcNan)
5765 InterestedSrcs |= fcNan;
5766 if (!ExponentKnownBits.isZero()) {
5767 if (InterestedClasses & fcInf)
5768 InterestedSrcs |= fcFinite | fcInf;
5769 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5770 InterestedSrcs |= fcNegative;
5771 }
5772
5773 KnownFPClass KnownSrc;
5774 if (InterestedSrcs != fcNone)
5775 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5776 KnownSrc, Q, Depth + 1);
5777
5778 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5779 break;
5780 }
5781 case Intrinsic::ldexp: {
5782 KnownFPClass KnownSrc;
5783 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5784 KnownSrc, Q, Depth + 1);
5785 // Can refine inf/zero handling based on the exponent operand.
5786 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5787
5788 const Value *ExpArg = II->getArgOperand(1);
5789 ConstantRange ExpKnownRange =
5790 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5791 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5792 : ConstantRange::getFull(
5793 ExpArg->getType()->getScalarSizeInBits());
5794
5795 const fltSemantics &Flt =
5796 II->getType()->getScalarType()->getFltSemantics();
5797
5798 const Function *F = II->getFunction();
5800 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5801
5802 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5803 ExpKnownRange.getSignedMax(), Flt, Mode);
5804 break;
5805 }
5806 case Intrinsic::arithmetic_fence: {
5807 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5808 Known, Q, Depth + 1);
5809 break;
5810 }
5811 case Intrinsic::experimental_constrained_sitofp:
5812 case Intrinsic::experimental_constrained_uitofp:
5813 // Cannot produce nan
5814 Known.knownNot(fcNan);
5815
5816 // sitofp and uitofp turn into +0.0 for zero.
5817 Known.knownNot(fcNegZero);
5818
5819 // Integers cannot be subnormal
5820 Known.knownNot(fcSubnormal);
5821
5822 if (IID == Intrinsic::experimental_constrained_uitofp)
5823 Known.signBitMustBeZero();
5824
5825 // TODO: Copy inf handling from instructions
5826 break;
5827
5828 case Intrinsic::amdgcn_fract: {
5829 Known.knownNot(fcInf);
5830
5831 if (InterestedClasses & fcNan) {
5832 KnownFPClass KnownSrc;
5833 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5834 InterestedClasses, KnownSrc, Q, Depth + 1);
5835
5836 if (KnownSrc.isKnownNeverInfOrNaN())
5837 Known.knownNot(fcNan);
5838 else if (KnownSrc.isKnownNever(fcSNan))
5839 Known.knownNot(fcSNan);
5840 }
5841
5842 break;
5843 }
5844 case Intrinsic::amdgcn_rcp: {
5845 KnownFPClass KnownSrc;
5846 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5847 KnownSrc, Q, Depth + 1);
5848
5849 Known.propagateNonNaN(KnownSrc);
5850
5851 Type *EltTy = II->getType()->getScalarType();
5852
5853 // f32 denormal always flushed.
5854 if (EltTy->isFloatTy()) {
5855 Known.knownNot(fcSubnormal);
5856 KnownSrc.knownNot(fcSubnormal);
5857 }
5858
5859 if (KnownSrc.isKnownNever(fcNegative))
5860 Known.knownNot(fcNegative);
5861 if (KnownSrc.isKnownNever(fcPositive))
5862 Known.knownNot(fcPositive);
5863
5864 if (const Function *F = II->getFunction()) {
5865 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5866 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5867 Known.knownNot(fcPosInf);
5868 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5869 Known.knownNot(fcNegInf);
5870 }
5871
5872 break;
5873 }
5874 case Intrinsic::amdgcn_rsq: {
5875 KnownFPClass KnownSrc;
5876 // The only negative value that can be returned is -inf for -0 inputs.
5878
5879 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5880 KnownSrc, Q, Depth + 1);
5881
5882 // Negative -> nan
5883 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5884 Known.knownNot(fcNan);
5885 else if (KnownSrc.isKnownNever(fcSNan))
5886 Known.knownNot(fcSNan);
5887
5888 // +inf -> +0
5889 if (KnownSrc.isKnownNeverPosInfinity())
5890 Known.knownNot(fcPosZero);
5891
5892 Type *EltTy = II->getType()->getScalarType();
5893
5894 // f32 denormal always flushed.
5895 if (EltTy->isFloatTy())
5896 Known.knownNot(fcPosSubnormal);
5897
5898 if (const Function *F = II->getFunction()) {
5899 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5900
5901 // -0 -> -inf
5902 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5903 Known.knownNot(fcNegInf);
5904
5905 // +0 -> +inf
5906 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5907 Known.knownNot(fcPosInf);
5908 }
5909
5910 break;
5911 }
5912 case Intrinsic::amdgcn_trig_preop: {
5913 // Always returns a value [0, 1)
5914 Known.knownNot(fcNan | fcInf | fcNegative);
5915 break;
5916 }
5917 case Intrinsic::convert_from_arbitrary_fp: {
5918 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5919 StringRef FormatStr = cast<MDString>(MD)->getString();
5920
5921 const fltSemantics *SrcSemantics =
5923 if (!SrcSemantics)
5924 break;
5925
5926 const fltSemantics DstSemantics =
5927 II->getType()->getScalarType()->getFltSemantics();
5928
5929 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5930 Known.knownNot(fcNan);
5931
5932 // fcInf can only be cleared if the source format has no Inf encoding
5933 // and the dst max exp can accommodate src max exp.
5934 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5935 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5936 APFloat::semanticsMaxExponent(DstSemantics))
5937 Known.knownNot(fcInf);
5938
5939 // Check and clear all neg flags for formats that do not have signed
5940 // representation.
5941 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5942 Known.knownNot(fcNegative);
5943
5944 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5945 // zero.
5946 if (!APFloat::semanticsHasZero(*SrcSemantics))
5947 Known.knownNot(fcZero);
5948 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5949 Known.knownNot(fcNegZero);
5950
5951 // If src lands normally in dest, the result can never be subnormal.
5952 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5953 Known.knownNot(fcSubnormal);
5954 break;
5955 }
5956 default:
5957 break;
5958 }
5959
5960 break;
5961 }
5962 case Instruction::FAdd:
5963 case Instruction::FSub: {
5964 KnownFPClass KnownLHS, KnownRHS;
5965 bool WantNegative =
5966 Op->getOpcode() == Instruction::FAdd &&
5967 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5968 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5969 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5970
5971 if (!WantNaN && !WantNegative && !WantNegZero)
5972 break;
5973
5974 FPClassTest InterestedSrcs = InterestedClasses;
5975 if (WantNegative)
5976 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5977 if (InterestedClasses & fcNan)
5978 InterestedSrcs |= fcInf;
5979 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5980 KnownRHS, Q, Depth + 1);
5981
5982 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5983 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5984 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5985 Depth + 1);
5986 if (Self)
5987 KnownLHS = KnownRHS;
5988
5989 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5990 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5991 WantNegZero || Opc == Instruction::FSub) {
5992
5993 // FIXME: Context function should always be passed in separately
5994 const Function *F = cast<Instruction>(Op)->getFunction();
5995 const fltSemantics &FltSem =
5996 Op->getType()->getScalarType()->getFltSemantics();
5998 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5999
6000 if (Self && Opc == Instruction::FAdd) {
6001 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6002 } else {
6003 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6004 // there's no point.
6005
6006 if (!Self) {
6007 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6008 KnownLHS, Q, Depth + 1);
6009 }
6010
6011 Known = Opc == Instruction::FAdd
6012 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6013 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6014 }
6015 }
6016
6017 break;
6018 }
6019 case Instruction::FMul: {
6020 const Function *F = cast<Instruction>(Op)->getFunction();
6022 F ? F->getDenormalMode(
6023 Op->getType()->getScalarType()->getFltSemantics())
6025
6026 Value *LHS = Op->getOperand(0);
6027 Value *RHS = Op->getOperand(1);
6028 // X * X is always non-negative or a NaN.
6029 // FIXME: Should check isGuaranteedNotToBeUndef
6030 if (LHS == RHS) {
6031 KnownFPClass KnownSrc;
6032 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6033 Depth + 1);
6034 Known = KnownFPClass::square(KnownSrc, Mode);
6035 break;
6036 }
6037
6038 KnownFPClass KnownLHS, KnownRHS;
6039
6040 const APFloat *CRHS;
6041 if (match(RHS, m_APFloat(CRHS))) {
6042 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6043 Depth + 1);
6044 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6045 } else {
6046 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6047 Depth + 1);
6048 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6049 // additional not-nan if the addend is known-not negative infinity if the
6050 // multiply is known-not infinity.
6051
6052 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6053 Depth + 1);
6054 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6055 }
6056
6057 /// Propgate no-infs if the other source is known smaller than one, such
6058 /// that this cannot introduce overflow.
6059 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6060 Known.knownNot(fcInf);
6061 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6062 Known.knownNot(fcInf);
6063
6064 break;
6065 }
6066 case Instruction::FDiv: {
6067 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6068
6069 const Function *F = cast<Instruction>(Op)->getFunction();
6070 const fltSemantics &FltSem =
6071 Op->getType()->getScalarType()->getFltSemantics();
6073 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6074
6075 if (Op->getOperand(0) == Op->getOperand(1) &&
6076 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6077 // X / X is always exactly 1.0 or a NaN.
6078 Known.setKnownFPClasses(fcNan | fcPosNormal);
6079
6080 if (!WantNan)
6081 break;
6082
6083 KnownFPClass KnownSrc;
6084 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6085 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6086 Depth + 1);
6087
6088 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6089 break;
6090 }
6091
6092 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6093 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6094 if (!WantNan && !WantNegative && !WantPositive)
6095 break;
6096
6097 KnownFPClass KnownLHS, KnownRHS;
6098 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6099 Q, Depth + 1);
6100
6101 bool KnowSomethingUseful =
6102 KnownRHS.isKnownNeverNaN() ||
6105
6106 if (KnowSomethingUseful)
6107 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6108 Q, Depth + 1);
6109
6110 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6111 break;
6112 }
6113 case Instruction::FRem: {
6114 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6115
6116 Known.knownNot(fcInf);
6117
6118 const Function *F = cast<Instruction>(Op)->getFunction();
6120 F ? F->getDenormalMode(
6121 Op->getType()->getScalarType()->getFltSemantics())
6123
6124 if (Op->getOperand(0) == Op->getOperand(1) &&
6125 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6126 // X % X is always exactly [+-]0.0 or a NaN.
6127 Known.setKnownFPClasses(fcNan | fcZero);
6128
6129 if (!WantNan)
6130 break;
6131
6132 KnownFPClass KnownSrc;
6133 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6134 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6135 Depth + 1);
6136
6137 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6138 break;
6139 }
6140
6141 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6142 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6143 if (!WantNan && !WantNegative && !WantPositive)
6144 break;
6145
6146 KnownFPClass KnownLHS, KnownRHS;
6147 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6148 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6149 Depth + 1);
6150
6151 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6152 KnownRHS.isKnownNever(fcNegative) ||
6153 KnownRHS.isKnownNever(fcPositive);
6154
6155 if (KnowSomethingUseful || WantPositive)
6156 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6157 Q, Depth + 1);
6158
6159 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6160
6161 break;
6162 }
6163 case Instruction::FPExt: {
6164 KnownFPClass KnownSrc;
6165 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6166 KnownSrc, Q, Depth + 1);
6167
6168 const fltSemantics &DstTy =
6169 Op->getType()->getScalarType()->getFltSemantics();
6170 const fltSemantics &SrcTy =
6171 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6172
6173 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6174 break;
6175 }
6176 case Instruction::FPTrunc: {
6177 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6178 Depth);
6179 break;
6180 }
6181 case Instruction::SIToFP:
6182 case Instruction::UIToFP: {
6183 // Cannot produce nan
6184 Known.knownNot(fcNan);
6185
6186 // Integers cannot be subnormal
6187 Known.knownNot(fcSubnormal);
6188
6189 // sitofp and uitofp turn into +0.0 for zero.
6190 Known.knownNot(fcNegZero);
6191
6192 // UIToFP is always non-negative regardless of known bits.
6193 if (Op->getOpcode() == Instruction::UIToFP)
6194 Known.signBitMustBeZero();
6195
6196 // Only compute known bits if we can learn something useful from them.
6197 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6198 break;
6199
6200 KnownBits IntKnown =
6201 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6202
6203 // If the integer is non-zero, the result cannot be +0.0
6204 if (IntKnown.isNonZero())
6205 Known.knownNot(fcPosZero);
6206
6207 if (Op->getOpcode() == Instruction::SIToFP) {
6208 // If the signed integer is known non-negative, the result is
6209 // non-negative. If the signed integer is known negative, the result is
6210 // negative.
6211 if (IntKnown.isNonNegative()) {
6212 Known.signBitMustBeZero();
6213 } else if (IntKnown.isNegative()) {
6214 Known.signBitMustBeOne();
6215 }
6216 }
6217
6218 // Guard kept for ilogb()
6219 if (InterestedClasses & fcInf) {
6220 // Get width of largest magnitude integer known.
6221 // This still works for a signed minimum value because the largest FP
6222 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6223 int IntSize = IntKnown.getBitWidth();
6224 if (Op->getOpcode() == Instruction::UIToFP)
6225 IntSize -= IntKnown.countMinLeadingZeros();
6226 else if (Op->getOpcode() == Instruction::SIToFP)
6227 IntSize -= IntKnown.countMinSignBits();
6228
6229 // If the exponent of the largest finite FP value can hold the largest
6230 // integer, the result of the cast must be finite.
6231 Type *FPTy = Op->getType()->getScalarType();
6232 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6233 Known.knownNot(fcInf);
6234 }
6235
6236 break;
6237 }
6238 case Instruction::ExtractElement: {
6239 // Look through extract element. If the index is non-constant or
6240 // out-of-range demand all elements, otherwise just the extracted element.
6241 const Value *Vec = Op->getOperand(0);
6242
6243 APInt DemandedVecElts;
6244 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6245 unsigned NumElts = VecTy->getNumElements();
6246 DemandedVecElts = APInt::getAllOnes(NumElts);
6247 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6248 if (CIdx && CIdx->getValue().ult(NumElts))
6249 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6250 } else {
6251 DemandedVecElts = APInt(1, 1);
6252 }
6253
6254 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6255 Q, Depth + 1);
6256 }
6257 case Instruction::InsertElement: {
6258 if (isa<ScalableVectorType>(Op->getType()))
6259 return;
6260
6261 const Value *Vec = Op->getOperand(0);
6262 const Value *Elt = Op->getOperand(1);
6263 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6264 unsigned NumElts = DemandedElts.getBitWidth();
6265 APInt DemandedVecElts = DemandedElts;
6266 bool NeedsElt = true;
6267 // If we know the index we are inserting to, clear it from Vec check.
6268 if (CIdx && CIdx->getValue().ult(NumElts)) {
6269 DemandedVecElts.clearBit(CIdx->getZExtValue());
6270 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6271 }
6272
6273 // Do we demand the inserted element?
6274 if (NeedsElt) {
6275 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6276 // If we don't know any bits, early out.
6277 if (Known.isUnknown())
6278 break;
6279 } else {
6280 Known.setKnownFPClasses(fcNone);
6281 }
6282
6283 // Do we need anymore elements from Vec?
6284 if (!DemandedVecElts.isZero()) {
6285 KnownFPClass Known2;
6286 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6287 Depth + 1);
6288 Known |= Known2;
6289 }
6290
6291 break;
6292 }
6293 case Instruction::ShuffleVector: {
6294 // Handle vector splat idiom
6295 if (Value *Splat = getSplatValue(V)) {
6296 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6297 break;
6298 }
6299
6300 // For undef elements, we don't know anything about the common state of
6301 // the shuffle result.
6302 APInt DemandedLHS, DemandedRHS;
6303 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6304 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6305 return;
6306
6307 if (!!DemandedLHS) {
6308 const Value *LHS = Shuf->getOperand(0);
6309 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6310 Depth + 1);
6311
6312 // If we don't know any bits, early out.
6313 if (Known.isUnknown())
6314 break;
6315 } else {
6316 Known.setKnownFPClasses(fcNone);
6317 }
6318
6319 if (!!DemandedRHS) {
6320 KnownFPClass Known2;
6321 const Value *RHS = Shuf->getOperand(1);
6322 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6323 Depth + 1);
6324 Known |= Known2;
6325 }
6326
6327 break;
6328 }
6329 case Instruction::ExtractValue: {
6330 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6331 ArrayRef<unsigned> Indices = Extract->getIndices();
6332 const Value *Src = Extract->getAggregateOperand();
6333 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6334 Indices[0] == 0) {
6335 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6336 switch (II->getIntrinsicID()) {
6337 case Intrinsic::frexp: {
6338 Known.knownNot(fcSubnormal);
6339
6340 KnownFPClass KnownSrc;
6341 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6342 InterestedClasses, KnownSrc, Q, Depth + 1);
6343
6344 const Function *F = cast<Instruction>(Op)->getFunction();
6345 const fltSemantics &FltSem =
6346 Op->getType()->getScalarType()->getFltSemantics();
6347
6349 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6350 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6351 return;
6352 }
6353 default:
6354 break;
6355 }
6356 }
6357 }
6358
6359 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6360 Depth + 1);
6361 break;
6362 }
6363 case Instruction::PHI: {
6364 const PHINode *P = cast<PHINode>(Op);
6365 // Unreachable blocks may have zero-operand PHI nodes.
6366 if (P->getNumIncomingValues() == 0)
6367 break;
6368
6369 // Otherwise take the unions of the known bit sets of the operands,
6370 // taking conservative care to avoid excessive recursion.
6371 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6372
6373 if (Depth < PhiRecursionLimit) {
6374 // Skip if every incoming value references to ourself.
6375 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6376 break;
6377
6378 bool First = true;
6379
6380 for (const Use &U : P->operands()) {
6381 Value *IncValue;
6382 Instruction *CxtI;
6383 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6384 // Skip direct self references.
6385 if (IncValue == P)
6386 continue;
6387
6388 KnownFPClass KnownSrc;
6389 // Recurse, but cap the recursion to two levels, because we don't want
6390 // to waste time spinning around in loops. We need at least depth 2 to
6391 // detect known sign bits.
6392 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6394 PhiRecursionLimit);
6395
6396 if (First) {
6397 Known = KnownSrc;
6398 First = false;
6399 } else {
6400 Known |= KnownSrc;
6401 }
6402
6403 if (Known.getKnownFPClasses() == fcAllFlags)
6404 break;
6405 }
6406 }
6407
6408 // Look for the case of a for loop which has a positive
6409 // initial value and is incremented by a squared value.
6410 // This will propagate sign information out of such loops.
6411 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6412 break;
6413 for (unsigned I = 0; I < 2; I++) {
6414 Value *RecurValue = P->getIncomingValue(1 - I);
6416 if (!II)
6417 continue;
6418 Value *R, *L, *Init;
6419 PHINode *PN;
6421 PN == P) {
6422 switch (II->getIntrinsicID()) {
6423 case Intrinsic::fma:
6424 case Intrinsic::fmuladd: {
6425 KnownFPClass KnownStart;
6426 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6427 Q, Depth + 1);
6428 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6429 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6431 break;
6432 }
6433 }
6434 }
6435 }
6436 break;
6437 }
6438 case Instruction::BitCast: {
6439 const Value *Src;
6440 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6441 !Src->getType()->isIntOrIntVectorTy())
6442 break;
6443
6444 const Type *Ty = Op->getType();
6445
6446 Value *CastLHS, *CastRHS;
6447
6448 // Match bitcast(umax(bitcast(a), bitcast(b)))
6449 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6450 m_BitCast(m_Value(CastRHS)))) &&
6451 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6452 KnownFPClass KnownLHS, KnownRHS;
6453 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6454 Depth + 1);
6455 if (!KnownRHS.isUnknown()) {
6456 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6457 Q, Depth + 1);
6458 Known = KnownLHS | KnownRHS;
6459 }
6460
6461 return;
6462 }
6463
6464 const Type *EltTy = Ty->getScalarType();
6465 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6466 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6467
6469 break;
6470 }
6471 default:
6472 break;
6473 }
6474}
6475
6477 const APInt &DemandedElts,
6478 FPClassTest InterestedClasses,
6479 const SimplifyQuery &SQ,
6480 unsigned Depth) {
6481 KnownFPClass KnownClasses;
6482 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6483 Depth);
6484 return KnownClasses;
6485}
6486
6488 FPClassTest InterestedClasses,
6489 const SimplifyQuery &SQ,
6490 unsigned Depth) {
6492 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6493 return Known;
6494}
6495
6497 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6498 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6499 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6500 return computeKnownFPClass(V, InterestedClasses,
6501 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6502 Depth);
6503}
6504
6506llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6507 FastMathFlags FMF, FPClassTest InterestedClasses,
6508 const SimplifyQuery &SQ, unsigned Depth) {
6509 if (FMF.noNaNs())
6510 InterestedClasses &= ~fcNan;
6511 if (FMF.noInfs())
6512 InterestedClasses &= ~fcInf;
6513
6514 KnownFPClass Result =
6515 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6516
6517 if (FMF.noNaNs())
6518 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6519 if (FMF.noInfs())
6520 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6521 return Result;
6522}
6523
6525 FPClassTest InterestedClasses,
6526 const SimplifyQuery &SQ,
6527 unsigned Depth) {
6528 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6529 APInt DemandedElts =
6530 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6531 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6532 Depth);
6533}
6534
6536 unsigned Depth) {
6538 return Known.isKnownNeverNegZero();
6539}
6540
6542 unsigned Depth) {
6545 return Known.cannotBeOrderedLessThanZero();
6546}
6547
6549 unsigned Depth) {
6551 return Known.isKnownNeverInfinity();
6552}
6553
6554/// Return true if the floating-point value can never contain a NaN or infinity.
6556 unsigned Depth) {
6558 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6559}
6560
6561/// Return true if the floating-point scalar value is not a NaN or if the
6562/// floating-point vector value has no NaN elements. Return false if a value
6563/// could ever be NaN.
6565 unsigned Depth) {
6567 return Known.isKnownNeverNaN();
6568}
6569
6570/// Return false if we can prove that the specified FP value's sign bit is 0.
6571/// Return true if we can prove that the specified FP value's sign bit is 1.
6572/// Otherwise return std::nullopt.
6573std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6574 const SimplifyQuery &SQ,
6575 unsigned Depth) {
6577 return Known.getSignBit();
6578}
6579
6581 auto *User = cast<Instruction>(U.getUser());
6582 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6583 if (FPOp->hasNoSignedZeros())
6584 return true;
6585 }
6586
6587 switch (User->getOpcode()) {
6588 case Instruction::FPToSI:
6589 case Instruction::FPToUI:
6590 return true;
6591 case Instruction::FCmp:
6592 // fcmp treats both positive and negative zero as equal.
6593 return true;
6594 case Instruction::Call:
6595 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6596 switch (II->getIntrinsicID()) {
6597 case Intrinsic::fabs:
6598 return true;
6599 case Intrinsic::copysign:
6600 return U.getOperandNo() == 0;
6601 case Intrinsic::is_fpclass: {
6602 auto Test =
6603 static_cast<FPClassTest>(
6604 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6607 }
6608 default:
6609 return false;
6610 }
6611 }
6612 return false;
6613 default:
6614 return false;
6615 }
6616}
6617
6619 auto *User = cast<Instruction>(U.getUser());
6620 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6621 if (FPOp->hasNoNaNs())
6622 return true;
6623 }
6624
6625 switch (User->getOpcode()) {
6626 case Instruction::FPToSI:
6627 case Instruction::FPToUI:
6628 return true;
6629 // Proper FP math operations ignore the sign bit of NaN.
6630 case Instruction::FAdd:
6631 case Instruction::FSub:
6632 case Instruction::FMul:
6633 case Instruction::FDiv:
6634 case Instruction::FRem:
6635 case Instruction::FPTrunc:
6636 case Instruction::FPExt:
6637 case Instruction::FCmp:
6638 return true;
6639 // Bitwise FP operations should preserve the sign bit of NaN.
6640 case Instruction::FNeg:
6641 case Instruction::Select:
6642 case Instruction::PHI:
6643 return false;
6644 case Instruction::Ret:
6645 return User->getFunction()->getAttributes().getRetNoFPClass() &
6647 case Instruction::Call:
6648 case Instruction::Invoke: {
6649 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6650 switch (II->getIntrinsicID()) {
6651 case Intrinsic::fabs:
6652 return true;
6653 case Intrinsic::copysign:
6654 return U.getOperandNo() == 0;
6655 // Other proper FP math intrinsics ignore the sign bit of NaN.
6656 case Intrinsic::maxnum:
6657 case Intrinsic::minnum:
6658 case Intrinsic::maximum:
6659 case Intrinsic::minimum:
6660 case Intrinsic::maximumnum:
6661 case Intrinsic::minimumnum:
6662 case Intrinsic::canonicalize:
6663 case Intrinsic::fma:
6664 case Intrinsic::fmuladd:
6665 case Intrinsic::sqrt:
6666 case Intrinsic::pow:
6667 case Intrinsic::powi:
6668 case Intrinsic::fptoui_sat:
6669 case Intrinsic::fptosi_sat:
6670 case Intrinsic::is_fpclass:
6671 return true;
6672 default:
6673 return false;
6674 }
6675 }
6676
6677 FPClassTest NoFPClass =
6678 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6679 return NoFPClass & FPClassTest::fcNan;
6680 }
6681 default:
6682 return false;
6683 }
6684}
6685
6687 FastMathFlags FMF) {
6688 if (isa<PoisonValue>(V))
6689 return true;
6690 if (isa<UndefValue>(V))
6691 return false;
6692
6693 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6694 return true;
6695
6697 if (!I)
6698 return false;
6699
6700 switch (I->getOpcode()) {
6701 case Instruction::SIToFP:
6702 case Instruction::UIToFP:
6703 // TODO: Could check nofpclass(inf) on incoming argument
6704 if (FMF.noInfs())
6705 return true;
6706
6707 // Need to check int size cannot produce infinity, which computeKnownFPClass
6708 // knows how to do already.
6709 return isKnownNeverInfinity(I, SQ);
6710 case Instruction::Call: {
6711 const CallInst *CI = cast<CallInst>(I);
6712 switch (CI->getIntrinsicID()) {
6713 case Intrinsic::trunc:
6714 case Intrinsic::floor:
6715 case Intrinsic::ceil:
6716 case Intrinsic::rint:
6717 case Intrinsic::nearbyint:
6718 case Intrinsic::round:
6719 case Intrinsic::roundeven:
6720 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6721 default:
6722 break;
6723 }
6724
6725 break;
6726 }
6727 default:
6728 break;
6729 }
6730
6731 return false;
6732}
6733
6735
6736 // All byte-wide stores are splatable, even of arbitrary variables.
6737 if (V->getType()->isIntegerTy(8))
6738 return V;
6739
6740 LLVMContext &Ctx = V->getContext();
6741
6742 // Undef don't care.
6743 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6744 if (isa<UndefValue>(V))
6745 return UndefInt8;
6746
6747 // Return poison for zero-sized type.
6748 if (DL.getTypeStoreSize(V->getType()).isZero())
6749 return PoisonValue::get(Type::getInt8Ty(Ctx));
6750
6752 if (!C) {
6753 // Conceptually, we could handle things like:
6754 // %a = zext i8 %X to i16
6755 // %b = shl i16 %a, 8
6756 // %c = or i16 %a, %b
6757 // but until there is an example that actually needs this, it doesn't seem
6758 // worth worrying about.
6759 return nullptr;
6760 }
6761
6762 // Handle 'null' ConstantArrayZero etc.
6763 if (C->isNullValue())
6765
6766 // Constant floating-point values can be handled as integer values if the
6767 // corresponding integer value is "byteable". An important case is 0.0.
6768 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6769 Type *ScalarTy = CFP->getType()->getScalarType();
6770 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6771 return isBytewiseValue(
6772 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6773
6774 // Don't handle long double formats, which have strange constraints.
6775 return nullptr;
6776 }
6777
6778 // We can handle constant integers that are multiple of 8 bits.
6779 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6780 if (CI->getBitWidth() % 8 == 0) {
6781 if (!CI->getValue().isSplat(8))
6782 return nullptr;
6783 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6784 }
6785 }
6786
6787 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6788 if (CE->getOpcode() == Instruction::IntToPtr) {
6789 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6790 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6792 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6793 return isBytewiseValue(Op, DL);
6794 }
6795 }
6796 }
6797
6798 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6799 if (LHS == RHS)
6800 return LHS;
6801 if (!LHS || !RHS)
6802 return nullptr;
6803 if (LHS == UndefInt8)
6804 return RHS;
6805 if (RHS == UndefInt8)
6806 return LHS;
6807 return nullptr;
6808 };
6809
6811 Value *Val = UndefInt8;
6812 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6813 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6814 return nullptr;
6815 return Val;
6816 }
6817
6819 Value *Val = UndefInt8;
6820 for (Value *Op : C->operands())
6821 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6822 return nullptr;
6823 return Val;
6824 }
6825
6826 // Don't try to handle the handful of other constants.
6827 return nullptr;
6828}
6829
6830// This is the recursive version of BuildSubAggregate. It takes a few different
6831// arguments. Idxs is the index within the nested struct From that we are
6832// looking at now (which is of type IndexedType). IdxSkip is the number of
6833// indices from Idxs that should be left out when inserting into the resulting
6834// struct. To is the result struct built so far, new insertvalue instructions
6835// build on that.
6836static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6838 unsigned IdxSkip,
6839 BasicBlock::iterator InsertBefore) {
6840 StructType *STy = dyn_cast<StructType>(IndexedType);
6841 if (STy) {
6842 // Save the original To argument so we can modify it
6843 Value *OrigTo = To;
6844 // General case, the type indexed by Idxs is a struct
6845 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6846 // Process each struct element recursively
6847 Idxs.push_back(i);
6848 Value *PrevTo = To;
6849 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6850 InsertBefore);
6851 Idxs.pop_back();
6852 if (!To) {
6853 // Couldn't find any inserted value for this index? Cleanup
6854 while (PrevTo != OrigTo) {
6856 PrevTo = Del->getAggregateOperand();
6857 Del->eraseFromParent();
6858 }
6859 // Stop processing elements
6860 break;
6861 }
6862 }
6863 // If we successfully found a value for each of our subaggregates
6864 if (To)
6865 return To;
6866 }
6867 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6868 // the struct's elements had a value that was inserted directly. In the latter
6869 // case, perhaps we can't determine each of the subelements individually, but
6870 // we might be able to find the complete struct somewhere.
6871
6872 // Find the value that is at that particular spot
6873 Value *V = FindInsertedValue(From, Idxs);
6874
6875 if (!V)
6876 return nullptr;
6877
6878 // Insert the value in the new (sub) aggregate
6879 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6880 InsertBefore);
6881}
6882
6883// This helper takes a nested struct and extracts a part of it (which is again a
6884// struct) into a new value. For example, given the struct:
6885// { a, { b, { c, d }, e } }
6886// and the indices "1, 1" this returns
6887// { c, d }.
6888//
6889// It does this by inserting an insertvalue for each element in the resulting
6890// struct, as opposed to just inserting a single struct. This will only work if
6891// each of the elements of the substruct are known (ie, inserted into From by an
6892// insertvalue instruction somewhere).
6893//
6894// All inserted insertvalue instructions are inserted before InsertBefore
6896 BasicBlock::iterator InsertBefore) {
6897 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6898 idx_range);
6899 Value *To = PoisonValue::get(IndexedType);
6900 SmallVector<unsigned, 10> Idxs(idx_range);
6901 unsigned IdxSkip = Idxs.size();
6902
6903 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6904}
6905
6906/// Given an aggregate and a sequence of indices, see if the scalar value
6907/// indexed is already around as a register, for example if it was inserted
6908/// directly into the aggregate.
6909///
6910/// If InsertBefore is not null, this function will duplicate (modified)
6911/// insertvalues when a part of a nested struct is extracted.
6912Value *
6914 std::optional<BasicBlock::iterator> InsertBefore) {
6915 // Nothing to index? Just return V then (this is useful at the end of our
6916 // recursion).
6917 if (idx_range.empty())
6918 return V;
6919 // We have indices, so V should have an indexable type.
6920 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6921 "Not looking at a struct or array?");
6922 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6923 "Invalid indices for type?");
6924
6925 if (Constant *C = dyn_cast<Constant>(V)) {
6926 C = C->getAggregateElement(idx_range[0]);
6927 if (!C) return nullptr;
6928 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6929 }
6930
6932 // Loop the indices for the insertvalue instruction in parallel with the
6933 // requested indices
6934 const unsigned *req_idx = idx_range.begin();
6935 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6936 i != e; ++i, ++req_idx) {
6937 if (req_idx == idx_range.end()) {
6938 // We can't handle this without inserting insertvalues
6939 if (!InsertBefore)
6940 return nullptr;
6941
6942 // The requested index identifies a part of a nested aggregate. Handle
6943 // this specially. For example,
6944 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6945 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6946 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6947 // This can be changed into
6948 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6949 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6950 // which allows the unused 0,0 element from the nested struct to be
6951 // removed.
6952 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6953 *InsertBefore);
6954 }
6955
6956 // This insert value inserts something else than what we are looking for.
6957 // See if the (aggregate) value inserted into has the value we are
6958 // looking for, then.
6959 if (*req_idx != *i)
6960 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6961 InsertBefore);
6962 }
6963 // If we end up here, the indices of the insertvalue match with those
6964 // requested (though possibly only partially). Now we recursively look at
6965 // the inserted value, passing any remaining indices.
6966 return FindInsertedValue(I->getInsertedValueOperand(),
6967 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6968 }
6969
6971 // If we're extracting a value from an aggregate that was extracted from
6972 // something else, we can extract from that something else directly instead.
6973 // However, we will need to chain I's indices with the requested indices.
6974
6975 // Calculate the number of indices required
6976 unsigned size = I->getNumIndices() + idx_range.size();
6977 // Allocate some space to put the new indices in
6979 Idxs.reserve(size);
6980 // Add indices from the extract value instruction
6981 Idxs.append(I->idx_begin(), I->idx_end());
6982
6983 // Add requested indices
6984 Idxs.append(idx_range.begin(), idx_range.end());
6985
6986 assert(Idxs.size() == size
6987 && "Number of indices added not correct?");
6988
6989 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6990 }
6991 // Otherwise, we don't know (such as, extracting from a function return value
6992 // or load instruction)
6993 return nullptr;
6994}
6995
6996// If V refers to an initialized global constant, set Slice either to
6997// its initializer if the size of its elements equals ElementSize, or,
6998// for ElementSize == 8, to its representation as an array of unsiged
6999// char. Return true on success.
7000// Offset is in the unit "nr of ElementSize sized elements".
7003 unsigned ElementSize, uint64_t Offset) {
7004 assert(V && "V should not be null.");
7005 assert((ElementSize % 8) == 0 &&
7006 "ElementSize expected to be a multiple of the size of a byte.");
7007 unsigned ElementSizeInBytes = ElementSize / 8;
7008
7009 // Drill down into the pointer expression V, ignoring any intervening
7010 // casts, and determine the identity of the object it references along
7011 // with the cumulative byte offset into it.
7012 const GlobalVariable *GV =
7014 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7015 // Fail if V is not based on constant global object.
7016 return false;
7017
7018 const DataLayout &DL = GV->getDataLayout();
7019 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7020
7021 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
7022 /*AllowNonInbounds*/ true))
7023 // Fail if a constant offset could not be determined.
7024 return false;
7025
7026 uint64_t StartIdx = Off.getLimitedValue();
7027 if (StartIdx == UINT64_MAX)
7028 // Fail if the constant offset is excessive.
7029 return false;
7030
7031 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7032 // elements. Simply bail out if that isn't possible.
7033 if ((StartIdx % ElementSizeInBytes) != 0)
7034 return false;
7035
7036 Offset += StartIdx / ElementSizeInBytes;
7037 ConstantDataArray *Array = nullptr;
7038 ArrayType *ArrayTy = nullptr;
7039
7040 if (GV->getInitializer()->isNullValue()) {
7041 Type *GVTy = GV->getValueType();
7042 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7043 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7044
7045 Slice.Array = nullptr;
7046 Slice.Offset = 0;
7047 // Return an empty Slice for undersized constants to let callers
7048 // transform even undefined library calls into simpler, well-defined
7049 // expressions. This is preferable to making the calls although it
7050 // prevents sanitizers from detecting such calls.
7051 Slice.Length = Length < Offset ? 0 : Length - Offset;
7052 return true;
7053 }
7054
7055 auto *Init = const_cast<Constant *>(GV->getInitializer());
7056 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7057 Type *InitElTy = ArrayInit->getElementType();
7058 if (InitElTy->isIntegerTy(ElementSize)) {
7059 // If Init is an initializer for an array of the expected type
7060 // and size, use it as is.
7061 Array = ArrayInit;
7062 ArrayTy = ArrayInit->getType();
7063 }
7064 }
7065
7066 if (!Array) {
7067 if (ElementSize != 8)
7068 // TODO: Handle conversions to larger integral types.
7069 return false;
7070
7071 // Otherwise extract the portion of the initializer starting
7072 // at Offset as an array of bytes, and reset Offset.
7074 if (!Init)
7075 return false;
7076
7077 Offset = 0;
7079 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7080 }
7081
7082 uint64_t NumElts = ArrayTy->getArrayNumElements();
7083 if (Offset > NumElts)
7084 return false;
7085
7086 Slice.Array = Array;
7087 Slice.Offset = Offset;
7088 Slice.Length = NumElts - Offset;
7089 return true;
7090}
7091
7092/// Extract bytes from the initializer of the constant array V, which need
7093/// not be a nul-terminated string. On success, store the bytes in Str and
7094/// return true. When TrimAtNul is set, Str will contain only the bytes up
7095/// to but not including the first nul. Return false on failure.
7097 bool TrimAtNul) {
7099 if (!getConstantDataArrayInfo(V, Slice, 8))
7100 return false;
7101
7102 if (Slice.Array == nullptr) {
7103 if (TrimAtNul) {
7104 // Return a nul-terminated string even for an empty Slice. This is
7105 // safe because all existing SimplifyLibcalls callers require string
7106 // arguments and the behavior of the functions they fold is undefined
7107 // otherwise. Folding the calls this way is preferable to making
7108 // the undefined library calls, even though it prevents sanitizers
7109 // from reporting such calls.
7110 Str = StringRef();
7111 return true;
7112 }
7113 if (Slice.Length == 1) {
7114 Str = StringRef("", 1);
7115 return true;
7116 }
7117 // We cannot instantiate a StringRef as we do not have an appropriate string
7118 // of 0s at hand.
7119 return false;
7120 }
7121
7122 // Start out with the entire array in the StringRef.
7123 Str = Slice.Array->getAsString();
7124 // Skip over 'offset' bytes.
7125 Str = Str.substr(Slice.Offset);
7126
7127 if (TrimAtNul) {
7128 // Trim off the \0 and anything after it. If the array is not nul
7129 // terminated, we just return the whole end of string. The client may know
7130 // some other way that the string is length-bound.
7131 Str = Str.substr(0, Str.find('\0'));
7132 }
7133 return true;
7134}
7135
7136// These next two are very similar to the above, but also look through PHI
7137// nodes.
7138// TODO: See if we can integrate these two together.
7139
7140/// If we can compute the length of the string pointed to by
7141/// the specified pointer, return 'len+1'. If we can't, return 0.
7144 unsigned CharSize) {
7145 // Look through noop bitcast instructions.
7146 V = V->stripPointerCasts();
7147
7148 // If this is a PHI node, there are two cases: either we have already seen it
7149 // or we haven't.
7150 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7151 if (!PHIs.insert(PN).second)
7152 return ~0ULL; // already in the set.
7153
7154 // If it was new, see if all the input strings are the same length.
7155 uint64_t LenSoFar = ~0ULL;
7156 for (Value *IncValue : PN->incoming_values()) {
7157 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7158 if (Len == 0) return 0; // Unknown length -> unknown.
7159
7160 if (Len == ~0ULL) continue;
7161
7162 if (Len != LenSoFar && LenSoFar != ~0ULL)
7163 return 0; // Disagree -> unknown.
7164 LenSoFar = Len;
7165 }
7166
7167 // Success, all agree.
7168 return LenSoFar;
7169 }
7170
7171 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7172 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7173 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7174 if (Len1 == 0) return 0;
7175 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7176 if (Len2 == 0) return 0;
7177 if (Len1 == ~0ULL) return Len2;
7178 if (Len2 == ~0ULL) return Len1;
7179 if (Len1 != Len2) return 0;
7180 return Len1;
7181 }
7182
7183 // Otherwise, see if we can read the string.
7185 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7186 return 0;
7187
7188 if (Slice.Array == nullptr)
7189 // Zeroinitializer (including an empty one).
7190 return 1;
7191
7192 // Search for the first nul character. Return a conservative result even
7193 // when there is no nul. This is safe since otherwise the string function
7194 // being folded such as strlen is undefined, and can be preferable to
7195 // making the undefined library call.
7196 unsigned NullIndex = 0;
7197 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7198 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7199 break;
7200 }
7201
7202 return NullIndex + 1;
7203}
7204
7205/// If we can compute the length of the string pointed to by
7206/// the specified pointer, return 'len+1'. If we can't, return 0.
7207uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7208 if (!V->getType()->isPointerTy())
7209 return 0;
7210
7212 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7213 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7214 // an empty string as a length.
7215 return Len == ~0ULL ? 1 : Len;
7216}
7217
7218const Value *
7220 bool MustPreserveOffset,
7221 bool MustPreserveProvenance) {
7222 assert(Call &&
7223 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7224 if (const Value *RV = Call->getReturnedArgOperand())
7225 return RV;
7226 // This can be used only as a aliasing property.
7228 Call, MustPreserveOffset, MustPreserveProvenance))
7229 return Call->getArgOperand(0);
7230 return nullptr;
7231}
7232
7234 const CallBase *Call, bool MustPreserveOffset,
7235 bool MustPreserveProvenance) {
7236 switch (Call->getIntrinsicID()) {
7237 case Intrinsic::launder_invariant_group:
7238 case Intrinsic::aarch64_irg:
7239 case Intrinsic::aarch64_tagp:
7240 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7241 // input pointer (and thus preserves the byte offset, which is the property
7242 // the MustPreserveOffset flag selects). However, it will not necessarily
7243 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7244 // descriptor", which has "all loads return 0, all stores are dropped"
7245 // semantics. Given the context of this intrinsic list, no one should be
7246 // relying on such a strict bit-exact null mapping (and, at time of
7247 // writing, they are not), but we document this fact out of an abundance
7248 // of caution.
7249 case Intrinsic::amdgcn_make_buffer_rsrc:
7250 return !MustPreserveProvenance;
7251 case Intrinsic::ptrmask:
7252 return !MustPreserveOffset;
7253 case Intrinsic::threadlocal_address:
7254 // The underlying variable changes with thread ID. The Thread ID may change
7255 // at coroutine suspend points.
7256 return !Call->getParent()->getParent()->isPresplitCoroutine();
7257 default:
7258 return false;
7259 }
7260}
7261
7262/// \p PN defines a loop-variant pointer to an object. Check if the
7263/// previous iteration of the loop was referring to the same object as \p PN.
7265 const LoopInfo *LI) {
7266 // Find the loop-defined value.
7267 Loop *L = LI->getLoopFor(PN->getParent());
7268 if (PN->getNumIncomingValues() != 2)
7269 return true;
7270
7271 // Find the value from previous iteration.
7272 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7273 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7274 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7275 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7276 return true;
7277
7278 // If a new pointer is loaded in the loop, the pointer references a different
7279 // object in every iteration. E.g.:
7280 // for (i)
7281 // int *p = a[i];
7282 // ...
7283 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7284 if (!L->isLoopInvariant(Load->getPointerOperand()))
7285 return false;
7286 return true;
7287}
7288
7289const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7290 bool MustPreserveProvenance) {
7291 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7292 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7293 const Value *PtrOp = GEP->getPointerOperand();
7294 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7295 return V;
7296 V = PtrOp;
7297 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7298 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7299 Value *NewV = cast<Operator>(V)->getOperand(0);
7300 if (!NewV->getType()->isPointerTy())
7301 return V;
7302 V = NewV;
7303 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7304 if (GA->isInterposable())
7305 return V;
7306 V = GA->getAliasee();
7307 } else {
7308 if (auto *PHI = dyn_cast<PHINode>(V)) {
7309 // Look through single-arg phi nodes created by LCSSA.
7310 if (PHI->getNumIncomingValues() == 1) {
7311 V = PHI->getIncomingValue(0);
7312 continue;
7313 }
7314 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7315 // CaptureTracking can know about special capturing properties of some
7316 // intrinsics like launder.invariant.group, that can't be expressed with
7317 // the attributes, but have properties like returning aliasing pointer.
7318 // Because some analysis may assume that nocaptured pointer is not
7319 // returned from some special intrinsic (because function would have to
7320 // be marked with returns attribute), it is crucial to use this function
7321 // because it should be in sync with CaptureTracking. Not using it may
7322 // cause weird miscompilations where 2 aliasing pointers are assumed to
7323 // noalias.
7325 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7326 V = RP;
7327 continue;
7328 }
7329 }
7330
7331 return V;
7332 }
7333 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7334 }
7335 return V;
7336}
7337
7340 const LoopInfo *LI, unsigned MaxLookup) {
7343 Worklist.push_back(V);
7344 do {
7345 const Value *P = Worklist.pop_back_val();
7346 P = getUnderlyingObject(P, MaxLookup);
7347
7348 if (!Visited.insert(P).second)
7349 continue;
7350
7351 if (auto *SI = dyn_cast<SelectInst>(P)) {
7352 Worklist.push_back(SI->getTrueValue());
7353 Worklist.push_back(SI->getFalseValue());
7354 continue;
7355 }
7356
7357 if (auto *PN = dyn_cast<PHINode>(P)) {
7358 // If this PHI changes the underlying object in every iteration of the
7359 // loop, don't look through it. Consider:
7360 // int **A;
7361 // for (i) {
7362 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7363 // Curr = A[i];
7364 // *Prev, *Curr;
7365 //
7366 // Prev is tracking Curr one iteration behind so they refer to different
7367 // underlying objects.
7368 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7370 append_range(Worklist, PN->incoming_values());
7371 else
7372 Objects.push_back(P);
7373 continue;
7374 }
7375
7376 Objects.push_back(P);
7377 } while (!Worklist.empty());
7378}
7379
7381 bool MustPreserveProvenance) {
7382 const unsigned MaxVisited = 8;
7383
7386 Worklist.push_back(V);
7387 const Value *Object = nullptr;
7388 // Used as fallback if we can't find a common underlying object through
7389 // recursion.
7390 bool First = true;
7391 const Value *FirstObject =
7392 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7393 do {
7394 const Value *P = Worklist.pop_back_val();
7395 P = First ? FirstObject
7397 MustPreserveProvenance);
7398 First = false;
7399
7400 if (!Visited.insert(P).second)
7401 continue;
7402
7403 if (Visited.size() == MaxVisited)
7404 return FirstObject;
7405
7406 if (auto *SI = dyn_cast<SelectInst>(P)) {
7407 Worklist.push_back(SI->getTrueValue());
7408 Worklist.push_back(SI->getFalseValue());
7409 continue;
7410 }
7411
7412 if (auto *PN = dyn_cast<PHINode>(P)) {
7413 append_range(Worklist, PN->incoming_values());
7414 continue;
7415 }
7416
7417 if (!Object)
7418 Object = P;
7419 else if (Object != P)
7420 return FirstObject;
7421 } while (!Worklist.empty());
7422
7423 return Object ? Object : FirstObject;
7424}
7425
7426/// This is the function that does the work of looking through basic
7427/// ptrtoint+arithmetic+inttoptr sequences.
7428static const Value *getUnderlyingObjectFromInt(const Value *V) {
7429 do {
7430 if (const Operator *U = dyn_cast<Operator>(V)) {
7431 // If we find a ptrtoint, we can transfer control back to the
7432 // regular getUnderlyingObjectFromInt.
7433 if (U->getOpcode() == Instruction::PtrToInt)
7434 return U->getOperand(0);
7435 // If we find an add of a constant, a multiplied value, or a phi, it's
7436 // likely that the other operand will lead us to the base
7437 // object. We don't have to worry about the case where the
7438 // object address is somehow being computed by the multiply,
7439 // because our callers only care when the result is an
7440 // identifiable object.
7441 if (U->getOpcode() != Instruction::Add ||
7442 (!isa<ConstantInt>(U->getOperand(1)) &&
7443 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7444 !isa<PHINode>(U->getOperand(1))))
7445 return V;
7446 V = U->getOperand(0);
7447 } else {
7448 return V;
7449 }
7450 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7451 } while (true);
7452}
7453
7454/// This is a wrapper around getUnderlyingObjects and adds support for basic
7455/// ptrtoint+arithmetic+inttoptr sequences.
7456/// It returns false if unidentified object is found in getUnderlyingObjects.
7458 SmallVectorImpl<Value *> &Objects) {
7460 SmallVector<const Value *, 4> Working(1, V);
7461 bool AllObjectsIdentified = true;
7462 do {
7463 V = Working.pop_back_val();
7464
7466 getUnderlyingObjects(V, Objs);
7467
7468 for (const Value *V : Objs) {
7469 if (!Visited.insert(V).second)
7470 continue;
7471 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7472 const Value *O =
7473 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7474 if (O->getType()->isPointerTy()) {
7475 Working.push_back(O);
7476 continue;
7477 }
7478 }
7479 AllObjectsIdentified &= isIdentifiedObject(V);
7480 Objects.push_back(const_cast<Value *>(V));
7481 }
7482 } while (!Working.empty());
7483 return AllObjectsIdentified;
7484}
7485
7487 AllocaInst *Result = nullptr;
7489 SmallVector<Value *, 4> Worklist;
7490
7491 auto AddWork = [&](Value *V) {
7492 if (Visited.insert(V).second)
7493 Worklist.push_back(V);
7494 };
7495
7496 AddWork(V);
7497 do {
7498 V = Worklist.pop_back_val();
7499 assert(Visited.count(V));
7500
7501 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7502 if (Result && Result != AI)
7503 return nullptr;
7504 Result = AI;
7505 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7506 AddWork(CI->getOperand(0));
7507 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7508 for (Value *IncValue : PN->incoming_values())
7509 AddWork(IncValue);
7510 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7511 AddWork(SI->getTrueValue());
7512 AddWork(SI->getFalseValue());
7514 if (OffsetZero && !GEP->hasAllZeroIndices())
7515 return nullptr;
7516 AddWork(GEP->getPointerOperand());
7517 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7518 Value *Returned = CB->getReturnedArgOperand();
7519 if (Returned)
7520 AddWork(Returned);
7521 else
7522 return nullptr;
7523 } else {
7524 return nullptr;
7525 }
7526 } while (!Worklist.empty());
7527
7528 return Result;
7529}
7530
7532 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7533 for (const User *U : V->users()) {
7535 if (!II)
7536 return false;
7537
7538 if (AllowLifetime && II->isLifetimeStartOrEnd())
7539 continue;
7540
7541 if (AllowDroppable && II->isDroppable())
7542 continue;
7543
7544 return false;
7545 }
7546 return true;
7547}
7548
7551 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7552}
7555 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7556}
7557
7559 if (auto *II = dyn_cast<IntrinsicInst>(I))
7560 return isTriviallyVectorizable(II->getIntrinsicID());
7561 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7562 return (!Shuffle || Shuffle->isSelect()) &&
7564}
7565
7567 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7568 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7569 bool IgnoreUBImplyingAttrs) {
7570 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7571 AC, DT, TLI, UseVariableInfo,
7572 IgnoreUBImplyingAttrs);
7573}
7574
7576 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7577 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7578 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7579#ifndef NDEBUG
7580 if (Inst->getOpcode() != Opcode) {
7581 // Check that the operands are actually compatible with the Opcode override.
7582 auto hasEqualReturnAndLeadingOperandTypes =
7583 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7584 if (Inst->getNumOperands() < NumLeadingOperands)
7585 return false;
7586 const Type *ExpectedType = Inst->getType();
7587 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7588 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7589 return false;
7590 return true;
7591 };
7593 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7594 assert(!Instruction::isUnaryOp(Opcode) ||
7595 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7596 }
7597#endif
7598
7599 switch (Opcode) {
7600 default:
7601 return true;
7602 case Instruction::UDiv:
7603 case Instruction::URem: {
7604 // x / y is undefined if y == 0.
7605 const APInt *V;
7606 if (match(Inst->getOperand(1), m_APInt(V)))
7607 return *V != 0;
7608 return false;
7609 }
7610 case Instruction::SDiv:
7611 case Instruction::SRem: {
7612 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7613 const APInt *Numerator, *Denominator;
7614 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7615 return false;
7616 // We cannot hoist this division if the denominator is 0.
7617 if (*Denominator == 0)
7618 return false;
7619 // It's safe to hoist if the denominator is not 0 or -1.
7620 if (!Denominator->isAllOnes())
7621 return true;
7622 // At this point we know that the denominator is -1. It is safe to hoist as
7623 // long we know that the numerator is not INT_MIN.
7624 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7625 return !Numerator->isMinSignedValue();
7626 // The numerator *might* be MinSignedValue.
7627 return false;
7628 }
7629 case Instruction::Load: {
7630 if (!UseVariableInfo)
7631 return false;
7632
7633 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7634 if (!LI)
7635 return false;
7636 if (mustSuppressSpeculation(*LI))
7637 return false;
7638 const DataLayout &DL = LI->getDataLayout();
7640 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7641 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7642 }
7643 case Instruction::Call: {
7644 auto *CI = dyn_cast<const CallInst>(Inst);
7645 if (!CI)
7646 return false;
7647 const Function *Callee = CI->getCalledFunction();
7648
7649 // The called function could have undefined behavior or side-effects, even
7650 // if marked readnone nounwind.
7651 if (!Callee || !Callee->isSpeculatable())
7652 return false;
7653 // Since the operands may be changed after hoisting, undefined behavior may
7654 // be triggered by some UB-implying attributes.
7655 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7656 }
7657 case Instruction::VAArg:
7658 case Instruction::Alloca:
7659 case Instruction::Invoke:
7660 case Instruction::CallBr:
7661 case Instruction::PHI:
7662 case Instruction::Store:
7663 case Instruction::Ret:
7664 case Instruction::UncondBr:
7665 case Instruction::CondBr:
7666 case Instruction::IndirectBr:
7667 case Instruction::Switch:
7668 case Instruction::Unreachable:
7669 case Instruction::Fence:
7670 case Instruction::AtomicRMW:
7671 case Instruction::AtomicCmpXchg:
7672 case Instruction::LandingPad:
7673 case Instruction::Resume:
7674 case Instruction::CatchSwitch:
7675 case Instruction::CatchPad:
7676 case Instruction::CatchRet:
7677 case Instruction::CleanupPad:
7678 case Instruction::CleanupRet:
7679 return false; // Misc instructions which have effects
7680 }
7681}
7682
7684 if (I.mayReadOrWriteMemory())
7685 // Memory dependency possible
7686 return true;
7688 // Can't move above a maythrow call or infinite loop. Or if an
7689 // inalloca alloca, above a stacksave call.
7690 return true;
7692 // 1) Can't reorder two inf-loop calls, even if readonly
7693 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7694 // safe to speculative execute. (Inverse of above)
7695 return true;
7696 return false;
7697}
7698
7699/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7713
7714/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7717 bool ForSigned,
7718 const SimplifyQuery &SQ) {
7719 ConstantRange CR1 =
7720 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7721 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7724 return CR1.intersectWith(CR2, RangeType);
7725}
7726
7728 const Value *RHS,
7729 const SimplifyQuery &SQ,
7730 bool IsNSW) {
7731 ConstantRange LHSRange =
7732 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7733 ConstantRange RHSRange =
7734 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7735
7736 // mul nsw of two non-negative numbers is also nuw.
7737 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7739
7740 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7741}
7742
7744 const Value *RHS,
7745 const SimplifyQuery &SQ) {
7746 // Multiplying n * m significant bits yields a result of n + m significant
7747 // bits. If the total number of significant bits does not exceed the
7748 // result bit width (minus 1), there is no overflow.
7749 // This means if we have enough leading sign bits in the operands
7750 // we can guarantee that the result does not overflow.
7751 // Ref: "Hacker's Delight" by Henry Warren
7752 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7753
7754 // Note that underestimating the number of sign bits gives a more
7755 // conservative answer.
7756 unsigned SignBits =
7757 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7758
7759 // First handle the easy case: if we have enough sign bits there's
7760 // definitely no overflow.
7761 if (SignBits > BitWidth + 1)
7763
7764 // There are two ambiguous cases where there can be no overflow:
7765 // SignBits == BitWidth + 1 and
7766 // SignBits == BitWidth
7767 // The second case is difficult to check, therefore we only handle the
7768 // first case.
7769 if (SignBits == BitWidth + 1) {
7770 // It overflows only when both arguments are negative and the true
7771 // product is exactly the minimum negative number.
7772 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7773 // For simplicity we just check if at least one side is not negative.
7774 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7775 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7776 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7778 }
7780}
7781
7784 const WithCache<const Value *> &RHS,
7785 const SimplifyQuery &SQ) {
7786 ConstantRange LHSRange =
7787 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7788 ConstantRange RHSRange =
7789 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7790 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7791}
7792
7793static OverflowResult
7796 const AddOperator *Add, const SimplifyQuery &SQ) {
7797 if (Add && Add->hasNoSignedWrap()) {
7799 }
7800
7801 // If LHS and RHS each have at least two sign bits, the addition will look
7802 // like
7803 //
7804 // XX..... +
7805 // YY.....
7806 //
7807 // If the carry into the most significant position is 0, X and Y can't both
7808 // be 1 and therefore the carry out of the addition is also 0.
7809 //
7810 // If the carry into the most significant position is 1, X and Y can't both
7811 // be 0 and therefore the carry out of the addition is also 1.
7812 //
7813 // Since the carry into the most significant position is always equal to
7814 // the carry out of the addition, there is no signed overflow.
7815 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7817
7818 ConstantRange LHSRange =
7819 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7820 ConstantRange RHSRange =
7821 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7822 OverflowResult OR =
7823 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7825 return OR;
7826
7827 // The remaining code needs Add to be available. Early returns if not so.
7828 if (!Add)
7830
7831 // If the sign of Add is the same as at least one of the operands, this add
7832 // CANNOT overflow. If this can be determined from the known bits of the
7833 // operands the above signedAddMayOverflow() check will have already done so.
7834 // The only other way to improve on the known bits is from an assumption, so
7835 // call computeKnownBitsFromContext() directly.
7836 bool LHSOrRHSKnownNonNegative =
7837 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7838 bool LHSOrRHSKnownNegative =
7839 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7840 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7841 KnownBits AddKnown(LHSRange.getBitWidth());
7842 computeKnownBitsFromContext(Add, AddKnown, SQ);
7843 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7844 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7846 }
7847
7849}
7850
7852 const Value *RHS,
7853 const SimplifyQuery &SQ) {
7854 // X - (X % ?)
7855 // The remainder of a value can't have greater magnitude than itself,
7856 // so the subtraction can't overflow.
7857
7858 // X - (X -nuw ?)
7859 // In the minimal case, this would simplify to "?", so there's no subtract
7860 // at all. But if this analysis is used to peek through casts, for example,
7861 // then determining no-overflow may allow other transforms.
7862
7863 // TODO: There are other patterns like this.
7864 // See simplifyICmpWithBinOpOnLHS() for candidates.
7865 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7866 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7867 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7869
7870 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7871 SQ.DL)) {
7872 if (*C)
7875 }
7876
7877 ConstantRange LHSRange =
7878 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7879 ConstantRange RHSRange =
7880 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7881 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7882}
7883
7885 const Value *RHS,
7886 const SimplifyQuery &SQ) {
7887 // X - (X % ?)
7888 // The remainder of a value can't have greater magnitude than itself,
7889 // so the subtraction can't overflow.
7890
7891 // X - (X -nsw ?)
7892 // In the minimal case, this would simplify to "?", so there's no subtract
7893 // at all. But if this analysis is used to peek through casts, for example,
7894 // then determining no-overflow may allow other transforms.
7895 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7896 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7897 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7899
7900 // If LHS and RHS each have at least two sign bits, the subtraction
7901 // cannot overflow.
7902 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7904
7905 ConstantRange LHSRange =
7906 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7907 ConstantRange RHSRange =
7908 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7909 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7910}
7911
7913 const DominatorTree &DT) {
7914 SmallVector<const CondBrInst *, 2> GuardingBranches;
7916
7917 for (const User *U : WO->users()) {
7918 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7919 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7920
7921 if (EVI->getIndices()[0] == 0)
7922 Results.push_back(EVI);
7923 else {
7924 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7925
7926 for (const auto *U : EVI->users())
7927 if (const auto *B = dyn_cast<CondBrInst>(U))
7928 GuardingBranches.push_back(B);
7929 }
7930 } else {
7931 // We are using the aggregate directly in a way we don't want to analyze
7932 // here (storing it to a global, say).
7933 return false;
7934 }
7935 }
7936
7937 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7938 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7939
7940 // Check if all users of the add are provably no-wrap.
7941 for (const auto *Result : Results) {
7942 // If the extractvalue itself is not executed on overflow, the we don't
7943 // need to check each use separately, since domination is transitive.
7944 if (DT.dominates(NoWrapEdge, Result->getParent()))
7945 continue;
7946
7947 for (const auto &RU : Result->uses())
7948 if (!DT.dominates(NoWrapEdge, RU))
7949 return false;
7950 }
7951
7952 return true;
7953 };
7954
7955 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7956}
7957
7958/// Shifts return poison if shiftwidth is larger than the bitwidth.
7959static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7960 auto *C = dyn_cast<Constant>(ShiftAmount);
7961 if (!C)
7962 return false;
7963
7964 // Shifts return poison if shiftwidth is larger than the bitwidth.
7966 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7967 unsigned NumElts = FVTy->getNumElements();
7968 for (unsigned i = 0; i < NumElts; ++i)
7969 ShiftAmounts.push_back(C->getAggregateElement(i));
7970 } else if (isa<ScalableVectorType>(C->getType()))
7971 return false; // Can't tell, just return false to be safe
7972 else
7973 ShiftAmounts.push_back(C);
7974
7975 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7976 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7977 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7978 });
7979
7980 return Safe;
7981}
7982
7984 bool ConsiderFlagsAndMetadata) {
7985
7986 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7987 Op->hasPoisonGeneratingAnnotations())
7988 return true;
7989
7990 unsigned Opcode = Op->getOpcode();
7991
7992 // Check whether opcode is a poison/undef-generating operation
7993 switch (Opcode) {
7994 case Instruction::Shl:
7995 case Instruction::AShr:
7996 case Instruction::LShr:
7997 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7998 case Instruction::FPToSI:
7999 case Instruction::FPToUI:
8000 // fptosi/ui yields poison if the resulting value does not fit in the
8001 // destination type.
8002 return true;
8003 case Instruction::Call:
8004 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8005 switch (II->getIntrinsicID()) {
8006 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8007 case Intrinsic::ctlz:
8008 case Intrinsic::cttz:
8009 case Intrinsic::abs:
8010 // We're not considering flags so it is safe to just return false.
8011 return false;
8012 case Intrinsic::sshl_sat:
8013 case Intrinsic::ushl_sat:
8014 if (!includesPoison(Kind) ||
8015 shiftAmountKnownInRange(II->getArgOperand(1)))
8016 return false;
8017 break;
8018 }
8019 }
8020 [[fallthrough]];
8021 case Instruction::CallBr:
8022 case Instruction::Invoke: {
8023 const auto *CB = cast<CallBase>(Op);
8024 return !CB->hasRetAttr(Attribute::NoUndef) &&
8025 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8026 }
8027 case Instruction::InsertElement:
8028 case Instruction::ExtractElement: {
8029 // If index exceeds the length of the vector, it returns poison
8030 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8031 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8032 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8033 if (includesPoison(Kind))
8034 return !Idx ||
8035 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8036 return false;
8037 }
8038 case Instruction::ShuffleVector: {
8040 ? cast<ConstantExpr>(Op)->getShuffleMask()
8041 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8042 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8043 }
8044 case Instruction::FNeg:
8045 case Instruction::PHI:
8046 case Instruction::Select:
8047 case Instruction::ExtractValue:
8048 case Instruction::InsertValue:
8049 case Instruction::Freeze:
8050 case Instruction::ICmp:
8051 case Instruction::FCmp:
8052 case Instruction::GetElementPtr:
8053 return false;
8054 case Instruction::AddrSpaceCast:
8055 return true;
8056 default: {
8057 const auto *CE = dyn_cast<ConstantExpr>(Op);
8058 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8059 return false;
8060 else if (Instruction::isBinaryOp(Opcode))
8061 return false;
8062 // Be conservative and return true.
8063 return true;
8064 }
8065 }
8066}
8067
8069 bool ConsiderFlagsAndMetadata) {
8070 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8071 ConsiderFlagsAndMetadata);
8072}
8073
8074bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8075 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8076 ConsiderFlagsAndMetadata);
8077}
8078
8079static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8080 unsigned Depth) {
8081 if (ValAssumedPoison == V)
8082 return true;
8083
8084 const unsigned MaxDepth = 2;
8085 if (Depth >= MaxDepth)
8086 return false;
8087
8088 if (const auto *I = dyn_cast<Instruction>(V)) {
8089 if (any_of(I->operands(), [=](const Use &Op) {
8090 return propagatesPoison(Op) &&
8091 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8092 }))
8093 return true;
8094
8095 // V = extractvalue V0, idx
8096 // V2 = extractvalue V0, idx2
8097 // V0's elements are all poison or not. (e.g., add_with_overflow)
8098 const WithOverflowInst *II;
8100 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8101 llvm::is_contained(II->args(), ValAssumedPoison)))
8102 return true;
8103 }
8104 return false;
8105}
8106
8107static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8108 unsigned Depth) {
8109 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8110 return true;
8111
8112 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8113 return true;
8114
8115 const unsigned MaxDepth = 2;
8116 if (Depth >= MaxDepth)
8117 return false;
8118
8119 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8120 if (I && !canCreatePoison(cast<Operator>(I))) {
8121 return all_of(I->operands(), [=](const Value *Op) {
8122 return impliesPoison(Op, V, Depth + 1);
8123 });
8124 }
8125 return false;
8126}
8127
8128bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8129 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8130}
8131
8132static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8133
8135 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8136 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8138 return false;
8139
8140 if (isa<MetadataAsValue>(V))
8141 return false;
8142
8143 if (const auto *A = dyn_cast<Argument>(V)) {
8144 if (A->hasAttribute(Attribute::NoUndef) ||
8145 A->hasAttribute(Attribute::Dereferenceable) ||
8146 A->hasAttribute(Attribute::DereferenceableOrNull))
8147 return true;
8148 }
8149
8150 if (auto *C = dyn_cast<Constant>(V)) {
8151 if (isa<PoisonValue>(C))
8152 return !includesPoison(Kind);
8153
8154 if (isa<UndefValue>(C))
8155 return !includesUndef(Kind);
8156
8159 return true;
8160
8161 if (C->getType()->isVectorTy()) {
8162 if (isa<ConstantExpr>(C)) {
8163 // Scalable vectors can use a ConstantExpr to build a splat.
8164 if (Constant *SplatC = C->getSplatValue())
8165 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8166 return true;
8167 } else {
8168 if (includesUndef(Kind) && C->containsUndefElement())
8169 return false;
8170 if (includesPoison(Kind) && C->containsPoisonElement())
8171 return false;
8172 return !C->containsConstantExpression();
8173 }
8174 }
8175 }
8176
8177 // Strip cast operations from a pointer value.
8178 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8179 // inbounds with zero offset. To guarantee that the result isn't poison, the
8180 // stripped pointer is checked as it has to be pointing into an allocated
8181 // object or be null `null` to ensure `inbounds` getelement pointers with a
8182 // zero offset could not produce poison.
8183 // It can strip off addrspacecast that do not change bit representation as
8184 // well. We believe that such addrspacecast is equivalent to no-op.
8185 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8186 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8187 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8188 return true;
8189
8190 auto OpCheck = [&](const Value *V) {
8191 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8192 };
8193
8194 if (auto *Opr = dyn_cast<Operator>(V)) {
8195 // If the value is a freeze instruction, then it can never
8196 // be undef or poison.
8197 if (isa<FreezeInst>(V))
8198 return true;
8199
8200 if (const auto *CB = dyn_cast<CallBase>(V)) {
8201 if (CB->hasRetAttr(Attribute::NoUndef) ||
8202 CB->hasRetAttr(Attribute::Dereferenceable) ||
8203 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8204 return true;
8205 }
8206
8207 if (!::canCreateUndefOrPoison(Opr, Kind,
8208 /*ConsiderFlagsAndMetadata=*/true)) {
8209 if (const auto *PN = dyn_cast<PHINode>(V)) {
8210 unsigned Num = PN->getNumIncomingValues();
8211 bool IsWellDefined = true;
8212 for (unsigned i = 0; i < Num; ++i) {
8213 if (PN == PN->getIncomingValue(i))
8214 continue;
8215 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8216 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8217 DT, Depth + 1, Kind)) {
8218 IsWellDefined = false;
8219 break;
8220 }
8221 }
8222 if (IsWellDefined)
8223 return true;
8224 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8225 : nullptr) {
8226 // For splats we only need to check the value being splatted.
8227 if (OpCheck(Splat))
8228 return true;
8229 } else if (all_of(Opr->operands(), OpCheck))
8230 return true;
8231 }
8232 }
8233
8234 if (auto *I = dyn_cast<LoadInst>(V))
8235 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8236 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8237 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8238 return true;
8239
8241 return true;
8242
8243 // CxtI may be null or a cloned instruction.
8244 if (!CtxI || !CtxI->getParent() || !DT)
8245 return false;
8246
8247 auto *DNode = DT->getNode(CtxI->getParent());
8248 if (!DNode)
8249 // Unreachable block
8250 return false;
8251
8252 // If V is used as a branch condition before reaching CtxI, V cannot be
8253 // undef or poison.
8254 // br V, BB1, BB2
8255 // BB1:
8256 // CtxI ; V cannot be undef or poison here
8257 auto *Dominator = DNode->getIDom();
8258 // This check is purely for compile time reasons: we can skip the IDom walk
8259 // if what we are checking for includes undef and the value is not an integer.
8260 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8261 while (Dominator) {
8262 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8263
8264 Value *Cond = nullptr;
8265 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8266 Cond = BI->getCondition();
8267 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8268 Cond = SI->getCondition();
8269 }
8270
8271 if (Cond) {
8272 if (Cond == V)
8273 return true;
8274 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8275 // For poison, we can analyze further
8276 auto *Opr = cast<Operator>(Cond);
8277 if (any_of(Opr->operands(), [V](const Use &U) {
8278 return V == U && propagatesPoison(U);
8279 }))
8280 return true;
8281 }
8282 }
8283
8284 Dominator = Dominator->getIDom();
8285 }
8286
8287 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8288 return true;
8289
8290 return false;
8291}
8292
8294 const Instruction *CtxI,
8295 const DominatorTree *DT,
8296 unsigned Depth) {
8297 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8299}
8300
8302 const Instruction *CtxI,
8303 const DominatorTree *DT, unsigned Depth) {
8304 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8306}
8307
8309 const Instruction *CtxI,
8310 const DominatorTree *DT, unsigned Depth) {
8311 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8313}
8314
8315/// Return true if undefined behavior would provably be executed on the path to
8316/// OnPathTo if Root produced a posion result. Note that this doesn't say
8317/// anything about whether OnPathTo is actually executed or whether Root is
8318/// actually poison. This can be used to assess whether a new use of Root can
8319/// be added at a location which is control equivalent with OnPathTo (such as
8320/// immediately before it) without introducing UB which didn't previously
8321/// exist. Note that a false result conveys no information.
8323 Instruction *OnPathTo,
8324 DominatorTree *DT) {
8325 // Basic approach is to assume Root is poison, propagate poison forward
8326 // through all users we can easily track, and then check whether any of those
8327 // users are provable UB and must execute before out exiting block might
8328 // exit.
8329
8330 // The set of all recursive users we've visited (which are assumed to all be
8331 // poison because of said visit)
8334 Worklist.push_back(Root);
8335 while (!Worklist.empty()) {
8336 const Instruction *I = Worklist.pop_back_val();
8337
8338 // If we know this must trigger UB on a path leading our target.
8339 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8340 return true;
8341
8342 // If we can't analyze propagation through this instruction, just skip it
8343 // and transitive users. Safe as false is a conservative result.
8344 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8345 return KnownPoison.contains(U) && propagatesPoison(U);
8346 }))
8347 continue;
8348
8349 if (KnownPoison.insert(I).second)
8350 for (const User *User : I->users())
8351 Worklist.push_back(cast<Instruction>(User));
8352 }
8353
8354 // Might be non-UB, or might have a path we couldn't prove must execute on
8355 // way to exiting bb.
8356 return false;
8357}
8358
8360 const SimplifyQuery &SQ) {
8361 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8362 Add, SQ);
8363}
8364
8367 const WithCache<const Value *> &RHS,
8368 const SimplifyQuery &SQ) {
8369 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8370}
8371
8373 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8374 // of time because it's possible for another thread to interfere with it for an
8375 // arbitrary length of time, but programs aren't allowed to rely on that.
8376
8377 // If there is no successor, then execution can't transfer to it.
8378 if (isa<ReturnInst>(I))
8379 return false;
8381 return false;
8382
8383 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8384 // Instruction::willReturn.
8385 //
8386 // FIXME: Move this check into Instruction::willReturn.
8387 if (isa<CatchPadInst>(I)) {
8388 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8389 default:
8390 // A catchpad may invoke exception object constructors and such, which
8391 // in some languages can be arbitrary code, so be conservative by default.
8392 return false;
8394 // For CoreCLR, it just involves a type test.
8395 return true;
8396 }
8397 }
8398
8399 // An instruction that returns without throwing must transfer control flow
8400 // to a successor.
8401 return !I->mayThrow() && I->willReturn();
8402}
8403
8405 // TODO: This is slightly conservative for invoke instruction since exiting
8406 // via an exception *is* normal control for them.
8407 for (const Instruction &I : *BB)
8409 return false;
8410 return true;
8411}
8412
8419
8422 assert(ScanLimit && "scan limit must be non-zero");
8423 for (const Instruction &I : Range) {
8424 if (--ScanLimit == 0)
8425 return false;
8427 return false;
8428 }
8429 return true;
8430}
8431
8433 const Loop *L) {
8434 // The loop header is guaranteed to be executed for every iteration.
8435 //
8436 // FIXME: Relax this constraint to cover all basic blocks that are
8437 // guaranteed to be executed at every iteration.
8438 if (I->getParent() != L->getHeader()) return false;
8439
8440 for (const Instruction &LI : *L->getHeader()) {
8441 if (&LI == I) return true;
8442 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8443 }
8444 llvm_unreachable("Instruction not contained in its own parent basic block.");
8445}
8446
8448 switch (IID) {
8449 // TODO: Add more intrinsics.
8450 case Intrinsic::sadd_with_overflow:
8451 case Intrinsic::ssub_with_overflow:
8452 case Intrinsic::smul_with_overflow:
8453 case Intrinsic::uadd_with_overflow:
8454 case Intrinsic::usub_with_overflow:
8455 case Intrinsic::umul_with_overflow:
8456 // If an input is a vector containing a poison element, the
8457 // two output vectors (calculated results, overflow bits)'
8458 // corresponding lanes are poison.
8459 return true;
8460 case Intrinsic::ctpop:
8461 case Intrinsic::ctlz:
8462 case Intrinsic::cttz:
8463 case Intrinsic::abs:
8464 case Intrinsic::smax:
8465 case Intrinsic::smin:
8466 case Intrinsic::umax:
8467 case Intrinsic::umin:
8468 case Intrinsic::scmp:
8469 case Intrinsic::is_fpclass:
8470 case Intrinsic::ptrmask:
8471 case Intrinsic::ucmp:
8472 case Intrinsic::bitreverse:
8473 case Intrinsic::bswap:
8474 case Intrinsic::sadd_sat:
8475 case Intrinsic::ssub_sat:
8476 case Intrinsic::sshl_sat:
8477 case Intrinsic::uadd_sat:
8478 case Intrinsic::usub_sat:
8479 case Intrinsic::ushl_sat:
8480 case Intrinsic::smul_fix:
8481 case Intrinsic::smul_fix_sat:
8482 case Intrinsic::umul_fix:
8483 case Intrinsic::umul_fix_sat:
8484 case Intrinsic::pow:
8485 case Intrinsic::powi:
8486 case Intrinsic::sin:
8487 case Intrinsic::sinh:
8488 case Intrinsic::cos:
8489 case Intrinsic::cosh:
8490 case Intrinsic::sincos:
8491 case Intrinsic::sincospi:
8492 case Intrinsic::tan:
8493 case Intrinsic::tanh:
8494 case Intrinsic::asin:
8495 case Intrinsic::acos:
8496 case Intrinsic::atan:
8497 case Intrinsic::atan2:
8498 case Intrinsic::canonicalize:
8499 case Intrinsic::sqrt:
8500 case Intrinsic::exp:
8501 case Intrinsic::exp2:
8502 case Intrinsic::exp10:
8503 case Intrinsic::log:
8504 case Intrinsic::log2:
8505 case Intrinsic::log10:
8506 case Intrinsic::modf:
8507 case Intrinsic::floor:
8508 case Intrinsic::ceil:
8509 case Intrinsic::trunc:
8510 case Intrinsic::rint:
8511 case Intrinsic::nearbyint:
8512 case Intrinsic::round:
8513 case Intrinsic::roundeven:
8514 case Intrinsic::lrint:
8515 case Intrinsic::llrint:
8516 case Intrinsic::fshl:
8517 case Intrinsic::fshr:
8518 case Intrinsic::frexp:
8519 case Intrinsic::get_active_lane_mask:
8520 return true;
8521 default:
8522 return false;
8523 }
8524}
8525
8526bool llvm::propagatesPoison(const Use &PoisonOp) {
8527 const Operator *I = cast<Operator>(PoisonOp.getUser());
8528 switch (I->getOpcode()) {
8529 case Instruction::Freeze:
8530 case Instruction::PHI:
8531 case Instruction::Invoke:
8532 return false;
8533 case Instruction::Select:
8534 return PoisonOp.getOperandNo() == 0;
8535 case Instruction::Call:
8536 if (auto *II = dyn_cast<IntrinsicInst>(I))
8537 return intrinsicPropagatesPoison(II->getIntrinsicID());
8538 return false;
8539 case Instruction::ICmp:
8540 case Instruction::FCmp:
8541 case Instruction::GetElementPtr:
8542 return true;
8543 default:
8545 return true;
8546
8547 // Be conservative and return false.
8548 return false;
8549 }
8550}
8551
8552/// Enumerates all operands of \p I that are guaranteed to not be undef or
8553/// poison. If the callback \p Handle returns true, stop processing and return
8554/// true. Otherwise, return false.
8555template <typename CallableT>
8557 const CallableT &Handle) {
8558 switch (I->getOpcode()) {
8559 case Instruction::Store:
8560 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8561 return true;
8562 break;
8563
8564 case Instruction::Load:
8565 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8566 return true;
8567 break;
8568
8569 // Since dereferenceable attribute imply noundef, atomic operations
8570 // also implicitly have noundef pointers too
8571 case Instruction::AtomicCmpXchg:
8573 return true;
8574 break;
8575
8576 case Instruction::AtomicRMW:
8577 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8578 return true;
8579 break;
8580
8581 case Instruction::Call:
8582 case Instruction::Invoke: {
8583 const CallBase *CB = cast<CallBase>(I);
8584 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8585 return true;
8586 for (unsigned i = 0; i < CB->arg_size(); ++i)
8587 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8588 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8589 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8590 Handle(CB->getArgOperand(i)))
8591 return true;
8592 break;
8593 }
8594 case Instruction::Ret:
8595 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8596 Handle(I->getOperand(0)))
8597 return true;
8598 break;
8599 case Instruction::Switch:
8600 if (Handle(cast<SwitchInst>(I)->getCondition()))
8601 return true;
8602 break;
8603 case Instruction::CondBr:
8604 if (Handle(cast<CondBrInst>(I)->getCondition()))
8605 return true;
8606 break;
8607 default:
8608 break;
8609 }
8610
8611 return false;
8612}
8613
8614/// Enumerates all operands of \p I that are guaranteed to not be poison.
8615template <typename CallableT>
8617 const CallableT &Handle) {
8618 if (handleGuaranteedWellDefinedOps(I, Handle))
8619 return true;
8620 switch (I->getOpcode()) {
8621 // Divisors of these operations are allowed to be partially undef.
8622 case Instruction::UDiv:
8623 case Instruction::SDiv:
8624 case Instruction::URem:
8625 case Instruction::SRem:
8626 return Handle(I->getOperand(1));
8627 default:
8628 return false;
8629 }
8630}
8631
8633 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8635 I, [&](const Value *V) { return KnownPoison.count(V); });
8636}
8637
8639 bool PoisonOnly) {
8640 // We currently only look for uses of values within the same basic
8641 // block, as that makes it easier to guarantee that the uses will be
8642 // executed given that Inst is executed.
8643 //
8644 // FIXME: Expand this to consider uses beyond the same basic block. To do
8645 // this, look out for the distinction between post-dominance and strong
8646 // post-dominance.
8647 const BasicBlock *BB = nullptr;
8649 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8650 BB = Inst->getParent();
8651 Begin = Inst->getIterator();
8652 Begin++;
8653 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8654 if (Arg->getParent()->isDeclaration())
8655 return false;
8656 BB = &Arg->getParent()->getEntryBlock();
8657 Begin = BB->begin();
8658 } else {
8659 return false;
8660 }
8661
8662 // Limit number of instructions we look at, to avoid scanning through large
8663 // blocks. The current limit is chosen arbitrarily.
8664 unsigned ScanLimit = 32;
8665 BasicBlock::const_iterator End = BB->end();
8666
8667 if (!PoisonOnly) {
8668 // Since undef does not propagate eagerly, be conservative & just check
8669 // whether a value is directly passed to an instruction that must take
8670 // well-defined operands.
8671
8672 for (const auto &I : make_range(Begin, End)) {
8673 if (--ScanLimit == 0)
8674 break;
8675
8676 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8677 return WellDefinedOp == V;
8678 }))
8679 return true;
8680
8682 break;
8683 }
8684 return false;
8685 }
8686
8687 // Set of instructions that we have proved will yield poison if Inst
8688 // does.
8689 SmallPtrSet<const Value *, 16> YieldsPoison;
8691
8692 YieldsPoison.insert(V);
8693 Visited.insert(BB);
8694
8695 while (true) {
8696 for (const auto &I : make_range(Begin, End)) {
8697 if (--ScanLimit == 0)
8698 return false;
8699 if (mustTriggerUB(&I, YieldsPoison))
8700 return true;
8702 return false;
8703
8704 // If an operand is poison and propagates it, mark I as yielding poison.
8705 for (const Use &Op : I.operands()) {
8706 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8707 YieldsPoison.insert(&I);
8708 break;
8709 }
8710 }
8711
8712 // Special handling for select, which returns poison if its operand 0 is
8713 // poison (handled in the loop above) *or* if both its true/false operands
8714 // are poison (handled here).
8715 if (I.getOpcode() == Instruction::Select &&
8716 YieldsPoison.count(I.getOperand(1)) &&
8717 YieldsPoison.count(I.getOperand(2))) {
8718 YieldsPoison.insert(&I);
8719 }
8720 }
8721
8722 BB = BB->getSingleSuccessor();
8723 if (!BB || !Visited.insert(BB).second)
8724 break;
8725
8726 Begin = BB->getFirstNonPHIIt();
8727 End = BB->end();
8728 }
8729 return false;
8730}
8731
8733 return ::programUndefinedIfUndefOrPoison(Inst, false);
8734}
8735
8737 return ::programUndefinedIfUndefOrPoison(Inst, true);
8738}
8739
8740static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8741 if (FMF.noNaNs())
8742 return true;
8743
8744 if (auto *C = dyn_cast<ConstantFP>(V))
8745 return !C->isNaN();
8746
8747 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8748 if (!C->getElementType()->isFloatingPointTy())
8749 return false;
8750 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8751 if (C->getElementAsAPFloat(I).isNaN())
8752 return false;
8753 }
8754 return true;
8755 }
8756
8758 return true;
8759
8760 return false;
8761}
8762
8763static bool isKnownNonZero(const Value *V) {
8764 if (auto *C = dyn_cast<ConstantFP>(V))
8765 return !C->isZero();
8766
8767 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8768 if (!C->getElementType()->isFloatingPointTy())
8769 return false;
8770 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8771 if (C->getElementAsAPFloat(I).isZero())
8772 return false;
8773 }
8774 return true;
8775 }
8776
8777 return false;
8778}
8779
8780/// Match clamp pattern for float types without care about NaNs or signed zeros.
8781/// Given non-min/max outer cmp/select from the clamp pattern this
8782/// function recognizes if it can be substitued by a "canonical" min/max
8783/// pattern.
8785 Value *CmpLHS, Value *CmpRHS,
8786 Value *TrueVal, Value *FalseVal,
8787 Value *&LHS, Value *&RHS) {
8788 // Try to match
8789 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8790 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8791 // and return description of the outer Max/Min.
8792
8793 // First, check if select has inverse order:
8794 if (CmpRHS == FalseVal) {
8795 std::swap(TrueVal, FalseVal);
8796 Pred = CmpInst::getInversePredicate(Pred);
8797 }
8798
8799 // Assume success now. If there's no match, callers should not use these anyway.
8800 LHS = TrueVal;
8801 RHS = FalseVal;
8802
8803 const APFloat *FC1;
8804 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8805 return {SPF_UNKNOWN, SPNB_NA, false};
8806
8807 const APFloat *FC2;
8808 switch (Pred) {
8809 case CmpInst::FCMP_OLT:
8810 case CmpInst::FCMP_OLE:
8811 case CmpInst::FCMP_ULT:
8812 case CmpInst::FCMP_ULE:
8813 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8814 *FC1 < *FC2)
8815 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8816 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8817 *FC1 < *FC2)
8818 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8819 break;
8820 case CmpInst::FCMP_OGT:
8821 case CmpInst::FCMP_OGE:
8822 case CmpInst::FCMP_UGT:
8823 case CmpInst::FCMP_UGE:
8824 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8825 *FC1 > *FC2)
8826 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8827 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8828 *FC1 > *FC2)
8829 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8830 break;
8831 default:
8832 break;
8833 }
8834
8835 return {SPF_UNKNOWN, SPNB_NA, false};
8836}
8837
8838/// Recognize variations of:
8839/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8841 Value *CmpLHS, Value *CmpRHS,
8842 Value *TrueVal, Value *FalseVal) {
8843 // Swap the select operands and predicate to match the patterns below.
8844 if (CmpRHS != TrueVal) {
8845 Pred = ICmpInst::getSwappedPredicate(Pred);
8846 std::swap(TrueVal, FalseVal);
8847 }
8848 const APInt *C1;
8849 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8850 const APInt *C2;
8851 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8852 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8853 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8854 return {SPF_SMAX, SPNB_NA, false};
8855
8856 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8857 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8858 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8859 return {SPF_SMIN, SPNB_NA, false};
8860
8861 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8862 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8863 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8864 return {SPF_UMAX, SPNB_NA, false};
8865
8866 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8867 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8868 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8869 return {SPF_UMIN, SPNB_NA, false};
8870 }
8871 return {SPF_UNKNOWN, SPNB_NA, false};
8872}
8873
8874/// Recognize variations of:
8875/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8877 Value *CmpLHS, Value *CmpRHS,
8878 Value *TVal, Value *FVal,
8879 unsigned Depth) {
8880 // TODO: Allow FP min/max with nnan/nsz.
8881 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8882
8883 Value *A = nullptr, *B = nullptr;
8884 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8885 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8886 return {SPF_UNKNOWN, SPNB_NA, false};
8887
8888 Value *C = nullptr, *D = nullptr;
8889 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8890 if (L.Flavor != R.Flavor)
8891 return {SPF_UNKNOWN, SPNB_NA, false};
8892
8893 // We have something like: x Pred y ? min(a, b) : min(c, d).
8894 // Try to match the compare to the min/max operations of the select operands.
8895 // First, make sure we have the right compare predicate.
8896 switch (L.Flavor) {
8897 case SPF_SMIN:
8898 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8899 Pred = ICmpInst::getSwappedPredicate(Pred);
8900 std::swap(CmpLHS, CmpRHS);
8901 }
8902 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8903 break;
8904 return {SPF_UNKNOWN, SPNB_NA, false};
8905 case SPF_SMAX:
8906 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8907 Pred = ICmpInst::getSwappedPredicate(Pred);
8908 std::swap(CmpLHS, CmpRHS);
8909 }
8910 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8911 break;
8912 return {SPF_UNKNOWN, SPNB_NA, false};
8913 case SPF_UMIN:
8914 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8915 Pred = ICmpInst::getSwappedPredicate(Pred);
8916 std::swap(CmpLHS, CmpRHS);
8917 }
8918 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8919 break;
8920 return {SPF_UNKNOWN, SPNB_NA, false};
8921 case SPF_UMAX:
8922 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8923 Pred = ICmpInst::getSwappedPredicate(Pred);
8924 std::swap(CmpLHS, CmpRHS);
8925 }
8926 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8927 break;
8928 return {SPF_UNKNOWN, SPNB_NA, false};
8929 default:
8930 return {SPF_UNKNOWN, SPNB_NA, false};
8931 }
8932
8933 // If there is a common operand in the already matched min/max and the other
8934 // min/max operands match the compare operands (either directly or inverted),
8935 // then this is min/max of the same flavor.
8936
8937 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8938 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8939 if (D == B) {
8940 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8941 match(A, m_Not(m_Specific(CmpRHS)))))
8942 return {L.Flavor, SPNB_NA, false};
8943 }
8944 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8945 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8946 if (C == B) {
8947 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8948 match(A, m_Not(m_Specific(CmpRHS)))))
8949 return {L.Flavor, SPNB_NA, false};
8950 }
8951 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8952 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8953 if (D == A) {
8954 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8955 match(B, m_Not(m_Specific(CmpRHS)))))
8956 return {L.Flavor, SPNB_NA, false};
8957 }
8958 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8959 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8960 if (C == A) {
8961 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8962 match(B, m_Not(m_Specific(CmpRHS)))))
8963 return {L.Flavor, SPNB_NA, false};
8964 }
8965
8966 return {SPF_UNKNOWN, SPNB_NA, false};
8967}
8968
8969/// If the input value is the result of a 'not' op, constant integer, or vector
8970/// splat of a constant integer, return the bitwise-not source value.
8971/// TODO: This could be extended to handle non-splat vector integer constants.
8973 Value *NotV;
8974 if (match(V, m_Not(m_Value(NotV))))
8975 return NotV;
8976
8977 const APInt *C;
8978 if (match(V, m_APInt(C)))
8979 return ConstantInt::get(V->getType(), ~(*C));
8980
8981 return nullptr;
8982}
8983
8984/// Match non-obvious integer minimum and maximum sequences.
8986 Value *CmpLHS, Value *CmpRHS,
8987 Value *TrueVal, Value *FalseVal,
8988 Value *&LHS, Value *&RHS,
8989 unsigned Depth) {
8990 // Assume success. If there's no match, callers should not use these anyway.
8991 LHS = TrueVal;
8992 RHS = FalseVal;
8993
8994 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8996 return SPR;
8997
8998 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
9000 return SPR;
9001
9002 // Look through 'not' ops to find disguised min/max.
9003 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9004 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9005 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9006 switch (Pred) {
9007 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9008 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9009 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9010 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9011 default: break;
9012 }
9013 }
9014
9015 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9016 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9017 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9018 switch (Pred) {
9019 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9020 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9021 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9022 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9023 default: break;
9024 }
9025 }
9026
9027 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9028 return {SPF_UNKNOWN, SPNB_NA, false};
9029
9030 const APInt *C1;
9031 if (!match(CmpRHS, m_APInt(C1)))
9032 return {SPF_UNKNOWN, SPNB_NA, false};
9033
9034 // An unsigned min/max can be written with a signed compare.
9035 const APInt *C2;
9036 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9037 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9038 // Is the sign bit set?
9039 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9040 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9041 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9042 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9043
9044 // Is the sign bit clear?
9045 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9046 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9047 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9048 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9049 }
9050
9051 return {SPF_UNKNOWN, SPNB_NA, false};
9052}
9053
9054bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9055 bool AllowPoison) {
9056 assert(X && Y && "Invalid operand");
9057
9058 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9059 if (!match(X, m_Neg(m_Specific(Y))))
9060 return false;
9061
9062 auto *BO = cast<BinaryOperator>(X);
9063 if (NeedNSW && !BO->hasNoSignedWrap())
9064 return false;
9065
9066 auto *Zero = cast<Constant>(BO->getOperand(0));
9067 if (!AllowPoison && !Zero->isNullValue())
9068 return false;
9069
9070 return true;
9071 };
9072
9073 // X = -Y or Y = -X
9074 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9075 return true;
9076
9077 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9078 Value *A, *B;
9079 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9080 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9081 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9083}
9084
9085bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9086 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9087 Value *A, *B, *C;
9088 CmpPredicate Pred1, Pred2;
9089 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9090 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9091 return false;
9092
9093 // They must both have samesign flag or not.
9094 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9095 return false;
9096
9097 if (B == C)
9098 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9099
9100 // Try to infer the relationship from constant ranges.
9101 const APInt *RHSC1, *RHSC2;
9102 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9103 return false;
9104
9105 // Sign bits of two RHSCs should match.
9106 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9107 return false;
9108
9109 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9110 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9111
9112 return CR1.inverse() == CR2;
9113}
9114
9116 SelectPatternNaNBehavior NaNBehavior,
9117 bool Ordered) {
9118 switch (Pred) {
9119 default:
9120 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9121 case ICmpInst::ICMP_UGT:
9122 case ICmpInst::ICMP_UGE:
9123 return {SPF_UMAX, SPNB_NA, false};
9124 case ICmpInst::ICMP_SGT:
9125 case ICmpInst::ICMP_SGE:
9126 return {SPF_SMAX, SPNB_NA, false};
9127 case ICmpInst::ICMP_ULT:
9128 case ICmpInst::ICMP_ULE:
9129 return {SPF_UMIN, SPNB_NA, false};
9130 case ICmpInst::ICMP_SLT:
9131 case ICmpInst::ICMP_SLE:
9132 return {SPF_SMIN, SPNB_NA, false};
9133 case FCmpInst::FCMP_UGT:
9134 case FCmpInst::FCMP_UGE:
9135 case FCmpInst::FCMP_OGT:
9136 case FCmpInst::FCMP_OGE:
9137 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9138 case FCmpInst::FCMP_ULT:
9139 case FCmpInst::FCMP_ULE:
9140 case FCmpInst::FCMP_OLT:
9141 case FCmpInst::FCMP_OLE:
9142 return {SPF_FMINNUM, NaNBehavior, Ordered};
9143 }
9144}
9145
9146std::optional<std::pair<CmpPredicate, Constant *>>
9149 "Only for relational integer predicates.");
9150 if (isa<UndefValue>(C))
9151 return std::nullopt;
9152
9153 Type *Type = C->getType();
9154 bool IsSigned = ICmpInst::isSigned(Pred);
9155
9157 bool WillIncrement =
9158 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9159
9160 // Check if the constant operand can be safely incremented/decremented
9161 // without overflowing/underflowing.
9162 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9163 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9164 return false;
9165
9166 if (!Pred.hasSameSign())
9167 return true;
9168
9169 // Crossing the corresponding boundary in the other ordering changes the
9170 // sign bit, and therefore changes the poison domain.
9171 return WillIncrement ? !C->isMaxValue(!IsSigned)
9172 : !C->isMinValue(!IsSigned);
9173 };
9174
9175 Constant *SafeReplacementConstant = nullptr;
9176 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9177 // Bail out if the constant can't be safely incremented/decremented.
9178 if (!ConstantIsOk(CI))
9179 return std::nullopt;
9180 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9181 unsigned NumElts = FVTy->getNumElements();
9182 for (unsigned i = 0; i != NumElts; ++i) {
9183 Constant *Elt = C->getAggregateElement(i);
9184 if (!Elt)
9185 return std::nullopt;
9186
9187 if (isa<UndefValue>(Elt))
9188 continue;
9189
9190 // Bail out if we can't determine if this constant is min/max or if we
9191 // know that this constant is min/max.
9192 auto *CI = dyn_cast<ConstantInt>(Elt);
9193 if (!CI || !ConstantIsOk(CI))
9194 return std::nullopt;
9195
9196 if (!SafeReplacementConstant)
9197 SafeReplacementConstant = CI;
9198 }
9199 } else if (isa<VectorType>(C->getType())) {
9200 // Handle scalable splat
9201 Value *SplatC = C->getSplatValue();
9202 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9203 // Bail out if the constant can't be safely incremented/decremented.
9204 if (!CI || !ConstantIsOk(CI))
9205 return std::nullopt;
9206 } else {
9207 // ConstantExpr?
9208 return std::nullopt;
9209 }
9210
9211 // It may not be safe to change a compare predicate in the presence of
9212 // undefined elements, so replace those elements with the first safe constant
9213 // that we found.
9214 // TODO: in case of poison, it is safe; let's replace undefs only.
9215 if (C->containsUndefOrPoisonElement()) {
9216 assert(SafeReplacementConstant && "Replacement constant not set");
9217 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9218 }
9219
9221 Pred.hasSameSign());
9222
9223 // Increment or decrement the constant.
9224 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9225 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9226
9227 return std::make_pair(NewPred, NewC);
9228}
9229
9231 FastMathFlags FMF,
9232 Value *CmpLHS, Value *CmpRHS,
9233 Value *TrueVal, Value *FalseVal,
9234 Value *&LHS, Value *&RHS,
9235 unsigned Depth) {
9236 if (CmpInst::isFPPredicate(Pred)) {
9237 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9238 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9239 // purpose of identifying min/max. Disregard vector constants with undefined
9240 // elements because those can not be back-propagated for analysis.
9241 Value *OutputZeroVal = nullptr;
9242 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9243 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9244 OutputZeroVal = TrueVal;
9245 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9246 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9247 OutputZeroVal = FalseVal;
9248
9249 if (OutputZeroVal) {
9250 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9251 CmpLHS = OutputZeroVal;
9252 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9253 CmpRHS = OutputZeroVal;
9254 }
9255 }
9256
9257 LHS = CmpLHS;
9258 RHS = CmpRHS;
9259
9260 // Signed zero may return inconsistent results between implementations.
9261 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9262 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9263 // Therefore, we behave conservatively and only proceed if at least one of the
9264 // operands is known to not be zero or if we don't care about signed zero.
9265 if (CmpInst::isFPPredicate(Pred)) {
9266 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9267 !isKnownNonZero(CmpRHS))
9268 return {SPF_UNKNOWN, SPNB_NA, false};
9269 }
9270
9271 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9272 bool Ordered = false;
9273
9274 // When given one NaN and one non-NaN input:
9275 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9276 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9277 // ordered comparison fails), which could be NaN or non-NaN.
9278 // so here we discover exactly what NaN behavior is required/accepted.
9279 if (CmpInst::isFPPredicate(Pred)) {
9280 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9281 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9282
9283 if (LHSSafe && RHSSafe) {
9284 // Both operands are known non-NaN.
9285 NaNBehavior = SPNB_RETURNS_ANY;
9286 Ordered = CmpInst::isOrdered(Pred);
9287 } else if (CmpInst::isOrdered(Pred)) {
9288 // An ordered comparison will return false when given a NaN, so it
9289 // returns the RHS.
9290 Ordered = true;
9291 if (LHSSafe)
9292 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9293 NaNBehavior = SPNB_RETURNS_NAN;
9294 else if (RHSSafe)
9295 NaNBehavior = SPNB_RETURNS_OTHER;
9296 else
9297 // Completely unsafe.
9298 return {SPF_UNKNOWN, SPNB_NA, false};
9299 } else {
9300 Ordered = false;
9301 // An unordered comparison will return true when given a NaN, so it
9302 // returns the LHS.
9303 if (LHSSafe)
9304 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9305 NaNBehavior = SPNB_RETURNS_OTHER;
9306 else if (RHSSafe)
9307 NaNBehavior = SPNB_RETURNS_NAN;
9308 else
9309 // Completely unsafe.
9310 return {SPF_UNKNOWN, SPNB_NA, false};
9311 }
9312 }
9313
9314 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9315 std::swap(CmpLHS, CmpRHS);
9316 Pred = CmpInst::getSwappedPredicate(Pred);
9317 if (NaNBehavior == SPNB_RETURNS_NAN)
9318 NaNBehavior = SPNB_RETURNS_OTHER;
9319 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9320 NaNBehavior = SPNB_RETURNS_NAN;
9321 Ordered = !Ordered;
9322 }
9323
9324 // ([if]cmp X, Y) ? X : Y
9325 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9326 return getSelectPattern(Pred, NaNBehavior, Ordered);
9327
9328 if (isKnownNegation(TrueVal, FalseVal)) {
9329 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9330 // match against either LHS or sign-preserving operations on LHS, like
9331 // sext(LHS), or binary ops that do not wrap in signed sense.
9332 auto CmpLHSOrSExt =
9333 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9334 auto MaybeSExtOrMulCmpLHS =
9335 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9336 m_NSWShl(CmpLHSOrSExt, m_Value()));
9337 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9338 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9339 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9340 // Set the return values. If the compare uses the negated value (-X >s 0),
9341 // swap the return values because the negated value is always 'RHS'.
9342 LHS = TrueVal;
9343 RHS = FalseVal;
9344 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9345 std::swap(LHS, RHS);
9346
9347 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9348 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9349 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9350 return {SPF_ABS, SPNB_NA, false};
9351
9352 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9353 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9354 return {SPF_ABS, SPNB_NA, false};
9355
9356 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9357 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9358 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9359 return {SPF_NABS, SPNB_NA, false};
9360 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9361 // Set the return values. If the compare uses the negated value (-X >s 0),
9362 // swap the return values because the negated value is always 'RHS'.
9363 LHS = FalseVal;
9364 RHS = TrueVal;
9365 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9366 std::swap(LHS, RHS);
9367
9368 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9369 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9370 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9371 return {SPF_NABS, SPNB_NA, false};
9372
9373 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9374 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9375 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9376 return {SPF_ABS, SPNB_NA, false};
9377 }
9378 }
9379
9380 if (CmpInst::isIntPredicate(Pred))
9381 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9382
9383 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9384 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9385 // semantics than minNum. Be conservative in such case.
9386 if (NaNBehavior != SPNB_RETURNS_ANY ||
9387 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9388 !isKnownNonZero(CmpRHS)))
9389 return {SPF_UNKNOWN, SPNB_NA, false};
9390
9391 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9392}
9393
9395 Instruction::CastOps *CastOp) {
9396 const DataLayout &DL = CmpI->getDataLayout();
9397
9398 Constant *CastedTo = nullptr;
9399 switch (*CastOp) {
9400 case Instruction::ZExt:
9401 if (CmpI->isUnsigned())
9402 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9403 break;
9404 case Instruction::SExt:
9405 if (CmpI->isSigned())
9406 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9407 break;
9408 case Instruction::Trunc:
9409 Constant *CmpConst;
9410 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9411 CmpConst->getType() == SrcTy) {
9412 // Here we have the following case:
9413 //
9414 // %cond = cmp iN %x, CmpConst
9415 // %tr = trunc iN %x to iK
9416 // %narrowsel = select i1 %cond, iK %t, iK C
9417 //
9418 // We can always move trunc after select operation:
9419 //
9420 // %cond = cmp iN %x, CmpConst
9421 // %widesel = select i1 %cond, iN %x, iN CmpConst
9422 // %tr = trunc iN %widesel to iK
9423 //
9424 // Note that C could be extended in any way because we don't care about
9425 // upper bits after truncation. It can't be abs pattern, because it would
9426 // look like:
9427 //
9428 // select i1 %cond, x, -x.
9429 //
9430 // So only min/max pattern could be matched. Such match requires widened C
9431 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9432 // CmpConst == C is checked below.
9433 CastedTo = CmpConst;
9434 } else {
9435 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9436 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9437 }
9438 break;
9439 case Instruction::FPTrunc:
9440 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9441 break;
9442 case Instruction::FPExt:
9443 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9444 break;
9445 case Instruction::FPToUI:
9446 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9447 break;
9448 case Instruction::FPToSI:
9449 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9450 break;
9451 case Instruction::UIToFP:
9452 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9453 break;
9454 case Instruction::SIToFP:
9455 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9456 break;
9457 default:
9458 break;
9459 }
9460
9461 if (!CastedTo)
9462 return nullptr;
9463
9464 // Make sure the cast doesn't lose any information.
9465 Constant *CastedBack =
9466 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9467 if (CastedBack && CastedBack != C)
9468 return nullptr;
9469
9470 return CastedTo;
9471}
9472
9473/// Helps to match a select pattern in case of a type mismatch.
9474///
9475/// The function processes the case when type of true and false values of a
9476/// select instruction differs from type of the cmp instruction operands because
9477/// of a cast instruction. The function checks if it is legal to move the cast
9478/// operation after "select". If yes, it returns the new second value of
9479/// "select" (with the assumption that cast is moved):
9480/// 1. As operand of cast instruction when both values of "select" are same cast
9481/// instructions.
9482/// 2. As restored constant (by applying reverse cast operation) when the first
9483/// value of the "select" is a cast operation and the second value is a
9484/// constant. It is implemented in lookThroughCastConst().
9485/// 3. As one operand is cast instruction and the other is not. The operands in
9486/// sel(cmp) are in different type integer.
9487/// NOTE: We return only the new second value because the first value could be
9488/// accessed as operand of cast instruction.
9490 Instruction::CastOps *CastOp) {
9491 auto *Cast1 = dyn_cast<CastInst>(V1);
9492 if (!Cast1)
9493 return nullptr;
9494
9495 *CastOp = Cast1->getOpcode();
9496 Type *SrcTy = Cast1->getSrcTy();
9497 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9498 // If V1 and V2 are both the same cast from the same type, look through V1.
9499 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9500 return Cast2->getOperand(0);
9501 return nullptr;
9502 }
9503
9504 auto *C = dyn_cast<Constant>(V2);
9505 if (C)
9506 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9507
9508 Value *CastedTo = nullptr;
9509 if (*CastOp == Instruction::Trunc) {
9510 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9511 // Here we have the following case:
9512 // %y_ext = sext iK %y to iN
9513 // %cond = cmp iN %x, %y_ext
9514 // %tr = trunc iN %x to iK
9515 // %narrowsel = select i1 %cond, iK %tr, iK %y
9516 //
9517 // We can always move trunc after select operation:
9518 // %y_ext = sext iK %y to iN
9519 // %cond = cmp iN %x, %y_ext
9520 // %widesel = select i1 %cond, iN %x, iN %y_ext
9521 // %tr = trunc iN %widesel to iK
9522 assert(V2->getType() == Cast1->getType() &&
9523 "V2 and Cast1 should be the same type.");
9524 CastedTo = CmpI->getOperand(1);
9525 }
9526 }
9527
9528 return CastedTo;
9529}
9531 Instruction::CastOps *CastOp,
9532 unsigned Depth) {
9534 return {SPF_UNKNOWN, SPNB_NA, false};
9535
9537 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9538
9539 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9540 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9541
9542 Value *TrueVal = SI->getTrueValue();
9543 Value *FalseVal = SI->getFalseValue();
9544
9545 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9546 SI->getFastMathFlagsOrNone(),
9547 CastOp, Depth);
9548}
9549
9551 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9552 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9553 CmpInst::Predicate Pred = CmpI->getPredicate();
9554 Value *CmpLHS = CmpI->getOperand(0);
9555 Value *CmpRHS = CmpI->getOperand(1);
9556 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9557 FMF.setNoNaNs();
9558
9559 // Bail out early.
9560 if (CmpI->isEquality())
9561 return {SPF_UNKNOWN, SPNB_NA, false};
9562
9563 // Deal with type mismatches.
9564 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9565 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9566 // If this is a potential fmin/fmax with a cast to integer, then ignore
9567 // -0.0 because there is no corresponding integer value.
9568 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9569 FMF.setNoSignedZeros();
9570 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9571 cast<CastInst>(TrueVal)->getOperand(0), C,
9572 LHS, RHS, Depth);
9573 }
9574 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9575 // If this is a potential fmin/fmax with a cast to integer, then ignore
9576 // -0.0 because there is no corresponding integer value.
9577 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9578 FMF.setNoSignedZeros();
9579 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9580 C, cast<CastInst>(FalseVal)->getOperand(0),
9581 LHS, RHS, Depth);
9582 }
9583 }
9584 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9585 LHS, RHS, Depth);
9586}
9587
9589 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9590 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9591 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9592 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9593 if (SPF == SPF_FMINNUM)
9594 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9595 if (SPF == SPF_FMAXNUM)
9596 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9597 llvm_unreachable("unhandled!");
9598}
9599
9601 switch (SPF) {
9603 return Intrinsic::umin;
9605 return Intrinsic::umax;
9607 return Intrinsic::smin;
9609 return Intrinsic::smax;
9610 default:
9611 llvm_unreachable("Unexpected SPF");
9612 }
9613}
9614
9616 if (SPF == SPF_SMIN) return SPF_SMAX;
9617 if (SPF == SPF_UMIN) return SPF_UMAX;
9618 if (SPF == SPF_SMAX) return SPF_SMIN;
9619 if (SPF == SPF_UMAX) return SPF_UMIN;
9620 llvm_unreachable("unhandled!");
9621}
9622
9624 switch (MinMaxID) {
9625 case Intrinsic::smax: return Intrinsic::smin;
9626 case Intrinsic::smin: return Intrinsic::smax;
9627 case Intrinsic::umax: return Intrinsic::umin;
9628 case Intrinsic::umin: return Intrinsic::umax;
9629 // Please note that next four intrinsics may produce the same result for
9630 // original and inverted case even if X != Y due to NaN is handled specially.
9631 case Intrinsic::maximum: return Intrinsic::minimum;
9632 case Intrinsic::minimum: return Intrinsic::maximum;
9633 case Intrinsic::maxnum: return Intrinsic::minnum;
9634 case Intrinsic::minnum: return Intrinsic::maxnum;
9635 case Intrinsic::maximumnum:
9636 return Intrinsic::minimumnum;
9637 case Intrinsic::minimumnum:
9638 return Intrinsic::maximumnum;
9639 default: llvm_unreachable("Unexpected intrinsic");
9640 }
9641}
9642
9644 switch (SPF) {
9647 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9648 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9649 default: llvm_unreachable("Unexpected flavor");
9650 }
9651}
9652
9653std::pair<Intrinsic::ID, bool>
9655 // Check if VL contains select instructions that can be folded into a min/max
9656 // vector intrinsic and return the intrinsic if it is possible.
9657 // TODO: Support floating point min/max.
9658 bool AllCmpSingleUse = true;
9659 SelectPatternResult SelectPattern;
9660 SelectPattern.Flavor = SPF_UNKNOWN;
9661 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9662 Value *LHS, *RHS;
9663 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9664 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9665 return false;
9666 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9667 SelectPattern.Flavor != CurrentPattern.Flavor)
9668 return false;
9669 SelectPattern = CurrentPattern;
9670 AllCmpSingleUse &=
9672 return true;
9673 })) {
9674 switch (SelectPattern.Flavor) {
9675 case SPF_SMIN:
9676 return {Intrinsic::smin, AllCmpSingleUse};
9677 case SPF_UMIN:
9678 return {Intrinsic::umin, AllCmpSingleUse};
9679 case SPF_SMAX:
9680 return {Intrinsic::smax, AllCmpSingleUse};
9681 case SPF_UMAX:
9682 return {Intrinsic::umax, AllCmpSingleUse};
9683 case SPF_FMAXNUM:
9684 return {Intrinsic::maxnum, AllCmpSingleUse};
9685 case SPF_FMINNUM:
9686 return {Intrinsic::minnum, AllCmpSingleUse};
9687 default:
9688 llvm_unreachable("unexpected select pattern flavor");
9689 }
9690 }
9691 return {Intrinsic::not_intrinsic, false};
9692}
9693
9694template <typename InstTy>
9695static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9696 Value *&Init, Value *&OtherOp) {
9697 // Handle the case of a simple two-predecessor recurrence PHI.
9698 // There's a lot more that could theoretically be done here, but
9699 // this is sufficient to catch some interesting cases.
9700 // TODO: Expand list -- gep, uadd.sat etc.
9701 if (PN->getNumIncomingValues() != 2)
9702 return false;
9703
9704 for (unsigned I = 0; I != 2; ++I) {
9705 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9706 Operation && Operation->getNumOperands() >= 2) {
9707 Value *LHS = Operation->getOperand(0);
9708 Value *RHS = Operation->getOperand(1);
9709 if (LHS != PN && RHS != PN)
9710 continue;
9711
9712 Inst = Operation;
9713 Init = PN->getIncomingValue(!I);
9714 OtherOp = (LHS == PN) ? RHS : LHS;
9715 return true;
9716 }
9717 }
9718 return false;
9719}
9720
9721template <typename InstTy>
9722static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9723 Value *&Init, Value *&OtherOp0,
9724 Value *&OtherOp1) {
9725 if (PN->getNumIncomingValues() != 2)
9726 return false;
9727
9728 for (unsigned I = 0; I != 2; ++I) {
9729 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9730 Operation && Operation->getNumOperands() >= 3) {
9731 Value *Op0 = Operation->getOperand(0);
9732 Value *Op1 = Operation->getOperand(1);
9733 Value *Op2 = Operation->getOperand(2);
9734
9735 if (Op0 != PN && Op1 != PN && Op2 != PN)
9736 continue;
9737
9738 Inst = Operation;
9739 Init = PN->getIncomingValue(!I);
9740 if (Op0 == PN) {
9741 OtherOp0 = Op1;
9742 OtherOp1 = Op2;
9743 } else if (Op1 == PN) {
9744 OtherOp0 = Op0;
9745 OtherOp1 = Op2;
9746 } else {
9747 OtherOp0 = Op0;
9748 OtherOp1 = Op1;
9749 }
9750 return true;
9751 }
9752 }
9753 return false;
9754}
9756 Value *&Start, Value *&Step) {
9757 // We try to match a recurrence of the form:
9758 // %iv = [Start, %entry], [%iv.next, %backedge]
9759 // %iv.next = binop %iv, Step
9760 // Or:
9761 // %iv = [Start, %entry], [%iv.next, %backedge]
9762 // %iv.next = binop Step, %iv
9763 return matchTwoInputRecurrence(P, BO, Start, Step);
9764}
9765
9767 Value *&Start, Value *&Step) {
9768 BinaryOperator *BO = nullptr;
9769 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9770 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9771}
9772
9774 PHINode *&P, Value *&Init,
9775 Value *&OtherOp) {
9776 // Binary intrinsics only supported for now.
9777 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9778 I->getType() != I->getArgOperand(1)->getType())
9779 return false;
9780
9781 IntrinsicInst *II = nullptr;
9782 P = dyn_cast<PHINode>(I->getArgOperand(0));
9783 if (!P)
9784 P = dyn_cast<PHINode>(I->getArgOperand(1));
9785
9786 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9787}
9788
9790 PHINode *&P, Value *&Init,
9791 Value *&OtherOp0,
9792 Value *&OtherOp1) {
9793 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9794 I->getType() != I->getArgOperand(1)->getType() ||
9795 I->getType() != I->getArgOperand(2)->getType())
9796 return false;
9797 IntrinsicInst *II = nullptr;
9798 P = dyn_cast<PHINode>(I->getArgOperand(0));
9799 if (!P) {
9800 P = dyn_cast<PHINode>(I->getArgOperand(1));
9801 if (!P)
9802 P = dyn_cast<PHINode>(I->getArgOperand(2));
9803 }
9804 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9805 II == I;
9806}
9807
9808/// Return true if "icmp Pred LHS RHS" is always true.
9810 const Value *RHS) {
9811 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9812 return true;
9813
9814 switch (Pred) {
9815 default:
9816 return false;
9817
9818 case CmpInst::ICMP_SLE: {
9819 const APInt *C;
9820
9821 // LHS s<= LHS +_{nsw} C if C >= 0
9822 // LHS s<= LHS | C if C >= 0
9823 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9825 return !C->isNegative();
9826
9827 // LHS s<= smax(LHS, V) for any V
9829 return true;
9830
9831 // smin(RHS, V) s<= RHS for any V
9833 return true;
9834
9835 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9836 const Value *X;
9837 const APInt *CLHS, *CRHS;
9838 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9840 return CLHS->sle(*CRHS);
9841
9842 return false;
9843 }
9844
9845 case CmpInst::ICMP_ULE: {
9846 // LHS u<= LHS +_{nuw} V for any V
9847 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9849 return true;
9850
9851 // LHS u<= LHS | V for any V
9852 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9853 return true;
9854
9855 // LHS u<= umax(LHS, V) for any V
9857 return true;
9858
9859 // RHS >> V u<= RHS for any V
9860 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9861 return true;
9862
9863 // RHS u/ C_ugt_1 u<= RHS
9864 const APInt *C;
9865 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9866 return true;
9867
9868 // RHS & V u<= RHS for any V
9870 return true;
9871
9872 // umin(RHS, V) u<= RHS for any V
9874 return true;
9875
9876 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9877 const Value *X;
9878 const APInt *CLHS, *CRHS;
9879 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9881 return CLHS->ule(*CRHS);
9882
9883 return false;
9884 }
9885 }
9886}
9887
9888/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9889/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9890static std::optional<bool>
9892 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9893 switch (Pred) {
9894 default:
9895 return std::nullopt;
9896
9897 case CmpInst::ICMP_SLT:
9898 case CmpInst::ICMP_SLE:
9899 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9901 return true;
9902 return std::nullopt;
9903
9904 case CmpInst::ICMP_SGT:
9905 case CmpInst::ICMP_SGE:
9906 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9908 return true;
9909 return std::nullopt;
9910
9911 case CmpInst::ICMP_ULT:
9912 case CmpInst::ICMP_ULE:
9913 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9915 return true;
9916 return std::nullopt;
9917
9918 case CmpInst::ICMP_UGT:
9919 case CmpInst::ICMP_UGE:
9920 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9922 return true;
9923 return std::nullopt;
9924 }
9925}
9926
9927/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9928/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9929/// Otherwise, return std::nullopt if we can't infer anything.
9930static std::optional<bool>
9932 CmpPredicate RPred, const ConstantRange &RCR) {
9933 auto CRImpliesPred = [&](ConstantRange CR,
9934 CmpInst::Predicate Pred) -> std::optional<bool> {
9935 // If all true values for lhs and true for rhs, lhs implies rhs
9936 if (CR.icmp(Pred, RCR))
9937 return true;
9938
9939 // If there is no overlap, lhs implies not rhs
9940 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9941 return false;
9942
9943 return std::nullopt;
9944 };
9945 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9946 RPred))
9947 return Res;
9948 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9950 : LPred.dropSameSign();
9952 : RPred.dropSameSign();
9953 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9954 RPred);
9955 }
9956 return std::nullopt;
9957}
9958
9959/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9960/// is true. Return false if LHS implies RHS is false. Otherwise, return
9961/// std::nullopt if we can't infer anything.
9962static std::optional<bool>
9963isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9964 CmpPredicate RPred, const Value *R0, const Value *R1,
9965 const DataLayout &DL, bool LHSIsTrue) {
9966 // The rest of the logic assumes the LHS condition is true. If that's not the
9967 // case, invert the predicate to make it so.
9968 if (!LHSIsTrue)
9969 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9970
9971 // We can have non-canonical operands, so try to normalize any common operand
9972 // to L0/R0.
9973 if (L0 == R1) {
9974 std::swap(R0, R1);
9975 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9976 }
9977 if (R0 == L1) {
9978 std::swap(L0, L1);
9979 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9980 }
9981 if (L1 == R1) {
9982 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9983 if (L0 != R0 || match(L0, m_ImmConstant())) {
9984 std::swap(L0, L1);
9985 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9986 std::swap(R0, R1);
9987 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9988 }
9989 }
9990
9991 // See if we can infer anything if operand-0 matches and we have at least one
9992 // constant.
9993 const APInt *Unused;
9994 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9995 // Potential TODO: We could also further use the constant range of L0/R0 to
9996 // further constraint the constant ranges. At the moment this leads to
9997 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9998 // C1` (see discussion: D58633).
9999 SimplifyQuery SQ(DL);
10004
10005 // Even if L1/R1 are not both constant, we can still sometimes deduce
10006 // relationship from a single constant. For example X u> Y implies X != 0.
10007 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10008 return R;
10009 // If both L1/R1 were exact constant ranges and we didn't get anything
10010 // here, we won't be able to deduce this.
10011 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10012 return std::nullopt;
10013 }
10014
10015 // Can we infer anything when the two compares have matching operands?
10016 if (L0 == R0 && L1 == R1)
10017 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10018
10019 // It only really makes sense in the context of signed comparison for "X - Y
10020 // must be positive if X >= Y and no overflow".
10021 // Take SGT as an example: L0:x > L1:y and C >= 0
10022 // ==> R0:(x -nsw y) < R1:(-C) is false
10023 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10024 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10025 SignedLPred == ICmpInst::ICMP_SGE) &&
10026 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10027 if (match(R1, m_NonPositive()) &&
10028 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10029 return false;
10030 }
10031
10032 // Take SLT as an example: L0:x < L1:y and C <= 0
10033 // ==> R0:(x -nsw y) < R1:(-C) is true
10034 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10035 SignedLPred == ICmpInst::ICMP_SLE) &&
10036 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10037 if (match(R1, m_NonNegative()) &&
10038 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10039 return true;
10040 }
10041
10042 // a - b == NonZero -> a != b
10043 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10044 const APInt *L1C;
10045 Value *A, *B;
10046 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10047 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10048 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10049 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10054 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10055 }
10056
10057 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10058 if (L0 == R0 &&
10059 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10060 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10061 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10062 return CmpPredicate::getMatching(LPred, RPred).has_value();
10063
10064 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10065 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10066
10067 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10068 // Example: L0 u< 13 => (L0 & 16) == 0
10069 const APInt *LC, *RC, *MaskC;
10070 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10071 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10073 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10074 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10075 return true;
10076 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10077 ConstantRange(*RC)))
10078 return false;
10079 }
10080
10081 return std::nullopt;
10082}
10083
10084/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10085/// is true. Return false if LHS implies RHS is false. Otherwise, return
10086/// std::nullopt if we can't infer anything.
10087static std::optional<bool>
10089 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10090 const DataLayout &DL, bool LHSIsTrue) {
10091 // The rest of the logic assumes the LHS condition is true. If that's not the
10092 // case, invert the predicate to make it so.
10093 if (!LHSIsTrue)
10094 LPred = FCmpInst::getInversePredicate(LPred);
10095
10096 // We can have non-canonical operands, so try to normalize any common operand
10097 // to L0/R0.
10098 if (L0 == R1) {
10099 std::swap(R0, R1);
10100 RPred = FCmpInst::getSwappedPredicate(RPred);
10101 }
10102 if (R0 == L1) {
10103 std::swap(L0, L1);
10104 LPred = FCmpInst::getSwappedPredicate(LPred);
10105 }
10106 if (L1 == R1) {
10107 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10108 if (L0 != R0 || match(L0, m_ImmConstant())) {
10109 std::swap(L0, L1);
10110 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10111 std::swap(R0, R1);
10112 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10113 }
10114 }
10115
10116 // Can we infer anything when the two compares have matching operands?
10117 if (L0 == R0 && L1 == R1) {
10118 if ((LPred & RPred) == LPred)
10119 return true;
10120 if ((LPred & ~RPred) == LPred)
10121 return false;
10122 }
10123
10124 // See if we can infer anything if operand-0 matches and we have at least one
10125 // constant.
10126 const APFloat *L1C, *R1C;
10127 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10128 if (std::optional<ConstantFPRange> DomCR =
10130 if (std::optional<ConstantFPRange> ImpliedCR =
10132 if (ImpliedCR->contains(*DomCR))
10133 return true;
10134 }
10135 if (std::optional<ConstantFPRange> ImpliedCR =
10137 FCmpInst::getInversePredicate(RPred), *R1C)) {
10138 if (ImpliedCR->contains(*DomCR))
10139 return false;
10140 }
10141 }
10142 }
10143
10144 return std::nullopt;
10145}
10146
10147/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10148/// false. Otherwise, return std::nullopt if we can't infer anything. We
10149/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10150/// instruction.
10151static std::optional<bool>
10153 const Value *RHSOp0, const Value *RHSOp1,
10154 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10155 // The LHS must be an 'or', 'and', or a 'select' instruction.
10156 assert((LHS->getOpcode() == Instruction::And ||
10157 LHS->getOpcode() == Instruction::Or ||
10158 LHS->getOpcode() == Instruction::Select) &&
10159 "Expected LHS to be 'and', 'or', or 'select'.");
10160
10161 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10162
10163 // If the result of an 'or' is false, then we know both legs of the 'or' are
10164 // false. Similarly, if the result of an 'and' is true, then we know both
10165 // legs of the 'and' are true.
10166 const Value *ALHS, *ARHS;
10167 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10168 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10169 // FIXME: Make this non-recursion.
10170 if (std::optional<bool> Implication = isImpliedCondition(
10171 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10172 return Implication;
10173 if (std::optional<bool> Implication = isImpliedCondition(
10174 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10175 return Implication;
10176 return std::nullopt;
10177 }
10178 return std::nullopt;
10179}
10180
10181std::optional<bool>
10183 const Value *RHSOp0, const Value *RHSOp1,
10184 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10185 // Bail out when we hit the limit.
10187 return std::nullopt;
10188
10189 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10190 // example.
10191 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10192 return std::nullopt;
10193
10194 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10195 "Expected integer type only!");
10196
10197 // Match not
10198 if (match(LHS, m_Not(m_Value(LHS))))
10199 LHSIsTrue = !LHSIsTrue;
10200
10201 // Both LHS and RHS are icmps.
10202 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10203 CmpPredicate LHSPred;
10204 Value *LHSOp0, *LHSOp1;
10205 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10206 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10207 RHSOp1, DL, LHSIsTrue);
10208 } else {
10209 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10210 "Expected floating point type only!");
10211 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10212 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10213 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10214 DL, LHSIsTrue);
10215 }
10216
10217 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10218 /// the RHS to be an icmp.
10219 /// FIXME: Add support for and/or/select on the RHS.
10220 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10221 if ((LHSI->getOpcode() == Instruction::And ||
10222 LHSI->getOpcode() == Instruction::Or ||
10223 LHSI->getOpcode() == Instruction::Select))
10224 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10225 Depth);
10226 }
10227 return std::nullopt;
10228}
10229
10230std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10231 const DataLayout &DL,
10232 bool LHSIsTrue, unsigned Depth) {
10233 // LHS ==> RHS by definition
10234 if (LHS == RHS)
10235 return LHSIsTrue;
10236
10237 // Match not
10238 bool InvertRHS = false;
10239 if (match(RHS, m_Not(m_Value(RHS)))) {
10240 if (LHS == RHS)
10241 return !LHSIsTrue;
10242 InvertRHS = true;
10243 }
10244
10245 CmpPredicate RHSPred;
10246 Value *RHSOp0, *RHSOp1;
10247 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10248 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10249 LHSIsTrue, Depth))
10250 return InvertRHS ? !*Implied : *Implied;
10251 return std::nullopt;
10252 }
10253 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10254 if (auto Implied = isImpliedCondition(
10255 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10256 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10257 return InvertRHS ? !*Implied : *Implied;
10258 return std::nullopt;
10259 }
10260
10262 return std::nullopt;
10263
10264 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10265 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10266 const Value *RHS1, *RHS2;
10267 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10268 if (std::optional<bool> Imp =
10269 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10270 if (*Imp == true)
10271 return !InvertRHS;
10272 if (std::optional<bool> Imp =
10273 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10274 if (*Imp == true)
10275 return !InvertRHS;
10276 }
10277 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10278 if (std::optional<bool> Imp =
10279 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10280 if (*Imp == false)
10281 return InvertRHS;
10282 if (std::optional<bool> Imp =
10283 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10284 if (*Imp == false)
10285 return InvertRHS;
10286 }
10287
10288 return std::nullopt;
10289}
10290
10291// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10292// condition dominating ContextI or nullptr, if no condition is found.
10293static std::pair<Value *, bool>
10295 if (!ContextI || !ContextI->getParent())
10296 return {nullptr, false};
10297
10298 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10299 // dominator tree (eg, from a SimplifyQuery) instead?
10300 const BasicBlock *ContextBB = ContextI->getParent();
10301 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10302 if (!PredBB)
10303 return {nullptr, false};
10304
10305 // We need a conditional branch in the predecessor.
10306 Value *PredCond;
10307 BasicBlock *TrueBB, *FalseBB;
10308 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10309 return {nullptr, false};
10310
10311 // The branch should get simplified. Don't bother simplifying this condition.
10312 if (TrueBB == FalseBB)
10313 return {nullptr, false};
10314
10315 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10316 "Predecessor block does not point to successor?");
10317
10318 // Is this condition implied by the predecessor condition?
10319 return {PredCond, TrueBB == ContextBB};
10320}
10321
10322std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10323 const Instruction *ContextI,
10324 const DataLayout &DL) {
10325 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10326 auto PredCond = getDomPredecessorCondition(ContextI);
10327 if (PredCond.first)
10328 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10329 return std::nullopt;
10330}
10331
10333 const Value *LHS,
10334 const Value *RHS,
10335 const Instruction *ContextI,
10336 const DataLayout &DL) {
10337 auto PredCond = getDomPredecessorCondition(ContextI);
10338 if (PredCond.first)
10339 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10340 PredCond.second);
10341 return std::nullopt;
10342}
10343
10345 APInt &Upper, const InstrInfoQuery &IIQ,
10346 bool PreferSignedRange) {
10347 unsigned Width = Lower.getBitWidth();
10348 const APInt *C;
10349 switch (BO.getOpcode()) {
10350 case Instruction::Sub:
10351 if (match(BO.getOperand(0), m_APInt(C))) {
10352 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10353 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10354
10355 // If the caller expects a signed compare, then try to use a signed range.
10356 // Otherwise if both no-wraps are set, use the unsigned range because it
10357 // is never larger than the signed range. Example:
10358 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10359 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10360 if (PreferSignedRange && HasNSW && HasNUW)
10361 HasNUW = false;
10362
10363 if (HasNUW) {
10364 // 'sub nuw c, x' produces [0, C].
10365 Upper = *C + 1;
10366 } else if (HasNSW) {
10367 if (C->isNegative()) {
10368 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10370 Upper = *C - APInt::getSignedMaxValue(Width);
10371 } else {
10372 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10373 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10374 Lower = *C - APInt::getSignedMaxValue(Width);
10376 }
10377 }
10378 }
10379 break;
10380 case Instruction::Add:
10381 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10382 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10383 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10384
10385 // If the caller expects a signed compare, then try to use a signed
10386 // range. Otherwise if both no-wraps are set, use the unsigned range
10387 // because it is never larger than the signed range. Example: "add nuw
10388 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10389 if (PreferSignedRange && HasNSW && HasNUW)
10390 HasNUW = false;
10391
10392 if (HasNUW) {
10393 // 'add nuw x, C' produces [C, UINT_MAX].
10394 Lower = *C;
10395 } else if (HasNSW) {
10396 if (C->isNegative()) {
10397 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10399 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10400 } else {
10401 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10402 Lower = APInt::getSignedMinValue(Width) + *C;
10403 Upper = APInt::getSignedMaxValue(Width) + 1;
10404 }
10405 }
10406 }
10407 break;
10408
10409 case Instruction::And:
10410 if (match(BO.getOperand(1), m_APInt(C)))
10411 // 'and x, C' produces [0, C].
10412 Upper = *C + 1;
10413 // X & -X is a power of two or zero. So we can cap the value at max power of
10414 // two.
10415 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10416 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10417 Upper = APInt::getSignedMinValue(Width) + 1;
10418 break;
10419
10420 case Instruction::Or:
10421 if (match(BO.getOperand(1), m_APInt(C)))
10422 // 'or x, C' produces [C, UINT_MAX].
10423 Lower = *C;
10424 break;
10425
10426 case Instruction::AShr:
10427 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10428 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10430 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10431 } else if (match(BO.getOperand(0), m_APInt(C))) {
10432 unsigned ShiftAmount = Width - 1;
10433 if (!C->isZero() && IIQ.isExact(&BO))
10434 ShiftAmount = C->countr_zero();
10435 if (C->isNegative()) {
10436 // 'ashr C, x' produces [C, C >> (Width-1)]
10437 Lower = *C;
10438 Upper = C->ashr(ShiftAmount) + 1;
10439 } else {
10440 // 'ashr C, x' produces [C >> (Width-1), C]
10441 Lower = C->ashr(ShiftAmount);
10442 Upper = *C + 1;
10443 }
10444 }
10445 break;
10446
10447 case Instruction::LShr:
10448 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10449 // 'lshr x, C' produces [0, UINT_MAX >> C].
10450 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10451 } else if (match(BO.getOperand(0), m_APInt(C))) {
10452 // 'lshr C, x' produces [C >> (Width-1), C].
10453 unsigned ShiftAmount = Width - 1;
10454 if (!C->isZero() && IIQ.isExact(&BO))
10455 ShiftAmount = C->countr_zero();
10456 Lower = C->lshr(ShiftAmount);
10457 Upper = *C + 1;
10458 }
10459 break;
10460
10461 case Instruction::Shl:
10462 if (match(BO.getOperand(0), m_APInt(C))) {
10463 if (IIQ.hasNoUnsignedWrap(&BO)) {
10464 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10465 Lower = *C;
10466 Upper = Lower.shl(Lower.countl_zero()) + 1;
10467 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10468 if (C->isNegative()) {
10469 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10470 unsigned ShiftAmount = C->countl_one() - 1;
10471 Lower = C->shl(ShiftAmount);
10472 Upper = *C + 1;
10473 } else {
10474 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10475 unsigned ShiftAmount = C->countl_zero() - 1;
10476 Lower = *C;
10477 Upper = C->shl(ShiftAmount) + 1;
10478 }
10479 } else {
10480 // If lowbit is set, value can never be zero.
10481 if ((*C)[0])
10482 Lower = APInt::getOneBitSet(Width, 0);
10483 // If we are shifting a constant the largest it can be is if the longest
10484 // sequence of consecutive ones is shifted to the highbits (breaking
10485 // ties for which sequence is higher). At the moment we take a liberal
10486 // upper bound on this by just popcounting the constant.
10487 // TODO: There may be a bitwise trick for it longest/highest
10488 // consecutative sequence of ones (naive method is O(Width) loop).
10489 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10490 }
10491 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10492 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10493 }
10494 break;
10495
10496 case Instruction::SDiv:
10497 if (match(BO.getOperand(1), m_APInt(C))) {
10498 APInt IntMin = APInt::getSignedMinValue(Width);
10499 APInt IntMax = APInt::getSignedMaxValue(Width);
10500 if (C->isAllOnes()) {
10501 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10502 // where C != -1 and C != 0 and C != 1
10503 Lower = IntMin + 1;
10504 Upper = IntMax + 1;
10505 } else if (C->countl_zero() < Width - 1) {
10506 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10507 // where C != -1 and C != 0 and C != 1
10508 Lower = IntMin.sdiv(*C);
10509 Upper = IntMax.sdiv(*C);
10510 if (Lower.sgt(Upper))
10512 Upper = Upper + 1;
10513 assert(Upper != Lower && "Upper part of range has wrapped!");
10514 }
10515 } else if (match(BO.getOperand(0), m_APInt(C))) {
10516 if (C->isMinSignedValue()) {
10517 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10518 Lower = *C;
10519 Upper = Lower.lshr(1) + 1;
10520 } else {
10521 // 'sdiv C, x' produces [-|C|, |C|].
10522 Upper = C->abs() + 1;
10523 Lower = (-Upper) + 1;
10524 }
10525 }
10526 break;
10527
10528 case Instruction::UDiv:
10529 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10530 // 'udiv x, C' produces [0, UINT_MAX / C].
10531 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10532 } else if (match(BO.getOperand(0), m_APInt(C))) {
10533 // 'udiv C, x' produces [0, C].
10534 Upper = *C + 1;
10535 }
10536 break;
10537
10538 case Instruction::SRem:
10539 if (match(BO.getOperand(1), m_APInt(C))) {
10540 // 'srem x, C' produces (-|C|, |C|).
10541 Upper = C->abs();
10542 Lower = (-Upper) + 1;
10543 } else if (match(BO.getOperand(0), m_APInt(C))) {
10544 if (C->isNegative()) {
10545 // 'srem -|C|, x' produces [-|C|, 0].
10546 Upper = 1;
10547 Lower = *C;
10548 } else {
10549 // 'srem |C|, x' produces [0, |C|].
10550 Upper = *C + 1;
10551 }
10552 }
10553 break;
10554
10555 case Instruction::URem:
10556 if (match(BO.getOperand(1), m_APInt(C)))
10557 // 'urem x, C' produces [0, C).
10558 Upper = *C;
10559 else if (match(BO.getOperand(0), m_APInt(C)))
10560 // 'urem C, x' produces [0, C].
10561 Upper = *C + 1;
10562 break;
10563
10564 default:
10565 break;
10566 }
10567}
10568
10570 bool UseInstrInfo) {
10571 unsigned Width = II.getType()->getScalarSizeInBits();
10572 const APInt *C;
10573 switch (II.getIntrinsicID()) {
10574 case Intrinsic::ctlz:
10575 case Intrinsic::cttz: {
10576 APInt Upper(Width, Width);
10577 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10578 Upper += 1;
10579 // Maximum of set/clear bits is the bit width.
10581 }
10582 case Intrinsic::ctpop:
10583 // Maximum of set/clear bits is the bit width.
10585 APInt(Width, Width) + 1);
10586 case Intrinsic::uadd_sat:
10587 // uadd.sat(x, C) produces [C, UINT_MAX].
10588 if (match(II.getOperand(0), m_APInt(C)) ||
10589 match(II.getOperand(1), m_APInt(C)))
10591 break;
10592 case Intrinsic::sadd_sat:
10593 if (match(II.getOperand(0), m_APInt(C)) ||
10594 match(II.getOperand(1), m_APInt(C))) {
10595 if (C->isNegative())
10596 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10598 APInt::getSignedMaxValue(Width) + *C +
10599 1);
10600
10601 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10603 APInt::getSignedMaxValue(Width) + 1);
10604 }
10605 break;
10606 case Intrinsic::usub_sat:
10607 // usub.sat(C, x) produces [0, C].
10608 if (match(II.getOperand(0), m_APInt(C)))
10609 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10610
10611 // usub.sat(x, C) produces [0, UINT_MAX - C].
10612 if (match(II.getOperand(1), m_APInt(C)))
10614 APInt::getMaxValue(Width) - *C + 1);
10615 break;
10616 case Intrinsic::ssub_sat:
10617 if (match(II.getOperand(0), m_APInt(C))) {
10618 if (C->isNegative())
10619 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10621 *C - APInt::getSignedMinValue(Width) +
10622 1);
10623
10624 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10626 APInt::getSignedMaxValue(Width) + 1);
10627 } else if (match(II.getOperand(1), m_APInt(C))) {
10628 if (C->isNegative())
10629 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10631 APInt::getSignedMaxValue(Width) + 1);
10632
10633 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10635 APInt::getSignedMaxValue(Width) - *C +
10636 1);
10637 }
10638 break;
10639 case Intrinsic::umin:
10640 case Intrinsic::umax:
10641 case Intrinsic::smin:
10642 case Intrinsic::smax:
10643 if (!match(II.getOperand(0), m_APInt(C)) &&
10644 !match(II.getOperand(1), m_APInt(C)))
10645 break;
10646
10647 switch (II.getIntrinsicID()) {
10648 case Intrinsic::umin:
10649 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10650 case Intrinsic::umax:
10652 case Intrinsic::smin:
10654 *C + 1);
10655 case Intrinsic::smax:
10657 APInt::getSignedMaxValue(Width) + 1);
10658 default:
10659 llvm_unreachable("Must be min/max intrinsic");
10660 }
10661 break;
10662 case Intrinsic::abs:
10663 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10664 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10665 if (match(II.getOperand(1), m_One()))
10667 APInt::getSignedMaxValue(Width) + 1);
10668
10670 APInt::getSignedMinValue(Width) + 1);
10671 case Intrinsic::vscale:
10672 if (!II.getParent() || !II.getFunction())
10673 break;
10674 return getVScaleRange(II.getFunction(), Width);
10675 case Intrinsic::read_register:
10676 case Intrinsic::read_volatile_register: {
10677 const Module *M = II.getModule();
10678 if (!M || !M->getTargetTriple().isRISCV())
10679 break;
10680 if (II.getFunction() && isReadVLENB(II))
10681 return getRISCVVLENBRange(II, Width);
10682 break;
10683 }
10684 default:
10685 break;
10686 }
10687
10688 return ConstantRange::getFull(Width);
10689}
10690
10692 const InstrInfoQuery &IIQ) {
10693 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10694 const Value *LHS = nullptr, *RHS = nullptr;
10696 if (R.Flavor == SPF_UNKNOWN)
10697 return ConstantRange::getFull(BitWidth);
10698
10699 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10700 // If the negation part of the abs (in RHS) has the NSW flag,
10701 // then the result of abs(X) is [0..SIGNED_MAX],
10702 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10703 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10707
10710 }
10711
10712 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10713 // The result of -abs(X) is <= 0.
10715 APInt(BitWidth, 1));
10716 }
10717
10718 const APInt *C;
10719 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10720 return ConstantRange::getFull(BitWidth);
10721
10722 switch (R.Flavor) {
10723 case SPF_UMIN:
10725 case SPF_UMAX:
10727 case SPF_SMIN:
10729 *C + 1);
10730 case SPF_SMAX:
10733 default:
10734 return ConstantRange::getFull(BitWidth);
10735 }
10736}
10737
10739 // The maximum representable value of a half is 65504. For floats the maximum
10740 // value is 3.4e38 which requires roughly 129 bits.
10741 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10742 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10743 return;
10744 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10745 Lower = APInt(BitWidth, -65504, true);
10746 Upper = APInt(BitWidth, 65505);
10747 }
10748
10749 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10750 // For a fptoui the lower limit is left as 0.
10751 Upper = APInt(BitWidth, 65505);
10752 }
10753}
10754
10756 const SimplifyQuery &SQ,
10757 unsigned Depth) {
10758 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10759
10761 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10762
10763 if (auto *C = dyn_cast<Constant>(V))
10764 return C->toConstantRange();
10765
10766 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10767 ConstantRange CR = ConstantRange::getFull(BitWidth);
10768 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10769 APInt Lower = APInt(BitWidth, 0);
10770 APInt Upper = APInt(BitWidth, 0);
10771 // TODO: Return ConstantRange.
10772 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10774 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10776 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10777 ConstantRange CRTrue =
10778 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10779 ConstantRange CRFalse =
10780 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10781 CR = CRTrue.unionWith(CRFalse);
10783 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10784 ConstantRange SrcCR =
10785 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10786 CR = SrcCR.truncate(BitWidth);
10787 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10788 APInt Lower = APInt(BitWidth, 0);
10789 APInt Upper = APInt(BitWidth, 0);
10790 // TODO: Return ConstantRange.
10793 } else if (const auto *A = dyn_cast<Argument>(V))
10794 if (std::optional<ConstantRange> Range = A->getRange())
10795 CR = *Range;
10796
10797 if (auto *I = dyn_cast<Instruction>(V)) {
10798 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10800
10801 Value *FrexpSrc;
10802 if (const auto *CB = dyn_cast<CallBase>(V)) {
10803 if (std::optional<ConstantRange> Range = CB->getRange())
10804 CR = CR.intersectWith(*Range);
10806 m_Value(FrexpSrc))))) {
10807 const fltSemantics &FltSem =
10808 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10809 // It should be possible to implement this for any type, but this logic
10810 // only computes the range assuming standard subnormal handling.
10811 if (APFloat::isIEEELikeFP(FltSem)) {
10813 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10814
10815 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10816 // constrain its range when the source can be neither.
10817 if (KnownSrc.isKnownNeverInfOrNaN()) {
10818 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10819
10820 // Offset to find the true minimum exponent value for a denormal.
10821 if (!KnownSrc.isKnownNeverSubnormal())
10822 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10823
10824 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10825
10826 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10828
10829 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10830 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10831
10832 MinExp = std::max(AdjustedMin, MinExp);
10833 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10834 MaxExp);
10835
10837 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10838 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10839 /*isSigned=*/true));
10840 }
10841 }
10842 }
10843 }
10844
10845 if (SQ.CxtI && SQ.AC) {
10846 // Try to restrict the range based on information from assumptions.
10847 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10848 if (!AssumeVH)
10849 continue;
10850 CallInst *I = cast<CallInst>(AssumeVH);
10851 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10852 "Got assumption for the wrong function!");
10853 assert(I->getIntrinsicID() == Intrinsic::assume &&
10854 "must be an assume intrinsic");
10855
10856 if (!isValidAssumeForContext(I, SQ))
10857 continue;
10858 Value *Arg = I->getArgOperand(0);
10859 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10860 // Currently we just use information from comparisons.
10861 if (!Cmp || Cmp->getOperand(0) != V)
10862 continue;
10863 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10864 ConstantRange RHS =
10865 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10866 SQ.getWithInstruction(I), Depth + 1);
10867 CR = CR.intersectWith(
10868 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10869 }
10870 }
10871
10872 return CR;
10873}
10874
10875static void
10877 function_ref<void(Value *)> InsertAffected) {
10878 assert(V != nullptr);
10879 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10880 InsertAffected(V);
10881 } else if (auto *I = dyn_cast<Instruction>(V)) {
10882 InsertAffected(V);
10883
10884 // Peek through unary operators to find the source of the condition.
10885 Value *Op;
10887 m_Trunc(m_Value(Op))))) {
10889 InsertAffected(Op);
10890 }
10891 }
10892}
10893
10895 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10896 auto AddAffected = [&InsertAffected](Value *V) {
10897 addValueAffectedByCondition(V, InsertAffected);
10898 };
10899
10900 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10901 if (IsAssume) {
10902 AddAffected(LHS);
10903 AddAffected(RHS);
10904 } else if (match(RHS, m_Constant()))
10905 AddAffected(LHS);
10906 };
10907
10908 SmallVector<Value *, 8> Worklist;
10910 Worklist.push_back(Cond);
10911 while (!Worklist.empty()) {
10912 Value *V = Worklist.pop_back_val();
10913 if (!Visited.insert(V).second)
10914 continue;
10915
10916 CmpPredicate Pred;
10917 Value *A, *B, *X;
10918
10919 if (IsAssume) {
10920 AddAffected(V);
10921 if (match(V, m_Not(m_Value(X))))
10922 AddAffected(X);
10923 }
10924
10925 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10926 // assume(A && B) is split to -> assume(A); assume(B);
10927 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10928 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10929 // enough information to be worth handling (intersection of information as
10930 // opposed to union).
10931 if (!IsAssume) {
10932 Worklist.push_back(A);
10933 Worklist.push_back(B);
10934 }
10935 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10936 bool HasRHSC = match(B, m_ConstantInt());
10937 if (ICmpInst::isEquality(Pred)) {
10938 AddAffected(A);
10939 if (IsAssume)
10940 AddAffected(B);
10941 if (HasRHSC) {
10942 Value *Y;
10943 // (X << C) or (X >>_s C) or (X >>_u C).
10944 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10945 AddAffected(X);
10946 // (X & C) or (X | C).
10947 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10948 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10949 AddAffected(X);
10950 AddAffected(Y);
10951 }
10952 // X - Y
10953 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10954 AddAffected(X);
10955 AddAffected(Y);
10956 }
10957 }
10958 } else {
10959 AddCmpOperands(A, B);
10960 if (HasRHSC) {
10961 // Handle (A + C1) u< C2, which is the canonical form of
10962 // A > C3 && A < C4.
10964 AddAffected(X);
10965
10966 if (ICmpInst::isUnsigned(Pred)) {
10967 Value *Y;
10968 // X & Y u> C -> X >u C && Y >u C
10969 // X | Y u< C -> X u< C && Y u< C
10970 // X nuw+ Y u< C -> X u< C && Y u< C
10971 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10972 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10973 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10974 AddAffected(X);
10975 AddAffected(Y);
10976 }
10977 // X nuw- Y u> C -> X u> C
10978 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10979 AddAffected(X);
10980 }
10981 }
10982
10983 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10984 // by computeKnownFPClass().
10986 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10987 InsertAffected(X);
10988 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10989 InsertAffected(X);
10990 }
10991 }
10992
10993 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10994 Value *SquareOp = nullptr;
10995 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10996 AddAffected(SquareOp);
10997 };
10998 AddNuwSquareOperand(A);
10999 AddNuwSquareOperand(B);
11000
11001 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11002 AddAffected(X);
11003 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11004 AddCmpOperands(A, B);
11005
11006 // fcmp fneg(x), y
11007 // fcmp fabs(x), y
11008 // fcmp fneg(fabs(x)), y
11009 if (match(A, m_FNeg(m_Value(A))))
11010 AddAffected(A);
11011 if (match(A, m_FAbs(m_Value(A))))
11012 AddAffected(A);
11013
11015 m_Value()))) {
11016 // Handle patterns that computeKnownFPClass() support.
11017 AddAffected(A);
11018 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11019 // Assume is checked here as X is already added above for assumes in
11020 // addValueAffectedByCondition
11021 AddAffected(X);
11022 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11023 // Assume is checked here to avoid issues with ephemeral values
11024 Worklist.push_back(X);
11025 }
11026 }
11027}
11028
11030 // (X >> C) or/add (X & mask(C) != 0)
11031 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11032 if (BO->getOpcode() == Instruction::Add ||
11033 BO->getOpcode() == Instruction::Or) {
11034 const Value *X;
11035 const APInt *C1, *C2;
11036 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11040 m_Zero())))) &&
11041 C2->popcount() == C1->getZExtValue())
11042 return X;
11043 }
11044 }
11045 return nullptr;
11046}
11047
11049 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11050}
11051
11054 unsigned MaxCount, bool AllowUndefOrPoison) {
11057 auto Push = [&](const Value *V) -> bool {
11058 Constant *C;
11059 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11060 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11061 return false;
11062 // Check existence first to avoid unnecessary allocations.
11063 if (Constants.contains(C))
11064 return true;
11065 if (Constants.size() == MaxCount)
11066 return false;
11067 Constants.insert(C);
11068 return true;
11069 }
11070
11071 if (auto *Inst = dyn_cast<Instruction>(V)) {
11072 if (Visited.insert(Inst).second)
11073 Worklist.push_back(Inst);
11074 return true;
11075 }
11076 return false;
11077 };
11078 if (!Push(V))
11079 return false;
11080 while (!Worklist.empty()) {
11081 const Instruction *CurInst = Worklist.pop_back_val();
11082 switch (CurInst->getOpcode()) {
11083 case Instruction::Select:
11084 if (!Push(CurInst->getOperand(1)))
11085 return false;
11086 if (!Push(CurInst->getOperand(2)))
11087 return false;
11088 break;
11089 case Instruction::PHI:
11090 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11091 // Fast path for recurrence PHI.
11092 if (IncomingValue == CurInst)
11093 continue;
11094 if (!Push(IncomingValue))
11095 return false;
11096 }
11097 break;
11098 default:
11099 return false;
11100 }
11101 }
11102 return true;
11103}
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 void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static 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 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 const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static 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
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 APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange 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)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp: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
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h: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 isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI 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 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 bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h: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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
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 OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool 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 unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h: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)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI 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 roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
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 sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041