LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98template <typename InstTy>
99static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
100 Value *&Init, Value *&OtherOp);
101
102/// Returns the bitwidth of the given scalar or pointer type. For vector types,
103/// returns the element type's bitwidth.
104static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
105 if (unsigned BitWidth = Ty->getScalarSizeInBits())
106 return BitWidth;
107
108 return DL.getPointerTypeSizeInBits(Ty);
109}
110
111// Given the provided Value and, potentially, a context instruction, return
112// the preferred context instruction (if any).
113static const Instruction *safeCtxI(const Value *V, const Instruction *CtxI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CtxI && CtxI->getParent())
117 return CtxI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CtxI = dyn_cast<Instruction>(V);
121 if (CtxI && CtxI->getParent())
122 return CtxI;
123
124 return nullptr;
125}
126
128 const APInt &DemandedElts,
129 APInt &DemandedLHS, APInt &DemandedRHS) {
130 if (isa<ScalableVectorType>(Shuf->getType())) {
131 assert(DemandedElts == APInt(1,1));
132 DemandedLHS = DemandedRHS = DemandedElts;
133 return true;
134 }
135
136 int NumElts =
137 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
138 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
139 DemandedElts, DemandedLHS, DemandedRHS);
140}
141
142static void computeKnownBits(const Value *V, const APInt &DemandedElts,
143 KnownBits &Known, const SimplifyQuery &Q,
144 unsigned Depth);
145
147 const SimplifyQuery &Q, unsigned Depth) {
148 // Since the number of lanes in a scalable vector is unknown at compile time,
149 // we track one bit which is implicitly broadcast to all lanes. This means
150 // that all lanes in a scalable vector are considered demanded.
151 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
152 APInt DemandedElts =
153 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
154 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
155}
156
158 const DataLayout &DL, AssumptionCache *AC,
159 const Instruction *CtxI, const DominatorTree *DT,
160 bool UseInstrInfo, unsigned Depth) {
162 SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
163 Depth);
164}
165
167 AssumptionCache *AC, const Instruction *CtxI,
168 const DominatorTree *DT, bool UseInstrInfo,
169 unsigned Depth) {
170 return computeKnownBits(
171 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
172}
173
176 const SimplifyQuery &SQ) {
177 // Look for an inverted mask: (X & ~M) op (Y & M).
178 {
179 Value *M;
180 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
182 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CtxI, SQ.DT)
185 }
186
187 // X op (Y & ~X)
189 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT)
192
193 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
194 // for constant Y.
195 Value *Y;
196 if (match(RHS,
198 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT) &&
199 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT);
200 return IsNoUndef ? NoCommonBitsSetResult::Known
202 }
203
204 // Peek through extends to find a 'not' of the other side:
205 // (ext Y) op ext(~Y)
206 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
208 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT)
211
212 // Look for: (A & B) op ~(A | B)
213 {
214 Value *A, *B;
215 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
217 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CtxI, SQ.DT) &&
218 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CtxI, SQ.DT);
219 return IsNoUndef ? NoCommonBitsSetResult::Known
221 }
222 }
223
224 // Look for: (X << V) op (Y >> (BitWidth - V))
225 // or (X >> V) op (Y << (BitWidth - V))
226 {
227 const Value *V;
228 const APInt *R;
229 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
230 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
231 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
232 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
233 R->uge(LHS->getType()->getScalarSizeInBits()))
235 }
236
238}
239
242 const WithCache<const Value *> &RHSCache,
243 const SimplifyQuery &SQ) {
244 const Value *LHS = LHSCache.getValue();
245 const Value *RHS = RHSCache.getValue();
246
247 assert(LHS->getType() == RHS->getType() &&
248 "LHS and RHS should have the same type");
249 assert(LHS->getType()->isIntOrIntVectorTy() &&
250 "LHS and RHS should be integers");
251
253 if (Result == NoCommonBitsSetResult::Known)
255
256 NoCommonBitsSetResult CommuteResult =
258 if (CommuteResult == NoCommonBitsSetResult::Known)
260
262 RHSCache.getKnownBits(SQ)))
264
268
270}
271
273 const WithCache<const Value *> &RHSCache,
274 const SimplifyQuery &SQ) {
275 NoCommonBitsSetResult Result =
276 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
277 return Result == NoCommonBitsSetResult::Known;
278}
279
281 return !I->user_empty() &&
282 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
283}
284
286 return !I->user_empty() && all_of(I->users(), [](const User *U) {
287 CmpPredicate P;
288 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
289 });
290}
291
293 bool OrZero, AssumptionCache *AC,
294 const Instruction *CtxI,
295 const DominatorTree *DT, bool UseInstrInfo,
296 unsigned Depth) {
297 return ::isKnownToBeAPowerOfTwo(
298 V, OrZero, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
299 Depth);
300}
301
302static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
303 const SimplifyQuery &Q, unsigned Depth);
304
306 unsigned Depth) {
307 return computeKnownBits(V, SQ, Depth).isNonNegative();
308}
309
311 unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
318 return Known.isNonNegative() &&
319 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
320}
321
323 unsigned Depth) {
324 return computeKnownBits(V, SQ, Depth).isNegative();
325}
326
327static bool isKnownNonEqual(const Value *V1, const Value *V2,
328 const APInt &DemandedElts, const SimplifyQuery &Q,
329 unsigned Depth);
330
331static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
332 const Value *RHS);
333
334bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
335 const SimplifyQuery &Q, unsigned Depth) {
336 // We don't support looking through casts.
337 if (V1 == V2 || V1->getType() != V2->getType())
338 return false;
339 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
340 APInt DemandedElts =
341 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
342 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
343}
344
345bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
346 const SimplifyQuery &SQ, unsigned Depth) {
347 KnownBits Known(Mask.getBitWidth());
349 return Mask.isSubsetOf(Known.Zero);
350}
351
352static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
353 const SimplifyQuery &Q, unsigned Depth);
354
355static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
356 unsigned Depth = 0) {
357 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
358 APInt DemandedElts =
359 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
360 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
361}
362
363unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
364 AssumptionCache *AC, const Instruction *CtxI,
365 const DominatorTree *DT, bool UseInstrInfo,
366 unsigned Depth) {
367 return ::ComputeNumSignBits(
368 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
369}
370
372 AssumptionCache *AC,
373 const Instruction *CtxI,
374 const DominatorTree *DT,
375 unsigned Depth) {
376 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
377 return V->getType()->getScalarSizeInBits() - SignBits + 1;
378}
379
380/// Try to detect the lerp pattern: a * (b - c) + c * d
381/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
382///
383/// In that particular case, we can use the following chain of reasoning:
384///
385/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
386///
387/// Since that is true for arbitrary a, b, c and d within our constraints, we
388/// can conclude that:
389///
390/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
391///
392/// Considering that any result of the lerp would be less or equal to U, it
393/// would have at least the number of leading 0s as in U.
394///
395/// While being quite a specific situation, it is fairly common in computer
396/// graphics in the shape of alpha blending.
397///
398/// Modifies given KnownOut in-place with the inferred information.
399static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
400 const APInt &DemandedElts,
401 KnownBits &KnownOut,
402 const SimplifyQuery &Q,
403 unsigned Depth) {
404
405 Type *Ty = Op0->getType();
406 const unsigned BitWidth = Ty->getScalarSizeInBits();
407
408 // Only handle scalar types for now
409 if (Ty->isVectorTy())
410 return;
411
412 // Try to match: a * (b - c) + c * d.
413 // When a == 1 => A == nullptr, the same applies to d/D as well.
414 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
415 const Instruction *SubBC = nullptr;
416
417 const auto MatchSubBC = [&]() {
418 // (b - c) can have two forms that interest us:
419 //
420 // 1. sub nuw %b, %c
421 // 2. xor %c, %b
422 //
423 // For the first case, nuw flag guarantees our requirement b >= c.
424 //
425 // The second case might happen when the analysis can infer that b is a mask
426 // for c and we can transform sub operation into xor (that is usually true
427 // for constant b's). Even though xor is symmetrical, canonicalization
428 // ensures that the constant will be the RHS. We have additional checks
429 // later on to ensure that this xor operation is equivalent to subtraction.
431 m_Xor(m_Value(C), m_Value(B))));
432 };
433
434 const auto MatchASubBC = [&]() {
435 // Cases:
436 // - a * (b - c)
437 // - (b - c) * a
438 // - (b - c) <- a implicitly equals 1
439 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
440 };
441
442 const auto MatchCD = [&]() {
443 // Cases:
444 // - d * c
445 // - c * d
446 // - c <- d implicitly equals 1
448 };
449
450 const auto Match = [&](const Value *LHS, const Value *RHS) {
451 // We do use m_Specific(C) in MatchCD, so we have to make sure that
452 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
453 // has to evaluate first and return true.
454 //
455 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
456 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
457 };
458
459 if (!Match(Op0, Op1) && !Match(Op1, Op0))
460 return;
461
462 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
463 // For some of the values we use the convention of leaving
464 // it nullptr to signify an implicit constant 1.
465 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
467 };
468
469 // Check that all operands are non-negative
470 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
471 if (!KnownA.isNonNegative())
472 return;
473
474 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
475 if (!KnownD.isNonNegative())
476 return;
477
478 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
479 if (!KnownB.isNonNegative())
480 return;
481
482 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
483 if (!KnownC.isNonNegative())
484 return;
485
486 // If we matched subtraction as xor, we need to actually check that xor
487 // is semantically equivalent to subtraction.
488 //
489 // For that to be true, b has to be a mask for c or that b's known
490 // ones cover all known and possible ones of c.
491 if (SubBC->getOpcode() == Instruction::Xor &&
492 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
493 return;
494
495 const APInt MaxA = KnownA.getMaxValue();
496 const APInt MaxD = KnownD.getMaxValue();
497 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
498 const APInt MaxB = KnownB.getMaxValue();
499
500 // We can't infer leading zeros info if the upper-bound estimate wraps.
501 bool Overflow;
502 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
503
504 if (Overflow)
505 return;
506
507 // If we know that x <= y and both are positive than x has at least the same
508 // number of leading zeros as y.
509 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
510 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
511}
512
513static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
514 bool NSW, bool NUW,
515 const APInt &DemandedElts,
516 KnownBits &KnownOut, KnownBits &Known2,
517 const SimplifyQuery &Q, unsigned Depth) {
518 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
519
520 // If one operand is unknown and we have no nowrap information,
521 // the result will be unknown independently of the second operand.
522 if (KnownOut.isUnknown() && !NSW && !NUW)
523 return;
524
525 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
526 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
527
528 if (!Add && NSW && !KnownOut.isNonNegative() &&
530 .value_or(false) ||
531 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
532 KnownOut.makeNonNegative();
533
534 if (Add)
535 // Try to match lerp pattern and combine results
536 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
537}
538
539static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
540 bool NUW, const APInt &DemandedElts,
541 KnownBits &Known, KnownBits &Known2,
542 const SimplifyQuery &Q, unsigned Depth) {
543 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
544 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
545
546 bool isKnownNegative = false;
547 bool isKnownNonNegative = false;
548 // If the multiplication is known not to overflow, compute the sign bit.
549 if (NSW) {
550 if (Op0 == Op1) {
551 // The product of a number with itself is non-negative.
552 isKnownNonNegative = true;
553 } else {
554 bool isKnownNonNegativeOp1 = Known.isNonNegative();
555 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
556 bool isKnownNegativeOp1 = Known.isNegative();
557 bool isKnownNegativeOp0 = Known2.isNegative();
558 // The product of two numbers with the same sign is non-negative.
559 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
560 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
561 if (!isKnownNonNegative && NUW) {
562 // mul nuw nsw with a factor > 1 is non-negative.
563 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
564 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
565 KnownBits::sgt(Known2, One).value_or(false);
566 }
567
568 // The product of a negative number and a non-negative number is either
569 // negative or zero.
572 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
573 Known2.isNonZero()) ||
574 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
575 }
576 }
577
578 bool SelfMultiply = Op0 == Op1;
579 if (SelfMultiply)
580 SelfMultiply &=
581 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
582 Known = KnownBits::mul(Known, Known2, SelfMultiply);
583
584 if (SelfMultiply) {
585 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
586 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
587 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
588
589 if (OutValidBits < TyBits) {
590 APInt KnownZeroMask =
591 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
592 Known.Zero |= KnownZeroMask;
593 }
594 }
595
596 // Only make use of no-wrap flags if we failed to compute the sign bit
597 // directly. This matters if the multiplication always overflows, in
598 // which case we prefer to follow the result of the direct computation,
599 // though as the program is invoking undefined behaviour we can choose
600 // whatever we like here.
601 if (isKnownNonNegative && !Known.isNegative())
602 Known.makeNonNegative();
603 else if (isKnownNegative && !Known.isNonNegative())
604 Known.makeNegative();
605}
606
608 KnownBits &Known) {
609 unsigned BitWidth = Known.getBitWidth();
610 unsigned NumRanges = Ranges.getNumOperands() / 2;
611 assert(NumRanges >= 1);
612
613 Known.setAllConflict();
614
615 for (unsigned i = 0; i < NumRanges; ++i) {
617 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
619 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
620 ConstantRange Range(Lower->getValue(), Upper->getValue());
621 // BitWidth must equal the Ranges BitWidth for the correct number of high
622 // bits to be set.
623 assert(BitWidth == Range.getBitWidth() &&
624 "Known bit width must match range bit width!");
625
626 // The first CommonPrefixBits of all values in Range are equal.
627 unsigned CommonPrefixBits =
628 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
629 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
630 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
631 Known.One &= UnsignedMax & Mask;
632 Known.Zero &= ~UnsignedMax & Mask;
633 }
634}
635
636static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
637 // The instruction defining an assumption's condition itself is always
638 // considered ephemeral to that assumption (even if it has other
639 // non-ephemeral users). See r246696's test case for an example.
640 if (is_contained(I->operands(), E))
641 return true;
642
643 const auto *EI = dyn_cast<Instruction>(E);
644 if (!EI)
645 return false;
646
647 if (EI == I)
648 return true;
649
652 Visited.insert(EI);
653 WorkList.push_back(EI);
654 bool ReachesI = false;
655 while (!WorkList.empty()) {
656 const Instruction *V = WorkList.pop_back_val();
657 for (const User *U : V->users()) {
658 const auto *UI = cast<Instruction>(U);
659 if (UI == I) {
660 ReachesI = true;
661 continue;
662 }
663 if (UI->mayHaveSideEffects() || UI->isTerminator())
664 return false;
665 if (Visited.insert(UI).second)
666 WorkList.push_back(UI);
667 }
668 }
669 return ReachesI;
670}
671
672// Is this an intrinsic that cannot be speculated but also cannot trap?
674 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
675 return CI->isAssumeLikeIntrinsic();
676
677 return false;
678}
679
681 const Instruction *CtxI,
682 const DominatorTree *DT,
683 bool AllowEphemerals) {
684 // There are two restrictions on the use of an assume:
685 // 1. The assume must dominate the context (or the control flow must
686 // reach the assume whenever it reaches the context).
687 // 2. The context must not be in the assume's set of ephemeral values
688 // (otherwise we will use the assume to prove that the condition
689 // feeding the assume is trivially true, thus causing the removal of
690 // the assume).
691
692 if (Inv->getParent() == CtxI->getParent()) {
693 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
694 // in the BB.
695 if (Inv->comesBefore(CtxI))
696 return true;
697
698 // Don't let an assume affect itself - this would cause the problems
699 // `isEphemeralValueOf` is trying to prevent, and it would also make
700 // the loop below go out of bounds.
701 if (!AllowEphemerals && Inv == CtxI)
702 return false;
703
704 // The context comes first, but they're both in the same block.
705 // Make sure there is nothing in between that might interrupt
706 // the control flow, not even CtxI itself.
707 // We limit the scan distance between the assume and its context instruction
708 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
709 // it can be adjusted if needed (could be turned into a cl::opt).
710 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
712 return false;
713
714 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
715 }
716
717 // Inv and CtxI are in different blocks.
718 if (DT) {
719 if (DT->dominates(Inv, CtxI))
720 return true;
721 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
722 Inv->getParent()->isEntryBlock()) {
723 // We don't have a DT, but this trivially dominates.
724 return true;
725 }
726
727 return false;
728}
729
732 unsigned &NumChecked) {
733 for (const Instruction &I : make_range(Begin, End)) {
734 if (NumChecked++ > MaxInstrsToCheckForFree)
735 return false;
736 if (auto *CB = dyn_cast<CallBase>(&I)) {
737 if (!CB->hasFnAttr(Attribute::NoFree))
738 return false;
739 } else if (I.maySynchronize()) {
740 return false;
741 }
742 }
743 return true;
744}
745
747 const Instruction *CtxI,
748 const DominatorTree *DT) {
749 const BasicBlock *CtxBB = CtxI->getParent();
750 const BasicBlock *AssumeBB = Assume->getParent();
751 unsigned NumChecked = 0;
752 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
753 if (CtxBB == AssumeBB) {
754 if (Assume != CtxI && !Assume->comesBefore(CtxI))
755 return false;
756 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
757 }
758 if (DT && !DT->dominates(Assume, CtxI))
759 return false;
760 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
761 return false;
762 if (pred_empty(CtxBB))
763 return false;
764
765 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
766 // backedges returning to CtxBB are enqueued and checked correctly.
769 while (!Worklist.empty()) {
770 const BasicBlock *CurBB = Worklist.pop_back_val();
771 if (!Visited.insert(CurBB).second)
772 continue;
773
774 if (CurBB == AssumeBB) {
775 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
776 return false;
777 continue;
778 }
779 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
780 "Blocks between Assume and CtxI must be dominated by AssumeBB");
781
782 if (pred_empty(CurBB))
783 return false;
784
785 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
786 // instructions from CtxIter to the end of CtxBB (instructions before
787 // CtxIter were checked above). Otherwise, check the entire block.
788 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
789 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
790 return false;
791 append_range(Worklist, predecessors(CurBB));
792 }
793 return true;
794}
795
796// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
797// we still have enough information about `RHS` to conclude non-zero. For
798// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
799// so the extra compile time may not be worth it, but possibly a second API
800// should be created for use outside of loops.
801static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
802 // v u> y implies v != 0.
803 if (Pred == ICmpInst::ICMP_UGT)
804 return true;
805
806 // Special-case v != 0 to also handle v != null.
807 if (Pred == ICmpInst::ICMP_NE)
808 return match(RHS, m_Zero());
809
810 // All other predicates - rely on generic ConstantRange handling.
811 const APInt *C;
812 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
813 if (match(RHS, m_APInt(C))) {
815 return !TrueValues.contains(Zero);
816 }
817
819 if (VC == nullptr)
820 return false;
821
822 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
823 ++ElemIdx) {
825 Pred, VC->getElementAsAPInt(ElemIdx));
826 if (TrueValues.contains(Zero))
827 return false;
828 }
829 return true;
830}
831
832static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
833 Value *&ValOut, Instruction *&CtxIOut,
834 const PHINode **PhiOut = nullptr) {
835 ValOut = U->get();
836 if (ValOut == PHI)
837 return;
838 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
839 if (PhiOut)
840 *PhiOut = PHI;
841 Value *V;
842 // If the Use is a select of this phi, compute analysis on other arm to break
843 // recursion.
844 // TODO: Min/Max
845 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
846 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
847 ValOut = V;
848
849 // Same for select, if this phi is 2-operand phi, compute analysis on other
850 // incoming value to break recursion.
851 // TODO: We could handle any number of incoming edges as long as we only have
852 // two unique values.
853 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
854 IncPhi && IncPhi->getNumIncomingValues() == 2) {
855 for (int Idx = 0; Idx < 2; ++Idx) {
856 if (IncPhi->getIncomingValue(Idx) == PHI) {
857 ValOut = IncPhi->getIncomingValue(1 - Idx);
858 if (PhiOut)
859 *PhiOut = IncPhi;
860 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
861 break;
862 }
863 }
864 }
865}
866
867static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
868 // Use of assumptions is context-sensitive. If we don't have a context, we
869 // cannot use them!
870 if (!Q.AC || !Q.CtxI)
871 return false;
872
873 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
874 if (!Elem.Assume)
875 continue;
876
877 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
878 assert(I->getFunction() == Q.CtxI->getFunction() &&
879 "Got assumption for the wrong function!");
880
881 if (Elem.Index != AssumptionCache::ExprResultIdx) {
883 I->getOperandBundleAt(Elem.Index)) &&
885 return true;
886 continue;
887 }
888
889 // Warning: This loop can end up being somewhat performance sensitive.
890 // We're running this loop for once for each value queried resulting in a
891 // runtime of ~O(#assumes * #values).
892
893 Value *RHS;
894 CmpPredicate Pred;
895 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
896 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
897 continue;
898
900 return true;
901 }
902
903 return false;
904}
905
908 const SimplifyQuery &Q) {
909 if (RHS->getType()->isPointerTy()) {
910 // Handle comparison of pointer to null explicitly, as it will not be
911 // covered by the m_APInt() logic below.
912 if (LHS == V && match(RHS, m_Zero())) {
913 switch (Pred) {
915 Known.setAllZero();
916 break;
919 Known.makeNonNegative();
920 break;
922 Known.makeNegative();
923 break;
924 default:
925 break;
926 }
927 }
928 return;
929 }
930
931 unsigned BitWidth = Known.getBitWidth();
932 auto m_V =
934
935 Value *Y;
936 const APInt *Mask, *C;
937 if (!match(RHS, m_APInt(C)))
938 return;
939
940 uint64_t ShAmt;
941 switch (Pred) {
943 // assume(V = C)
944 if (match(LHS, m_V)) {
945 Known = Known.unionWith(KnownBits::makeConstant(*C));
946 // assume(V & Mask = C)
947 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
948 // For one bits in Mask, we can propagate bits from C to V.
949 Known.One |= *C;
950 if (match(Y, m_APInt(Mask)))
951 Known.Zero |= ~*C & *Mask;
952 // assume(V | Mask = C)
953 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
954 // For zero bits in Mask, we can propagate bits from C to V.
955 Known.Zero |= ~*C;
956 if (match(Y, m_APInt(Mask)))
957 Known.One |= *C & ~*Mask;
958 // assume(V << ShAmt = C)
959 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
960 ShAmt < BitWidth) {
961 // For those bits in C that are known, we can propagate them to known
962 // bits in V shifted to the right by ShAmt.
964 RHSKnown >>= ShAmt;
965 Known = Known.unionWith(RHSKnown);
966 // assume(V >> ShAmt = C)
967 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
968 ShAmt < BitWidth) {
969 // For those bits in RHS that are known, we can propagate them to known
970 // bits in V shifted to the right by C.
972 RHSKnown <<= ShAmt;
973 Known = Known.unionWith(RHSKnown);
974 }
975 break;
976 case ICmpInst::ICMP_NE: {
977 // assume (V & B != 0) where B is a power of 2
978 const APInt *BPow2;
979 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
980 Known.One |= *BPow2;
981 break;
982 }
983 default: {
984 const APInt *Offset = nullptr;
985 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
987 if (Offset)
988 LHSRange = LHSRange.sub(*Offset);
989 Known = Known.unionWith(LHSRange.toKnownBits());
990 }
991 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
992 // X & Y u> C -> X u> C && Y u> C
993 // X nuw- Y u> C -> X u> C
994 if (match(LHS, m_c_And(m_V, m_Value())) ||
995 match(LHS, m_NUWSub(m_V, m_Value())))
996 Known.One.setHighBits(
997 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
998 }
999 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1000 // X | Y u< C -> X u< C && Y u< C
1001 // X nuw+ Y u< C -> X u< C && Y u< C
1002 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1003 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1004 Known.Zero.setHighBits(
1005 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1006 }
1007 }
1008 } break;
1009 }
1010}
1011
1014 const SimplifyQuery &SQ, bool Invert) {
1015 ICmpInst::Predicate Pred =
1016 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1017 Value *LHS = Cmp->getOperand(0);
1018 Value *RHS = Cmp->getOperand(1);
1019
1020 // Handle icmp pred (trunc V), C
1021 if (match(LHS, m_Trunc(m_Specific(V)))) {
1022 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1023 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1025 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1026 else
1027 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1028 return;
1029 }
1030
1031 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1032}
1033
1035 KnownBits &Known, const SimplifyQuery &SQ,
1036 bool Invert, unsigned Depth) {
1037 Value *A, *B;
1040 KnownBits Known2(Known.getBitWidth());
1041 KnownBits Known3(Known.getBitWidth());
1042 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1043 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1044 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1046 Known2 = Known2.unionWith(Known3);
1047 else
1048 Known2 = Known2.intersectWith(Known3);
1049 Known = Known.unionWith(Known2);
1050 return;
1051 }
1052
1053 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1054 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1055 return;
1056 }
1057
1058 if (match(Cond, m_Trunc(m_Specific(V)))) {
1059 KnownBits DstKnown(1);
1060 if (Invert) {
1061 DstKnown.setAllZero();
1062 } else {
1063 DstKnown.setAllOnes();
1064 }
1066 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1067 return;
1068 }
1069 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1070 return;
1071 }
1072
1074 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1075}
1076
1078 const SimplifyQuery &Q, unsigned Depth) {
1079 // Handle injected condition.
1080 if (Q.CC && Q.CC->AffectedValues.contains(V))
1082
1083 if (!Q.CtxI)
1084 return;
1085
1086 if (Q.DC && Q.DT) {
1087 // Handle dominating conditions.
1088 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1089 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1090 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1091 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1092 /*Invert*/ false, Depth);
1093
1094 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1095 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1096 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1097 /*Invert*/ true, Depth);
1098 }
1099
1100 if (Known.hasConflict())
1101 Known.resetAll();
1102 }
1103
1104 if (!Q.AC)
1105 return;
1106
1107 unsigned BitWidth = Known.getBitWidth();
1108
1109 // Note that the patterns below need to be kept in sync with the code
1110 // in AssumptionCache::updateAffectedValues.
1111
1112 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1113 if (!Elem.Assume)
1114 continue;
1115
1116 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1117 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1118 "Got assumption for the wrong function!");
1119
1120 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1121 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1122 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1123 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1124 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1126 Known.Zero |= (*Alignment - 1) & ~*Offset;
1127 Known.One |= (*Alignment - 1) & *Offset;
1128 }
1129 }
1130 continue;
1131 }
1132
1133 // Warning: This loop can end up being somewhat performance sensitive.
1134 // We're running this loop for once for each value queried resulting in a
1135 // runtime of ~O(#assumes * #values).
1136
1137 Value *Arg = I->getArgOperand(0);
1138
1139 if (Arg == V && isValidAssumeForContext(I, Q)) {
1140 assert(BitWidth == 1 && "assume operand is not i1?");
1141 (void)BitWidth;
1142 Known.setAllOnes();
1143 return;
1144 }
1145 if (match(Arg, m_Not(m_Specific(V))) &&
1147 assert(BitWidth == 1 && "assume operand is not i1?");
1148 (void)BitWidth;
1149 Known.setAllZero();
1150 return;
1151 }
1152 auto *Trunc = dyn_cast<TruncInst>(Arg);
1153 if (Trunc && Trunc->getOperand(0) == V &&
1155 if (Trunc->hasNoUnsignedWrap()) {
1157 return;
1158 }
1159 Known.One.setBit(0);
1160 return;
1161 }
1162
1163 // The remaining tests are all recursive, so bail out if we hit the limit.
1165 continue;
1166
1167 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1168 if (!Cmp)
1169 continue;
1170
1171 if (!isValidAssumeForContext(I, Q))
1172 continue;
1173
1174 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1175 }
1176
1177 // Conflicting assumption: Undefined behavior will occur on this execution
1178 // path.
1179 if (Known.hasConflict())
1180 Known.resetAll();
1181}
1182
1183/// Compute known bits from a shift operator, including those with a
1184/// non-constant shift amount. Known is the output of this function. Known2 is a
1185/// pre-allocated temporary with the same bit width as Known and on return
1186/// contains the known bit of the shift value source. KF is an
1187/// operator-specific function that, given the known-bits and a shift amount,
1188/// compute the implied known-bits of the shift operator's result respectively
1189/// for that shift amount. The results from calling KF are conservatively
1190/// combined for all permitted shift amounts.
1192 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1193 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1194 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1195 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1196 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1197 // To limit compile-time impact, only query isKnownNonZero() if we know at
1198 // least something about the shift amount.
1199 bool ShAmtNonZero =
1200 Known.isNonZero() ||
1201 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1202 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1203 Known = KF(Known2, Known, ShAmtNonZero);
1204}
1205
1206static KnownBits
1207getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1208 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1209 const SimplifyQuery &Q, unsigned Depth) {
1210 unsigned BitWidth = KnownLHS.getBitWidth();
1211 KnownBits KnownOut(BitWidth);
1212 bool IsAnd = false;
1213 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1214 Value *X = nullptr, *Y = nullptr;
1215
1216 switch (I->getOpcode()) {
1217 case Instruction::And:
1218 KnownOut = KnownLHS & KnownRHS;
1219 IsAnd = true;
1220 // and(x, -x) is common idioms that will clear all but lowest set
1221 // bit. If we have a single known bit in x, we can clear all bits
1222 // above it.
1223 // TODO: instcombine often reassociates independent `and` which can hide
1224 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1225 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1226 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1227 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1228 KnownOut = KnownLHS.blsi();
1229 else
1230 KnownOut = KnownRHS.blsi();
1231 }
1232 break;
1233 case Instruction::Or:
1234 KnownOut = KnownLHS | KnownRHS;
1235 break;
1236 case Instruction::Xor:
1237 KnownOut = KnownLHS ^ KnownRHS;
1238 // xor(x, x-1) is common idioms that will clear all but lowest set
1239 // bit. If we have a single known bit in x, we can clear all bits
1240 // above it.
1241 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1242 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1243 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1244 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1245 if (HasKnownOne &&
1247 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1248 KnownOut = XBits.blsmsk();
1249 }
1250 break;
1251 default:
1252 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1253 }
1254
1255 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1256 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1257 // here we handle the more general case of adding any odd number by
1258 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1259 // TODO: This could be generalized to clearing any bit set in y where the
1260 // following bit is known to be unset in y.
1261 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1265 KnownBits KnownY(BitWidth);
1266 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1267 if (KnownY.countMinTrailingOnes() > 0) {
1268 if (IsAnd)
1269 KnownOut.Zero.setBit(0);
1270 else
1271 KnownOut.One.setBit(0);
1272 }
1273 }
1274 return KnownOut;
1275}
1276
1278 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1279 unsigned Depth,
1280 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1281 KnownBitsFunc) {
1282 APInt DemandedEltsLHS, DemandedEltsRHS;
1284 DemandedElts, DemandedEltsLHS,
1285 DemandedEltsRHS);
1286
1287 const auto ComputeForSingleOpFunc =
1288 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1289 return KnownBitsFunc(
1290 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1291 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1292 };
1293
1294 if (DemandedEltsRHS.isZero())
1295 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1296 if (DemandedEltsLHS.isZero())
1297 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1298
1299 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1300 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1301}
1302
1303// Public so this can be used in `SimplifyDemandedUseBits`.
1305 const KnownBits &KnownLHS,
1306 const KnownBits &KnownRHS,
1307 const SimplifyQuery &SQ,
1308 unsigned Depth) {
1309 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1310 APInt DemandedElts =
1311 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1312
1313 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1314 Depth);
1315}
1316
1318 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1319 // Without vscale_range, we only know that vscale is non-zero.
1320 if (!Attr.isValid())
1322
1323 unsigned AttrMin = Attr.getVScaleRangeMin();
1324 // Minimum is larger than vscale width, result is always poison.
1325 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1326 return ConstantRange::getEmpty(BitWidth);
1327
1328 APInt Min(BitWidth, AttrMin);
1329 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1330 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1332
1333 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1334}
1335
1336/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1337/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1338/// target's VLEN range. Callers must ensure the target is RISC-V.
1339static bool isReadVLENB(const IntrinsicInst &II) {
1340 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1341 if (!MAV)
1342 return false;
1343 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1344 if (!MD || MD->getNumOperands() != 1)
1345 return false;
1346 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1347 return RegName && RegName->getString() == "vlenb";
1348}
1349
1350/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1351/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1352/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1353/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1354/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1355/// attribute, when present, pins the subtarget's VLEN in units of
1356/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1357/// RVVBytesPerBlock.
1359 unsigned Width) {
1360 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1361 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1362
1363 const Function *F = II.getFunction();
1364 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1365 ConstantRange VScale = getVScaleRange(F, Width);
1366 Range = Range.intersectWith(
1368 }
1369 return Range;
1370}
1371
1373 Value *Arm, bool Invert,
1374 const SimplifyQuery &Q, unsigned Depth) {
1375 // If we have a constant arm, we are done.
1376 if (Known.isConstant())
1377 return;
1378
1379 // See what condition implies about the bits of the select arm.
1380 KnownBits CondRes(Known.getBitWidth());
1381 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1382 // If we don't get any information from the condition, no reason to
1383 // proceed.
1384 if (CondRes.isUnknown())
1385 return;
1386
1387 // We can have conflict if the condition is dead. I.e if we have
1388 // (x | 64) < 32 ? (x | 64) : y
1389 // we will have conflict at bit 6 from the condition/the `or`.
1390 // In that case just return. Its not particularly important
1391 // what we do, as this select is going to be simplified soon.
1392 CondRes = CondRes.unionWith(Known);
1393 if (CondRes.hasConflict())
1394 return;
1395
1396 // Finally make sure the information we found is valid. This is relatively
1397 // expensive so it's left for the very end.
1398 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1399 return;
1400
1401 // Finally, we know we get information from the condition and its valid,
1402 // so return it.
1403 Known = std::move(CondRes);
1404}
1405
1406// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1407// Returns the input and lower/upper bounds.
1408static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1409 const APInt *&CLow, const APInt *&CHigh) {
1411 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1412 "Input should be a Select!");
1413
1414 const Value *LHS = nullptr, *RHS = nullptr;
1416 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1417 return false;
1418
1419 if (!match(RHS, m_APInt(CLow)))
1420 return false;
1421
1422 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1424 if (getInverseMinMaxFlavor(SPF) != SPF2)
1425 return false;
1426
1427 if (!match(RHS2, m_APInt(CHigh)))
1428 return false;
1429
1430 if (SPF == SPF_SMIN)
1431 std::swap(CLow, CHigh);
1432
1433 In = LHS2;
1434 return CLow->sle(*CHigh);
1435}
1436
1438 const APInt *&CLow,
1439 const APInt *&CHigh) {
1440 assert((II->getIntrinsicID() == Intrinsic::smin ||
1441 II->getIntrinsicID() == Intrinsic::smax) &&
1442 "Must be smin/smax");
1443
1444 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1445 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1446 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1447 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1448 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1449 return false;
1450
1451 if (II->getIntrinsicID() == Intrinsic::smin)
1452 std::swap(CLow, CHigh);
1453 return CLow->sle(*CHigh);
1454}
1455
1457 KnownBits &Known) {
1458 const APInt *CLow, *CHigh;
1459 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1460 Known = Known.unionWith(
1461 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1462}
1463
1465 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1466 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1467 unsigned Depth) {
1468 // Change the context instruction to the "edge" that flows into the phi. This
1469 // is important because that is where the value is actually "evaluated" even
1470 // though it is used later somewhere else. (see also D69571).
1472 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1473
1474 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1475 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1476
1477 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1478 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1479}
1480
1482 const APInt &DemandedElts,
1484 const SimplifyQuery &Q,
1485 unsigned Depth) {
1486 unsigned BitWidth = Known.getBitWidth();
1487
1488 KnownBits Known2(BitWidth);
1489 switch (I->getOpcode()) {
1490 default: break;
1491 case Instruction::Load:
1492 if (MDNode *MD =
1493 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1495 break;
1496 case Instruction::And:
1497 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1498 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1499
1500 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1501 break;
1502 case Instruction::Or:
1503 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1504 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1505
1506 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1507 break;
1508 case Instruction::Xor:
1509 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1510 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1511
1512 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1513 break;
1514 case Instruction::Mul: {
1517 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1518 DemandedElts, Known, Known2, Q, Depth);
1519 break;
1520 }
1521 case Instruction::UDiv: {
1522 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1523 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1524 Known =
1526 break;
1527 }
1528 case Instruction::SDiv: {
1529 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1530 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1531 Known =
1533 break;
1534 }
1535 case Instruction::Select: {
1536 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1537 KnownBits Res(Known.getBitWidth());
1538 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1539 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1540 return Res;
1541 };
1542 // Only known if known in both the LHS and RHS.
1543 Known =
1544 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1545 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1546 break;
1547 }
1548 case Instruction::FPToSI: {
1549 // fptosi is poison if the rounded value doesn't fit in the result type,
1550 // so we can assume the conversion is well-defined and rounds towards
1551 // zero. +-Inf can never fit in an integer type, so it is always poison,
1552 // like NaN. Negative subnormals and negative zero round to 0. That
1553 // leaves negative normals as the only class that can produce a defined
1554 // negative result.
1555 KnownFPClass SrcFPClass = computeKnownFPClass(
1556 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1557 if (SrcFPClass.isKnownNever(fcNegNormal))
1558 Known.makeNonNegative();
1559 break;
1560 }
1561 case Instruction::FPTrunc:
1562 case Instruction::FPExt:
1563 case Instruction::FPToUI:
1564 case Instruction::SIToFP:
1565 case Instruction::UIToFP:
1566 break; // Can't work with floating point.
1567 case Instruction::PtrToInt:
1568 case Instruction::PtrToAddr:
1569 case Instruction::IntToPtr:
1570 // Fall through and handle them the same as zext/trunc.
1571 [[fallthrough]];
1572 case Instruction::ZExt:
1573 case Instruction::Trunc: {
1574 Type *SrcTy = I->getOperand(0)->getType();
1575
1576 unsigned SrcBitWidth;
1577 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1578 // which fall through here.
1579 Type *ScalarTy = SrcTy->getScalarType();
1580 SrcBitWidth = ScalarTy->isPointerTy() ?
1581 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1582 Q.DL.getTypeSizeInBits(ScalarTy);
1583
1584 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1585 Known = Known.anyextOrTrunc(SrcBitWidth);
1586 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1587 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1588 Inst && Inst->hasNonNeg() && !Known.isNegative())
1589 Known.makeNonNegative();
1590 Known = Known.zextOrTrunc(BitWidth);
1591 break;
1592 }
1593 case Instruction::BitCast: {
1594 Type *SrcTy = I->getOperand(0)->getType();
1595 if (SrcTy->isIntOrPtrTy() &&
1596 // TODO: For now, not handling conversions like:
1597 // (bitcast i64 %x to <2 x i32>)
1598 !I->getType()->isVectorTy()) {
1599 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1600 break;
1601 }
1602
1603 const Value *V;
1604 // Handle bitcast from floating point to integer.
1605 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1606 V->getType()->isFPOrFPVectorTy()) {
1607 Type *FPType = V->getType()->getScalarType();
1608 KnownFPClass Result =
1609 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1610
1611 Known = Result.toKnownBits(FPType->getFltSemantics());
1612
1613 break;
1614 }
1615
1616 // Handle cast from vector integer type to scalar or vector integer.
1617 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1618 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1619 !I->getType()->isIntOrIntVectorTy() ||
1620 isa<ScalableVectorType>(I->getType()))
1621 break;
1622
1623 unsigned NumElts = DemandedElts.getBitWidth();
1624 bool IsLE = Q.DL.isLittleEndian();
1625 // Look through a cast from narrow vector elements to wider type.
1626 // Examples: v4i32 -> v2i64, v3i8 -> v24
1627 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1628 if (BitWidth % SubBitWidth == 0) {
1629 // Known bits are automatically intersected across demanded elements of a
1630 // vector. So for example, if a bit is computed as known zero, it must be
1631 // zero across all demanded elements of the vector.
1632 //
1633 // For this bitcast, each demanded element of the output is sub-divided
1634 // across a set of smaller vector elements in the source vector. To get
1635 // the known bits for an entire element of the output, compute the known
1636 // bits for each sub-element sequentially. This is done by shifting the
1637 // one-set-bit demanded elements parameter across the sub-elements for
1638 // consecutive calls to computeKnownBits. We are using the demanded
1639 // elements parameter as a mask operator.
1640 //
1641 // The known bits of each sub-element are then inserted into place
1642 // (dependent on endian) to form the full result of known bits.
1643 unsigned SubScale = BitWidth / SubBitWidth;
1644 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1645 for (unsigned i = 0; i != NumElts; ++i) {
1646 if (DemandedElts[i])
1647 SubDemandedElts.setBit(i * SubScale);
1648 }
1649
1650 KnownBits KnownSrc(SubBitWidth);
1651 for (unsigned i = 0; i != SubScale; ++i) {
1652 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1653 Depth + 1);
1654 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1655 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1656 }
1657 }
1658 // Look through a cast from wider vector elements to narrow type.
1659 // Examples: v2i64 -> v4i32
1660 if (SubBitWidth % BitWidth == 0) {
1661 unsigned SubScale = SubBitWidth / BitWidth;
1662 KnownBits KnownSrc(SubBitWidth);
1663 APInt SubDemandedElts =
1664 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1665 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1666 Depth + 1);
1667
1668 Known.setAllConflict();
1669 for (unsigned i = 0; i != NumElts; ++i) {
1670 if (DemandedElts[i]) {
1671 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1672 unsigned Offset = (Shifts % SubScale) * BitWidth;
1673 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1674 if (Known.isUnknown())
1675 break;
1676 }
1677 }
1678 }
1679 break;
1680 }
1681 case Instruction::SExt: {
1682 // Compute the bits in the result that are not present in the input.
1683 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1684
1685 Known = Known.trunc(SrcBitWidth);
1686 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1687 // If the sign bit of the input is known set or clear, then we know the
1688 // top bits of the result.
1689 Known = Known.sext(BitWidth);
1690 break;
1691 }
1692 case Instruction::Shl: {
1695 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1696 bool ShAmtNonZero) {
1697 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1698 };
1699 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1700 KF);
1701 // Trailing zeros of a right-shifted constant never decrease.
1702 const APInt *C;
1703 if (match(I->getOperand(0), m_APInt(C)))
1704 Known.Zero.setLowBits(C->countr_zero());
1705
1706 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1707 // lands at bit Y, when BitWidth is a power of 2.
1708 const APInt *YC;
1709 Value *X = I->getOperand(0);
1710 if (isPowerOf2_32(BitWidth) &&
1711 match(I->getOperand(1),
1713 m_SpecificInt(BitWidth - 1)))) &&
1714 YC->ult(BitWidth - 1)) {
1715 unsigned Y = YC->getZExtValue();
1716 Known.One.setBit(Y);
1717 Known.Zero.setBitsFrom(Y + 1);
1718 }
1719 break;
1720 }
1721 case Instruction::LShr: {
1722 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1723 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1724 bool ShAmtNonZero) {
1725 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1726 };
1727 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1728 KF);
1729 // Leading zeros of a left-shifted constant never decrease.
1730 const APInt *C;
1731 if (match(I->getOperand(0), m_APInt(C)))
1732 Known.Zero.setHighBits(C->countl_zero());
1733 break;
1734 }
1735 case Instruction::AShr: {
1736 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1737 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1738 bool ShAmtNonZero) {
1739 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1740 };
1741 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1742 KF);
1743 break;
1744 }
1745 case Instruction::Sub: {
1748 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1749 DemandedElts, Known, Known2, Q, Depth);
1750 break;
1751 }
1752 case Instruction::Add: {
1755 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1756 DemandedElts, Known, Known2, Q, Depth);
1757 break;
1758 }
1759 case Instruction::SRem:
1760 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1761 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1762 Known = KnownBits::srem(Known, Known2);
1763 break;
1764
1765 case Instruction::URem:
1766 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1767 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1768 Known = KnownBits::urem(Known, Known2);
1769 break;
1770 case Instruction::Alloca:
1771 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1772 break;
1773 case Instruction::GetElementPtr: {
1774 // Analyze all of the subscripts of this getelementptr instruction
1775 // to determine if we can prove known low zero bits.
1776 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1777 // Accumulate the constant indices in a separate variable
1778 // to minimize the number of calls to computeForAddSub.
1779 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1780 APInt AccConstIndices(IndexWidth, 0);
1781
1782 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1783 if (IndexWidth == BitWidth) {
1784 // Note that inbounds does *not* guarantee nsw for the addition, as only
1785 // the offset is signed, while the base address is unsigned.
1786 Known = KnownBits::add(Known, IndexBits);
1787 } else {
1788 // If the index width is smaller than the pointer width, only add the
1789 // value to the low bits.
1790 assert(IndexWidth < BitWidth &&
1791 "Index width can't be larger than pointer width");
1792 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1793 }
1794 };
1795
1797 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1798 // TrailZ can only become smaller, short-circuit if we hit zero.
1799 if (Known.isUnknown())
1800 break;
1801
1802 Value *Index = I->getOperand(i);
1803
1804 // Handle case when index is zero.
1805 Constant *CIndex = dyn_cast<Constant>(Index);
1806 if (CIndex && CIndex->isNullValue())
1807 continue;
1808
1809 if (StructType *STy = GTI.getStructTypeOrNull()) {
1810 // Handle struct member offset arithmetic.
1811
1812 assert(CIndex &&
1813 "Access to structure field must be known at compile time");
1814
1815 if (CIndex->getType()->isVectorTy())
1816 Index = CIndex->getSplatValue();
1817
1818 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1819 const StructLayout *SL = Q.DL.getStructLayout(STy);
1820 uint64_t Offset = SL->getElementOffset(Idx);
1821 AccConstIndices += Offset;
1822 continue;
1823 }
1824
1825 // Handle array index arithmetic.
1826 Type *IndexedTy = GTI.getIndexedType();
1827 if (!IndexedTy->isSized()) {
1828 Known.resetAll();
1829 break;
1830 }
1831
1832 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1833 uint64_t StrideInBytes = Stride.getKnownMinValue();
1834 if (!Stride.isScalable()) {
1835 // Fast path for constant offset.
1836 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1837 AccConstIndices +=
1838 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1839 continue;
1840 }
1841 }
1842
1843 KnownBits IndexBits =
1844 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1845 KnownBits ScalingFactor(IndexWidth);
1846 // Multiply by current sizeof type.
1847 // &A[i] == A + i * sizeof(*A[i]).
1848 if (Stride.isScalable()) {
1849 // For scalable types the only thing we know about sizeof is
1850 // that this is a multiple of the minimum size.
1851 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1852 } else {
1853 ScalingFactor =
1854 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1855 }
1856 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1857 }
1858 if (!Known.isUnknown() && !AccConstIndices.isZero())
1859 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1860 break;
1861 }
1862 case Instruction::PHI: {
1863 const PHINode *P = cast<PHINode>(I);
1864 BinaryOperator *BO = nullptr;
1865 Value *Start = nullptr, *Step = nullptr;
1866 KnownBits &KnownStart = Known2;
1867 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1868 // Handle the case of a simple two-predecessor recurrence PHI.
1869 // There's a lot more that could theoretically be done here, but
1870 // this is sufficient to catch some interesting cases.
1871 unsigned Opcode = BO->getOpcode();
1872
1873 switch (Opcode) {
1874 // If this is a shift recurrence, we know the bits being shifted in. We
1875 // can combine that with information about the start value of the
1876 // recurrence to conclude facts about the result. If this is a udiv
1877 // recurrence, we know that the result can never exceed either the
1878 // numerator or the start value, whichever is greater.
1879 case Instruction::LShr:
1880 case Instruction::AShr:
1881 case Instruction::Shl:
1882 case Instruction::UDiv:
1883 if (BO->getOperand(0) != I)
1884 break;
1885 [[fallthrough]];
1886
1887 // For a urem recurrence, the result can never exceed the start value. The
1888 // phi could either be the numerator or the denominator.
1889 case Instruction::URem: {
1890 // We have matched a recurrence of the form:
1891 // %iv = [R, %entry], [%iv.next, %backedge]
1892 // %iv.next = shift_op %iv, L
1893
1894 // Recurse with the phi context to avoid concern about whether facts
1895 // inferred hold at original context instruction. TODO: It may be
1896 // correct to use the original context. IF warranted, explore and
1897 // add sufficient tests to cover.
1899 RecQ.CtxI = P;
1900 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1901 switch (Opcode) {
1902 case Instruction::Shl:
1903 // A shl recurrence will only increase the tailing zeros
1904 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1905 break;
1906 case Instruction::LShr:
1907 case Instruction::UDiv:
1908 case Instruction::URem:
1909 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1910 // the start value.
1911 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1912 break;
1913 case Instruction::AShr:
1914 // An ashr recurrence will extend the initial sign bit
1915 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1916 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1917 break;
1918 }
1919 break;
1920 }
1921
1922 // Check for operations that have the property that if
1923 // both their operands have low zero bits, the result
1924 // will have low zero bits.
1925 case Instruction::Add:
1926 case Instruction::Sub:
1927 case Instruction::And:
1928 case Instruction::Or:
1929 case Instruction::Mul: {
1930 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1931 // zero bits.
1932 KnownBits KnownStep(BitWidth);
1933 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1934 KnownStart, KnownStep, Q, Depth);
1935
1936 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1937 KnownStep.countMinTrailingZeros()));
1938
1939 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1940 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1941 break;
1942
1943 switch (Opcode) {
1944 // If initial value of recurrence is nonnegative, and we are adding
1945 // a nonnegative number with nsw, the result can only be nonnegative
1946 // or poison value regardless of the number of times we execute the
1947 // add in phi recurrence. If initial value is negative and we are
1948 // adding a negative number with nsw, the result can only be
1949 // negative or poison value. Similar arguments apply to sub and mul.
1950 //
1951 // (add non-negative, non-negative) --> non-negative
1952 // (add negative, negative) --> negative
1953 case Instruction::Add: {
1954 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1955 Known.makeNonNegative();
1956 else if (KnownStart.isNegative() && KnownStep.isNegative())
1957 Known.makeNegative();
1958 break;
1959 }
1960
1961 // (sub nsw non-negative, negative) --> non-negative
1962 // (sub nsw negative, non-negative) --> negative
1963 case Instruction::Sub: {
1964 if (BO->getOperand(0) != I)
1965 break;
1966 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1967 Known.makeNonNegative();
1968 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1969 Known.makeNegative();
1970 break;
1971 }
1972
1973 // (mul nsw non-negative, non-negative) --> non-negative
1974 case Instruction::Mul:
1975 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1976 Known.makeNonNegative();
1977 break;
1978
1979 default:
1980 break;
1981 }
1982 break;
1983 }
1984
1985 default:
1986 break;
1987 }
1988 } else {
1989 IntrinsicInst *II = nullptr;
1990 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
1991 // %iv = [<Start>, %entry], [%iv.next, %backedge]
1992 //
1993 // %iv.next = <II>(%iv, <Step>)
1994 // or
1995 // %iv.next = <II>(<Step>, %iv)
1996 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
1997 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
1998 KnownBits KnownStep(BitWidth);
2000 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2001
2002 if (IntrinsicID == Intrinsic::umin) {
2003 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2004 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2005 KnownStep.countMinLeadingOnes()));
2006 } else {
2007 // umax
2008 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2009 KnownStep.countMinLeadingZeros()));
2010 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2011 }
2012 }
2013 }
2014 }
2015
2016 // Unreachable blocks may have zero-operand PHI nodes.
2017 if (P->getNumIncomingValues() == 0)
2018 break;
2019
2020 // Otherwise take the unions of the known bit sets of the operands,
2021 // taking conservative care to avoid excessive recursion.
2022 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2023 // Skip if every incoming value references to ourself.
2024 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2025 break;
2026
2027 Known.setAllConflict();
2028 for (const Use &U : P->operands()) {
2029 Value *IncValue;
2030 const PHINode *CtxPhi;
2031 Instruction *CtxI;
2032 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2033 // Skip direct self references.
2034 if (IncValue == P)
2035 continue;
2036
2037 // Change the context instruction to the "edge" that flows into the
2038 // phi. This is important because that is where the value is actually
2039 // "evaluated" even though it is used later somewhere else. (see also
2040 // D69571).
2042
2043 Known2 = KnownBits(BitWidth);
2044
2045 // Recurse, but cap the recursion to one level, because we don't
2046 // want to waste time spinning around in loops.
2047 // TODO: See if we can base recursion limiter on number of incoming phi
2048 // edges so we don't overly clamp analysis.
2049 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2051
2052 // See if we can further use a conditional branch into the phi
2053 // to help us determine the range of the value.
2054 if (!Known2.isConstant()) {
2055 CmpPredicate Pred;
2056 const APInt *RHSC;
2057 BasicBlock *TrueSucc, *FalseSucc;
2058 // TODO: Use RHS Value and compute range from its known bits.
2059 if (match(RecQ.CtxI,
2060 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2061 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2062 // Check for cases of duplicate successors.
2063 if ((TrueSucc == CtxPhi->getParent()) !=
2064 (FalseSucc == CtxPhi->getParent())) {
2065 // If we're using the false successor, invert the predicate.
2066 if (FalseSucc == CtxPhi->getParent())
2067 Pred = CmpInst::getInversePredicate(Pred);
2068 // Get the knownbits implied by the incoming phi condition.
2069 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2070 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2071 // We can have conflicts here if we are analyzing deadcode (its
2072 // impossible for us reach this BB based the icmp).
2073 if (KnownUnion.hasConflict()) {
2074 // No reason to continue analyzing in a known dead region, so
2075 // just resetAll and break. This will cause us to also exit the
2076 // outer loop.
2077 Known.resetAll();
2078 break;
2079 }
2080 Known2 = KnownUnion;
2081 }
2082 }
2083 }
2084
2085 Known = Known.intersectWith(Known2);
2086 // If all bits have been ruled out, there's no need to check
2087 // more operands.
2088 if (Known.isUnknown())
2089 break;
2090 }
2091 }
2092 break;
2093 }
2094 case Instruction::Call:
2095 case Instruction::Invoke: {
2096 // If range metadata is attached to this call, set known bits from that,
2097 // and then intersect with known bits based on other properties of the
2098 // function.
2099 if (MDNode *MD =
2100 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2102
2103 const auto *CB = cast<CallBase>(I);
2104
2105 if (std::optional<ConstantRange> Range = CB->getRange())
2106 Known = Known.unionWith(Range->toKnownBits());
2107
2108 if (const Value *RV = CB->getReturnedArgOperand()) {
2109 if (RV->getType() == I->getType()) {
2110 computeKnownBits(RV, Known2, Q, Depth + 1);
2111 Known = Known.unionWith(Known2);
2112 // If the function doesn't return properly for all input values
2113 // (e.g. unreachable exits) then there might be conflicts between the
2114 // argument value and the range metadata. Simply discard the known bits
2115 // in case of conflicts.
2116 if (Known.hasConflict())
2117 Known.resetAll();
2118 }
2119 }
2120 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2121 switch (II->getIntrinsicID()) {
2122 default:
2123 break;
2124 case Intrinsic::abs: {
2125 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2126 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2127 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2128 break;
2129 }
2130 case Intrinsic::bitreverse:
2131 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2132 Known = Known.unionWith(Known2.reverseBits());
2133 break;
2134 case Intrinsic::bswap:
2135 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2136 Known = Known.unionWith(Known2.byteSwap());
2137 break;
2138 case Intrinsic::ctlz: {
2139 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2140 // If we have a known 1, its position is our upper bound.
2141 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2142 // If this call is poison for 0 input, the result will be less than 2^n.
2143 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2144 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2145 unsigned LowBits = llvm::bit_width(PossibleLZ);
2146 Known.Zero.setBitsFrom(LowBits);
2147 break;
2148 }
2149 case Intrinsic::cttz: {
2150 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2151 // If we have a known 1, its position is our upper bound.
2152 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2153 // If this call is poison for 0 input, the result will be less than 2^n.
2154 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2155 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2156 unsigned LowBits = llvm::bit_width(PossibleTZ);
2157 Known.Zero.setBitsFrom(LowBits);
2158 break;
2159 }
2160 case Intrinsic::ctpop: {
2161 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2162 // We can bound the space the count needs. Also, bits known to be zero
2163 // can't contribute to the population.
2164 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2165 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2166 Known.Zero.setBitsFrom(LowBits);
2167 // TODO: we could bound KnownOne using the lower bound on the number
2168 // of bits which might be set provided by popcnt KnownOne2.
2169 break;
2170 }
2171 case Intrinsic::fshr:
2172 case Intrinsic::fshl: {
2173 const APInt *SA;
2174 if (!match(I->getOperand(2), m_APInt(SA)))
2175 break;
2176
2177 KnownBits Known3(BitWidth);
2178 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2179 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2180 Known = II->getIntrinsicID() == Intrinsic::fshl
2181 ? KnownBits::fshl(Known2, Known3, *SA)
2182 : KnownBits::fshr(Known2, Known3, *SA);
2183 break;
2184 }
2185 case Intrinsic::clmul:
2186 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2187 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2188 Known = KnownBits::clmul(Known, Known2);
2189 break;
2190 case Intrinsic::pext:
2191 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2192 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2193 Known = KnownBits::pext(Known, Known2);
2194 break;
2195 case Intrinsic::pdep:
2196 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2197 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2198 Known = KnownBits::pdep(Known, Known2);
2199 break;
2200 case Intrinsic::smulh:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::mulhs(Known, Known2);
2204 break;
2205 case Intrinsic::umulh:
2206 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2207 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2208 Known = KnownBits::mulhu(Known, Known2);
2209 break;
2210 case Intrinsic::uadd_sat:
2211 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2212 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2213 Known = KnownBits::uadd_sat(Known, Known2);
2214 break;
2215 case Intrinsic::usub_sat:
2216 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2217 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2218 Known = KnownBits::usub_sat(Known, Known2);
2219 break;
2220 case Intrinsic::sadd_sat:
2221 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2222 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2223 Known = KnownBits::sadd_sat(Known, Known2);
2224 break;
2225 case Intrinsic::ssub_sat:
2226 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2227 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2228 Known = KnownBits::ssub_sat(Known, Known2);
2229 break;
2230 // Vec reverse preserves bits from input vec.
2231 case Intrinsic::vector_reverse:
2232 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2233 Depth + 1);
2234 break;
2235 // for min/max/and/or reduce, any bit common to each element in the
2236 // input vec is set in the output.
2237 case Intrinsic::vector_reduce_and:
2238 case Intrinsic::vector_reduce_or:
2239 case Intrinsic::vector_reduce_umax:
2240 case Intrinsic::vector_reduce_umin:
2241 case Intrinsic::vector_reduce_smax:
2242 case Intrinsic::vector_reduce_smin:
2243 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2244 break;
2245 case Intrinsic::vector_reduce_xor: {
2246 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2247 // The zeros common to all vecs are zero in the output.
2248 // If the number of elements is odd, then the common ones remain. If the
2249 // number of elements is even, then the common ones becomes zeros.
2250 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2251 // Even, so the ones become zeros.
2252 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2253 if (EvenCnt)
2254 Known.Zero |= Known.One;
2255 // Maybe even element count so need to clear ones.
2256 if (VecTy->isScalableTy() || EvenCnt)
2257 Known.One.clearAllBits();
2258 break;
2259 }
2260 case Intrinsic::vector_reduce_add: {
2261 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2262 if (!VecTy)
2263 break;
2264 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2265 Known = Known.reduceAdd(VecTy->getNumElements());
2266 break;
2267 }
2268 case Intrinsic::umin:
2269 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2270 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2271 Known = KnownBits::umin(Known, Known2);
2272 break;
2273 case Intrinsic::umax:
2274 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2275 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2276 Known = KnownBits::umax(Known, Known2);
2277 break;
2278 case Intrinsic::smin:
2279 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2280 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2281 Known = KnownBits::smin(Known, Known2);
2283 break;
2284 case Intrinsic::smax:
2285 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2286 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2287 Known = KnownBits::smax(Known, Known2);
2289 break;
2290 case Intrinsic::ptrmask: {
2291 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2292
2293 const Value *Mask = I->getOperand(1);
2294 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2295 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2296 // TODO: 1-extend would be more precise.
2297 Known &= Known2.anyextOrTrunc(BitWidth);
2298 break;
2299 }
2300 case Intrinsic::x86_sse42_crc32_64_64:
2301 Known.Zero.setBitsFrom(32);
2302 break;
2303 case Intrinsic::x86_ssse3_phadd_d_128:
2304 case Intrinsic::x86_ssse3_phadd_w_128:
2305 case Intrinsic::x86_avx2_phadd_d:
2306 case Intrinsic::x86_avx2_phadd_w: {
2308 I, DemandedElts, Q, Depth,
2309 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2310 return KnownBits::add(KnownLHS, KnownRHS);
2311 });
2312 break;
2313 }
2314 case Intrinsic::x86_ssse3_phadd_sw_128:
2315 case Intrinsic::x86_avx2_phadd_sw: {
2317 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2318 break;
2319 }
2320 case Intrinsic::x86_ssse3_phsub_d_128:
2321 case Intrinsic::x86_ssse3_phsub_w_128:
2322 case Intrinsic::x86_avx2_phsub_d:
2323 case Intrinsic::x86_avx2_phsub_w: {
2325 I, DemandedElts, Q, Depth,
2326 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2327 return KnownBits::sub(KnownLHS, KnownRHS);
2328 });
2329 break;
2330 }
2331 case Intrinsic::x86_ssse3_phsub_sw_128:
2332 case Intrinsic::x86_avx2_phsub_sw: {
2334 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2335 break;
2336 }
2337 case Intrinsic::riscv_vsetvli:
2338 case Intrinsic::riscv_vsetvlimax: {
2339 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2340 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2342 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2343 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2344 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2345 uint64_t MaxVLEN =
2346 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2347 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2348
2349 // Result of vsetvli must be not larger than AVL.
2350 if (HasAVL)
2351 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2352 MaxVL = std::min(MaxVL, CI->getZExtValue());
2353
2354 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2355 if (BitWidth > KnownZeroFirstBit)
2356 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2357 break;
2358 }
2359 case Intrinsic::amdgcn_mbcnt_hi:
2360 case Intrinsic::amdgcn_mbcnt_lo: {
2361 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2362 // most 31 + src1.
2363 Known.Zero.setBitsFrom(
2364 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2365 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2366 Known = KnownBits::add(Known, Known2);
2367 break;
2368 }
2369 case Intrinsic::vscale: {
2370 if (!II->getParent() || !II->getFunction())
2371 break;
2372
2373 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2374 break;
2375 }
2376 case Intrinsic::stepvector: {
2377 auto *VecTy = cast<VectorType>(II->getType());
2378 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2379 if (!isUIntN(BitWidth, MinNumElts))
2380 break;
2381
2382 bool Overflow = false;
2383 APInt MaxNumElts(BitWidth, MinNumElts);
2384 if (VecTy->isScalableTy()) {
2385 if (!II->getParent() || !II->getFunction())
2386 break;
2387 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2389 .umul_ov(MaxNumElts, Overflow);
2390 }
2391
2392 // Give up if the lane count could wrap. Stepvector truncates lane
2393 // indices that do not fit in the element type.
2394 if (Overflow)
2395 break;
2396
2397 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2398 break;
2399 }
2400 }
2401 }
2402 break;
2403 }
2404 case Instruction::ShuffleVector: {
2405 if (auto *Splat = getSplatValue(I)) {
2407 break;
2408 }
2409
2410 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2411 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2412 if (!Shuf) {
2413 Known.resetAll();
2414 return;
2415 }
2416 // For undef elements, we don't know anything about the common state of
2417 // the shuffle result.
2418 APInt DemandedLHS, DemandedRHS;
2419 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2420 Known.resetAll();
2421 return;
2422 }
2423 Known.setAllConflict();
2424 if (!!DemandedLHS) {
2425 const Value *LHS = Shuf->getOperand(0);
2426 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2427 // If we don't know any bits, early out.
2428 if (Known.isUnknown())
2429 break;
2430 }
2431 if (!!DemandedRHS) {
2432 const Value *RHS = Shuf->getOperand(1);
2433 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2434 Known = Known.intersectWith(Known2);
2435 }
2436 break;
2437 }
2438 case Instruction::InsertElement: {
2439 if (isa<ScalableVectorType>(I->getType())) {
2440 Known.resetAll();
2441 return;
2442 }
2443 const Value *Vec = I->getOperand(0);
2444 const Value *Elt = I->getOperand(1);
2445 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2446 unsigned NumElts = DemandedElts.getBitWidth();
2447 APInt DemandedVecElts = DemandedElts;
2448 bool NeedsElt = true;
2449 // If we know the index we are inserting too, clear it from Vec check.
2450 if (CIdx && CIdx->getValue().ult(NumElts)) {
2451 DemandedVecElts.clearBit(CIdx->getZExtValue());
2452 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2453 }
2454
2455 Known.setAllConflict();
2456 if (NeedsElt) {
2457 computeKnownBits(Elt, Known, Q, Depth + 1);
2458 // If we don't know any bits, early out.
2459 if (Known.isUnknown())
2460 break;
2461 }
2462
2463 if (!DemandedVecElts.isZero()) {
2464 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2465 Known = Known.intersectWith(Known2);
2466 }
2467 break;
2468 }
2469 case Instruction::ExtractElement: {
2470 // Look through extract element. If the index is non-constant or
2471 // out-of-range demand all elements, otherwise just the extracted element.
2472 const Value *Vec = I->getOperand(0);
2473 const Value *Idx = I->getOperand(1);
2474 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2475 if (isa<ScalableVectorType>(Vec->getType())) {
2476 // FIXME: there's probably *something* we can do with scalable vectors
2477 Known.resetAll();
2478 break;
2479 }
2480 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2481 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2482 if (CIdx && CIdx->getValue().ult(NumElts))
2483 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2484 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2485 break;
2486 }
2487 case Instruction::ExtractValue:
2488 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2490 if (EVI->getNumIndices() != 1) break;
2491 if (EVI->getIndices()[0] == 0) {
2492 switch (II->getIntrinsicID()) {
2493 default: break;
2494 case Intrinsic::uadd_with_overflow:
2495 case Intrinsic::sadd_with_overflow:
2497 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2498 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2499 break;
2500 case Intrinsic::usub_with_overflow:
2501 case Intrinsic::ssub_with_overflow:
2503 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2504 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2505 break;
2506 case Intrinsic::umul_with_overflow:
2507 case Intrinsic::smul_with_overflow:
2508 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2509 false, DemandedElts, Known, Known2, Q, Depth);
2510 break;
2511 }
2512 }
2513 }
2514 break;
2515 case Instruction::Freeze:
2516 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2517 Depth + 1))
2518 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2519 break;
2520 }
2521}
2522
2523/// Determine which bits of V are known to be either zero or one and return
2524/// them.
2525KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2526 const SimplifyQuery &Q, unsigned Depth) {
2527 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2528 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2529 return Known;
2530}
2531
2532/// Determine which bits of V are known to be either zero or one and return
2533/// them.
2535 unsigned Depth) {
2536 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2538 return Known;
2539}
2540
2541/// Determine which bits of V are known to be either zero or one and return
2542/// them in the Known bit set.
2543///
2544/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2545/// we cannot optimize based on the assumption that it is zero without changing
2546/// it to be an explicit zero. If we don't change it to zero, other code could
2547/// optimized based on the contradictory assumption that it is non-zero.
2548/// Because instcombine aggressively folds operations with undef args anyway,
2549/// this won't lose us code quality.
2550///
2551/// This function is defined on values with integer type, values with pointer
2552/// type, and vectors of integers. In the case
2553/// where V is a vector, known zero, and known one values are the
2554/// same width as the vector element, and the bit is set only if it is true
2555/// for all of the demanded elements in the vector specified by DemandedElts.
2556void computeKnownBits(const Value *V, const APInt &DemandedElts,
2557 KnownBits &Known, const SimplifyQuery &Q,
2558 unsigned Depth) {
2559 if (!DemandedElts) {
2560 // No demanded elts, better to assume we don't know anything.
2561 Known.resetAll();
2562 return;
2563 }
2564
2565 assert(V && "No Value?");
2566 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2567
2568#ifndef NDEBUG
2569 Type *Ty = V->getType();
2570 unsigned BitWidth = Known.getBitWidth();
2571
2572 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2573 "Not integer or pointer type!");
2574
2575 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2576 assert(
2577 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2578 "DemandedElt width should equal the fixed vector number of elements");
2579 } else {
2580 assert(DemandedElts == APInt(1, 1) &&
2581 "DemandedElt width should be 1 for scalars or scalable vectors");
2582 }
2583
2584 Type *ScalarTy = Ty->getScalarType();
2585 if (ScalarTy->isPointerTy()) {
2586 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2587 "V and Known should have same BitWidth");
2588 } else {
2589 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2590 "V and Known should have same BitWidth");
2591 }
2592#endif
2593
2594 const APInt *C;
2595 if (match(V, m_APInt(C))) {
2596 // We know all of the bits for a scalar constant or a splat vector constant!
2598 return;
2599 }
2600 // Null and aggregate-zero are all-zeros.
2602 Known.setAllZero();
2603 return;
2604 }
2605 // Handle a constant vector by taking the intersection of the known bits of
2606 // each element.
2608 assert(!isa<ScalableVectorType>(V->getType()));
2609 // We know that CDV must be a vector of integers. Take the intersection of
2610 // each element.
2611 Known.setAllConflict();
2612 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2613 if (!DemandedElts[i])
2614 continue;
2615 APInt Elt = CDV->getElementAsAPInt(i);
2616 Known.Zero &= ~Elt;
2617 Known.One &= Elt;
2618 }
2619 if (Known.hasConflict())
2620 Known.resetAll();
2621 return;
2622 }
2623
2624 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2625 assert(!isa<ScalableVectorType>(V->getType()));
2626 // We know that CV must be a vector of integers. Take the intersection of
2627 // each element.
2628 Known.setAllConflict();
2629 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2630 if (!DemandedElts[i])
2631 continue;
2632 Constant *Element = CV->getAggregateElement(i);
2633 if (isa<PoisonValue>(Element))
2634 continue;
2635 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2636 if (!ElementCI) {
2637 Known.resetAll();
2638 return;
2639 }
2640 const APInt &Elt = ElementCI->getValue();
2641 Known.Zero &= ~Elt;
2642 Known.One &= Elt;
2643 }
2644 if (Known.hasConflict())
2645 Known.resetAll();
2646 return;
2647 }
2648
2649 // Start out not knowing anything.
2650 Known.resetAll();
2651
2652 // We can't imply anything about undefs.
2653 if (isa<UndefValue>(V))
2654 return;
2655
2656 // There's no point in looking through other users of ConstantData for
2657 // assumptions. Confirm that we've handled them all.
2658 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2659
2660 if (const auto *A = dyn_cast<Argument>(V))
2661 if (std::optional<ConstantRange> Range = A->getRange())
2662 Known = Range->toKnownBits();
2663
2664 // All recursive calls that increase depth must come after this.
2666 return;
2667
2668 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2669 // the bits of its aliasee.
2670 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2671 if (!GA->isInterposable())
2672 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2673 return;
2674 }
2675
2676 if (const Operator *I = dyn_cast<Operator>(V))
2677 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2678 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2679 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2680 Known = CR->toKnownBits();
2681 }
2682
2683 // Aligned pointers have trailing zeros - refine Known.Zero set
2684 if (isa<PointerType>(V->getType())) {
2685 Align Alignment = V->getPointerAlignment(Q.DL);
2686 Known.Zero.setLowBits(Log2(Alignment));
2687 }
2688
2689 // computeKnownBitsFromContext strictly refines Known.
2690 // Therefore, we run them after computeKnownBitsFromOperator.
2691
2692 // Check whether we can determine known bits from context such as assumes.
2694}
2695
2696/// Try to detect a recurrence that the value of the induction variable is
2697/// always a power of two (or zero).
2698static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2699 SimplifyQuery &Q, unsigned Depth) {
2700 BinaryOperator *BO = nullptr;
2701 Value *Start = nullptr, *Step = nullptr;
2702 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2703 return false;
2704
2705 // Initial value must be a power of two.
2706 for (const Use &U : PN->operands()) {
2707 if (U.get() == Start) {
2708 // Initial value comes from a different BB, need to adjust context
2709 // instruction for analysis.
2710 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2711 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2712 return false;
2713 }
2714 }
2715
2716 // Except for Mul, the induction variable must be on the left side of the
2717 // increment expression, otherwise its value can be arbitrary.
2718 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2719 return false;
2720
2721 Q.CtxI = BO->getParent()->getTerminator();
2722 switch (BO->getOpcode()) {
2723 case Instruction::Mul:
2724 // Power of two is closed under multiplication.
2725 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2726 Q.IIQ.hasNoSignedWrap(BO)) &&
2727 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2728 case Instruction::SDiv:
2729 // Start value must not be signmask for signed division, so simply being a
2730 // power of two is not sufficient, and it has to be a constant.
2731 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2732 return false;
2733 [[fallthrough]];
2734 case Instruction::UDiv:
2735 // Divisor must be a power of two.
2736 // If OrZero is false, cannot guarantee induction variable is non-zero after
2737 // division, same for Shr, unless it is exact division.
2738 return (OrZero || Q.IIQ.isExact(BO)) &&
2739 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2740 case Instruction::Shl:
2741 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2742 case Instruction::AShr:
2743 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2744 return false;
2745 [[fallthrough]];
2746 case Instruction::LShr:
2747 return OrZero || Q.IIQ.isExact(BO);
2748 default:
2749 return false;
2750 }
2751}
2752
2753/// Return true if we can infer that \p V is known to be a power of 2 from
2754/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2755static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2756 const Value *Cond,
2757 bool CondIsTrue) {
2758 CmpPredicate Pred;
2759 const APInt *RHSC;
2760 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2761 return false;
2762 if (!CondIsTrue)
2763 Pred = ICmpInst::getInversePredicate(Pred);
2764 // ctpop(V) u< 2
2765 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2766 return true;
2767 // ctpop(V) == 1
2768 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2769}
2770
2771/// Return true if the given value is known to have exactly one
2772/// bit set when defined. For vectors return true if every element is known to
2773/// be a power of two when defined. Supports values with integer or pointer
2774/// types and vectors of integers.
2775bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2776 const SimplifyQuery &Q, unsigned Depth) {
2777 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2778
2779 if (isa<Constant>(V))
2780 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2781
2782 // i1 is by definition a power of 2 or zero.
2783 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2784 return true;
2785
2786 // Try to infer from assumptions.
2787 if (Q.AC && Q.CtxI) {
2788 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2789 if (!AssumeVH)
2790 continue;
2791 CallInst *I = cast<CallInst>(AssumeVH);
2792 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2793 /*CondIsTrue=*/true) &&
2795 return true;
2796 }
2797 }
2798
2799 // Handle dominating conditions.
2800 if (Q.DC && Q.CtxI && Q.DT) {
2801 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2802 Value *Cond = BI->getCondition();
2803
2804 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2806 /*CondIsTrue=*/true) &&
2807 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2808 return true;
2809
2810 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2812 /*CondIsTrue=*/false) &&
2813 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2814 return true;
2815 }
2816 }
2817
2818 auto *I = dyn_cast<Instruction>(V);
2819 if (!I)
2820 return false;
2821
2822 if (Q.CtxI && match(V, m_VScale())) {
2823 const Function *F = Q.CtxI->getFunction();
2824 // The vscale_range indicates vscale is a power-of-two.
2825 return F->hasFnAttribute(Attribute::VScaleRange);
2826 }
2827
2828 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2829 // it is shifted off the end then the result is undefined.
2830 if (match(I, m_Shl(m_One(), m_Value())))
2831 return true;
2832
2833 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2834 // the bottom. If it is shifted off the bottom then the result is undefined.
2835 if (match(I, m_LShr(m_SignMask(), m_Value())))
2836 return true;
2837
2838 // The remaining tests are all recursive, so bail out if we hit the limit.
2840 return false;
2841
2842 switch (I->getOpcode()) {
2843 case Instruction::ZExt:
2844 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2845 case Instruction::Trunc:
2846 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2847 case Instruction::Shl:
2848 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2849 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2850 return false;
2851 case Instruction::LShr:
2852 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2853 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2854 return false;
2855 case Instruction::UDiv:
2857 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2858 return false;
2859 case Instruction::Mul:
2860 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2861 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2862 (OrZero || isKnownNonZero(I, Q, Depth));
2863 case Instruction::And:
2864 // A power of two and'd with anything is a power of two or zero.
2865 if (OrZero &&
2866 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2867 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2868 return true;
2869 // X & (-X) is always a power of two or zero.
2870 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2871 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2872 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2873 return false;
2874 case Instruction::Add: {
2875 // Adding a power-of-two or zero to the same power-of-two or zero yields
2876 // either the original power-of-two, a larger power-of-two or zero.
2878 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2879 Q.IIQ.hasNoSignedWrap(VOBO)) {
2880 if (match(I->getOperand(0),
2881 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2882 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2883 return true;
2884 if (match(I->getOperand(1),
2885 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2886 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2887 return true;
2888
2889 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2890 KnownBits LHSBits(BitWidth);
2891 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2892
2893 KnownBits RHSBits(BitWidth);
2894 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2895 // If i8 V is a power of two or zero:
2896 // ZeroBits: 1 1 1 0 1 1 1 1
2897 // ~ZeroBits: 0 0 0 1 0 0 0 0
2898 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2899 // If OrZero isn't set, we cannot give back a zero result.
2900 // Make sure either the LHS or RHS has a bit set.
2901 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2902 return true;
2903 }
2904
2905 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2906 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2907 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2908 return true;
2909 return false;
2910 }
2911 case Instruction::Select:
2912 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2913 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2914 case Instruction::PHI: {
2915 // A PHI node is power of two if all incoming values are power of two, or if
2916 // it is an induction variable where in each step its value is a power of
2917 // two.
2918 auto *PN = cast<PHINode>(I);
2920
2921 // Check if it is an induction variable and always power of two.
2922 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2923 return true;
2924
2925 // Recursively check all incoming values. Limit recursion to 2 levels, so
2926 // that search complexity is limited to number of operands^2.
2927 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2928 return llvm::all_of(PN->operands(), [&](const Use &U) {
2929 // Value is power of 2 if it is coming from PHI node itself by induction.
2930 if (U.get() == PN)
2931 return true;
2932
2933 // Change the context instruction to the incoming block where it is
2934 // evaluated.
2935 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
2936 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2937 });
2938 }
2939 case Instruction::Invoke:
2940 case Instruction::Call: {
2941 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2942 switch (II->getIntrinsicID()) {
2943 case Intrinsic::umax:
2944 case Intrinsic::smax:
2945 case Intrinsic::umin:
2946 case Intrinsic::smin:
2947 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2948 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2949 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2950 // thus dont change pow2/non-pow2 status.
2951 case Intrinsic::bitreverse:
2952 case Intrinsic::bswap:
2953 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2954 case Intrinsic::fshr:
2955 case Intrinsic::fshl:
2956 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2957 if (II->getArgOperand(0) == II->getArgOperand(1))
2958 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2959 break;
2960 case Intrinsic::riscv_vsetvlimax:
2961 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2962 // for any valid vtype, so it is a power of two regardless of OrZero.
2963 return true;
2964 case Intrinsic::read_register:
2965 case Intrinsic::read_volatile_register: {
2966 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2967 // of two, so it is a power of two regardless of OrZero.
2968 const Module *M = II->getModule();
2969 if (!M || !M->getTargetTriple().isRISCV())
2970 break;
2971 return isReadVLENB(*II);
2972 }
2973 default:
2974 break;
2975 }
2976 }
2977 return false;
2978 }
2979 default:
2980 return false;
2981 }
2982}
2983
2984/// Test whether a GEP's result is known to be non-null.
2985///
2986/// Uses properties inherent in a GEP to try to determine whether it is known
2987/// to be non-null.
2988///
2989/// Currently this routine does not support vector GEPs.
2990static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2991 unsigned Depth) {
2992 const Function *F = nullptr;
2993 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2994 F = I->getFunction();
2995
2996 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2997 // may be null iff the base pointer is null and the offset is zero.
2998 if (!GEP->hasNoUnsignedWrap() &&
2999 !(GEP->isInBounds() &&
3000 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3001 return false;
3002
3003 // FIXME: Support vector-GEPs.
3004 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3005
3006 // If the base pointer is non-null, we cannot walk to a null address with an
3007 // inbounds GEP in address space zero.
3008 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3009 return true;
3010
3011 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3012 // If so, then the GEP cannot produce a null pointer, as doing so would
3013 // inherently violate the inbounds contract within address space zero.
3015 GTI != GTE; ++GTI) {
3016 // Struct types are easy -- they must always be indexed by a constant.
3017 if (StructType *STy = GTI.getStructTypeOrNull()) {
3018 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3019 unsigned ElementIdx = OpC->getZExtValue();
3020 const StructLayout *SL = Q.DL.getStructLayout(STy);
3021 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3022 if (ElementOffset > 0)
3023 return true;
3024 continue;
3025 }
3026
3027 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3028 if (GTI.getSequentialElementStride(Q.DL).isZero())
3029 continue;
3030
3031 // Fast path the constant operand case both for efficiency and so we don't
3032 // increment Depth when just zipping down an all-constant GEP.
3033 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3034 if (!OpC->isZero())
3035 return true;
3036 continue;
3037 }
3038
3039 // We post-increment Depth here because while isKnownNonZero increments it
3040 // as well, when we pop back up that increment won't persist. We don't want
3041 // to recurse 10k times just because we have 10k GEP operands. We don't
3042 // bail completely out because we want to handle constant GEPs regardless
3043 // of depth.
3045 continue;
3046
3047 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3048 return true;
3049 }
3050
3051 return false;
3052}
3053
3055 const Instruction *CtxI,
3056 const DominatorTree *DT) {
3057 assert(!isa<Constant>(V) && "Called for constant?");
3058
3059 if (!CtxI || !DT)
3060 return false;
3061
3062 unsigned NumUsesExplored = 0;
3063 for (auto &U : V->uses()) {
3064 // Avoid massive lists
3065 if (NumUsesExplored >= DomConditionsMaxUses)
3066 break;
3067 NumUsesExplored++;
3068
3069 const Instruction *UI = cast<Instruction>(U.getUser());
3070 // If the value is used as an argument to a call or invoke, then argument
3071 // attributes may provide an answer about null-ness.
3072 if (V->getType()->isPointerTy()) {
3073 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3074 if (CB->isArgOperand(&U) &&
3075 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3076 /*AllowUndefOrPoison=*/false) &&
3077 DT->dominates(CB, CtxI))
3078 return true;
3079 }
3080 }
3081
3082 // If the value is used as a load/store, then the pointer must be non null.
3083 if (V == getLoadStorePointerOperand(UI)) {
3086 DT->dominates(UI, CtxI))
3087 return true;
3088 }
3089
3090 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3091 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3092 isValidAssumeForContext(UI, CtxI, DT))
3093 return true;
3094
3095 // Consider only compare instructions uniquely controlling a branch
3096 Value *RHS;
3097 CmpPredicate Pred;
3098 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3099 continue;
3100
3101 bool NonNullIfTrue;
3102 if (cmpExcludesZero(Pred, RHS))
3103 NonNullIfTrue = true;
3105 NonNullIfTrue = false;
3106 else
3107 continue;
3108
3111 for (const auto *CmpU : UI->users()) {
3112 assert(WorkList.empty() && "Should be!");
3113 if (Visited.insert(CmpU).second)
3114 WorkList.push_back(CmpU);
3115
3116 while (!WorkList.empty()) {
3117 auto *Curr = WorkList.pop_back_val();
3118
3119 // If a user is an AND, add all its users to the work list. We only
3120 // propagate "pred != null" condition through AND because it is only
3121 // correct to assume that all conditions of AND are met in true branch.
3122 // TODO: Support similar logic of OR and EQ predicate?
3123 if (NonNullIfTrue)
3124 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3125 for (const auto *CurrU : Curr->users())
3126 if (Visited.insert(CurrU).second)
3127 WorkList.push_back(CurrU);
3128 continue;
3129 }
3130
3131 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3132 BasicBlock *NonNullSuccessor =
3133 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3134 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3135 if (DT->dominates(Edge, CtxI->getParent()))
3136 return true;
3137 } else if (NonNullIfTrue && isGuard(Curr) &&
3138 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3139 return true;
3140 }
3141 }
3142 }
3143 }
3144
3145 return false;
3146}
3147
3148/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3149/// ensure that the value it's attached to is never Value? 'RangeType' is
3150/// is the type of the value described by the range.
3151static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3152 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3153 assert(NumRanges >= 1);
3154 for (unsigned i = 0; i < NumRanges; ++i) {
3156 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3158 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3159 ConstantRange Range(Lower->getValue(), Upper->getValue());
3160 if (Range.contains(Value))
3161 return false;
3162 }
3163 return true;
3164}
3165
3166/// Try to detect a recurrence that monotonically increases/decreases from a
3167/// non-zero starting value. These are common as induction variables.
3168static bool isNonZeroRecurrence(const PHINode *PN) {
3169 BinaryOperator *BO = nullptr;
3170 Value *Start = nullptr, *Step = nullptr;
3171 const APInt *StartC, *StepC;
3172 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3173 !match(Start, m_APInt(StartC)) || StartC->isZero())
3174 return false;
3175
3176 switch (BO->getOpcode()) {
3177 case Instruction::Add:
3178 // Starting from non-zero and stepping away from zero can never wrap back
3179 // to zero.
3180 return BO->hasNoUnsignedWrap() ||
3181 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3182 StartC->isNegative() == StepC->isNegative());
3183 case Instruction::Mul:
3184 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3185 match(Step, m_APInt(StepC)) && !StepC->isZero();
3186 case Instruction::Shl:
3187 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3188 case Instruction::AShr:
3189 case Instruction::LShr:
3190 return BO->isExact();
3191 case Instruction::Or:
3192 return true;
3193 default:
3194 return false;
3195 }
3196}
3197
3198static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3200 m_Specific(Op1), m_Zero()))) ||
3202 m_Specific(Op0), m_Zero())));
3203}
3204
3205static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3206 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3207 bool NUW, unsigned Depth) {
3208 // (X + (X != 0)) is non zero
3209 if (matchOpWithOpEqZero(X, Y))
3210 return true;
3211
3212 if (NUW)
3213 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3214 isKnownNonZero(X, DemandedElts, Q, Depth);
3215
3216 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3217 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3218
3219 // If X and Y are both non-negative (as signed values) then their sum is not
3220 // zero unless both X and Y are zero.
3221 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3222 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3223 isKnownNonZero(X, DemandedElts, Q, Depth))
3224 return true;
3225
3226 // If X and Y are both negative (as signed values) then their sum is not
3227 // zero unless both X and Y equal INT_MIN.
3228 if (XKnown.isNegative() && YKnown.isNegative()) {
3230 // The sign bit of X is set. If some other bit is set then X is not equal
3231 // to INT_MIN.
3232 if (XKnown.One.intersects(Mask))
3233 return true;
3234 // The sign bit of Y is set. If some other bit is set then Y is not equal
3235 // to INT_MIN.
3236 if (YKnown.One.intersects(Mask))
3237 return true;
3238 }
3239
3240 // The sum of a non-negative number and a power of two is not zero.
3241 if (XKnown.isNonNegative() &&
3242 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3243 return true;
3244 if (YKnown.isNonNegative() &&
3245 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3246 return true;
3247
3248 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3249}
3250
3251static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3252 unsigned BitWidth, Value *X, Value *Y,
3253 unsigned Depth) {
3254 // (X - (X != 0)) is non zero
3255 // ((X != 0) - X) is non zero
3256 if (matchOpWithOpEqZero(X, Y))
3257 return true;
3258
3259 // TODO: Move this case into isKnownNonEqual().
3260 if (auto *C = dyn_cast<Constant>(X))
3261 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3262 return true;
3263
3264 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3265}
3266
3267static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3268 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3269 bool NUW, unsigned Depth) {
3270 // If X and Y are non-zero then so is X * Y as long as the multiplication
3271 // does not overflow.
3272 if (NSW || NUW)
3273 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3274 isKnownNonZero(Y, DemandedElts, Q, Depth);
3275
3276 // If either X or Y is odd, then if the other is non-zero the result can't
3277 // be zero.
3278 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3279 if (XKnown.One[0])
3280 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3281
3282 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3283 if (YKnown.One[0])
3284 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3285
3286 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3287 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3288 // the lowest known One of X and Y. If they are non-zero, the result
3289 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3290 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3291 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3292 BitWidth;
3293}
3294
3295static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3296 const SimplifyQuery &Q, const KnownBits &KnownVal,
3297 unsigned Depth) {
3298 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3299 switch (I->getOpcode()) {
3300 case Instruction::Shl:
3301 return Lhs.shl(Rhs);
3302 case Instruction::LShr:
3303 return Lhs.lshr(Rhs);
3304 case Instruction::AShr:
3305 return Lhs.ashr(Rhs);
3306 default:
3307 llvm_unreachable("Unknown Shift Opcode");
3308 }
3309 };
3310
3311 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3312 switch (I->getOpcode()) {
3313 case Instruction::Shl:
3314 return Lhs.lshr(Rhs);
3315 case Instruction::LShr:
3316 case Instruction::AShr:
3317 return Lhs.shl(Rhs);
3318 default:
3319 llvm_unreachable("Unknown Shift Opcode");
3320 }
3321 };
3322
3323 if (KnownVal.isUnknown())
3324 return false;
3325
3326 KnownBits KnownCnt =
3327 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3328 APInt MaxShift = KnownCnt.getMaxValue();
3329 unsigned NumBits = KnownVal.getBitWidth();
3330 if (MaxShift.uge(NumBits))
3331 return false;
3332
3333 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3334 return true;
3335
3336 // If all of the bits shifted out are known to be zero, and Val is known
3337 // non-zero then at least one non-zero bit must remain.
3338 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3339 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3340 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3341 return true;
3342
3343 return false;
3344}
3345
3347 const APInt &DemandedElts,
3348 const SimplifyQuery &Q, unsigned Depth) {
3349 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3350 switch (I->getOpcode()) {
3351 case Instruction::Alloca:
3352 // Alloca never returns null, malloc might.
3353 return I->getType()->getPointerAddressSpace() == 0;
3354 case Instruction::GetElementPtr:
3355 if (I->getType()->isPointerTy())
3357 break;
3358 case Instruction::BitCast: {
3359 // We need to be a bit careful here. We can only peek through the bitcast
3360 // if the scalar size of elements in the operand are smaller than and a
3361 // multiple of the size they are casting too. Take three cases:
3362 //
3363 // 1) Unsafe:
3364 // bitcast <2 x i16> %NonZero to <4 x i8>
3365 //
3366 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3367 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3368 // guranteed (imagine just sign bit set in the 2 i16 elements).
3369 //
3370 // 2) Unsafe:
3371 // bitcast <4 x i3> %NonZero to <3 x i4>
3372 //
3373 // Even though the scalar size of the src (`i3`) is smaller than the
3374 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3375 // its possible for the `3 x i4` elements to be zero because there are
3376 // some elements in the destination that don't contain any full src
3377 // element.
3378 //
3379 // 3) Safe:
3380 // bitcast <4 x i8> %NonZero to <2 x i16>
3381 //
3382 // This is always safe as non-zero in the 4 i8 elements implies
3383 // non-zero in the combination of any two adjacent ones. Since i8 is a
3384 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3385 // This all implies the 2 i16 elements are non-zero.
3386 Type *FromTy = I->getOperand(0)->getType();
3387 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3388 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3389 return isKnownNonZero(I->getOperand(0), Q, Depth);
3390 } break;
3391 case Instruction::IntToPtr:
3392 // Note that we have to take special care to avoid looking through
3393 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3394 // as casts that can alter the value, e.g., AddrSpaceCasts.
3395 if (!isa<ScalableVectorType>(I->getType()) &&
3396 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3397 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3398 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3399 break;
3400 case Instruction::PtrToAddr:
3401 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3402 // so we can directly forward.
3403 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3404 case Instruction::PtrToInt:
3405 // For inttoptr, make sure the result size is >= the address size. If the
3406 // address is non-zero, any larger value is also non-zero.
3407 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3408 I->getType()->getScalarSizeInBits())
3409 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3410 break;
3411 case Instruction::Trunc:
3412 // nuw/nsw trunc preserves zero/non-zero status of input.
3413 if (auto *TI = dyn_cast<TruncInst>(I))
3414 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3415 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3416 break;
3417
3418 // Iff x - y != 0, then x ^ y != 0
3419 // Therefore we can do the same exact checks
3420 case Instruction::Xor:
3421 case Instruction::Sub:
3422 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3423 I->getOperand(1), Depth);
3424 case Instruction::Or:
3425 // (X | (X != 0)) is non zero
3426 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3427 return true;
3428 // X | Y != 0 if X != Y.
3429 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3430 Depth))
3431 return true;
3432 // X | Y != 0 if X != 0 or Y != 0.
3433 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3434 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3435 case Instruction::SExt:
3436 case Instruction::ZExt:
3437 // ext X != 0 if X != 0.
3438 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3439
3440 case Instruction::Shl: {
3441 // shl nsw/nuw can't remove any non-zero bits.
3443 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3444 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3445
3446 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3447 // if the lowest bit is shifted off the end.
3449 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3450 if (Known.One[0])
3451 return true;
3452
3453 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3454 }
3455 case Instruction::LShr:
3456 case Instruction::AShr: {
3457 // shr exact can only shift out zero bits.
3459 if (BO->isExact())
3460 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3461
3462 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3463 // defined if the sign bit is shifted off the end.
3465 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3466 if (Known.isNegative())
3467 return true;
3468
3469 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3470 // position >= C, because the sum >= max(A, B).
3471 Value *A, *B;
3472 const APInt *C;
3473 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3474 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3475 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3476 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3477 if (!KnownA.One.lshr(*C).isZero())
3478 return true;
3479 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3480 if (!KnownB.One.lshr(*C).isZero())
3481 return true;
3482 }
3483
3484 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3485 }
3486 case Instruction::UDiv:
3487 case Instruction::SDiv: {
3488 // X / Y
3489 // div exact can only produce a zero if the dividend is zero.
3490 if (cast<PossiblyExactOperator>(I)->isExact())
3491 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3492
3493 KnownBits XKnown =
3494 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3495 // If X is fully unknown we won't be able to figure anything out so don't
3496 // both computing knownbits for Y.
3497 if (XKnown.isUnknown())
3498 return false;
3499
3500 KnownBits YKnown =
3501 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3502 if (I->getOpcode() == Instruction::SDiv) {
3503 // For signed division need to compare abs value of the operands.
3504 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3505 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3506 }
3507 // If X u>= Y then div is non zero (0/0 is UB).
3508 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3509 // If X is total unknown or X u< Y we won't be able to prove non-zero
3510 // with compute known bits so just return early.
3511 return XUgeY && *XUgeY;
3512 }
3513 case Instruction::Add: {
3514 // X + Y.
3515
3516 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3517 // non-zero.
3519 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3520 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3521 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3522 }
3523 case Instruction::Mul: {
3525 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3526 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3527 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3528 }
3529 case Instruction::Select: {
3530 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3531
3532 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3533 // then see if the select condition implies the arm is non-zero. For example
3534 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3535 // dominated by `X != 0`.
3536 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3537 Value *Op;
3538 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3539 // Op is trivially non-zero.
3540 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3541 return true;
3542
3543 // The condition of the select dominates the true/false arm. Check if the
3544 // condition implies that a given arm is non-zero.
3545 Value *X;
3546 CmpPredicate Pred;
3547 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3548 return false;
3549
3550 if (!IsTrueArm)
3551 Pred = ICmpInst::getInversePredicate(Pred);
3552
3553 return cmpExcludesZero(Pred, X);
3554 };
3555
3556 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3557 SelectArmIsNonZero(/* IsTrueArm */ false))
3558 return true;
3559 break;
3560 }
3561 case Instruction::PHI: {
3562 auto *PN = cast<PHINode>(I);
3564 return true;
3565
3566 // Check if all incoming values are non-zero using recursion.
3568 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3569 return llvm::all_of(PN->operands(), [&](const Use &U) {
3570 if (U.get() == PN)
3571 return true;
3572 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3573 // Check if the branch on the phi excludes zero.
3574 CmpPredicate Pred;
3575 Value *X;
3576 BasicBlock *TrueSucc, *FalseSucc;
3577 if (match(RecQ.CtxI,
3578 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3579 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3580 // Check for cases of duplicate successors.
3581 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3582 // If we're using the false successor, invert the predicate.
3583 if (FalseSucc == PN->getParent())
3584 Pred = CmpInst::getInversePredicate(Pred);
3585 if (cmpExcludesZero(Pred, X))
3586 return true;
3587 }
3588 }
3589 // Finally recurse on the edge and check it directly.
3590 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3591 });
3592 }
3593 case Instruction::InsertElement: {
3594 if (isa<ScalableVectorType>(I->getType()))
3595 break;
3596
3597 const Value *Vec = I->getOperand(0);
3598 const Value *Elt = I->getOperand(1);
3599 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3600
3601 unsigned NumElts = DemandedElts.getBitWidth();
3602 APInt DemandedVecElts = DemandedElts;
3603 bool SkipElt = false;
3604 // If we know the index we are inserting too, clear it from Vec check.
3605 if (CIdx && CIdx->getValue().ult(NumElts)) {
3606 DemandedVecElts.clearBit(CIdx->getZExtValue());
3607 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3608 }
3609
3610 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3611 // are non-zero.
3612 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3613 (DemandedVecElts.isZero() ||
3614 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3615 }
3616 case Instruction::ExtractElement:
3617 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3618 const Value *Vec = EEI->getVectorOperand();
3619 const Value *Idx = EEI->getIndexOperand();
3620 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3621 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3622 unsigned NumElts = VecTy->getNumElements();
3623 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3624 if (CIdx && CIdx->getValue().ult(NumElts))
3625 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3626 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3627 }
3628 }
3629 break;
3630 case Instruction::ShuffleVector: {
3631 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3632 if (!Shuf)
3633 break;
3634 APInt DemandedLHS, DemandedRHS;
3635 // For undef elements, we don't know anything about the common state of
3636 // the shuffle result.
3637 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3638 break;
3639 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3640 return (DemandedRHS.isZero() ||
3641 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3642 (DemandedLHS.isZero() ||
3643 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3644 }
3645 case Instruction::Freeze:
3646 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3647 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3648 Depth);
3649 case Instruction::Load: {
3650 auto *LI = cast<LoadInst>(I);
3651 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3652 // is never null.
3653 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3654 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3655 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3656 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3657 return true;
3658 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3660 }
3661
3662 // No need to fall through to computeKnownBits as range metadata is already
3663 // handled in isKnownNonZero.
3664 return false;
3665 }
3666 case Instruction::ExtractValue: {
3667 const WithOverflowInst *WO;
3669 switch (WO->getBinaryOp()) {
3670 default:
3671 break;
3672 case Instruction::Add:
3673 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3674 WO->getArgOperand(1),
3675 /*NSW=*/false,
3676 /*NUW=*/false, Depth);
3677 case Instruction::Sub:
3678 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3679 WO->getArgOperand(1), Depth);
3680 case Instruction::Mul:
3681 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3682 WO->getArgOperand(1),
3683 /*NSW=*/false, /*NUW=*/false, Depth);
3684 break;
3685 }
3686 }
3687 break;
3688 }
3689 case Instruction::Call:
3690 case Instruction::Invoke: {
3691 const auto *Call = cast<CallBase>(I);
3692 if (I->getType()->isPointerTy()) {
3693 if (Call->isReturnNonNull())
3694 return true;
3695 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3696 Call, /*MustPreserveOffset=*/true))
3697 return isKnownNonZero(RP, Q, Depth);
3698 } else {
3699 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3701 if (std::optional<ConstantRange> Range = Call->getRange()) {
3702 const APInt ZeroValue(Range->getBitWidth(), 0);
3703 if (!Range->contains(ZeroValue))
3704 return true;
3705 }
3706 if (const Value *RV = Call->getReturnedArgOperand())
3707 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3708 return true;
3709 }
3710
3711 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3712 switch (II->getIntrinsicID()) {
3713 case Intrinsic::sshl_sat:
3714 case Intrinsic::ushl_sat:
3715 case Intrinsic::abs:
3716 case Intrinsic::bitreverse:
3717 case Intrinsic::bswap:
3718 case Intrinsic::ctpop:
3719 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3720 // NB: We don't do usub_sat here as in any case we can prove its
3721 // non-zero, we will fold it to `sub nuw` in InstCombine.
3722 case Intrinsic::ssub_sat:
3723 // For most types, if x != y then ssub.sat x, y != 0. But
3724 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3725 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3726 if (BitWidth == 1)
3727 return false;
3728 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3729 II->getArgOperand(1), Depth);
3730 case Intrinsic::sadd_sat:
3731 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3732 II->getArgOperand(1),
3733 /*NSW=*/true, /* NUW=*/false, Depth);
3734 // Vec reverse preserves zero/non-zero status from input vec.
3735 case Intrinsic::vector_reverse:
3736 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3737 Q, Depth);
3738 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3739 case Intrinsic::vector_reduce_or:
3740 case Intrinsic::vector_reduce_umax:
3741 case Intrinsic::vector_reduce_umin:
3742 case Intrinsic::vector_reduce_smax:
3743 case Intrinsic::vector_reduce_smin:
3744 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3745 case Intrinsic::umax:
3746 case Intrinsic::uadd_sat:
3747 // umax(X, (X != 0)) is non zero
3748 // X +usat (X != 0) is non zero
3749 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3750 return true;
3751
3752 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3753 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3754 case Intrinsic::smax: {
3755 // If either arg is strictly positive the result is non-zero. Otherwise
3756 // the result is non-zero if both ops are non-zero.
3757 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3758 const KnownBits &OpKnown) {
3759 if (!OpNonZero.has_value())
3760 OpNonZero = OpKnown.isNonZero() ||
3761 isKnownNonZero(Op, DemandedElts, Q, Depth);
3762 return *OpNonZero;
3763 };
3764 // Avoid re-computing isKnownNonZero.
3765 std::optional<bool> Op0NonZero, Op1NonZero;
3766 KnownBits Op1Known =
3767 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3768 if (Op1Known.isNonNegative() &&
3769 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3770 return true;
3771 KnownBits Op0Known =
3772 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3773 if (Op0Known.isNonNegative() &&
3774 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3775 return true;
3776 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3777 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3778 }
3779 case Intrinsic::smin: {
3780 // If either arg is negative the result is non-zero. Otherwise
3781 // the result is non-zero if both ops are non-zero.
3782 KnownBits Op1Known =
3783 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3784 if (Op1Known.isNegative())
3785 return true;
3786 KnownBits Op0Known =
3787 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3788 if (Op0Known.isNegative())
3789 return true;
3790
3791 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3792 return true;
3793 }
3794 [[fallthrough]];
3795 case Intrinsic::umin:
3796 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3797 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3798 case Intrinsic::cttz:
3799 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3800 .Zero[0];
3801 case Intrinsic::ctlz:
3802 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3803 .isNonNegative();
3804 case Intrinsic::fshr:
3805 case Intrinsic::fshl:
3806 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3807 if (II->getArgOperand(0) == II->getArgOperand(1))
3808 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3809 break;
3810 case Intrinsic::vscale:
3811 return true;
3812 case Intrinsic::experimental_get_vector_length:
3813 return isKnownNonZero(I->getOperand(0), Q, Depth);
3814 default:
3815 break;
3816 }
3817 break;
3818 }
3819
3820 return false;
3821 }
3822 }
3823
3825 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3826 return Known.One != 0;
3827}
3828
3829/// Return true if the given value is known to be non-zero when defined. For
3830/// vectors, return true if every demanded element is known to be non-zero when
3831/// defined. For pointers, if the context instruction and dominator tree are
3832/// specified, perform context-sensitive analysis and return true if the
3833/// pointer couldn't possibly be null at the specified instruction.
3834/// Supports values with integer or pointer type and vectors of integers.
3835bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3836 const SimplifyQuery &Q, unsigned Depth) {
3837 Type *Ty = V->getType();
3838
3839#ifndef NDEBUG
3840 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3841
3842 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3843 assert(
3844 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3845 "DemandedElt width should equal the fixed vector number of elements");
3846 } else {
3847 assert(DemandedElts == APInt(1, 1) &&
3848 "DemandedElt width should be 1 for scalars");
3849 }
3850#endif
3851
3852 if (auto *C = dyn_cast<Constant>(V)) {
3853 if (C->isNullValue())
3854 return false;
3855 if (isa<ConstantInt>(C))
3856 // Must be non-zero due to null test above.
3857 return true;
3858
3859 // For constant vectors, check that all elements are poison or known
3860 // non-zero to determine that the whole vector is known non-zero.
3861 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3862 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3863 if (!DemandedElts[i])
3864 continue;
3865 Constant *Elt = C->getAggregateElement(i);
3866 if (!Elt || Elt->isNullValue())
3867 return false;
3868 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3869 return false;
3870 }
3871 return true;
3872 }
3873
3874 // Constant ptrauth can be null, iff the base pointer can be.
3875 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3876 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3877
3878 // A global variable in address space 0 is non null unless extern weak
3879 // or an absolute symbol reference. Other address spaces may have null as a
3880 // valid address for a global, so we can't assume anything.
3881 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3882 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3883 GV->getType()->getAddressSpace() == 0)
3884 return true;
3885 }
3886
3887 // For constant expressions, fall through to the Operator code below.
3888 if (!isa<ConstantExpr>(V))
3889 return false;
3890 }
3891
3892 if (const auto *A = dyn_cast<Argument>(V))
3893 if (std::optional<ConstantRange> Range = A->getRange()) {
3894 const APInt ZeroValue(Range->getBitWidth(), 0);
3895 if (!Range->contains(ZeroValue))
3896 return true;
3897 }
3898
3899 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3900 return true;
3901
3902 // Some of the tests below are recursive, so bail out if we hit the limit.
3904 return false;
3905
3906 // Check for pointer simplifications.
3907
3908 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3909 // A byval, inalloca may not be null in a non-default addres space. A
3910 // nonnull argument is assumed never 0.
3911 if (const Argument *A = dyn_cast<Argument>(V)) {
3912 if (((A->hasPassPointeeByValueCopyAttr() &&
3913 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3914 A->hasNonNullAttr()))
3915 return true;
3916 }
3917 }
3918
3919 if (const auto *I = dyn_cast<Operator>(V))
3920 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3921 return true;
3922
3923 if (!isa<Constant>(V) &&
3925 return true;
3926
3927 if (const Value *Stripped = stripNullTest(V))
3928 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3929
3930 return false;
3931}
3932
3934 unsigned Depth) {
3935 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3936 APInt DemandedElts =
3937 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3938 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3939}
3940
3941/// If the pair of operators are the same invertible function, return the
3942/// the operands of the function corresponding to each input. Otherwise,
3943/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3944/// every input value to exactly one output value. This is equivalent to
3945/// saying that Op1 and Op2 are equal exactly when the specified pair of
3946/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3947static std::optional<std::pair<Value*, Value*>>
3949 const Operator *Op2) {
3950 if (Op1->getOpcode() != Op2->getOpcode())
3951 return std::nullopt;
3952
3953 auto getOperands = [&](unsigned OpNum) -> auto {
3954 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3955 };
3956
3957 switch (Op1->getOpcode()) {
3958 default:
3959 break;
3960 case Instruction::Or:
3961 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3962 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3963 break;
3964 [[fallthrough]];
3965 case Instruction::Xor:
3966 case Instruction::Add: {
3967 Value *Other;
3968 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3969 return std::make_pair(Op1->getOperand(1), Other);
3970 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3971 return std::make_pair(Op1->getOperand(0), Other);
3972 break;
3973 }
3974 case Instruction::Sub:
3975 if (Op1->getOperand(0) == Op2->getOperand(0))
3976 return getOperands(1);
3977 if (Op1->getOperand(1) == Op2->getOperand(1))
3978 return getOperands(0);
3979 break;
3980 case Instruction::Mul: {
3981 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3982 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3983 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3984 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3985 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3986 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3987 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3988 break;
3989
3990 // Assume operand order has been canonicalized
3991 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3992 isa<ConstantInt>(Op1->getOperand(1)) &&
3993 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3994 return getOperands(0);
3995 break;
3996 }
3997 case Instruction::Shl: {
3998 // Same as multiplies, with the difference that we don't need to check
3999 // for a non-zero multiply. Shifts always multiply by non-zero.
4000 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4001 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4002 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4003 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4004 break;
4005
4006 if (Op1->getOperand(1) == Op2->getOperand(1))
4007 return getOperands(0);
4008 break;
4009 }
4010 case Instruction::AShr:
4011 case Instruction::LShr: {
4012 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4013 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4014 if (!PEO1->isExact() || !PEO2->isExact())
4015 break;
4016
4017 if (Op1->getOperand(1) == Op2->getOperand(1))
4018 return getOperands(0);
4019 break;
4020 }
4021 case Instruction::SExt:
4022 case Instruction::ZExt:
4023 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4024 return getOperands(0);
4025 break;
4026 case Instruction::PHI: {
4027 const PHINode *PN1 = cast<PHINode>(Op1);
4028 const PHINode *PN2 = cast<PHINode>(Op2);
4029
4030 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4031 // are a single invertible function of the start values? Note that repeated
4032 // application of an invertible function is also invertible
4033 BinaryOperator *BO1 = nullptr;
4034 Value *Start1 = nullptr, *Step1 = nullptr;
4035 BinaryOperator *BO2 = nullptr;
4036 Value *Start2 = nullptr, *Step2 = nullptr;
4037 if (PN1->getParent() != PN2->getParent() ||
4038 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4039 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4040 break;
4041
4043 cast<Operator>(BO2));
4044 if (!Values)
4045 break;
4046
4047 // We have to be careful of mutually defined recurrences here. Ex:
4048 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4049 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4050 // The invertibility of these is complicated, and not worth reasoning
4051 // about (yet?).
4052 if (Values->first != PN1 || Values->second != PN2)
4053 break;
4054
4055 return std::make_pair(Start1, Start2);
4056 }
4057 }
4058 return std::nullopt;
4059}
4060
4061/// Return true if V1 == (binop V2, X), where X is known non-zero.
4062/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4063/// implies V2 != V1.
4064static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4065 const APInt &DemandedElts,
4066 const SimplifyQuery &Q, unsigned Depth) {
4068 if (!BO)
4069 return false;
4070 switch (BO->getOpcode()) {
4071 default:
4072 break;
4073 case Instruction::Or:
4074 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4075 break;
4076 [[fallthrough]];
4077 case Instruction::Xor:
4078 case Instruction::Add:
4079 Value *Op = nullptr;
4080 if (V2 == BO->getOperand(0))
4081 Op = BO->getOperand(1);
4082 else if (V2 == BO->getOperand(1))
4083 Op = BO->getOperand(0);
4084 else
4085 return false;
4086 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4087 }
4088 return false;
4089}
4090
4091/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4092/// the multiplication is nuw or nsw.
4093static bool isNonEqualMul(const Value *V1, const Value *V2,
4094 const APInt &DemandedElts, const SimplifyQuery &Q,
4095 unsigned Depth) {
4096 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4097 const APInt *C;
4098 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4099 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4100 !C->isZero() && !C->isOne() &&
4101 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4102 }
4103 return false;
4104}
4105
4106/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4107/// the shift is nuw or nsw.
4108static bool isNonEqualShl(const Value *V1, const Value *V2,
4109 const APInt &DemandedElts, const SimplifyQuery &Q,
4110 unsigned Depth) {
4111 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4112 const APInt *C;
4113 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4114 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4115 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4116 }
4117 return false;
4118}
4119
4120static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4121 const APInt &DemandedElts, const SimplifyQuery &Q,
4122 unsigned Depth) {
4123 // Check two PHIs are in same block.
4124 if (PN1->getParent() != PN2->getParent())
4125 return false;
4126
4128 bool UsedFullRecursion = false;
4129 for (const BasicBlock *IncomBB : PN1->blocks()) {
4130 if (!VisitedBBs.insert(IncomBB).second)
4131 continue; // Don't reprocess blocks that we have dealt with already.
4132 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4133 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4134 const APInt *C1, *C2;
4135 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4136 continue;
4137
4138 // Only one pair of phi operands is allowed for full recursion.
4139 if (UsedFullRecursion)
4140 return false;
4141
4143 RecQ.CtxI = IncomBB->getTerminator();
4144 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4145 return false;
4146 UsedFullRecursion = true;
4147 }
4148 return true;
4149}
4150
4151static bool isNonEqualSelect(const Value *V1, const Value *V2,
4152 const APInt &DemandedElts, const SimplifyQuery &Q,
4153 unsigned Depth) {
4154 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4155 if (!SI1)
4156 return false;
4157
4158 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4159 const Value *Cond1 = SI1->getCondition();
4160 const Value *Cond2 = SI2->getCondition();
4161 if (Cond1 == Cond2)
4162 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4163 DemandedElts, Q, Depth + 1) &&
4164 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4165 DemandedElts, Q, Depth + 1);
4166 }
4167 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4168 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4169}
4170
4171// Check to see if A is both a GEP and is the incoming value for a PHI in the
4172// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4173// one of them being the recursive GEP A and the other a ptr at same base and at
4174// the same/higher offset than B we are only incrementing the pointer further in
4175// loop if offset of recursive GEP is greater than 0.
4177 const SimplifyQuery &Q) {
4178 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4179 return false;
4180
4181 auto *GEPA = dyn_cast<GEPOperator>(A);
4182 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4183 return false;
4184
4185 // Handle 2 incoming PHI values with one being a recursive GEP.
4186 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4187 if (!PN || PN->getNumIncomingValues() != 2)
4188 return false;
4189
4190 // Search for the recursive GEP as an incoming operand, and record that as
4191 // Step.
4192 Value *Start = nullptr;
4193 Value *Step = const_cast<Value *>(A);
4194 if (PN->getIncomingValue(0) == Step)
4195 Start = PN->getIncomingValue(1);
4196 else if (PN->getIncomingValue(1) == Step)
4197 Start = PN->getIncomingValue(0);
4198 else
4199 return false;
4200
4201 // Other incoming node base should match the B base.
4202 // StartOffset >= OffsetB && StepOffset > 0?
4203 // StartOffset <= OffsetB && StepOffset < 0?
4204 // Is non-equal if above are true.
4205 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4206 // optimisation to inbounds GEPs only.
4207 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4208 APInt StartOffset(IndexWidth, 0);
4209 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4210 APInt StepOffset(IndexWidth, 0);
4211 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4212
4213 // Check if Base Pointer of Step matches the PHI.
4214 if (Step != PN)
4215 return false;
4216 APInt OffsetB(IndexWidth, 0);
4217 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4218 return Start == B &&
4219 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4220 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4221}
4222
4223static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4224 const SimplifyQuery &Q, unsigned Depth) {
4225 if (!Q.CtxI)
4226 return false;
4227
4228 // Try to infer NonEqual based on information from dominating conditions.
4229 if (Q.DC && Q.DT) {
4230 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4231 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4232 Value *Cond = BI->getCondition();
4233 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4234 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4236 /*LHSIsTrue=*/true, Depth)
4237 .value_or(false))
4238 return true;
4239
4240 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4241 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4243 /*LHSIsTrue=*/false, Depth)
4244 .value_or(false))
4245 return true;
4246 }
4247
4248 return false;
4249 };
4250
4251 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4252 IsKnownNonEqualFromDominatingCondition(V2))
4253 return true;
4254 }
4255
4256 if (!Q.AC)
4257 return false;
4258
4259 // Try to infer NonEqual based on information from assumptions.
4260 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4261 if (!AssumeVH)
4262 continue;
4263 CallInst *I = cast<CallInst>(AssumeVH);
4264
4265 assert(I->getFunction() == Q.CtxI->getFunction() &&
4266 "Got assumption for the wrong function!");
4267 assert(I->getIntrinsicID() == Intrinsic::assume &&
4268 "must be an assume intrinsic");
4269
4270 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4271 /*LHSIsTrue=*/true, Depth)
4272 .value_or(false) &&
4274 return true;
4275 }
4276
4277 return false;
4278}
4279
4280static bool isNonEqualURem(const Value *X, const Value *Rem,
4281 const SimplifyQuery &Q) {
4282 const Value *Y;
4283 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4284 return false;
4285
4286 // For a defined urem, X != X urem Y exactly when X u>= Y.
4287 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4289 return true;
4290
4291 std::optional<bool> Implied =
4293 return Implied && *Implied;
4294}
4295
4296/// Return true if it is known that V1 != V2.
4297static bool isKnownNonEqual(const Value *V1, const Value *V2,
4298 const APInt &DemandedElts, const SimplifyQuery &Q,
4299 unsigned Depth) {
4300 if (V1 == V2)
4301 return false;
4302 if (V1->getType() != V2->getType())
4303 // We can't look through casts yet.
4304 return false;
4305
4307 return false;
4308
4309 // See if we can recurse through (exactly one of) our operands. This
4310 // requires our operation be 1-to-1 and map every input value to exactly
4311 // one output value. Such an operation is invertible.
4312 auto *O1 = dyn_cast<Operator>(V1);
4313 auto *O2 = dyn_cast<Operator>(V2);
4314 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4315 if (auto Values = getInvertibleOperands(O1, O2))
4316 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4317 Depth + 1);
4318
4319 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4320 const PHINode *PN2 = cast<PHINode>(V2);
4321 // FIXME: This is missing a generalization to handle the case where one is
4322 // a PHI and another one isn't.
4323 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4324 return true;
4325 };
4326 }
4327
4328 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4329 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4330 return true;
4331
4332 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4333 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4334 return true;
4335
4336 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4337 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4338 return true;
4339
4340 if (V1->getType()->isIntOrIntVectorTy()) {
4341 // Are any known bits in V1 contradictory to known bits in V2? If V1
4342 // has a known zero where V2 has a known one, they must not be equal.
4343 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4344 if (!Known1.isUnknown()) {
4345 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4346 if (Known1.Zero.intersects(Known2.One) ||
4347 Known2.Zero.intersects(Known1.One))
4348 return true;
4349 }
4350 }
4351
4352 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4353 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4354 return true;
4355
4358 return true;
4359
4360 Value *A, *B;
4361 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4362 // Check PtrToInt type matches the pointer size.
4363 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4365 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4366
4367 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4368 return true;
4369
4370 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4371 return true;
4372
4373 return false;
4374}
4375
4376/// For vector constants, loop over the elements and find the constant with the
4377/// minimum number of sign bits. Return 0 if the value is not a vector constant
4378/// or if any element was not analyzed; otherwise, return the count for the
4379/// element with the minimum number of sign bits.
4381 const APInt &DemandedElts,
4382 unsigned TyBits) {
4383 const auto *CV = dyn_cast<Constant>(V);
4384 if (!CV || !isa<FixedVectorType>(CV->getType()))
4385 return 0;
4386
4387 unsigned MinSignBits = TyBits;
4388 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4389 for (unsigned i = 0; i != NumElts; ++i) {
4390 if (!DemandedElts[i])
4391 continue;
4392 // If we find a non-ConstantInt, bail out.
4393 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4394 if (!Elt)
4395 return 0;
4396
4397 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4398 }
4399
4400 return MinSignBits;
4401}
4402
4403static unsigned ComputeNumSignBitsImpl(const Value *V,
4404 const APInt &DemandedElts,
4405 const SimplifyQuery &Q, unsigned Depth);
4406
4407static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4408 const SimplifyQuery &Q, unsigned Depth) {
4409 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4410 assert(Result > 0 && "At least one sign bit needs to be present!");
4411 return Result;
4412}
4413
4414/// Return the number of times the sign bit of the register is replicated into
4415/// the other bits. We know that at least 1 bit is always equal to the sign bit
4416/// (itself), but other cases can give us information. For example, immediately
4417/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4418/// other, so we return 3. For vectors, return the number of sign bits for the
4419/// vector element with the minimum number of known sign bits of the demanded
4420/// elements in the vector specified by DemandedElts.
4421static unsigned ComputeNumSignBitsImpl(const Value *V,
4422 const APInt &DemandedElts,
4423 const SimplifyQuery &Q, unsigned Depth) {
4424 Type *Ty = V->getType();
4425#ifndef NDEBUG
4426 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4427
4428 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4429 assert(
4430 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4431 "DemandedElt width should equal the fixed vector number of elements");
4432 } else {
4433 assert(DemandedElts == APInt(1, 1) &&
4434 "DemandedElt width should be 1 for scalars");
4435 }
4436#endif
4437
4438 // We return the minimum number of sign bits that are guaranteed to be present
4439 // in V, so for undef we have to conservatively return 1. We don't have the
4440 // same behavior for poison though -- that's a FIXME today.
4441
4442 Type *ScalarTy = Ty->getScalarType();
4443 unsigned TyBits = ScalarTy->isPointerTy() ?
4444 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4445 Q.DL.getTypeSizeInBits(ScalarTy);
4446
4447 unsigned Tmp, Tmp2;
4448 unsigned FirstAnswer = 1;
4449
4450 // Note that ConstantInt is handled by the general computeKnownBits case
4451 // below.
4452
4454 return 1;
4455
4456 if (auto *U = dyn_cast<Operator>(V)) {
4457 switch (Operator::getOpcode(V)) {
4458 default: break;
4459 case Instruction::BitCast: {
4460 Value *Src = U->getOperand(0);
4461 Type *SrcTy = Src->getType();
4462
4463 // Skip if the source type is not an integer or integer vector type
4464 // This ensures we only process integer-like types
4465 if (!SrcTy->isIntOrIntVectorTy())
4466 break;
4467
4468 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4469
4470 // Bitcast 'large element' scalar/vector to 'small element' vector.
4471 if ((SrcBits % TyBits) != 0)
4472 break;
4473
4474 // Only proceed if the destination type is a fixed-size vector
4475 if (isa<FixedVectorType>(Ty)) {
4476 // Fast case - sign splat can be simply split across the small elements.
4477 // This works for both vector and scalar sources
4478 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4479 if (Tmp == SrcBits)
4480 return TyBits;
4481 }
4482 break;
4483 }
4484 case Instruction::SExt:
4485 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4486 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4487 Tmp;
4488
4489 case Instruction::SDiv: {
4490 const APInt *Denominator;
4491 // sdiv X, C -> adds log(C) sign bits.
4492 if (match(U->getOperand(1), m_APInt(Denominator))) {
4493
4494 // Ignore non-positive denominator.
4495 if (!Denominator->isStrictlyPositive())
4496 break;
4497
4498 // Calculate the incoming numerator bits.
4499 unsigned NumBits =
4500 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4501
4502 // Add floor(log(C)) bits to the numerator bits.
4503 return std::min(TyBits, NumBits + Denominator->logBase2());
4504 }
4505 break;
4506 }
4507
4508 case Instruction::SRem: {
4509 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4510
4511 const APInt *Denominator;
4512 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4513 // positive constant. This let us put a lower bound on the number of sign
4514 // bits.
4515 if (match(U->getOperand(1), m_APInt(Denominator))) {
4516
4517 // Ignore non-positive denominator.
4518 if (Denominator->isStrictlyPositive()) {
4519 // Calculate the leading sign bit constraints by examining the
4520 // denominator. Given that the denominator is positive, there are two
4521 // cases:
4522 //
4523 // 1. The numerator is positive. The result range is [0,C) and
4524 // [0,C) u< (1 << ceilLogBase2(C)).
4525 //
4526 // 2. The numerator is negative. Then the result range is (-C,0] and
4527 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4528 //
4529 // Thus a lower bound on the number of sign bits is `TyBits -
4530 // ceilLogBase2(C)`.
4531
4532 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4533 Tmp = std::max(Tmp, ResBits);
4534 }
4535 }
4536 return Tmp;
4537 }
4538
4539 case Instruction::AShr: {
4540 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4541 // ashr X, C -> adds C sign bits. Vectors too.
4542 const APInt *ShAmt;
4543 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4544 if (ShAmt->uge(TyBits))
4545 break; // Bad shift.
4546 unsigned ShAmtLimited = ShAmt->getZExtValue();
4547 Tmp += ShAmtLimited;
4548 if (Tmp > TyBits) Tmp = TyBits;
4549 }
4550 return Tmp;
4551 }
4552 case Instruction::Shl: {
4553 const APInt *ShAmt;
4554 Value *X = nullptr;
4555 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4556 // shl destroys sign bits.
4557 if (ShAmt->uge(TyBits))
4558 break; // Bad shift.
4559 // We can look through a zext (more or less treating it as a sext) if
4560 // all extended bits are shifted out.
4561 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4562 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4563 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4564 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4565 } else
4566 Tmp =
4567 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4568 if (ShAmt->uge(Tmp))
4569 break; // Shifted all sign bits out.
4570 Tmp2 = ShAmt->getZExtValue();
4571 return Tmp - Tmp2;
4572 }
4573 break;
4574 }
4575 case Instruction::And:
4576 case Instruction::Or:
4577 case Instruction::Xor: // NOT is handled here.
4578 // Logical binary ops preserve the number of sign bits at the worst.
4579 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4580 if (Tmp != 1) {
4581 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4582 FirstAnswer = std::min(Tmp, Tmp2);
4583 // We computed what we know about the sign bits as our first
4584 // answer. Now proceed to the generic code that uses
4585 // computeKnownBits, and pick whichever answer is better.
4586 }
4587 break;
4588
4589 case Instruction::Select: {
4590 // If we have a clamp pattern, we know that the number of sign bits will
4591 // be the minimum of the clamp min/max range.
4592 const Value *X;
4593 const APInt *CLow, *CHigh;
4594 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4595 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4596
4597 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4598 if (Tmp == 1)
4599 break;
4600 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4601 return std::min(Tmp, Tmp2);
4602 }
4603
4604 case Instruction::Add:
4605 // Add can have at most one carry bit. Thus we know that the output
4606 // is, at worst, one more bit than the inputs.
4607 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4608 if (Tmp == 1) break;
4609
4610 // Special case decrementing a value (ADD X, -1):
4611 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4612 if (CRHS->isAllOnesValue()) {
4613 KnownBits Known(TyBits);
4614 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4615
4616 // If the input is known to be 0 or 1, the output is 0/-1, which is
4617 // all sign bits set.
4618 if ((Known.Zero | 1).isAllOnes())
4619 return TyBits;
4620
4621 // If we are subtracting one from a positive number, there is no carry
4622 // out of the result.
4623 if (Known.isNonNegative())
4624 return Tmp;
4625 }
4626
4627 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4628 if (Tmp2 == 1)
4629 break;
4630 return std::min(Tmp, Tmp2) - 1;
4631
4632 case Instruction::Sub:
4633 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4634 if (Tmp2 == 1)
4635 break;
4636
4637 // Handle NEG.
4638 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4639 if (CLHS->isNullValue()) {
4640 KnownBits Known(TyBits);
4641 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4642 // If the input is known to be 0 or 1, the output is 0/-1, which is
4643 // all sign bits set.
4644 if ((Known.Zero | 1).isAllOnes())
4645 return TyBits;
4646
4647 // If the input is known to be positive (the sign bit is known clear),
4648 // the output of the NEG has the same number of sign bits as the
4649 // input.
4650 if (Known.isNonNegative())
4651 return Tmp2;
4652
4653 // Otherwise, we treat this like a SUB.
4654 }
4655
4656 // Sub can have at most one carry bit. Thus we know that the output
4657 // is, at worst, one more bit than the inputs.
4658 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4659 if (Tmp == 1)
4660 break;
4661 return std::min(Tmp, Tmp2) - 1;
4662
4663 case Instruction::Mul: {
4664 // The output of the Mul can be at most twice the valid bits in the
4665 // inputs.
4666 unsigned SignBitsOp0 =
4667 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4668 if (SignBitsOp0 == 1)
4669 break;
4670 unsigned SignBitsOp1 =
4671 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4672 if (SignBitsOp1 == 1)
4673 break;
4674 unsigned OutValidBits =
4675 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4676 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4677 }
4678
4679 case Instruction::PHI: {
4680 const PHINode *PN = cast<PHINode>(U);
4681 unsigned NumIncomingValues = PN->getNumIncomingValues();
4682 // Don't analyze large in-degree PHIs.
4683 if (NumIncomingValues > 4) break;
4684 // Unreachable blocks may have zero-operand PHI nodes.
4685 if (NumIncomingValues == 0) break;
4686
4687 // Take the minimum of all incoming values. This can't infinitely loop
4688 // because of our depth threshold.
4690 Tmp = TyBits;
4691 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4692 if (Tmp == 1) return Tmp;
4693 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4694 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4695 DemandedElts, RecQ, Depth + 1));
4696 }
4697 return Tmp;
4698 }
4699
4700 case Instruction::Trunc: {
4701 // If the input contained enough sign bits that some remain after the
4702 // truncation, then we can make use of that. Otherwise we don't know
4703 // anything.
4704 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4705 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4706 if (Tmp > (OperandTyBits - TyBits))
4707 return Tmp - (OperandTyBits - TyBits);
4708
4709 return 1;
4710 }
4711
4712 case Instruction::ExtractElement:
4713 // Look through extract element. At the moment we keep this simple and
4714 // skip tracking the specific element. But at least we might find
4715 // information valid for all elements of the vector (for example if vector
4716 // is sign extended, shifted, etc).
4717 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4718
4719 case Instruction::ShuffleVector: {
4720 // Collect the minimum number of sign bits that are shared by every vector
4721 // element referenced by the shuffle.
4722 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4723 if (!Shuf) {
4724 // FIXME: Add support for shufflevector constant expressions.
4725 return 1;
4726 }
4727 APInt DemandedLHS, DemandedRHS;
4728 // For undef elements, we don't know anything about the common state of
4729 // the shuffle result.
4730 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4731 return 1;
4732 Tmp = std::numeric_limits<unsigned>::max();
4733 if (!!DemandedLHS) {
4734 const Value *LHS = Shuf->getOperand(0);
4735 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4736 }
4737 // If we don't know anything, early out and try computeKnownBits
4738 // fall-back.
4739 if (Tmp == 1)
4740 break;
4741 if (!!DemandedRHS) {
4742 const Value *RHS = Shuf->getOperand(1);
4743 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4744 Tmp = std::min(Tmp, Tmp2);
4745 }
4746 // If we don't know anything, early out and try computeKnownBits
4747 // fall-back.
4748 if (Tmp == 1)
4749 break;
4750 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4751 return Tmp;
4752 }
4753 case Instruction::Call: {
4754 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4755 switch (II->getIntrinsicID()) {
4756 default:
4757 break;
4758 case Intrinsic::abs:
4759 Tmp =
4760 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4761 if (Tmp == 1)
4762 break;
4763
4764 // Absolute value reduces number of sign bits by at most 1.
4765 return Tmp - 1;
4766 case Intrinsic::smin:
4767 case Intrinsic::smax: {
4768 const APInt *CLow, *CHigh;
4769 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4770 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4771 }
4772 }
4773 }
4774 }
4775 }
4776 }
4777
4778 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4779 // use this information.
4780
4781 // If we can examine all elements of a vector constant successfully, we're
4782 // done (we can't do any better than that). If not, keep trying.
4783 if (unsigned VecSignBits =
4784 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4785 return VecSignBits;
4786
4787 KnownBits Known(TyBits);
4788 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4789
4790 // If we know that the sign bit is either zero or one, determine the number of
4791 // identical bits in the top of the input value.
4792 return std::max(FirstAnswer, Known.countMinSignBits());
4793}
4794
4796 const TargetLibraryInfo *TLI) {
4797 const Function *F = CB.getCalledFunction();
4798 if (!F)
4800
4801 if (F->isIntrinsic())
4802 return F->getIntrinsicID();
4803
4804 // We are going to infer semantics of a library function based on mapping it
4805 // to an LLVM intrinsic. Check that the library function is available from
4806 // this callbase and in this environment.
4807 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4809
4810 LibFunc Func = TLI->getLibFunc(CB);
4811 if (Func == NotLibFunc)
4813
4814 switch (Func) {
4815 default:
4816 break;
4817 case LibFunc_sin:
4818 case LibFunc_sinf:
4819 case LibFunc_sinl:
4820 return Intrinsic::sin;
4821 case LibFunc_cos:
4822 case LibFunc_cosf:
4823 case LibFunc_cosl:
4824 return Intrinsic::cos;
4825 case LibFunc_tan:
4826 case LibFunc_tanf:
4827 case LibFunc_tanl:
4828 return Intrinsic::tan;
4829 case LibFunc_asin:
4830 case LibFunc_asinf:
4831 case LibFunc_asinl:
4832 return Intrinsic::asin;
4833 case LibFunc_acos:
4834 case LibFunc_acosf:
4835 case LibFunc_acosl:
4836 return Intrinsic::acos;
4837 case LibFunc_atan:
4838 case LibFunc_atanf:
4839 case LibFunc_atanl:
4840 return Intrinsic::atan;
4841 case LibFunc_atan2:
4842 case LibFunc_atan2f:
4843 case LibFunc_atan2l:
4844 return Intrinsic::atan2;
4845 case LibFunc_sinh:
4846 case LibFunc_sinhf:
4847 case LibFunc_sinhl:
4848 return Intrinsic::sinh;
4849 case LibFunc_cosh:
4850 case LibFunc_coshf:
4851 case LibFunc_coshl:
4852 return Intrinsic::cosh;
4853 case LibFunc_tanh:
4854 case LibFunc_tanhf:
4855 case LibFunc_tanhl:
4856 return Intrinsic::tanh;
4857 case LibFunc_exp:
4858 case LibFunc_expf:
4859 case LibFunc_expl:
4860 return Intrinsic::exp;
4861 case LibFunc_exp2:
4862 case LibFunc_exp2f:
4863 case LibFunc_exp2l:
4864 return Intrinsic::exp2;
4865 case LibFunc_exp10:
4866 case LibFunc_exp10f:
4867 case LibFunc_exp10l:
4868 return Intrinsic::exp10;
4869 case LibFunc_log:
4870 case LibFunc_logf:
4871 case LibFunc_logl:
4872 return Intrinsic::log;
4873 case LibFunc_log10:
4874 case LibFunc_log10f:
4875 case LibFunc_log10l:
4876 return Intrinsic::log10;
4877 case LibFunc_log2:
4878 case LibFunc_log2f:
4879 case LibFunc_log2l:
4880 return Intrinsic::log2;
4881 case LibFunc_fabs:
4882 case LibFunc_fabsf:
4883 case LibFunc_fabsl:
4884 return Intrinsic::fabs;
4885 case LibFunc_fmin:
4886 case LibFunc_fminf:
4887 case LibFunc_fminl:
4888 return Intrinsic::minnum;
4889 case LibFunc_fmax:
4890 case LibFunc_fmaxf:
4891 case LibFunc_fmaxl:
4892 return Intrinsic::maxnum;
4893 case LibFunc_copysign:
4894 case LibFunc_copysignf:
4895 case LibFunc_copysignl:
4896 return Intrinsic::copysign;
4897 case LibFunc_floor:
4898 case LibFunc_floorf:
4899 case LibFunc_floorl:
4900 return Intrinsic::floor;
4901 case LibFunc_ceil:
4902 case LibFunc_ceilf:
4903 case LibFunc_ceill:
4904 return Intrinsic::ceil;
4905 case LibFunc_trunc:
4906 case LibFunc_truncf:
4907 case LibFunc_truncl:
4908 return Intrinsic::trunc;
4909 case LibFunc_rint:
4910 case LibFunc_rintf:
4911 case LibFunc_rintl:
4912 return Intrinsic::rint;
4913 case LibFunc_nearbyint:
4914 case LibFunc_nearbyintf:
4915 case LibFunc_nearbyintl:
4916 return Intrinsic::nearbyint;
4917 case LibFunc_round:
4918 case LibFunc_roundf:
4919 case LibFunc_roundl:
4920 return Intrinsic::round;
4921 case LibFunc_roundeven:
4922 case LibFunc_roundevenf:
4923 case LibFunc_roundevenl:
4924 return Intrinsic::roundeven;
4925 case LibFunc_pow:
4926 case LibFunc_powf:
4927 case LibFunc_powl:
4928 return Intrinsic::pow;
4929 case LibFunc_sqrt:
4930 case LibFunc_sqrtf:
4931 case LibFunc_sqrtl:
4932 return Intrinsic::sqrt;
4933 }
4934
4936}
4937
4938/// Given an exploded icmp instruction, return true if the comparison only
4939/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4940/// the result of the comparison is true when the input value is signed.
4942 bool &TrueIfSigned) {
4943 switch (Pred) {
4944 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4945 TrueIfSigned = true;
4946 return RHS.isZero();
4947 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4948 TrueIfSigned = true;
4949 return RHS.isAllOnes();
4950 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4951 TrueIfSigned = false;
4952 return RHS.isAllOnes();
4953 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4954 TrueIfSigned = false;
4955 return RHS.isZero();
4956 case ICmpInst::ICMP_UGT:
4957 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4958 TrueIfSigned = true;
4959 return RHS.isMaxSignedValue();
4960 case ICmpInst::ICMP_UGE:
4961 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4962 TrueIfSigned = true;
4963 return RHS.isMinSignedValue();
4964 case ICmpInst::ICMP_ULT:
4965 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4966 TrueIfSigned = false;
4967 return RHS.isMinSignedValue();
4968 case ICmpInst::ICMP_ULE:
4969 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4970 TrueIfSigned = false;
4971 return RHS.isMaxSignedValue();
4972 default:
4973 return false;
4974 }
4975}
4976
4978 bool CondIsTrue,
4979 const Instruction *CtxI,
4980 KnownFPClass &KnownFromContext,
4981 unsigned Depth = 0) {
4982 Value *A, *B;
4984 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4985 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4986 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
4987 Depth + 1);
4988 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
4989 Depth + 1);
4990 return;
4991 }
4993 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
4994 Depth + 1);
4995 return;
4996 }
4997 CmpPredicate Pred;
4998 Value *LHS;
4999 uint64_t ClassVal = 0;
5000 const APFloat *CRHS;
5001 const APInt *RHS;
5002 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5003 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5004 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5005 LHS != V);
5006 if (CmpVal == V)
5007 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5009 m_Specific(V), m_ConstantInt(ClassVal)))) {
5010 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5011 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5012 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5013 m_APInt(RHS)))) {
5014 bool TrueIfSigned;
5015 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5016 return;
5017 if (TrueIfSigned == CondIsTrue)
5018 KnownFromContext.signBitMustBeOne();
5019 else
5020 KnownFromContext.signBitMustBeZero();
5021 }
5022}
5023
5024/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5025/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5026/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5027/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5028/// exponent range is [-149, -2], but the 0 edge case is above this range).
5029static std::tuple<int, int, int>
5031 if (!Q.CtxI || !Q.DC || !Q.DT)
5033
5034 // Intersect the bounds implied by every dominating condition, keeping the
5035 // tightest maximum. A value may participate in multiple compares
5036 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5037 int MaxExp = APFloat::IEK_Inf;
5038 int MaxExpNonZero = APFloat::IEK_Inf;
5039
5040 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5041 CmpPredicate Pred;
5042 const APFloat *LimitC;
5043 if (!match(BI->getCondition(),
5044 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5045 continue;
5046
5047 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5048 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5049 continue;
5050
5051 // If fabs(x) <= K, implies the exponent min exp range.
5052 // if fabs(x) >= K, swap the successor
5053 bool IsLessEqual =
5054 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5055 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5056 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5057
5058 bool KnownStrictlyLess =
5059 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5060 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5061
5062 BasicBlockEdge Edge1(BI->getParent(),
5063 BI->getSuccessor(IsLessEqual ? 0 : 1));
5064 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5065 // frexp returns an exponent one greater than ilogb.
5066 int Exp = ilogb(*LimitC) + 1;
5067
5068 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5069 // exponent drops by one when K is exact power of two.
5070 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5071 --Exp;
5072
5073 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5074 // may exclude.
5075
5076 // TODO: Figure out lower bound to detect no-underflow.
5077 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5078 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5079 }
5080 }
5081
5082 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5083}
5084
5086 const SimplifyQuery &Q) {
5087 KnownFPClass KnownFromContext;
5088
5089 if (Q.CC && Q.CC->AffectedValues.contains(V))
5091 KnownFromContext);
5092
5093 if (!Q.CtxI)
5094 return KnownFromContext;
5095
5096 if (Q.DC && Q.DT) {
5097 // Handle dominating conditions.
5098 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5099 Value *Cond = BI->getCondition();
5100
5101 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5102 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5103 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5104 KnownFromContext);
5105
5106 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5107 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5108 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5109 KnownFromContext);
5110 }
5111 }
5112
5113 if (!Q.AC)
5114 return KnownFromContext;
5115
5116 // Try to restrict the floating-point classes based on information from
5117 // assumptions.
5118 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5119 if (!AssumeVH)
5120 continue;
5121 CallInst *I = cast<CallInst>(AssumeVH);
5122
5123 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5124 "Got assumption for the wrong function!");
5125 assert(I->getIntrinsicID() == Intrinsic::assume &&
5126 "must be an assume intrinsic");
5127
5128 if (!isValidAssumeForContext(I, Q))
5129 continue;
5130
5131 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5132 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5133 }
5134
5135 return KnownFromContext;
5136}
5137
5139 Value *Arm, bool Invert,
5140 const SimplifyQuery &SQ,
5141 unsigned Depth) {
5142
5143 KnownFPClass KnownSrc;
5145 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5146 Depth + 1);
5147 KnownSrc = KnownSrc.unionWith(Known);
5148 if (KnownSrc.isUnknown())
5149 return;
5150
5151 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5152 Known = KnownSrc;
5153}
5154
5155void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5156 FPClassTest InterestedClasses, KnownFPClass &Known,
5157 const SimplifyQuery &Q, unsigned Depth);
5158
5160 FPClassTest InterestedClasses,
5161 const SimplifyQuery &Q, unsigned Depth) {
5162 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5163 APInt DemandedElts =
5164 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5165 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5166}
5167
5169 const APInt &DemandedElts,
5170 FPClassTest InterestedClasses,
5172 const SimplifyQuery &Q,
5173 unsigned Depth) {
5174 if ((InterestedClasses &
5176 return;
5177
5178 KnownFPClass KnownSrc;
5179 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5180 KnownSrc, Q, Depth + 1);
5181 Known = KnownFPClass::fptrunc(KnownSrc);
5182}
5183
5185 switch (IID) {
5186 case Intrinsic::minimum:
5188 case Intrinsic::maximum:
5190 case Intrinsic::minimumnum:
5192 case Intrinsic::maximumnum:
5194 case Intrinsic::minnum:
5196 case Intrinsic::maxnum:
5198 default:
5199 llvm_unreachable("not a floating-point min-max intrinsic");
5200 }
5201}
5202
5203/// \return true if this is a floating point value that is known to have a
5204/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5205static bool isAbsoluteValueULEOne(const Value *V) {
5206 // TODO: Handle frexp
5207 // TODO: Other rounding intrinsics?
5208 // TODO: Try computeKnownExponentRangeFromContext
5209
5210 // fabs(x - floor(x)) <= 1
5211 const Value *SubFloorX;
5212 if (match(V, m_FSub(m_Value(SubFloorX),
5214 return true;
5215
5218}
5219
5220void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5221 FPClassTest InterestedClasses, KnownFPClass &Known,
5222 const SimplifyQuery &Q, unsigned Depth) {
5223 assert(Known.isUnknown() && "should not be called with known information");
5224
5225 if (!DemandedElts) {
5226 // No demanded elts, better to assume we don't know anything.
5227 Known.resetAll();
5228 return;
5229 }
5230
5231 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5232
5233 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5234 Known = KnownFPClass(CFP->getValueAPF());
5235 return;
5236 }
5237
5239 Known.setKnownFPClasses(fcPosZero);
5240 Known.setSignBit(false);
5241 return;
5242 }
5243
5244 if (isa<PoisonValue>(V)) {
5245 Known.setKnownFPClasses(fcNone);
5246 Known.setSignBit(false);
5247 return;
5248 }
5249
5250 // Try to handle fixed width vector constants
5251 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5252 const Constant *CV = dyn_cast<Constant>(V);
5253 if (VFVTy && CV) {
5254 Known.setKnownFPClasses(fcNone);
5255 bool SignBitAllZero = true;
5256 bool SignBitAllOne = true;
5257
5258 // For vectors, verify that each element is not NaN.
5259 unsigned NumElts = VFVTy->getNumElements();
5260 for (unsigned i = 0; i != NumElts; ++i) {
5261 if (!DemandedElts[i])
5262 continue;
5263
5264 Constant *Elt = CV->getAggregateElement(i);
5265 if (!Elt) {
5266 Known = KnownFPClass();
5267 return;
5268 }
5269 if (isa<PoisonValue>(Elt))
5270 continue;
5271 auto *CElt = dyn_cast<ConstantFP>(Elt);
5272 if (!CElt) {
5273 Known = KnownFPClass();
5274 return;
5275 }
5276
5277 const APFloat &C = CElt->getValueAPF();
5278 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5279 if (C.isNegative())
5280 SignBitAllZero = false;
5281 else
5282 SignBitAllOne = false;
5283 }
5284 if (SignBitAllOne != SignBitAllZero)
5285 Known.setSignBit(SignBitAllOne);
5286 return;
5287 }
5288
5289 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5290 Known.setKnownFPClasses(fcNone);
5291 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5292 Known |= CDS->getElementAsAPFloat(I).classify();
5293 return;
5294 }
5295
5296 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5297 // TODO: Handle complex aggregates
5298 Known.setKnownFPClasses(fcNone);
5299 for (const Use &Op : CA->operands()) {
5300 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5301 if (!CFP) {
5302 Known = KnownFPClass();
5303 return;
5304 }
5305
5306 Known |= CFP->getValueAPF().classify();
5307 }
5308
5309 return;
5310 }
5311
5312 FPClassTest KnownNotFromFlags = fcNone;
5313 if (const auto *CB = dyn_cast<CallBase>(V))
5314 KnownNotFromFlags |= CB->getRetNoFPClass();
5315 else if (const auto *Arg = dyn_cast<Argument>(V))
5316 KnownNotFromFlags |= Arg->getNoFPClass();
5317
5318 const Operator *Op = dyn_cast<Operator>(V);
5320 if (FPOp->hasNoNaNs())
5321 KnownNotFromFlags |= fcNan;
5322 if (FPOp->hasNoInfs())
5323 KnownNotFromFlags |= fcInf;
5324 }
5325
5326 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5327 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5328
5329 // We no longer need to find out about these bits from inputs if we can
5330 // assume this from flags/attributes.
5331 InterestedClasses &= ~KnownNotFromFlags;
5332
5333 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5334 Known.knownNot(KnownNotFromFlags);
5335 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5336 if (*AssumedClasses.getSignBit())
5337 Known.signBitMustBeOne();
5338 else
5339 Known.signBitMustBeZero();
5340 }
5341 });
5342
5343 if (!Op)
5344 return;
5345
5346 // All recursive calls that increase depth must come after this.
5348 return;
5349
5350 const unsigned Opc = Op->getOpcode();
5351 switch (Opc) {
5352 case Instruction::FNeg: {
5353 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5354 Known, Q, Depth + 1);
5355 Known.fneg();
5356 break;
5357 }
5358 case Instruction::Select: {
5359 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5360 KnownFPClass Res;
5361 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5362 Depth + 1);
5363 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5364 Depth);
5365 return Res;
5366 };
5367 // Only known if known in both the LHS and RHS.
5368 Known =
5369 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5370 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5371 break;
5372 }
5373 case Instruction::Load: {
5374 const MDNode *NoFPClass =
5375 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5376 if (!NoFPClass)
5377 break;
5378
5379 ConstantInt *MaskVal =
5381 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5382 break;
5383 }
5384 case Instruction::Call: {
5385 const CallInst *II = cast<CallInst>(Op);
5386 const Intrinsic::ID IID = II->getIntrinsicID();
5387 switch (IID) {
5388 case Intrinsic::fabs: {
5389 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5390 // If we only care about the sign bit we don't need to inspect the
5391 // operand.
5392 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5393 InterestedClasses, Known, Q, Depth + 1);
5394 }
5395
5396 Known.fabs();
5397 break;
5398 }
5399 case Intrinsic::copysign: {
5400 KnownFPClass KnownSign;
5401
5402 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5403 Known, Q, Depth + 1);
5404 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5405 KnownSign, Q, Depth + 1);
5406 Known.copysign(KnownSign);
5407 break;
5408 }
5409 case Intrinsic::fma:
5410 case Intrinsic::fmuladd: {
5411 if ((InterestedClasses & fcNegative) == fcNone)
5412 break;
5413
5414 // FIXME: This should check isGuaranteedNotToBeUndef
5415 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5416 KnownFPClass KnownSrc, KnownAddend;
5417 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5418 InterestedClasses, KnownAddend, Q, Depth + 1);
5419 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5420 InterestedClasses, KnownSrc, Q, Depth + 1);
5421
5422 const Function *F = II->getFunction();
5423 const fltSemantics &FltSem =
5424 II->getType()->getScalarType()->getFltSemantics();
5426 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5427
5428 if (KnownNotFromFlags & fcNan) {
5429 KnownSrc.knownNot(fcNan);
5430 KnownAddend.knownNot(fcNan);
5431 }
5432
5433 if (KnownNotFromFlags & fcInf) {
5434 KnownSrc.knownNot(fcInf);
5435 KnownAddend.knownNot(fcInf);
5436 }
5437
5438 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5439 break;
5440 }
5441
5442 KnownFPClass KnownSrc[3];
5443 for (int I = 0; I != 3; ++I) {
5444 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5445 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5446 if (KnownSrc[I].isUnknown())
5447 return;
5448
5449 if (KnownNotFromFlags & fcNan)
5450 KnownSrc[I].knownNot(fcNan);
5451 if (KnownNotFromFlags & fcInf)
5452 KnownSrc[I].knownNot(fcInf);
5453 }
5454
5455 const Function *F = II->getFunction();
5456 const fltSemantics &FltSem =
5457 II->getType()->getScalarType()->getFltSemantics();
5459 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5460 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5461 break;
5462 }
5463 case Intrinsic::sqrt:
5464 case Intrinsic::experimental_constrained_sqrt: {
5465 KnownFPClass KnownSrc;
5466 FPClassTest InterestedSrcs = InterestedClasses;
5467 if (InterestedClasses & fcNan)
5468 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5469
5470 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5471 KnownSrc, Q, Depth + 1);
5472
5474
5475 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5476 if (!HasNSZ) {
5477 const Function *F = II->getFunction();
5478 const fltSemantics &FltSem =
5479 II->getType()->getScalarType()->getFltSemantics();
5480 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5481 }
5482
5483 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5484 if (HasNSZ)
5485 Known.knownNot(fcNegZero);
5486
5487 break;
5488 }
5489 case Intrinsic::sin: {
5490 KnownFPClass KnownSrc;
5491 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5492 KnownSrc, Q, Depth + 1);
5493 Known = KnownFPClass::sin(KnownSrc);
5494 break;
5495 }
5496 case Intrinsic::cos: {
5497 KnownFPClass KnownSrc;
5498 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5499 KnownSrc, Q, Depth + 1);
5500 Known = KnownFPClass::cos(KnownSrc);
5501 break;
5502 }
5503 case Intrinsic::tan: {
5504 KnownFPClass KnownSrc;
5505 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5506 KnownSrc, Q, Depth + 1);
5507 Known = KnownFPClass::tan(KnownSrc);
5508 break;
5509 }
5510 case Intrinsic::sinh: {
5511 KnownFPClass KnownSrc;
5512 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5513 KnownSrc, Q, Depth + 1);
5514 Known = KnownFPClass::sinh(KnownSrc);
5515 break;
5516 }
5517 case Intrinsic::cosh: {
5518 KnownFPClass KnownSrc;
5519 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5520 KnownSrc, Q, Depth + 1);
5521 Known = KnownFPClass::cosh(KnownSrc);
5522 break;
5523 }
5524 case Intrinsic::tanh: {
5525 KnownFPClass KnownSrc;
5526 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5527 KnownSrc, Q, Depth + 1);
5528 Known = KnownFPClass::tanh(KnownSrc);
5529 break;
5530 }
5531 case Intrinsic::asin: {
5532 KnownFPClass KnownSrc;
5533 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5534 KnownSrc, Q, Depth + 1);
5535 Known = KnownFPClass::asin(KnownSrc);
5536 break;
5537 }
5538 case Intrinsic::acos: {
5539 KnownFPClass KnownSrc;
5540 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5541 KnownSrc, Q, Depth + 1);
5542 Known = KnownFPClass::acos(KnownSrc);
5543 break;
5544 }
5545 case Intrinsic::atan: {
5546 KnownFPClass KnownSrc;
5547 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5548 KnownSrc, Q, Depth + 1);
5549 Known = KnownFPClass::atan(KnownSrc);
5550 break;
5551 }
5552 case Intrinsic::atan2: {
5553 FPClassTest InterestedY = InterestedClasses;
5554 FPClassTest InterestedX = InterestedClasses;
5555
5556 // We can rule out negative values if y cannot have a negative value.
5557 if ((InterestedClasses & fcNegFinite) != fcNone)
5558 InterestedY |= fcNegative;
5559
5560 // We can rule out positive values if y cannot have a positive value.
5561 if ((InterestedClasses & fcPosFinite) != fcNone)
5562 InterestedY |= fcPositive | fcNegSubnormal;
5563
5564 // We can rule out zero and subnormal if x cannot have a positive value.
5565 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5566 InterestedX |= fcPositive | fcNegSubnormal;
5567
5568 KnownFPClass KnownY, KnownX;
5569 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5570 KnownY, Q, Depth + 1);
5571 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5572 KnownX, Q, Depth + 1);
5573
5574 const Function *F = II->getFunction();
5576 F ? F->getDenormalMode(
5577 II->getType()->getScalarType()->getFltSemantics())
5579 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5580 break;
5581 }
5582 case Intrinsic::maxnum:
5583 case Intrinsic::minnum:
5584 case Intrinsic::minimum:
5585 case Intrinsic::maximum:
5586 case Intrinsic::minimumnum:
5587 case Intrinsic::maximumnum: {
5588 KnownFPClass KnownLHS, KnownRHS;
5589 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5590 KnownLHS, Q, Depth + 1);
5591 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5592 KnownRHS, Q, Depth + 1);
5593
5594 const Function *F = II->getFunction();
5595
5597 F ? F->getDenormalMode(
5598 II->getType()->getScalarType()->getFltSemantics())
5600
5601 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5602 Mode);
5603 break;
5604 }
5605 case Intrinsic::canonicalize: {
5606 KnownFPClass KnownSrc;
5607 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5608 KnownSrc, Q, Depth + 1);
5609
5610 const Function *F = II->getFunction();
5611 DenormalMode DenormMode =
5612 F ? F->getDenormalMode(
5613 II->getType()->getScalarType()->getFltSemantics())
5615 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5616 break;
5617 }
5618 case Intrinsic::vector_reduce_fmax:
5619 case Intrinsic::vector_reduce_fmin:
5620 case Intrinsic::vector_reduce_fmaximum:
5621 case Intrinsic::vector_reduce_fminimum:
5622 case Intrinsic::vector_reduce_fmaximumnum:
5623 case Intrinsic::vector_reduce_fminimumnum: {
5624 // reduce min/max will choose an element from one of the vector elements,
5625 // so we can infer and class information that is common to all elements.
5626 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5627 InterestedClasses, Q, Depth + 1);
5628 // Can only propagate sign if output is never NaN.
5629 if (!Known.isKnownNeverNaN())
5630 Known.setSignBit(std::nullopt);
5631 break;
5632 }
5633 // reverse preserves all characteristics of the input vec's element.
5634 case Intrinsic::vector_reverse:
5636 II->getArgOperand(0), DemandedElts.reverseBits(),
5637 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5638 break;
5639 case Intrinsic::trunc:
5640 case Intrinsic::floor:
5641 case Intrinsic::ceil:
5642 case Intrinsic::rint:
5643 case Intrinsic::nearbyint:
5644 case Intrinsic::round:
5645 case Intrinsic::roundeven: {
5646 KnownFPClass KnownSrc;
5647 FPClassTest InterestedSrcs = InterestedClasses;
5648 if (InterestedSrcs & fcPosFinite)
5649 InterestedSrcs |= fcPosFinite;
5650 if (InterestedSrcs & fcNegFinite)
5651 InterestedSrcs |= fcNegFinite;
5652 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5653 KnownSrc, Q, Depth + 1);
5654
5656 KnownSrc, IID == Intrinsic::trunc,
5657 V->getType()->getScalarType()->isMultiUnitFPType());
5658 break;
5659 }
5660 case Intrinsic::exp:
5661 case Intrinsic::exp2:
5662 case Intrinsic::exp10:
5663 case Intrinsic::amdgcn_exp2: {
5664 KnownFPClass KnownSrc;
5665 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5666 KnownSrc, Q, Depth + 1);
5667
5668 Known = KnownFPClass::exp(KnownSrc);
5669
5670 Type *EltTy = II->getType()->getScalarType();
5671 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5672 Known.knownNot(fcSubnormal);
5673
5674 break;
5675 }
5676 case Intrinsic::fptrunc_round: {
5677 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5678 Q, Depth);
5679 break;
5680 }
5681 case Intrinsic::log:
5682 case Intrinsic::log10:
5683 case Intrinsic::log2:
5684 case Intrinsic::experimental_constrained_log:
5685 case Intrinsic::experimental_constrained_log10:
5686 case Intrinsic::experimental_constrained_log2:
5687 case Intrinsic::amdgcn_log: {
5688 FPClassTest InterestedSrcs = fcNone;
5689
5690 // log(negative) produces NaN.
5691 if ((InterestedClasses & fcNan) != fcNone)
5692 InterestedSrcs |= fcNan | fcNegative;
5693
5694 // log(logical-zero) produces negative infinity.
5695 if ((InterestedClasses & fcNegInf) != fcNone)
5696 InterestedSrcs |= fcZero | fcSubnormal;
5697
5698 // log(x) < -0.0 if x < +1.0
5699 if ((InterestedClasses & fcNegNormal) != fcNone)
5700 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5701
5702 // log(x) >= +0.0 if x >= +1.0
5703 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5704 InterestedSrcs |= fcPosNormal;
5705
5706 // log(x) is positive infinity iff x is positive infinity.
5707 if ((InterestedClasses & fcPosInf) != fcNone)
5708 InterestedSrcs |= fcPosInf;
5709
5710 KnownFPClass KnownSrc;
5711 if (InterestedSrcs != fcNone)
5712 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5713 KnownSrc, Q, Depth + 1);
5714 const Function *F = II->getFunction();
5716 F ? F->getDenormalMode(
5717 II->getType()->getScalarType()->getFltSemantics())
5719 Known = KnownFPClass::log(KnownSrc, Mode);
5720 break;
5721 }
5722 case Intrinsic::pow: {
5723 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5724 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5725 if (!WantNaN && !WantNegative)
5726 break;
5727
5728 FPClassTest InterestedLHS = fcNone;
5729 FPClassTest InterestedRHS = fcNone;
5730 if (WantNaN) {
5731 // pow may return NaN if one of the arguments is NaN. NaN may also be
5732 // produced from a negative, non-zero finite base and a non-integer
5733 // exponent.
5734 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5735 InterestedRHS |= fcNan;
5736 }
5737 if (WantNegative) {
5738 // A negative value is returned when a negative base is raised to an odd
5739 // integer power. Only normal values can be odd integers.
5740 InterestedLHS |= fcNegative;
5741 InterestedRHS |= fcNormal;
5742 }
5743
5744 KnownFPClass KnownLHS;
5745 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5746 KnownLHS, Q, Depth + 1);
5747
5748 // If the LHS is unknown, then querying the RHS is only useful for rare
5749 // edge cases.
5750 if (KnownLHS.isUnknown())
5751 break;
5752
5753 KnownFPClass KnownRHS;
5754 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5755 KnownRHS, Q, Depth + 1);
5756 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5757 break;
5758 }
5759 case Intrinsic::powi: {
5760 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5761 break;
5762
5763 // The exponent is always a scalar, even when raising a vector to a power.
5764 const Value *Exp = II->getArgOperand(1);
5765 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5766 KnownBits ExponentKnownBits(BitWidth);
5767 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5768
5769 FPClassTest InterestedSrcs = fcNone;
5770 if (InterestedClasses & fcNan)
5771 InterestedSrcs |= fcNan;
5772 if (!ExponentKnownBits.isZero()) {
5773 if (InterestedClasses & fcInf)
5774 InterestedSrcs |= fcFinite | fcInf;
5775 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5776 InterestedSrcs |= fcNegative;
5777 }
5778
5779 KnownFPClass KnownSrc;
5780 if (InterestedSrcs != fcNone)
5781 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5782 KnownSrc, Q, Depth + 1);
5783
5784 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5785 break;
5786 }
5787 case Intrinsic::ldexp: {
5788 KnownFPClass KnownSrc;
5789 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5790 KnownSrc, Q, Depth + 1);
5791 // Can refine inf/zero handling based on the exponent operand.
5792 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5793
5794 const Value *ExpArg = II->getArgOperand(1);
5795 ConstantRange ExpKnownRange =
5796 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5797 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5798 : ConstantRange::getFull(
5799 ExpArg->getType()->getScalarSizeInBits());
5800
5801 const fltSemantics &Flt =
5802 II->getType()->getScalarType()->getFltSemantics();
5803
5804 const Function *F = II->getFunction();
5806 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5807
5808 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5809 ExpKnownRange.getSignedMax(), Flt, Mode);
5810 break;
5811 }
5812 case Intrinsic::arithmetic_fence: {
5813 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5814 Known, Q, Depth + 1);
5815 break;
5816 }
5817 case Intrinsic::experimental_constrained_sitofp:
5818 case Intrinsic::experimental_constrained_uitofp:
5819 // Cannot produce nan
5820 Known.knownNot(fcNan);
5821
5822 // sitofp and uitofp turn into +0.0 for zero.
5823 Known.knownNot(fcNegZero);
5824
5825 // Integers cannot be subnormal
5826 Known.knownNot(fcSubnormal);
5827
5828 if (IID == Intrinsic::experimental_constrained_uitofp)
5829 Known.signBitMustBeZero();
5830
5831 // TODO: Copy inf handling from instructions
5832 break;
5833
5834 case Intrinsic::amdgcn_fract: {
5835 Known.knownNot(fcInf);
5836
5837 if (InterestedClasses & fcNan) {
5838 KnownFPClass KnownSrc;
5839 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5840 InterestedClasses, KnownSrc, Q, Depth + 1);
5841
5842 if (KnownSrc.isKnownNeverInfOrNaN())
5843 Known.knownNot(fcNan);
5844 else if (KnownSrc.isKnownNever(fcSNan))
5845 Known.knownNot(fcSNan);
5846 }
5847
5848 break;
5849 }
5850 case Intrinsic::amdgcn_rcp: {
5851 KnownFPClass KnownSrc;
5852 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5853 KnownSrc, Q, Depth + 1);
5854
5855 Known.propagateNonNaN(KnownSrc);
5856
5857 Type *EltTy = II->getType()->getScalarType();
5858
5859 // f32 denormal always flushed.
5860 if (EltTy->isFloatTy()) {
5861 Known.knownNot(fcSubnormal);
5862 KnownSrc.knownNot(fcSubnormal);
5863 }
5864
5865 if (KnownSrc.isKnownNever(fcNegative))
5866 Known.knownNot(fcNegative);
5867 if (KnownSrc.isKnownNever(fcPositive))
5868 Known.knownNot(fcPositive);
5869
5870 if (const Function *F = II->getFunction()) {
5871 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5872 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5873 Known.knownNot(fcPosInf);
5874 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5875 Known.knownNot(fcNegInf);
5876 }
5877
5878 break;
5879 }
5880 case Intrinsic::amdgcn_rsq: {
5881 KnownFPClass KnownSrc;
5882 // The only negative value that can be returned is -inf for -0 inputs.
5884
5885 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5886 KnownSrc, Q, Depth + 1);
5887
5888 // Negative -> nan
5889 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5890 Known.knownNot(fcNan);
5891 else if (KnownSrc.isKnownNever(fcSNan))
5892 Known.knownNot(fcSNan);
5893
5894 // +inf -> +0
5895 if (KnownSrc.isKnownNeverPosInfinity())
5896 Known.knownNot(fcPosZero);
5897
5898 Type *EltTy = II->getType()->getScalarType();
5899
5900 // f32 denormal always flushed.
5901 if (EltTy->isFloatTy())
5902 Known.knownNot(fcPosSubnormal);
5903
5904 if (const Function *F = II->getFunction()) {
5905 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5906
5907 // -0 -> -inf
5908 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5909 Known.knownNot(fcNegInf);
5910
5911 // +0 -> +inf
5912 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5913 Known.knownNot(fcPosInf);
5914 }
5915
5916 break;
5917 }
5918 case Intrinsic::amdgcn_trig_preop: {
5919 // Always returns a value [0, 1)
5920 Known.knownNot(fcNan | fcInf | fcNegative);
5921 break;
5922 }
5923 case Intrinsic::convert_from_arbitrary_fp: {
5924 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5925 StringRef FormatStr = cast<MDString>(MD)->getString();
5926
5927 const fltSemantics *SrcSemantics =
5929 if (!SrcSemantics)
5930 break;
5931
5932 const fltSemantics DstSemantics =
5933 II->getType()->getScalarType()->getFltSemantics();
5934
5935 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5936 Known.knownNot(fcNan);
5937
5938 // fcInf can only be cleared if the source format has no Inf encoding
5939 // and the dst max exp can accommodate src max exp.
5940 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5941 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5942 APFloat::semanticsMaxExponent(DstSemantics))
5943 Known.knownNot(fcInf);
5944
5945 // Check and clear all neg flags for formats that do not have signed
5946 // representation.
5947 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5948 Known.knownNot(fcNegative);
5949
5950 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5951 // zero.
5952 if (!APFloat::semanticsHasZero(*SrcSemantics))
5953 Known.knownNot(fcZero);
5954 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5955 Known.knownNot(fcNegZero);
5956
5957 // If src lands normally in dest, the result can never be subnormal.
5958 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5959 Known.knownNot(fcSubnormal);
5960 break;
5961 }
5962 default:
5963 break;
5964 }
5965
5966 break;
5967 }
5968 case Instruction::FAdd:
5969 case Instruction::FSub: {
5970 KnownFPClass KnownLHS, KnownRHS;
5971 bool WantNegative =
5972 Op->getOpcode() == Instruction::FAdd &&
5973 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5974 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5975 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5976
5977 if (!WantNaN && !WantNegative && !WantNegZero)
5978 break;
5979
5980 FPClassTest InterestedSrcs = InterestedClasses;
5981 if (WantNegative)
5982 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5983 if (InterestedClasses & fcNan)
5984 InterestedSrcs |= fcInf;
5985 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5986 KnownRHS, Q, Depth + 1);
5987
5988 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5989 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5990 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
5991 Depth + 1);
5992 if (Self)
5993 KnownLHS = KnownRHS;
5994
5995 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5996 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5997 WantNegZero || Opc == Instruction::FSub) {
5998
5999 // FIXME: Context function should always be passed in separately
6000 const Function *F = cast<Instruction>(Op)->getFunction();
6001 const fltSemantics &FltSem =
6002 Op->getType()->getScalarType()->getFltSemantics();
6004 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6005
6006 if (Self && Opc == Instruction::FAdd) {
6007 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6008 } else {
6009 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6010 // there's no point.
6011
6012 if (!Self) {
6013 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6014 KnownLHS, Q, Depth + 1);
6015 }
6016
6017 Known = Opc == Instruction::FAdd
6018 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6019 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6020 }
6021 }
6022
6023 break;
6024 }
6025 case Instruction::FMul: {
6026 const Function *F = cast<Instruction>(Op)->getFunction();
6028 F ? F->getDenormalMode(
6029 Op->getType()->getScalarType()->getFltSemantics())
6031
6032 Value *LHS = Op->getOperand(0);
6033 Value *RHS = Op->getOperand(1);
6034 // X * X is always non-negative or a NaN.
6035 // FIXME: Should check isGuaranteedNotToBeUndef
6036 if (LHS == RHS) {
6037 KnownFPClass KnownSrc;
6038 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6039 Depth + 1);
6040 Known = KnownFPClass::square(KnownSrc, Mode);
6041 break;
6042 }
6043
6044 KnownFPClass KnownLHS, KnownRHS;
6045
6046 const APFloat *CRHS;
6047 if (match(RHS, m_APFloat(CRHS))) {
6048 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6049 Depth + 1);
6050 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6051 } else {
6052 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6053 Depth + 1);
6054 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6055 // additional not-nan if the addend is known-not negative infinity if the
6056 // multiply is known-not infinity.
6057
6058 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6059 Depth + 1);
6060 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6061 }
6062
6063 /// Propgate no-infs if the other source is known smaller than one, such
6064 /// that this cannot introduce overflow.
6065 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6066 Known.knownNot(fcInf);
6067 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6068 Known.knownNot(fcInf);
6069
6070 break;
6071 }
6072 case Instruction::FDiv: {
6073 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6074
6075 const Function *F = cast<Instruction>(Op)->getFunction();
6076 const fltSemantics &FltSem =
6077 Op->getType()->getScalarType()->getFltSemantics();
6079 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6080
6081 if (Op->getOperand(0) == Op->getOperand(1) &&
6082 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6083 // X / X is always exactly 1.0 or a NaN.
6084 Known.setKnownFPClasses(fcNan | fcPosNormal);
6085
6086 if (!WantNan)
6087 break;
6088
6089 KnownFPClass KnownSrc;
6090 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6091 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6092 Depth + 1);
6093
6094 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6095 break;
6096 }
6097
6098 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6099 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6100 if (!WantNan && !WantNegative && !WantPositive)
6101 break;
6102
6103 KnownFPClass KnownLHS, KnownRHS;
6104 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6105 Q, Depth + 1);
6106
6107 bool KnowSomethingUseful =
6108 KnownRHS.isKnownNeverNaN() ||
6111
6112 if (KnowSomethingUseful)
6113 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6114 Q, Depth + 1);
6115
6116 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6117 break;
6118 }
6119 case Instruction::FRem: {
6120 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6121
6122 Known.knownNot(fcInf);
6123
6124 const Function *F = cast<Instruction>(Op)->getFunction();
6126 F ? F->getDenormalMode(
6127 Op->getType()->getScalarType()->getFltSemantics())
6129
6130 if (Op->getOperand(0) == Op->getOperand(1) &&
6131 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6132 // X % X is always exactly [+-]0.0 or a NaN.
6133 Known.setKnownFPClasses(fcNan | fcZero);
6134
6135 if (!WantNan)
6136 break;
6137
6138 KnownFPClass KnownSrc;
6139 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6140 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6141 Depth + 1);
6142
6143 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6144 break;
6145 }
6146
6147 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6148 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6149 if (!WantNan && !WantNegative && !WantPositive)
6150 break;
6151
6152 KnownFPClass KnownLHS, KnownRHS;
6153 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6154 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6155 Depth + 1);
6156
6157 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6158 KnownRHS.isKnownNever(fcNegative) ||
6159 KnownRHS.isKnownNever(fcPositive);
6160
6161 if (KnowSomethingUseful || WantPositive)
6162 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6163 Q, Depth + 1);
6164
6165 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6166
6167 break;
6168 }
6169 case Instruction::FPExt: {
6170 KnownFPClass KnownSrc;
6171 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6172 KnownSrc, Q, Depth + 1);
6173
6174 const fltSemantics &DstTy =
6175 Op->getType()->getScalarType()->getFltSemantics();
6176 const fltSemantics &SrcTy =
6177 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6178
6179 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6180 break;
6181 }
6182 case Instruction::FPTrunc: {
6183 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6184 Depth);
6185 break;
6186 }
6187 case Instruction::SIToFP:
6188 case Instruction::UIToFP: {
6189 // Cannot produce nan
6190 Known.knownNot(fcNan);
6191
6192 // Integers cannot be subnormal
6193 Known.knownNot(fcSubnormal);
6194
6195 // sitofp and uitofp turn into +0.0 for zero.
6196 Known.knownNot(fcNegZero);
6197
6198 // UIToFP is always non-negative regardless of known bits.
6199 if (Op->getOpcode() == Instruction::UIToFP)
6200 Known.signBitMustBeZero();
6201
6202 // Only compute known bits if we can learn something useful from them.
6203 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6204 break;
6205
6206 KnownBits IntKnown =
6207 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6208
6209 // If the integer is non-zero, the result cannot be +0.0
6210 if (IntKnown.isNonZero())
6211 Known.knownNot(fcPosZero);
6212
6213 if (Op->getOpcode() == Instruction::SIToFP) {
6214 // If the signed integer is known non-negative, the result is
6215 // non-negative. If the signed integer is known negative, the result is
6216 // negative.
6217 if (IntKnown.isNonNegative()) {
6218 Known.signBitMustBeZero();
6219 } else if (IntKnown.isNegative()) {
6220 Known.signBitMustBeOne();
6221 }
6222 }
6223
6224 // Guard kept for ilogb()
6225 if (InterestedClasses & fcInf) {
6226 // Get width of largest magnitude integer known.
6227 // This still works for a signed minimum value because the largest FP
6228 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6229 int IntSize = IntKnown.getBitWidth();
6230 if (Op->getOpcode() == Instruction::UIToFP)
6231 IntSize -= IntKnown.countMinLeadingZeros();
6232 else if (Op->getOpcode() == Instruction::SIToFP)
6233 IntSize -= IntKnown.countMinSignBits();
6234
6235 // If the exponent of the largest finite FP value can hold the largest
6236 // integer, the result of the cast must be finite.
6237 Type *FPTy = Op->getType()->getScalarType();
6238 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6239 Known.knownNot(fcInf);
6240 }
6241
6242 break;
6243 }
6244 case Instruction::ExtractElement: {
6245 // Look through extract element. If the index is non-constant or
6246 // out-of-range demand all elements, otherwise just the extracted element.
6247 const Value *Vec = Op->getOperand(0);
6248
6249 APInt DemandedVecElts;
6250 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6251 unsigned NumElts = VecTy->getNumElements();
6252 DemandedVecElts = APInt::getAllOnes(NumElts);
6253 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6254 if (CIdx && CIdx->getValue().ult(NumElts))
6255 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6256 } else {
6257 DemandedVecElts = APInt(1, 1);
6258 }
6259
6260 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6261 Q, Depth + 1);
6262 }
6263 case Instruction::InsertElement: {
6264 if (isa<ScalableVectorType>(Op->getType()))
6265 return;
6266
6267 const Value *Vec = Op->getOperand(0);
6268 const Value *Elt = Op->getOperand(1);
6269 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6270 unsigned NumElts = DemandedElts.getBitWidth();
6271 APInt DemandedVecElts = DemandedElts;
6272 bool NeedsElt = true;
6273 // If we know the index we are inserting to, clear it from Vec check.
6274 if (CIdx && CIdx->getValue().ult(NumElts)) {
6275 DemandedVecElts.clearBit(CIdx->getZExtValue());
6276 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6277 }
6278
6279 // Do we demand the inserted element?
6280 if (NeedsElt) {
6281 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6282 // If we don't know any bits, early out.
6283 if (Known.isUnknown())
6284 break;
6285 } else {
6286 Known.setKnownFPClasses(fcNone);
6287 }
6288
6289 // Do we need anymore elements from Vec?
6290 if (!DemandedVecElts.isZero()) {
6291 KnownFPClass Known2;
6292 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6293 Depth + 1);
6294 Known |= Known2;
6295 }
6296
6297 break;
6298 }
6299 case Instruction::ShuffleVector: {
6300 // Handle vector splat idiom
6301 if (Value *Splat = getSplatValue(V)) {
6302 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6303 break;
6304 }
6305
6306 // For undef elements, we don't know anything about the common state of
6307 // the shuffle result.
6308 APInt DemandedLHS, DemandedRHS;
6309 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6310 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6311 return;
6312
6313 if (!!DemandedLHS) {
6314 const Value *LHS = Shuf->getOperand(0);
6315 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6316 Depth + 1);
6317
6318 // If we don't know any bits, early out.
6319 if (Known.isUnknown())
6320 break;
6321 } else {
6322 Known.setKnownFPClasses(fcNone);
6323 }
6324
6325 if (!!DemandedRHS) {
6326 KnownFPClass Known2;
6327 const Value *RHS = Shuf->getOperand(1);
6328 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6329 Depth + 1);
6330 Known |= Known2;
6331 }
6332
6333 break;
6334 }
6335 case Instruction::ExtractValue: {
6336 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6337 ArrayRef<unsigned> Indices = Extract->getIndices();
6338 const Value *Src = Extract->getAggregateOperand();
6339 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6340 Indices[0] == 0) {
6341 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6342 switch (II->getIntrinsicID()) {
6343 case Intrinsic::frexp: {
6344 Known.knownNot(fcSubnormal);
6345
6346 KnownFPClass KnownSrc;
6347 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6348 InterestedClasses, KnownSrc, Q, Depth + 1);
6349
6350 const Function *F = cast<Instruction>(Op)->getFunction();
6351 const fltSemantics &FltSem =
6352 Op->getType()->getScalarType()->getFltSemantics();
6353
6355 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6356 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6357 return;
6358 }
6359 default:
6360 break;
6361 }
6362 }
6363 }
6364
6365 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6366 Depth + 1);
6367 break;
6368 }
6369 case Instruction::PHI: {
6370 const PHINode *P = cast<PHINode>(Op);
6371 // Unreachable blocks may have zero-operand PHI nodes.
6372 if (P->getNumIncomingValues() == 0)
6373 break;
6374
6375 // Otherwise take the unions of the known bit sets of the operands,
6376 // taking conservative care to avoid excessive recursion.
6377 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6378
6379 if (Depth < PhiRecursionLimit) {
6380 // Skip if every incoming value references to ourself.
6381 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6382 break;
6383
6384 bool First = true;
6385
6386 for (const Use &U : P->operands()) {
6387 Value *IncValue;
6388 Instruction *CtxI;
6389 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6390 // Skip direct self references.
6391 if (IncValue == P)
6392 continue;
6393
6394 KnownFPClass KnownSrc;
6395 // Recurse, but cap the recursion to two levels, because we don't want
6396 // to waste time spinning around in loops. We need at least depth 2 to
6397 // detect known sign bits.
6398 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6400 PhiRecursionLimit);
6401
6402 if (First) {
6403 Known = KnownSrc;
6404 First = false;
6405 } else {
6406 Known |= KnownSrc;
6407 }
6408
6409 if (Known.getKnownFPClasses() == fcAllFlags)
6410 break;
6411 }
6412 }
6413
6414 // Look for the case of a for loop which has a positive
6415 // initial value and is incremented by a squared value.
6416 // This will propagate sign information out of such loops.
6417 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6418 break;
6419 for (unsigned I = 0; I < 2; I++) {
6420 Value *RecurValue = P->getIncomingValue(1 - I);
6422 if (!II)
6423 continue;
6424 Value *R, *L, *Init;
6425 PHINode *PN;
6427 PN == P) {
6428 switch (II->getIntrinsicID()) {
6429 case Intrinsic::fma:
6430 case Intrinsic::fmuladd: {
6431 KnownFPClass KnownStart;
6432 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6433 Q, Depth + 1);
6434 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6435 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6437 break;
6438 }
6439 }
6440 }
6441 }
6442 break;
6443 }
6444 case Instruction::BitCast: {
6445 const Value *Src;
6446 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6447 !Src->getType()->isIntOrIntVectorTy())
6448 break;
6449
6450 const Type *Ty = Op->getType();
6451
6452 Value *CastLHS, *CastRHS;
6453
6454 // Match bitcast(umax(bitcast(a), bitcast(b)))
6455 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6456 m_BitCast(m_Value(CastRHS)))) &&
6457 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6458 KnownFPClass KnownLHS, KnownRHS;
6459 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6460 Depth + 1);
6461 if (!KnownRHS.isUnknown()) {
6462 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6463 Q, Depth + 1);
6464 Known = KnownLHS | KnownRHS;
6465 }
6466
6467 return;
6468 }
6469
6470 const Type *EltTy = Ty->getScalarType();
6471 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6472 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6473
6475 break;
6476 }
6477 default:
6478 break;
6479 }
6480}
6481
6483 const APInt &DemandedElts,
6484 FPClassTest InterestedClasses,
6485 const SimplifyQuery &SQ,
6486 unsigned Depth) {
6487 KnownFPClass KnownClasses;
6488 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6489 Depth);
6490 return KnownClasses;
6491}
6492
6494 FPClassTest InterestedClasses,
6495 const SimplifyQuery &SQ,
6496 unsigned Depth) {
6498 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6499 return Known;
6500}
6501
6503 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6504 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6505 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6506 return computeKnownFPClass(V, InterestedClasses,
6507 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6508 Depth);
6509}
6510
6512llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6513 FastMathFlags FMF, FPClassTest InterestedClasses,
6514 const SimplifyQuery &SQ, unsigned Depth) {
6515 if (FMF.noNaNs())
6516 InterestedClasses &= ~fcNan;
6517 if (FMF.noInfs())
6518 InterestedClasses &= ~fcInf;
6519
6520 KnownFPClass Result =
6521 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6522
6523 if (FMF.noNaNs())
6524 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6525 if (FMF.noInfs())
6526 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6527 return Result;
6528}
6529
6531 FPClassTest InterestedClasses,
6532 const SimplifyQuery &SQ,
6533 unsigned Depth) {
6534 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6535 APInt DemandedElts =
6536 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6537 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6538 Depth);
6539}
6540
6542 unsigned Depth) {
6544 return Known.isKnownNeverNegZero();
6545}
6546
6548 unsigned Depth) {
6551 return Known.cannotBeOrderedLessThanZero();
6552}
6553
6555 unsigned Depth) {
6557 return Known.isKnownNeverInfinity();
6558}
6559
6560/// Return true if the floating-point value can never contain a NaN or infinity.
6562 unsigned Depth) {
6564 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6565}
6566
6567/// Return true if the floating-point scalar value is not a NaN or if the
6568/// floating-point vector value has no NaN elements. Return false if a value
6569/// could ever be NaN.
6571 unsigned Depth) {
6573 return Known.isKnownNeverNaN();
6574}
6575
6576/// Return false if we can prove that the specified FP value's sign bit is 0.
6577/// Return true if we can prove that the specified FP value's sign bit is 1.
6578/// Otherwise return std::nullopt.
6579std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6580 const SimplifyQuery &SQ,
6581 unsigned Depth) {
6583 return Known.getSignBit();
6584}
6585
6587 auto *User = cast<Instruction>(U.getUser());
6588 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6589 if (FPOp->hasNoSignedZeros())
6590 return true;
6591 }
6592
6593 switch (User->getOpcode()) {
6594 case Instruction::FPToSI:
6595 case Instruction::FPToUI:
6596 return true;
6597 case Instruction::FCmp:
6598 // fcmp treats both positive and negative zero as equal.
6599 return true;
6600 case Instruction::Call:
6601 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6602 switch (II->getIntrinsicID()) {
6603 case Intrinsic::fabs:
6604 return true;
6605 case Intrinsic::copysign:
6606 return U.getOperandNo() == 0;
6607 case Intrinsic::is_fpclass: {
6608 auto Test =
6609 static_cast<FPClassTest>(
6610 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6613 }
6614 default:
6615 return false;
6616 }
6617 }
6618 return false;
6619 default:
6620 return false;
6621 }
6622}
6623
6625 auto *User = cast<Instruction>(U.getUser());
6626 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6627 if (FPOp->hasNoNaNs())
6628 return true;
6629 }
6630
6631 switch (User->getOpcode()) {
6632 case Instruction::FPToSI:
6633 case Instruction::FPToUI:
6634 return true;
6635 // Proper FP math operations ignore the sign bit of NaN.
6636 case Instruction::FAdd:
6637 case Instruction::FSub:
6638 case Instruction::FMul:
6639 case Instruction::FDiv:
6640 case Instruction::FRem:
6641 case Instruction::FPTrunc:
6642 case Instruction::FPExt:
6643 case Instruction::FCmp:
6644 return true;
6645 // Bitwise FP operations should preserve the sign bit of NaN.
6646 case Instruction::FNeg:
6647 case Instruction::Select:
6648 case Instruction::PHI:
6649 return false;
6650 case Instruction::Ret:
6651 return User->getFunction()->getAttributes().getRetNoFPClass() &
6653 case Instruction::Call:
6654 case Instruction::Invoke: {
6655 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6656 switch (II->getIntrinsicID()) {
6657 case Intrinsic::fabs:
6658 return true;
6659 case Intrinsic::copysign:
6660 return U.getOperandNo() == 0;
6661 // Other proper FP math intrinsics ignore the sign bit of NaN.
6662 case Intrinsic::maxnum:
6663 case Intrinsic::minnum:
6664 case Intrinsic::maximum:
6665 case Intrinsic::minimum:
6666 case Intrinsic::maximumnum:
6667 case Intrinsic::minimumnum:
6668 case Intrinsic::canonicalize:
6669 case Intrinsic::fma:
6670 case Intrinsic::fmuladd:
6671 case Intrinsic::sqrt:
6672 case Intrinsic::pow:
6673 case Intrinsic::powi:
6674 case Intrinsic::fptoui_sat:
6675 case Intrinsic::fptosi_sat:
6676 case Intrinsic::is_fpclass:
6677 return true;
6678 default:
6679 return false;
6680 }
6681 }
6682
6683 FPClassTest NoFPClass =
6684 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6685 return NoFPClass & FPClassTest::fcNan;
6686 }
6687 default:
6688 return false;
6689 }
6690}
6691
6693 FastMathFlags FMF) {
6694 if (isa<PoisonValue>(V))
6695 return true;
6696 if (isa<UndefValue>(V))
6697 return false;
6698
6699 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6700 return true;
6701
6703 if (!I)
6704 return false;
6705
6706 switch (I->getOpcode()) {
6707 case Instruction::SIToFP:
6708 case Instruction::UIToFP:
6709 // TODO: Could check nofpclass(inf) on incoming argument
6710 if (FMF.noInfs())
6711 return true;
6712
6713 // Need to check int size cannot produce infinity, which computeKnownFPClass
6714 // knows how to do already.
6715 return isKnownNeverInfinity(I, SQ);
6716 case Instruction::Call: {
6717 const CallInst *CI = cast<CallInst>(I);
6718 switch (CI->getIntrinsicID()) {
6719 case Intrinsic::trunc:
6720 case Intrinsic::floor:
6721 case Intrinsic::ceil:
6722 case Intrinsic::rint:
6723 case Intrinsic::nearbyint:
6724 case Intrinsic::round:
6725 case Intrinsic::roundeven:
6726 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6727 default:
6728 break;
6729 }
6730
6731 break;
6732 }
6733 default:
6734 break;
6735 }
6736
6737 return false;
6738}
6739
6741
6742 // All byte-wide stores are splatable, even of arbitrary variables.
6743 if (V->getType()->isIntegerTy(8))
6744 return V;
6745
6746 LLVMContext &Ctx = V->getContext();
6747
6748 // Undef don't care.
6749 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6750 if (isa<UndefValue>(V))
6751 return UndefInt8;
6752
6753 // Return poison for zero-sized type.
6754 if (DL.getTypeStoreSize(V->getType()).isZero())
6755 return PoisonValue::get(Type::getInt8Ty(Ctx));
6756
6758 if (!C) {
6759 // Conceptually, we could handle things like:
6760 // %a = zext i8 %X to i16
6761 // %b = shl i16 %a, 8
6762 // %c = or i16 %a, %b
6763 // but until there is an example that actually needs this, it doesn't seem
6764 // worth worrying about.
6765 return nullptr;
6766 }
6767
6768 // Handle 'null' ConstantArrayZero etc.
6769 if (C->isNullValue())
6771
6772 // Constant floating-point values can be handled as integer values if the
6773 // corresponding integer value is "byteable". An important case is 0.0.
6774 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6775 Type *ScalarTy = CFP->getType()->getScalarType();
6776 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6777 return isBytewiseValue(
6778 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6779
6780 // Don't handle long double formats, which have strange constraints.
6781 return nullptr;
6782 }
6783
6784 // We can handle constant integers that are multiple of 8 bits.
6785 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6786 if (CI->getBitWidth() % 8 == 0) {
6787 if (!CI->getValue().isSplat(8))
6788 return nullptr;
6789 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6790 }
6791 }
6792
6793 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6794 if (CE->getOpcode() == Instruction::IntToPtr) {
6795 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6796 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6798 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6799 return isBytewiseValue(Op, DL);
6800 }
6801 }
6802 }
6803
6804 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6805 if (LHS == RHS)
6806 return LHS;
6807 if (!LHS || !RHS)
6808 return nullptr;
6809 if (LHS == UndefInt8)
6810 return RHS;
6811 if (RHS == UndefInt8)
6812 return LHS;
6813 return nullptr;
6814 };
6815
6817 Value *Val = UndefInt8;
6818 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6819 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6820 return nullptr;
6821 return Val;
6822 }
6823
6825 Value *Val = UndefInt8;
6826 for (Value *Op : C->operands())
6827 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6828 return nullptr;
6829 return Val;
6830 }
6831
6832 // Don't try to handle the handful of other constants.
6833 return nullptr;
6834}
6835
6836// This is the recursive version of BuildSubAggregate. It takes a few different
6837// arguments. Idxs is the index within the nested struct From that we are
6838// looking at now (which is of type IndexedType). IdxSkip is the number of
6839// indices from Idxs that should be left out when inserting into the resulting
6840// struct. To is the result struct built so far, new insertvalue instructions
6841// build on that.
6842static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6844 unsigned IdxSkip,
6845 BasicBlock::iterator InsertBefore) {
6846 StructType *STy = dyn_cast<StructType>(IndexedType);
6847 if (STy) {
6848 // Save the original To argument so we can modify it
6849 Value *OrigTo = To;
6850 // General case, the type indexed by Idxs is a struct
6851 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6852 // Process each struct element recursively
6853 Idxs.push_back(i);
6854 Value *PrevTo = To;
6855 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6856 InsertBefore);
6857 Idxs.pop_back();
6858 if (!To) {
6859 // Couldn't find any inserted value for this index? Cleanup
6860 while (PrevTo != OrigTo) {
6862 PrevTo = Del->getAggregateOperand();
6863 Del->eraseFromParent();
6864 }
6865 // Stop processing elements
6866 break;
6867 }
6868 }
6869 // If we successfully found a value for each of our subaggregates
6870 if (To)
6871 return To;
6872 }
6873 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6874 // the struct's elements had a value that was inserted directly. In the latter
6875 // case, perhaps we can't determine each of the subelements individually, but
6876 // we might be able to find the complete struct somewhere.
6877
6878 // Find the value that is at that particular spot
6879 Value *V = FindInsertedValue(From, Idxs);
6880
6881 if (!V)
6882 return nullptr;
6883
6884 // Insert the value in the new (sub) aggregate
6885 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6886 InsertBefore);
6887}
6888
6889// This helper takes a nested struct and extracts a part of it (which is again a
6890// struct) into a new value. For example, given the struct:
6891// { a, { b, { c, d }, e } }
6892// and the indices "1, 1" this returns
6893// { c, d }.
6894//
6895// It does this by inserting an insertvalue for each element in the resulting
6896// struct, as opposed to just inserting a single struct. This will only work if
6897// each of the elements of the substruct are known (ie, inserted into From by an
6898// insertvalue instruction somewhere).
6899//
6900// All inserted insertvalue instructions are inserted before InsertBefore
6902 BasicBlock::iterator InsertBefore) {
6903 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6904 idx_range);
6905 Value *To = PoisonValue::get(IndexedType);
6906 SmallVector<unsigned, 10> Idxs(idx_range);
6907 unsigned IdxSkip = Idxs.size();
6908
6909 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6910}
6911
6912/// Given an aggregate and a sequence of indices, see if the scalar value
6913/// indexed is already around as a register, for example if it was inserted
6914/// directly into the aggregate.
6915///
6916/// If InsertBefore is not null, this function will duplicate (modified)
6917/// insertvalues when a part of a nested struct is extracted.
6918Value *
6920 std::optional<BasicBlock::iterator> InsertBefore) {
6921 // Nothing to index? Just return V then (this is useful at the end of our
6922 // recursion).
6923 if (idx_range.empty())
6924 return V;
6925 // We have indices, so V should have an indexable type.
6926 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6927 "Not looking at a struct or array?");
6928 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6929 "Invalid indices for type?");
6930
6931 if (Constant *C = dyn_cast<Constant>(V)) {
6932 C = C->getAggregateElement(idx_range[0]);
6933 if (!C) return nullptr;
6934 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6935 }
6936
6938 // Loop the indices for the insertvalue instruction in parallel with the
6939 // requested indices
6940 const unsigned *req_idx = idx_range.begin();
6941 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6942 i != e; ++i, ++req_idx) {
6943 if (req_idx == idx_range.end()) {
6944 // We can't handle this without inserting insertvalues
6945 if (!InsertBefore)
6946 return nullptr;
6947
6948 // The requested index identifies a part of a nested aggregate. Handle
6949 // this specially. For example,
6950 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6951 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6952 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6953 // This can be changed into
6954 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6955 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6956 // which allows the unused 0,0 element from the nested struct to be
6957 // removed.
6958 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6959 *InsertBefore);
6960 }
6961
6962 // This insert value inserts something else than what we are looking for.
6963 // See if the (aggregate) value inserted into has the value we are
6964 // looking for, then.
6965 if (*req_idx != *i)
6966 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6967 InsertBefore);
6968 }
6969 // If we end up here, the indices of the insertvalue match with those
6970 // requested (though possibly only partially). Now we recursively look at
6971 // the inserted value, passing any remaining indices.
6972 return FindInsertedValue(I->getInsertedValueOperand(),
6973 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6974 }
6975
6977 // If we're extracting a value from an aggregate that was extracted from
6978 // something else, we can extract from that something else directly instead.
6979 // However, we will need to chain I's indices with the requested indices.
6980
6981 // Calculate the number of indices required
6982 unsigned size = I->getNumIndices() + idx_range.size();
6983 // Allocate some space to put the new indices in
6985 Idxs.reserve(size);
6986 // Add indices from the extract value instruction
6987 Idxs.append(I->idx_begin(), I->idx_end());
6988
6989 // Add requested indices
6990 Idxs.append(idx_range.begin(), idx_range.end());
6991
6992 assert(Idxs.size() == size
6993 && "Number of indices added not correct?");
6994
6995 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6996 }
6997 // Otherwise, we don't know (such as, extracting from a function return value
6998 // or load instruction)
6999 return nullptr;
7000}
7001
7002// If V refers to an initialized global constant, set Slice either to
7003// its initializer if the size of its elements equals ElementSize, or,
7004// for ElementSize == 8, to its representation as an array of unsiged
7005// char. Return true on success.
7006// Offset is in the unit "nr of ElementSize sized elements".
7009 unsigned ElementSize, uint64_t Offset) {
7010 assert(V && "V should not be null.");
7011 assert((ElementSize % 8) == 0 &&
7012 "ElementSize expected to be a multiple of the size of a byte.");
7013 unsigned ElementSizeInBytes = ElementSize / 8;
7014
7015 // Drill down into the pointer expression V, ignoring any intervening
7016 // casts, and determine the identity of the object it references along
7017 // with the cumulative byte offset into it.
7018 const GlobalVariable *GV =
7020 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7021 // Fail if V is not based on constant global object.
7022 return false;
7023
7024 const DataLayout &DL = GV->getDataLayout();
7025 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7026
7028 /*AllowNonInbounds*/ true))
7029 // Fail if a constant offset could not be determined.
7030 return false;
7031
7032 uint64_t StartIdx = Off.getLimitedValue();
7033 if (StartIdx == UINT64_MAX)
7034 // Fail if the constant offset is excessive.
7035 return false;
7036
7037 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7038 // elements. Simply bail out if that isn't possible.
7039 if ((StartIdx % ElementSizeInBytes) != 0)
7040 return false;
7041
7042 Offset += StartIdx / ElementSizeInBytes;
7043 ConstantDataArray *Array = nullptr;
7044 ArrayType *ArrayTy = nullptr;
7045
7046 if (GV->getInitializer()->isNullValue()) {
7047 Type *GVTy = GV->getValueType();
7048 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7049 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7050
7051 Slice.Array = nullptr;
7052 Slice.Offset = 0;
7053 // Return an empty Slice for undersized constants to let callers
7054 // transform even undefined library calls into simpler, well-defined
7055 // expressions. This is preferable to making the calls although it
7056 // prevents sanitizers from detecting such calls.
7057 Slice.Length = Length < Offset ? 0 : Length - Offset;
7058 return true;
7059 }
7060
7061 auto *Init = const_cast<Constant *>(GV->getInitializer());
7062 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7063 Type *InitElTy = ArrayInit->getElementType();
7064 if (InitElTy->isIntegerTy(ElementSize)) {
7065 // If Init is an initializer for an array of the expected type
7066 // and size, use it as is.
7067 Array = ArrayInit;
7068 ArrayTy = ArrayInit->getType();
7069 }
7070 }
7071
7072 if (!Array) {
7073 if (ElementSize != 8)
7074 // TODO: Handle conversions to larger integral types.
7075 return false;
7076
7077 // Otherwise extract the portion of the initializer starting
7078 // at Offset as an array of bytes, and reset Offset.
7080 if (!Init)
7081 return false;
7082
7083 Offset = 0;
7085 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7086 }
7087
7088 uint64_t NumElts = ArrayTy->getArrayNumElements();
7089 if (Offset > NumElts)
7090 return false;
7091
7092 Slice.Array = Array;
7093 Slice.Offset = Offset;
7094 Slice.Length = NumElts - Offset;
7095 return true;
7096}
7097
7098/// Extract bytes from the initializer of the constant array V, which need
7099/// not be a nul-terminated string. On success, store the bytes in Str and
7100/// return true. When TrimAtNul is set, Str will contain only the bytes up
7101/// to but not including the first nul. Return false on failure.
7103 bool TrimAtNul) {
7105 if (!getConstantDataArrayInfo(V, Slice, 8))
7106 return false;
7107
7108 if (Slice.Array == nullptr) {
7109 if (TrimAtNul) {
7110 // Return a nul-terminated string even for an empty Slice. This is
7111 // safe because all existing SimplifyLibcalls callers require string
7112 // arguments and the behavior of the functions they fold is undefined
7113 // otherwise. Folding the calls this way is preferable to making
7114 // the undefined library calls, even though it prevents sanitizers
7115 // from reporting such calls.
7116 Str = StringRef();
7117 return true;
7118 }
7119 if (Slice.Length == 1) {
7120 Str = StringRef("", 1);
7121 return true;
7122 }
7123 // We cannot instantiate a StringRef as we do not have an appropriate string
7124 // of 0s at hand.
7125 return false;
7126 }
7127
7128 // Start out with the entire array in the StringRef.
7129 Str = Slice.Array->getAsString();
7130 // Skip over 'offset' bytes.
7131 Str = Str.substr(Slice.Offset);
7132
7133 if (TrimAtNul) {
7134 // Trim off the \0 and anything after it. If the array is not nul
7135 // terminated, we just return the whole end of string. The client may know
7136 // some other way that the string is length-bound.
7137 Str = Str.substr(0, Str.find('\0'));
7138 }
7139 return true;
7140}
7141
7142// These next two are very similar to the above, but also look through PHI
7143// nodes.
7144// TODO: See if we can integrate these two together.
7145
7146/// If we can compute the length of the string pointed to by
7147/// the specified pointer, return 'len+1'. If we can't, return 0.
7150 unsigned CharSize) {
7151 // Look through noop bitcast instructions.
7152 V = V->stripPointerCasts();
7153
7154 // If this is a PHI node, there are two cases: either we have already seen it
7155 // or we haven't.
7156 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7157 if (!PHIs.insert(PN).second)
7158 return ~0ULL; // already in the set.
7159
7160 // If it was new, see if all the input strings are the same length.
7161 uint64_t LenSoFar = ~0ULL;
7162 for (Value *IncValue : PN->incoming_values()) {
7163 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7164 if (Len == 0) return 0; // Unknown length -> unknown.
7165
7166 if (Len == ~0ULL) continue;
7167
7168 if (Len != LenSoFar && LenSoFar != ~0ULL)
7169 return 0; // Disagree -> unknown.
7170 LenSoFar = Len;
7171 }
7172
7173 // Success, all agree.
7174 return LenSoFar;
7175 }
7176
7177 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7178 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7179 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7180 if (Len1 == 0) return 0;
7181 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7182 if (Len2 == 0) return 0;
7183 if (Len1 == ~0ULL) return Len2;
7184 if (Len2 == ~0ULL) return Len1;
7185 if (Len1 != Len2) return 0;
7186 return Len1;
7187 }
7188
7189 // Otherwise, see if we can read the string.
7191 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7192 return 0;
7193
7194 if (Slice.Array == nullptr)
7195 // Zeroinitializer (including an empty one).
7196 return 1;
7197
7198 // Search for the first nul character. Return a conservative result even
7199 // when there is no nul. This is safe since otherwise the string function
7200 // being folded such as strlen is undefined, and can be preferable to
7201 // making the undefined library call.
7202 unsigned NullIndex = 0;
7203 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7204 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7205 break;
7206 }
7207
7208 return NullIndex + 1;
7209}
7210
7211/// If we can compute the length of the string pointed to by
7212/// the specified pointer, return 'len+1'. If we can't, return 0.
7213uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7214 if (!V->getType()->isPointerTy())
7215 return 0;
7216
7218 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7219 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7220 // an empty string as a length.
7221 return Len == ~0ULL ? 1 : Len;
7222}
7223
7224const Value *
7226 bool MustPreserveOffset,
7227 bool MustPreserveProvenance) {
7228 assert(Call &&
7229 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7230 if (const Value *RV = Call->getReturnedArgOperand())
7231 return RV;
7232 // This can be used only as a aliasing property.
7234 Call, MustPreserveOffset, MustPreserveProvenance))
7235 return Call->getArgOperand(0);
7236 return nullptr;
7237}
7238
7240 const CallBase *Call, bool MustPreserveOffset,
7241 bool MustPreserveProvenance) {
7242 switch (Call->getIntrinsicID()) {
7243 case Intrinsic::launder_invariant_group:
7244 case Intrinsic::aarch64_irg:
7245 case Intrinsic::aarch64_tagp:
7246 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7247 // input pointer (and thus preserves the byte offset, which is the property
7248 // the MustPreserveOffset flag selects). However, it will not necessarily
7249 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7250 // descriptor", which has "all loads return 0, all stores are dropped"
7251 // semantics. Given the context of this intrinsic list, no one should be
7252 // relying on such a strict bit-exact null mapping (and, at time of
7253 // writing, they are not), but we document this fact out of an abundance
7254 // of caution.
7255 case Intrinsic::amdgcn_make_buffer_rsrc:
7256 return !MustPreserveProvenance;
7257 case Intrinsic::ptrmask:
7258 return !MustPreserveOffset;
7259 case Intrinsic::threadlocal_address:
7260 // The underlying variable changes with thread ID. The Thread ID may change
7261 // at coroutine suspend points.
7262 return !Call->getParent()->getParent()->isPresplitCoroutine();
7263 default:
7264 return false;
7265 }
7266}
7267
7268/// \p PN defines a loop-variant pointer to an object. Check if the
7269/// previous iteration of the loop was referring to the same object as \p PN.
7271 const LoopInfo *LI) {
7272 // Find the loop-defined value.
7273 Loop *L = LI->getLoopFor(PN->getParent());
7274 if (PN->getNumIncomingValues() != 2)
7275 return true;
7276
7277 // Find the value from previous iteration.
7278 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7279 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7280 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7281 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7282 return true;
7283
7284 // If a new pointer is loaded in the loop, the pointer references a different
7285 // object in every iteration. E.g.:
7286 // for (i)
7287 // int *p = a[i];
7288 // ...
7289 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7290 if (!L->isLoopInvariant(Load->getPointerOperand()))
7291 return false;
7292 return true;
7293}
7294
7295const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7296 bool MustPreserveProvenance) {
7297 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7298 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7299 const Value *PtrOp = GEP->getPointerOperand();
7300 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7301 return V;
7302 V = PtrOp;
7303 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7304 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7305 Value *NewV = cast<Operator>(V)->getOperand(0);
7306 if (!NewV->getType()->isPointerTy())
7307 return V;
7308 V = NewV;
7309 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7310 if (GA->isInterposable())
7311 return V;
7312 V = GA->getAliasee();
7313 } else {
7314 if (auto *PHI = dyn_cast<PHINode>(V)) {
7315 // Look through single-arg phi nodes created by LCSSA.
7316 if (PHI->getNumIncomingValues() == 1) {
7317 V = PHI->getIncomingValue(0);
7318 continue;
7319 }
7320 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7321 // CaptureTracking can know about special capturing properties of some
7322 // intrinsics like launder.invariant.group, that can't be expressed with
7323 // the attributes, but have properties like returning aliasing pointer.
7324 // Because some analysis may assume that nocaptured pointer is not
7325 // returned from some special intrinsic (because function would have to
7326 // be marked with returns attribute), it is crucial to use this function
7327 // because it should be in sync with CaptureTracking. Not using it may
7328 // cause weird miscompilations where 2 aliasing pointers are assumed to
7329 // noalias.
7331 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7332 V = RP;
7333 continue;
7334 }
7335 }
7336
7337 return V;
7338 }
7339 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7340 }
7341 return V;
7342}
7343
7346 const LoopInfo *LI, unsigned MaxLookup) {
7349 Worklist.push_back(V);
7350 do {
7351 const Value *P = Worklist.pop_back_val();
7352 P = getUnderlyingObject(P, MaxLookup);
7353
7354 if (!Visited.insert(P).second)
7355 continue;
7356
7357 if (auto *SI = dyn_cast<SelectInst>(P)) {
7358 Worklist.push_back(SI->getTrueValue());
7359 Worklist.push_back(SI->getFalseValue());
7360 continue;
7361 }
7362
7363 if (auto *PN = dyn_cast<PHINode>(P)) {
7364 // If this PHI changes the underlying object in every iteration of the
7365 // loop, don't look through it. Consider:
7366 // int **A;
7367 // for (i) {
7368 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7369 // Curr = A[i];
7370 // *Prev, *Curr;
7371 //
7372 // Prev is tracking Curr one iteration behind so they refer to different
7373 // underlying objects.
7374 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7376 append_range(Worklist, PN->incoming_values());
7377 else
7378 Objects.push_back(P);
7379 continue;
7380 }
7381
7382 Objects.push_back(P);
7383 } while (!Worklist.empty());
7384}
7385
7387 bool MustPreserveProvenance) {
7388 const unsigned MaxVisited = 8;
7389
7392 Worklist.push_back(V);
7393 const Value *Object = nullptr;
7394 // Used as fallback if we can't find a common underlying object through
7395 // recursion.
7396 bool First = true;
7397 const Value *FirstObject =
7398 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7399 do {
7400 const Value *P = Worklist.pop_back_val();
7401 P = First ? FirstObject
7403 MustPreserveProvenance);
7404 First = false;
7405
7406 if (!Visited.insert(P).second)
7407 continue;
7408
7409 if (Visited.size() == MaxVisited)
7410 return FirstObject;
7411
7412 if (auto *SI = dyn_cast<SelectInst>(P)) {
7413 Worklist.push_back(SI->getTrueValue());
7414 Worklist.push_back(SI->getFalseValue());
7415 continue;
7416 }
7417
7418 if (auto *PN = dyn_cast<PHINode>(P)) {
7419 append_range(Worklist, PN->incoming_values());
7420 continue;
7421 }
7422
7423 if (!Object)
7424 Object = P;
7425 else if (Object != P)
7426 return FirstObject;
7427 } while (!Worklist.empty());
7428
7429 return Object ? Object : FirstObject;
7430}
7431
7432/// This is the function that does the work of looking through basic
7433/// ptrtoint+arithmetic+inttoptr sequences.
7434static const Value *getUnderlyingObjectFromInt(const Value *V) {
7435 do {
7436 if (const Operator *U = dyn_cast<Operator>(V)) {
7437 // If we find a ptrtoint, we can transfer control back to the
7438 // regular getUnderlyingObjectFromInt.
7439 if (U->getOpcode() == Instruction::PtrToInt)
7440 return U->getOperand(0);
7441 // If we find an add of a constant, a multiplied value, or a phi, it's
7442 // likely that the other operand will lead us to the base
7443 // object. We don't have to worry about the case where the
7444 // object address is somehow being computed by the multiply,
7445 // because our callers only care when the result is an
7446 // identifiable object.
7447 if (U->getOpcode() != Instruction::Add ||
7448 (!isa<ConstantInt>(U->getOperand(1)) &&
7449 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7450 !isa<PHINode>(U->getOperand(1))))
7451 return V;
7452 V = U->getOperand(0);
7453 } else {
7454 return V;
7455 }
7456 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7457 } while (true);
7458}
7459
7460/// This is a wrapper around getUnderlyingObjects and adds support for basic
7461/// ptrtoint+arithmetic+inttoptr sequences.
7462/// It returns false if unidentified object is found in getUnderlyingObjects.
7464 SmallVectorImpl<Value *> &Objects) {
7466 SmallVector<const Value *, 4> Working(1, V);
7467 bool AllObjectsIdentified = true;
7468 do {
7469 V = Working.pop_back_val();
7470
7472 getUnderlyingObjects(V, Objs);
7473
7474 for (const Value *V : Objs) {
7475 if (!Visited.insert(V).second)
7476 continue;
7477 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7478 const Value *O =
7479 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7480 if (O->getType()->isPointerTy()) {
7481 Working.push_back(O);
7482 continue;
7483 }
7484 }
7485 AllObjectsIdentified &= isIdentifiedObject(V);
7486 Objects.push_back(const_cast<Value *>(V));
7487 }
7488 } while (!Working.empty());
7489 return AllObjectsIdentified;
7490}
7491
7493 AllocaInst *Result = nullptr;
7495 SmallVector<Value *, 4> Worklist;
7496
7497 auto AddWork = [&](Value *V) {
7498 if (Visited.insert(V).second)
7499 Worklist.push_back(V);
7500 };
7501
7502 AddWork(V);
7503 do {
7504 V = Worklist.pop_back_val();
7505 assert(Visited.count(V));
7506
7507 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7508 if (Result && Result != AI)
7509 return nullptr;
7510 Result = AI;
7511 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7512 AddWork(CI->getOperand(0));
7513 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7514 for (Value *IncValue : PN->incoming_values())
7515 AddWork(IncValue);
7516 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7517 AddWork(SI->getTrueValue());
7518 AddWork(SI->getFalseValue());
7520 if (OffsetZero && !GEP->hasAllZeroIndices())
7521 return nullptr;
7522 AddWork(GEP->getPointerOperand());
7523 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7524 Value *Returned = CB->getReturnedArgOperand();
7525 if (Returned)
7526 AddWork(Returned);
7527 else
7528 return nullptr;
7529 } else {
7530 return nullptr;
7531 }
7532 } while (!Worklist.empty());
7533
7534 return Result;
7535}
7536
7538 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7539 for (const User *U : V->users()) {
7541 if (!II)
7542 return false;
7543
7544 if (AllowLifetime && II->isLifetimeStartOrEnd())
7545 continue;
7546
7547 if (AllowDroppable && II->isDroppable())
7548 continue;
7549
7550 return false;
7551 }
7552 return true;
7553}
7554
7557 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7558}
7561 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7562}
7563
7565 if (auto *II = dyn_cast<IntrinsicInst>(I))
7566 return isTriviallyVectorizable(II->getIntrinsicID());
7567 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7568 return (!Shuffle || Shuffle->isSelect()) &&
7570}
7571
7573 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7574 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7575 bool IgnoreUBImplyingAttrs) {
7576 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7577 AC, DT, TLI, UseVariableInfo,
7578 IgnoreUBImplyingAttrs);
7579}
7580
7582 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7583 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7584 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7585#ifndef NDEBUG
7586 if (Inst->getOpcode() != Opcode) {
7587 // Check that the operands are actually compatible with the Opcode override.
7588 auto hasEqualReturnAndLeadingOperandTypes =
7589 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7590 if (Inst->getNumOperands() < NumLeadingOperands)
7591 return false;
7592 const Type *ExpectedType = Inst->getType();
7593 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7594 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7595 return false;
7596 return true;
7597 };
7599 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7600 assert(!Instruction::isUnaryOp(Opcode) ||
7601 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7602 }
7603#endif
7604
7605 switch (Opcode) {
7606 default:
7607 return true;
7608 case Instruction::UDiv:
7609 case Instruction::URem: {
7610 // x / y is undefined if y == 0.
7611 const APInt *V;
7612 if (match(Inst->getOperand(1), m_APInt(V)))
7613 return *V != 0;
7614 return false;
7615 }
7616 case Instruction::SDiv:
7617 case Instruction::SRem: {
7618 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7619 const APInt *Numerator, *Denominator;
7620 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7621 return false;
7622 // We cannot hoist this division if the denominator is 0.
7623 if (*Denominator == 0)
7624 return false;
7625 // It's safe to hoist if the denominator is not 0 or -1.
7626 if (!Denominator->isAllOnes())
7627 return true;
7628 // At this point we know that the denominator is -1. It is safe to hoist as
7629 // long we know that the numerator is not INT_MIN.
7630 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7631 return !Numerator->isMinSignedValue();
7632 // The numerator *might* be MinSignedValue.
7633 return false;
7634 }
7635 case Instruction::Load: {
7636 if (!UseVariableInfo)
7637 return false;
7638
7639 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7640 if (!LI)
7641 return false;
7642 if (mustSuppressSpeculation(*LI))
7643 return false;
7644 const DataLayout &DL = LI->getDataLayout();
7646 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7647 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7648 }
7649 case Instruction::Call: {
7650 auto *CI = dyn_cast<const CallInst>(Inst);
7651 if (!CI)
7652 return false;
7653 const Function *Callee = CI->getCalledFunction();
7654
7655 // The called function could have undefined behavior or side-effects, even
7656 // if marked readnone nounwind.
7657 if (!Callee || !Callee->isSpeculatable())
7658 return false;
7659 // Since the operands may be changed after hoisting, undefined behavior may
7660 // be triggered by some UB-implying attributes.
7661 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7662 }
7663 case Instruction::VAArg:
7664 case Instruction::Alloca:
7665 case Instruction::Invoke:
7666 case Instruction::CallBr:
7667 case Instruction::PHI:
7668 case Instruction::Store:
7669 case Instruction::Ret:
7670 case Instruction::UncondBr:
7671 case Instruction::CondBr:
7672 case Instruction::IndirectBr:
7673 case Instruction::Switch:
7674 case Instruction::Unreachable:
7675 case Instruction::Fence:
7676 case Instruction::AtomicRMW:
7677 case Instruction::AtomicCmpXchg:
7678 case Instruction::LandingPad:
7679 case Instruction::Resume:
7680 case Instruction::CatchSwitch:
7681 case Instruction::CatchPad:
7682 case Instruction::CatchRet:
7683 case Instruction::CleanupPad:
7684 case Instruction::CleanupRet:
7685 return false; // Misc instructions which have effects
7686 }
7687}
7688
7690 if (I.mayReadOrWriteMemory())
7691 // Memory dependency possible
7692 return true;
7694 // Can't move above a maythrow call or infinite loop. Or if an
7695 // inalloca alloca, above a stacksave call.
7696 return true;
7698 // 1) Can't reorder two inf-loop calls, even if readonly
7699 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7700 // safe to speculative execute. (Inverse of above)
7701 return true;
7702 return false;
7703}
7704
7705/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7719
7720/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7723 bool ForSigned,
7724 const SimplifyQuery &SQ) {
7725 ConstantRange CR1 =
7726 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7727 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7730 return CR1.intersectWith(CR2, RangeType);
7731}
7732
7734 const Value *RHS,
7735 const SimplifyQuery &SQ,
7736 bool IsNSW) {
7737 ConstantRange LHSRange =
7738 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7739 ConstantRange RHSRange =
7740 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7741
7742 // mul nsw of two non-negative numbers is also nuw.
7743 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7745
7746 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7747}
7748
7750 const Value *RHS,
7751 const SimplifyQuery &SQ) {
7752 // Multiplying n * m significant bits yields a result of n + m significant
7753 // bits. If the total number of significant bits does not exceed the
7754 // result bit width (minus 1), there is no overflow.
7755 // This means if we have enough leading sign bits in the operands
7756 // we can guarantee that the result does not overflow.
7757 // Ref: "Hacker's Delight" by Henry Warren
7758 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7759
7760 // Note that underestimating the number of sign bits gives a more
7761 // conservative answer.
7762 unsigned SignBits =
7763 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7764
7765 // First handle the easy case: if we have enough sign bits there's
7766 // definitely no overflow.
7767 if (SignBits > BitWidth + 1)
7769
7770 // There are two ambiguous cases where there can be no overflow:
7771 // SignBits == BitWidth + 1 and
7772 // SignBits == BitWidth
7773 // The second case is difficult to check, therefore we only handle the
7774 // first case.
7775 if (SignBits == BitWidth + 1) {
7776 // It overflows only when both arguments are negative and the true
7777 // product is exactly the minimum negative number.
7778 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7779 // For simplicity we just check if at least one side is not negative.
7780 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7781 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7782 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7784 }
7786}
7787
7790 const WithCache<const Value *> &RHS,
7791 const SimplifyQuery &SQ) {
7792 ConstantRange LHSRange =
7793 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7794 ConstantRange RHSRange =
7795 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7796 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7797}
7798
7799static OverflowResult
7802 const AddOperator *Add, const SimplifyQuery &SQ) {
7803 if (Add && Add->hasNoSignedWrap()) {
7805 }
7806
7807 // If LHS and RHS each have at least two sign bits, the addition will look
7808 // like
7809 //
7810 // XX..... +
7811 // YY.....
7812 //
7813 // If the carry into the most significant position is 0, X and Y can't both
7814 // be 1 and therefore the carry out of the addition is also 0.
7815 //
7816 // If the carry into the most significant position is 1, X and Y can't both
7817 // be 0 and therefore the carry out of the addition is also 1.
7818 //
7819 // Since the carry into the most significant position is always equal to
7820 // the carry out of the addition, there is no signed overflow.
7821 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7823
7824 ConstantRange LHSRange =
7825 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7826 ConstantRange RHSRange =
7827 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7828 OverflowResult OR =
7829 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7831 return OR;
7832
7833 // The remaining code needs Add to be available. Early returns if not so.
7834 if (!Add)
7836
7837 // If the sign of Add is the same as at least one of the operands, this add
7838 // CANNOT overflow. If this can be determined from the known bits of the
7839 // operands the above signedAddMayOverflow() check will have already done so.
7840 // The only other way to improve on the known bits is from an assumption, so
7841 // call computeKnownBitsFromContext() directly.
7842 bool LHSOrRHSKnownNonNegative =
7843 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7844 bool LHSOrRHSKnownNegative =
7845 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7846 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7847 KnownBits AddKnown(LHSRange.getBitWidth());
7848 computeKnownBitsFromContext(Add, AddKnown, SQ);
7849 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7850 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7852 }
7853
7855}
7856
7858 const Value *RHS,
7859 const SimplifyQuery &SQ) {
7860 // X - (X % ?)
7861 // The remainder of a value can't have greater magnitude than itself,
7862 // so the subtraction can't overflow.
7863
7864 // X - (X -nuw ?)
7865 // In the minimal case, this would simplify to "?", so there's no subtract
7866 // at all. But if this analysis is used to peek through casts, for example,
7867 // then determining no-overflow may allow other transforms.
7868
7869 // TODO: There are other patterns like this.
7870 // See simplifyICmpWithBinOpOnLHS() for candidates.
7871 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7872 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7873 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7875
7876 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
7877 SQ.DL)) {
7878 if (*C)
7881 }
7882
7883 ConstantRange LHSRange =
7884 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7885 ConstantRange RHSRange =
7886 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7887 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7888}
7889
7891 const Value *RHS,
7892 const SimplifyQuery &SQ) {
7893 // X - (X % ?)
7894 // The remainder of a value can't have greater magnitude than itself,
7895 // so the subtraction can't overflow.
7896
7897 // X - (X -nsw ?)
7898 // In the minimal case, this would simplify to "?", so there's no subtract
7899 // at all. But if this analysis is used to peek through casts, for example,
7900 // then determining no-overflow may allow other transforms.
7901 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7902 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7903 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7905
7906 // If LHS and RHS each have at least two sign bits, the subtraction
7907 // cannot overflow.
7908 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7910
7911 ConstantRange LHSRange =
7912 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7913 ConstantRange RHSRange =
7914 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7915 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7916}
7917
7919 const DominatorTree &DT) {
7920 SmallVector<const CondBrInst *, 2> GuardingBranches;
7922
7923 for (const User *U : WO->users()) {
7924 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7925 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7926
7927 if (EVI->getIndices()[0] == 0)
7928 Results.push_back(EVI);
7929 else {
7930 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7931
7932 for (const auto *U : EVI->users())
7933 if (const auto *B = dyn_cast<CondBrInst>(U))
7934 GuardingBranches.push_back(B);
7935 }
7936 } else {
7937 // We are using the aggregate directly in a way we don't want to analyze
7938 // here (storing it to a global, say).
7939 return false;
7940 }
7941 }
7942
7943 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7944 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7945
7946 // Check if all users of the add are provably no-wrap.
7947 for (const auto *Result : Results) {
7948 // If the extractvalue itself is not executed on overflow, the we don't
7949 // need to check each use separately, since domination is transitive.
7950 if (DT.dominates(NoWrapEdge, Result->getParent()))
7951 continue;
7952
7953 for (const auto &RU : Result->uses())
7954 if (!DT.dominates(NoWrapEdge, RU))
7955 return false;
7956 }
7957
7958 return true;
7959 };
7960
7961 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7962}
7963
7964/// Shifts return poison if shiftwidth is larger than the bitwidth.
7965static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7966 auto *C = dyn_cast<Constant>(ShiftAmount);
7967 if (!C)
7968 return false;
7969
7970 // Shifts return poison if shiftwidth is larger than the bitwidth.
7972 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7973 unsigned NumElts = FVTy->getNumElements();
7974 for (unsigned i = 0; i < NumElts; ++i)
7975 ShiftAmounts.push_back(C->getAggregateElement(i));
7976 } else if (isa<ScalableVectorType>(C->getType()))
7977 return false; // Can't tell, just return false to be safe
7978 else
7979 ShiftAmounts.push_back(C);
7980
7981 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7982 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7983 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7984 });
7985
7986 return Safe;
7987}
7988
7990 bool ConsiderFlagsAndMetadata) {
7991
7992 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7993 Op->hasPoisonGeneratingAnnotations())
7994 return true;
7995
7996 unsigned Opcode = Op->getOpcode();
7997
7998 // Check whether opcode is a poison/undef-generating operation
7999 switch (Opcode) {
8000 case Instruction::Shl:
8001 case Instruction::AShr:
8002 case Instruction::LShr:
8003 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8004 case Instruction::FPToSI:
8005 case Instruction::FPToUI:
8006 // fptosi/ui yields poison if the resulting value does not fit in the
8007 // destination type.
8008 return true;
8009 case Instruction::Call:
8010 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8011 switch (II->getIntrinsicID()) {
8012 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8013 case Intrinsic::ctlz:
8014 case Intrinsic::cttz:
8015 case Intrinsic::abs:
8016 // We're not considering flags so it is safe to just return false.
8017 return false;
8018 case Intrinsic::sshl_sat:
8019 case Intrinsic::ushl_sat:
8020 if (!includesPoison(Kind) ||
8021 shiftAmountKnownInRange(II->getArgOperand(1)))
8022 return false;
8023 break;
8024 }
8025 }
8026 [[fallthrough]];
8027 case Instruction::CallBr:
8028 case Instruction::Invoke: {
8029 const auto *CB = cast<CallBase>(Op);
8030 return !CB->hasRetAttr(Attribute::NoUndef) &&
8031 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8032 }
8033 case Instruction::InsertElement:
8034 case Instruction::ExtractElement: {
8035 // If index exceeds the length of the vector, it returns poison
8036 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8037 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8038 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8039 if (includesPoison(Kind))
8040 return !Idx ||
8041 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8042 return false;
8043 }
8044 case Instruction::ShuffleVector: {
8046 ? cast<ConstantExpr>(Op)->getShuffleMask()
8047 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8048 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8049 }
8050 case Instruction::FNeg:
8051 case Instruction::PHI:
8052 case Instruction::Select:
8053 case Instruction::ExtractValue:
8054 case Instruction::InsertValue:
8055 case Instruction::Freeze:
8056 case Instruction::ICmp:
8057 case Instruction::FCmp:
8058 case Instruction::GetElementPtr:
8059 return false;
8060 case Instruction::AddrSpaceCast:
8061 return true;
8062 default: {
8063 const auto *CE = dyn_cast<ConstantExpr>(Op);
8064 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8065 return false;
8066 else if (Instruction::isBinaryOp(Opcode))
8067 return false;
8068 // Be conservative and return true.
8069 return true;
8070 }
8071 }
8072}
8073
8075 bool ConsiderFlagsAndMetadata) {
8076 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8077 ConsiderFlagsAndMetadata);
8078}
8079
8080bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8081 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8082 ConsiderFlagsAndMetadata);
8083}
8084
8085static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8086 unsigned Depth) {
8087 if (ValAssumedPoison == V)
8088 return true;
8089
8090 const unsigned MaxDepth = 2;
8091 if (Depth >= MaxDepth)
8092 return false;
8093
8094 if (const auto *I = dyn_cast<Instruction>(V)) {
8095 if (any_of(I->operands(), [=](const Use &Op) {
8096 return propagatesPoison(Op) &&
8097 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8098 }))
8099 return true;
8100
8101 // V = extractvalue V0, idx
8102 // V2 = extractvalue V0, idx2
8103 // V0's elements are all poison or not. (e.g., add_with_overflow)
8104 const WithOverflowInst *II;
8106 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8107 llvm::is_contained(II->args(), ValAssumedPoison)))
8108 return true;
8109 }
8110 return false;
8111}
8112
8113static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8114 unsigned Depth) {
8115 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8116 return true;
8117
8118 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8119 return true;
8120
8121 const unsigned MaxDepth = 2;
8122 if (Depth >= MaxDepth)
8123 return false;
8124
8125 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8126 if (I && !canCreatePoison(cast<Operator>(I))) {
8127 return all_of(I->operands(), [=](const Value *Op) {
8128 return impliesPoison(Op, V, Depth + 1);
8129 });
8130 }
8131 return false;
8132}
8133
8134bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8135 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8136}
8137
8138static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8139
8141 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8142 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8144 return false;
8145
8146 if (isa<MetadataAsValue>(V))
8147 return false;
8148
8149 if (const auto *A = dyn_cast<Argument>(V)) {
8150 if (A->hasAttribute(Attribute::NoUndef) ||
8151 A->hasAttribute(Attribute::Dereferenceable) ||
8152 A->hasAttribute(Attribute::DereferenceableOrNull))
8153 return true;
8154 }
8155
8156 if (auto *C = dyn_cast<Constant>(V)) {
8157 if (isa<PoisonValue>(C))
8158 return !includesPoison(Kind);
8159
8160 if (isa<UndefValue>(C))
8161 return !includesUndef(Kind);
8162
8165 return true;
8166
8167 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8168 if (isa<ConstantExpr>(C)) {
8169 // Scalable vectors can use a ConstantExpr to build a splat.
8170 if (Constant *SplatC = C->getSplatValue())
8171 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8172 return true;
8173 } else {
8174 if (includesUndef(Kind) && C->containsUndefElement())
8175 return false;
8176 if (includesPoison(Kind) && C->containsPoisonElement())
8177 return false;
8178 return !C->containsConstantExpression();
8179 }
8180 }
8181 }
8182
8183 // Strip cast operations from a pointer value.
8184 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8185 // inbounds with zero offset. To guarantee that the result isn't poison, the
8186 // stripped pointer is checked as it has to be pointing into an allocated
8187 // object or be null `null` to ensure `inbounds` getelement pointers with a
8188 // zero offset could not produce poison.
8189 // It can strip off addrspacecast that do not change bit representation as
8190 // well. We believe that such addrspacecast is equivalent to no-op.
8191 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8192 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8193 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8194 return true;
8195
8196 auto OpCheck = [&](const Value *V) {
8197 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8198 };
8199
8200 if (auto *Opr = dyn_cast<Operator>(V)) {
8201 // If the value is a freeze instruction, then it can never
8202 // be undef or poison.
8203 if (isa<FreezeInst>(V))
8204 return true;
8205
8206 if (const auto *CB = dyn_cast<CallBase>(V)) {
8207 if (CB->hasRetAttr(Attribute::NoUndef) ||
8208 CB->hasRetAttr(Attribute::Dereferenceable) ||
8209 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8210 return true;
8211 }
8212
8213 if (!::canCreateUndefOrPoison(Opr, Kind,
8214 /*ConsiderFlagsAndMetadata=*/true)) {
8215 if (const auto *PN = dyn_cast<PHINode>(V)) {
8216 unsigned Num = PN->getNumIncomingValues();
8217 bool IsWellDefined = true;
8218 for (unsigned i = 0; i < Num; ++i) {
8219 if (PN == PN->getIncomingValue(i))
8220 continue;
8221 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8222 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8223 DT, Depth + 1, Kind)) {
8224 IsWellDefined = false;
8225 break;
8226 }
8227 }
8228 if (IsWellDefined)
8229 return true;
8230 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8231 : nullptr) {
8232 // For splats we only need to check the value being splatted.
8233 if (OpCheck(Splat))
8234 return true;
8235 } else if (all_of(Opr->operands(), OpCheck))
8236 return true;
8237 }
8238 }
8239
8240 if (auto *I = dyn_cast<LoadInst>(V))
8241 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8242 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8243 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8244 return true;
8245
8247 return true;
8248
8249 // CtxI may be null or a cloned instruction.
8250 if (!CtxI || !CtxI->getParent() || !DT)
8251 return false;
8252
8253 auto *DNode = DT->getNode(CtxI->getParent());
8254 if (!DNode)
8255 // Unreachable block
8256 return false;
8257
8258 // If V is used as a branch condition before reaching CtxI, V cannot be
8259 // undef or poison.
8260 // br V, BB1, BB2
8261 // BB1:
8262 // CtxI ; V cannot be undef or poison here
8263 auto *Dominator = DNode->getIDom();
8264 // This check is purely for compile time reasons: we can skip the IDom walk
8265 // if what we are checking for includes undef and the value is not an integer.
8266 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8267 while (Dominator) {
8268 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8269
8270 Value *Cond = nullptr;
8271 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8272 Cond = BI->getCondition();
8273 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8274 Cond = SI->getCondition();
8275 }
8276
8277 if (Cond) {
8278 if (Cond == V)
8279 return true;
8280 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8281 // For poison, we can analyze further
8282 auto *Opr = cast<Operator>(Cond);
8283 if (any_of(Opr->operands(), [V](const Use &U) {
8284 return V == U && propagatesPoison(U);
8285 }))
8286 return true;
8287 }
8288 }
8289
8290 Dominator = Dominator->getIDom();
8291 }
8292
8293 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8294 return true;
8295
8296 return false;
8297}
8298
8300 const Instruction *CtxI,
8301 const DominatorTree *DT,
8302 unsigned Depth) {
8303 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8305}
8306
8308 const Instruction *CtxI,
8309 const DominatorTree *DT, unsigned Depth) {
8310 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8312}
8313
8315 const Instruction *CtxI,
8316 const DominatorTree *DT, unsigned Depth) {
8317 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8319}
8320
8321/// Return true if undefined behavior would provably be executed on the path to
8322/// OnPathTo if Root produced a posion result. Note that this doesn't say
8323/// anything about whether OnPathTo is actually executed or whether Root is
8324/// actually poison. This can be used to assess whether a new use of Root can
8325/// be added at a location which is control equivalent with OnPathTo (such as
8326/// immediately before it) without introducing UB which didn't previously
8327/// exist. Note that a false result conveys no information.
8329 Instruction *OnPathTo,
8330 DominatorTree *DT) {
8331 // Basic approach is to assume Root is poison, propagate poison forward
8332 // through all users we can easily track, and then check whether any of those
8333 // users are provable UB and must execute before out exiting block might
8334 // exit.
8335
8336 // The set of all recursive users we've visited (which are assumed to all be
8337 // poison because of said visit)
8340 Worklist.push_back(Root);
8341 while (!Worklist.empty()) {
8342 const Instruction *I = Worklist.pop_back_val();
8343
8344 // If we know this must trigger UB on a path leading our target.
8345 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8346 return true;
8347
8348 // If we can't analyze propagation through this instruction, just skip it
8349 // and transitive users. Safe as false is a conservative result.
8350 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8351 return KnownPoison.contains(U) && propagatesPoison(U);
8352 }))
8353 continue;
8354
8355 if (KnownPoison.insert(I).second)
8356 for (const User *User : I->users())
8357 Worklist.push_back(cast<Instruction>(User));
8358 }
8359
8360 // Might be non-UB, or might have a path we couldn't prove must execute on
8361 // way to exiting bb.
8362 return false;
8363}
8364
8366 const SimplifyQuery &SQ) {
8367 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8368 Add, SQ);
8369}
8370
8373 const WithCache<const Value *> &RHS,
8374 const SimplifyQuery &SQ) {
8375 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8376}
8377
8379 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8380 // of time because it's possible for another thread to interfere with it for an
8381 // arbitrary length of time, but programs aren't allowed to rely on that.
8382
8383 // If there is no successor, then execution can't transfer to it.
8384 if (isa<ReturnInst>(I))
8385 return false;
8387 return false;
8388
8389 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8390 // Instruction::willReturn.
8391 //
8392 // FIXME: Move this check into Instruction::willReturn.
8393 if (isa<CatchPadInst>(I)) {
8394 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8395 default:
8396 // A catchpad may invoke exception object constructors and such, which
8397 // in some languages can be arbitrary code, so be conservative by default.
8398 return false;
8400 // For CoreCLR, it just involves a type test.
8401 return true;
8402 }
8403 }
8404
8405 // An instruction that returns without throwing must transfer control flow
8406 // to a successor.
8407 return !I->mayThrow() && I->willReturn();
8408}
8409
8411 // TODO: This is slightly conservative for invoke instruction since exiting
8412 // via an exception *is* normal control for them.
8413 for (const Instruction &I : *BB)
8415 return false;
8416 return true;
8417}
8418
8425
8428 assert(ScanLimit && "scan limit must be non-zero");
8429 for (const Instruction &I : Range) {
8430 if (--ScanLimit == 0)
8431 return false;
8433 return false;
8434 }
8435 return true;
8436}
8437
8439 const Loop *L) {
8440 // The loop header is guaranteed to be executed for every iteration.
8441 //
8442 // FIXME: Relax this constraint to cover all basic blocks that are
8443 // guaranteed to be executed at every iteration.
8444 if (I->getParent() != L->getHeader()) return false;
8445
8446 for (const Instruction &LI : *L->getHeader()) {
8447 if (&LI == I) return true;
8448 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8449 }
8450 llvm_unreachable("Instruction not contained in its own parent basic block.");
8451}
8452
8454 switch (IID) {
8455 // TODO: Add more intrinsics.
8456 case Intrinsic::sadd_with_overflow:
8457 case Intrinsic::ssub_with_overflow:
8458 case Intrinsic::smul_with_overflow:
8459 case Intrinsic::uadd_with_overflow:
8460 case Intrinsic::usub_with_overflow:
8461 case Intrinsic::umul_with_overflow:
8462 // If an input is a vector containing a poison element, the
8463 // two output vectors (calculated results, overflow bits)'
8464 // corresponding lanes are poison.
8465 return true;
8466 case Intrinsic::ctpop:
8467 case Intrinsic::ctlz:
8468 case Intrinsic::cttz:
8469 case Intrinsic::abs:
8470 case Intrinsic::smax:
8471 case Intrinsic::smin:
8472 case Intrinsic::umax:
8473 case Intrinsic::umin:
8474 case Intrinsic::scmp:
8475 case Intrinsic::smulh:
8476 case Intrinsic::umulh:
8477 case Intrinsic::is_fpclass:
8478 case Intrinsic::ptrmask:
8479 case Intrinsic::ucmp:
8480 case Intrinsic::bitreverse:
8481 case Intrinsic::bswap:
8482 case Intrinsic::sadd_sat:
8483 case Intrinsic::ssub_sat:
8484 case Intrinsic::sshl_sat:
8485 case Intrinsic::uadd_sat:
8486 case Intrinsic::usub_sat:
8487 case Intrinsic::ushl_sat:
8488 case Intrinsic::smul_fix:
8489 case Intrinsic::smul_fix_sat:
8490 case Intrinsic::umul_fix:
8491 case Intrinsic::umul_fix_sat:
8492 case Intrinsic::pow:
8493 case Intrinsic::powi:
8494 case Intrinsic::sin:
8495 case Intrinsic::sinh:
8496 case Intrinsic::cos:
8497 case Intrinsic::cosh:
8498 case Intrinsic::sincos:
8499 case Intrinsic::sincospi:
8500 case Intrinsic::tan:
8501 case Intrinsic::tanh:
8502 case Intrinsic::asin:
8503 case Intrinsic::acos:
8504 case Intrinsic::atan:
8505 case Intrinsic::atan2:
8506 case Intrinsic::canonicalize:
8507 case Intrinsic::sqrt:
8508 case Intrinsic::exp:
8509 case Intrinsic::exp2:
8510 case Intrinsic::exp10:
8511 case Intrinsic::log:
8512 case Intrinsic::log2:
8513 case Intrinsic::log10:
8514 case Intrinsic::modf:
8515 case Intrinsic::floor:
8516 case Intrinsic::ceil:
8517 case Intrinsic::trunc:
8518 case Intrinsic::rint:
8519 case Intrinsic::nearbyint:
8520 case Intrinsic::round:
8521 case Intrinsic::roundeven:
8522 case Intrinsic::lrint:
8523 case Intrinsic::llrint:
8524 case Intrinsic::fshl:
8525 case Intrinsic::fshr:
8526 case Intrinsic::frexp:
8527 case Intrinsic::get_active_lane_mask:
8528 return true;
8529 default:
8530 return false;
8531 }
8532}
8533
8534bool llvm::propagatesPoison(const Use &PoisonOp) {
8535 const Operator *I = cast<Operator>(PoisonOp.getUser());
8536 switch (I->getOpcode()) {
8537 case Instruction::Freeze:
8538 case Instruction::PHI:
8539 case Instruction::Invoke:
8540 return false;
8541 case Instruction::Select:
8542 return PoisonOp.getOperandNo() == 0;
8543 case Instruction::Call:
8544 if (auto *II = dyn_cast<IntrinsicInst>(I))
8545 return intrinsicPropagatesPoison(II->getIntrinsicID());
8546 return false;
8547 case Instruction::ICmp:
8548 case Instruction::FCmp:
8549 case Instruction::GetElementPtr:
8550 return true;
8551 default:
8553 return true;
8554
8555 // Be conservative and return false.
8556 return false;
8557 }
8558}
8559
8560/// Enumerates all operands of \p I that are guaranteed to not be undef or
8561/// poison. If the callback \p Handle returns true, stop processing and return
8562/// true. Otherwise, return false.
8563template <typename CallableT>
8565 const CallableT &Handle) {
8566 switch (I->getOpcode()) {
8567 case Instruction::Store:
8568 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8569 return true;
8570 break;
8571
8572 case Instruction::Load:
8573 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8574 return true;
8575 break;
8576
8577 // Since dereferenceable attribute imply noundef, atomic operations
8578 // also implicitly have noundef pointers too
8579 case Instruction::AtomicCmpXchg:
8581 return true;
8582 break;
8583
8584 case Instruction::AtomicRMW:
8585 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8586 return true;
8587 break;
8588
8589 case Instruction::Call:
8590 case Instruction::Invoke: {
8591 const CallBase *CB = cast<CallBase>(I);
8592 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8593 return true;
8594 for (unsigned i = 0; i < CB->arg_size(); ++i)
8595 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8596 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8597 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8598 Handle(CB->getArgOperand(i)))
8599 return true;
8600 break;
8601 }
8602 case Instruction::Ret:
8603 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8604 Handle(I->getOperand(0)))
8605 return true;
8606 break;
8607 case Instruction::Switch:
8608 if (Handle(cast<SwitchInst>(I)->getCondition()))
8609 return true;
8610 break;
8611 case Instruction::CondBr:
8612 if (Handle(cast<CondBrInst>(I)->getCondition()))
8613 return true;
8614 break;
8615 default:
8616 break;
8617 }
8618
8619 return false;
8620}
8621
8622/// Enumerates all operands of \p I that are guaranteed to not be poison.
8623template <typename CallableT>
8625 const CallableT &Handle) {
8626 if (handleGuaranteedWellDefinedOps(I, Handle))
8627 return true;
8628 switch (I->getOpcode()) {
8629 // Divisors of these operations are allowed to be partially undef.
8630 case Instruction::UDiv:
8631 case Instruction::SDiv:
8632 case Instruction::URem:
8633 case Instruction::SRem:
8634 return Handle(I->getOperand(1));
8635 default:
8636 return false;
8637 }
8638}
8639
8641 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8643 I, [&](const Value *V) { return KnownPoison.count(V); });
8644}
8645
8647 bool PoisonOnly) {
8648 // We currently only look for uses of values within the same basic
8649 // block, as that makes it easier to guarantee that the uses will be
8650 // executed given that Inst is executed.
8651 //
8652 // FIXME: Expand this to consider uses beyond the same basic block. To do
8653 // this, look out for the distinction between post-dominance and strong
8654 // post-dominance.
8655 const BasicBlock *BB = nullptr;
8657 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8658 BB = Inst->getParent();
8659 Begin = Inst->getIterator();
8660 Begin++;
8661 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8662 if (Arg->getParent()->isDeclaration())
8663 return false;
8664 BB = &Arg->getParent()->getEntryBlock();
8665 Begin = BB->begin();
8666 } else {
8667 return false;
8668 }
8669
8670 // Limit number of instructions we look at, to avoid scanning through large
8671 // blocks. The current limit is chosen arbitrarily.
8672 unsigned ScanLimit = 32;
8673 BasicBlock::const_iterator End = BB->end();
8674
8675 if (!PoisonOnly) {
8676 // Since undef does not propagate eagerly, be conservative & just check
8677 // whether a value is directly passed to an instruction that must take
8678 // well-defined operands.
8679
8680 for (const auto &I : make_range(Begin, End)) {
8681 if (--ScanLimit == 0)
8682 break;
8683
8684 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8685 return WellDefinedOp == V;
8686 }))
8687 return true;
8688
8690 break;
8691 }
8692 return false;
8693 }
8694
8695 // Set of instructions that we have proved will yield poison if Inst
8696 // does.
8697 SmallPtrSet<const Value *, 16> YieldsPoison;
8699
8700 YieldsPoison.insert(V);
8701 Visited.insert(BB);
8702
8703 while (true) {
8704 for (const auto &I : make_range(Begin, End)) {
8705 if (--ScanLimit == 0)
8706 return false;
8707 if (mustTriggerUB(&I, YieldsPoison))
8708 return true;
8710 return false;
8711
8712 // If an operand is poison and propagates it, mark I as yielding poison.
8713 for (const Use &Op : I.operands()) {
8714 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8715 YieldsPoison.insert(&I);
8716 break;
8717 }
8718 }
8719
8720 // Special handling for select, which returns poison if its operand 0 is
8721 // poison (handled in the loop above) *or* if both its true/false operands
8722 // are poison (handled here).
8723 if (I.getOpcode() == Instruction::Select &&
8724 YieldsPoison.count(I.getOperand(1)) &&
8725 YieldsPoison.count(I.getOperand(2))) {
8726 YieldsPoison.insert(&I);
8727 }
8728 }
8729
8730 BB = BB->getSingleSuccessor();
8731 if (!BB || !Visited.insert(BB).second)
8732 break;
8733
8734 Begin = BB->getFirstNonPHIIt();
8735 End = BB->end();
8736 }
8737 return false;
8738}
8739
8741 return ::programUndefinedIfUndefOrPoison(Inst, false);
8742}
8743
8745 return ::programUndefinedIfUndefOrPoison(Inst, true);
8746}
8747
8748static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8749 if (FMF.noNaNs())
8750 return true;
8751
8752 if (auto *C = dyn_cast<ConstantFP>(V))
8753 return !C->isNaN();
8754
8755 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8756 if (!C->getElementType()->isFloatingPointTy())
8757 return false;
8758 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8759 if (C->getElementAsAPFloat(I).isNaN())
8760 return false;
8761 }
8762 return true;
8763 }
8764
8766 return true;
8767
8768 return false;
8769}
8770
8771static bool isKnownNonZero(const Value *V) {
8772 if (auto *C = dyn_cast<ConstantFP>(V))
8773 return !C->isZero();
8774
8775 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8776 if (!C->getElementType()->isFloatingPointTy())
8777 return false;
8778 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8779 if (C->getElementAsAPFloat(I).isZero())
8780 return false;
8781 }
8782 return true;
8783 }
8784
8785 return false;
8786}
8787
8788/// Match clamp pattern for float types without care about NaNs or signed zeros.
8789/// Given non-min/max outer cmp/select from the clamp pattern this
8790/// function recognizes if it can be substitued by a "canonical" min/max
8791/// pattern.
8793 Value *CmpLHS, Value *CmpRHS,
8794 Value *TrueVal, Value *FalseVal,
8795 Value *&LHS, Value *&RHS) {
8796 // Try to match
8797 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8798 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8799 // and return description of the outer Max/Min.
8800
8801 // First, check if select has inverse order:
8802 if (CmpRHS == FalseVal) {
8803 std::swap(TrueVal, FalseVal);
8804 Pred = CmpInst::getInversePredicate(Pred);
8805 }
8806
8807 // Assume success now. If there's no match, callers should not use these anyway.
8808 LHS = TrueVal;
8809 RHS = FalseVal;
8810
8811 const APFloat *FC1;
8812 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8813 return {SPF_UNKNOWN, SPNB_NA, false};
8814
8815 const APFloat *FC2;
8816 switch (Pred) {
8817 case CmpInst::FCMP_OLT:
8818 case CmpInst::FCMP_OLE:
8819 case CmpInst::FCMP_ULT:
8820 case CmpInst::FCMP_ULE:
8821 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8822 *FC1 < *FC2)
8823 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8824 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8825 *FC1 < *FC2)
8826 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8827 break;
8828 case CmpInst::FCMP_OGT:
8829 case CmpInst::FCMP_OGE:
8830 case CmpInst::FCMP_UGT:
8831 case CmpInst::FCMP_UGE:
8832 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8833 *FC1 > *FC2)
8834 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8835 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8836 *FC1 > *FC2)
8837 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8838 break;
8839 default:
8840 break;
8841 }
8842
8843 return {SPF_UNKNOWN, SPNB_NA, false};
8844}
8845
8846/// Recognize variations of:
8847/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8849 Value *CmpLHS, Value *CmpRHS,
8850 Value *TrueVal, Value *FalseVal) {
8851 // Swap the select operands and predicate to match the patterns below.
8852 if (CmpRHS != TrueVal) {
8853 Pred = ICmpInst::getSwappedPredicate(Pred);
8854 std::swap(TrueVal, FalseVal);
8855 }
8856 const APInt *C1;
8857 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8858 const APInt *C2;
8859 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8860 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8861 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8862 return {SPF_SMAX, SPNB_NA, false};
8863
8864 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8865 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8866 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8867 return {SPF_SMIN, SPNB_NA, false};
8868
8869 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8870 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8871 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8872 return {SPF_UMAX, SPNB_NA, false};
8873
8874 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8875 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8876 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8877 return {SPF_UMIN, SPNB_NA, false};
8878 }
8879 return {SPF_UNKNOWN, SPNB_NA, false};
8880}
8881
8882/// Recognize variations of:
8883/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8885 Value *CmpLHS, Value *CmpRHS,
8886 Value *TVal, Value *FVal,
8887 unsigned Depth) {
8888 // TODO: Allow FP min/max with nnan/nsz.
8889 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8890
8891 Value *A = nullptr, *B = nullptr;
8892 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8893 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8894 return {SPF_UNKNOWN, SPNB_NA, false};
8895
8896 Value *C = nullptr, *D = nullptr;
8897 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8898 if (L.Flavor != R.Flavor)
8899 return {SPF_UNKNOWN, SPNB_NA, false};
8900
8901 // We have something like: x Pred y ? min(a, b) : min(c, d).
8902 // Try to match the compare to the min/max operations of the select operands.
8903 // First, make sure we have the right compare predicate.
8904 switch (L.Flavor) {
8905 case SPF_SMIN:
8906 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8907 Pred = ICmpInst::getSwappedPredicate(Pred);
8908 std::swap(CmpLHS, CmpRHS);
8909 }
8910 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8911 break;
8912 return {SPF_UNKNOWN, SPNB_NA, false};
8913 case SPF_SMAX:
8914 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8915 Pred = ICmpInst::getSwappedPredicate(Pred);
8916 std::swap(CmpLHS, CmpRHS);
8917 }
8918 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8919 break;
8920 return {SPF_UNKNOWN, SPNB_NA, false};
8921 case SPF_UMIN:
8922 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8923 Pred = ICmpInst::getSwappedPredicate(Pred);
8924 std::swap(CmpLHS, CmpRHS);
8925 }
8926 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8927 break;
8928 return {SPF_UNKNOWN, SPNB_NA, false};
8929 case SPF_UMAX:
8930 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8931 Pred = ICmpInst::getSwappedPredicate(Pred);
8932 std::swap(CmpLHS, CmpRHS);
8933 }
8934 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8935 break;
8936 return {SPF_UNKNOWN, SPNB_NA, false};
8937 default:
8938 return {SPF_UNKNOWN, SPNB_NA, false};
8939 }
8940
8941 // If there is a common operand in the already matched min/max and the other
8942 // min/max operands match the compare operands (either directly or inverted),
8943 // then this is min/max of the same flavor.
8944
8945 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8946 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8947 if (D == B) {
8948 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8949 match(A, m_Not(m_Specific(CmpRHS)))))
8950 return {L.Flavor, SPNB_NA, false};
8951 }
8952 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8953 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8954 if (C == B) {
8955 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8956 match(A, m_Not(m_Specific(CmpRHS)))))
8957 return {L.Flavor, SPNB_NA, false};
8958 }
8959 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8960 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8961 if (D == A) {
8962 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8963 match(B, m_Not(m_Specific(CmpRHS)))))
8964 return {L.Flavor, SPNB_NA, false};
8965 }
8966 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8967 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8968 if (C == A) {
8969 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8970 match(B, m_Not(m_Specific(CmpRHS)))))
8971 return {L.Flavor, SPNB_NA, false};
8972 }
8973
8974 return {SPF_UNKNOWN, SPNB_NA, false};
8975}
8976
8977/// If the input value is the result of a 'not' op, constant integer, or vector
8978/// splat of a constant integer, return the bitwise-not source value.
8979/// TODO: This could be extended to handle non-splat vector integer constants.
8981 Value *NotV;
8982 if (match(V, m_Not(m_Value(NotV))))
8983 return NotV;
8984
8985 const APInt *C;
8986 if (match(V, m_APInt(C)))
8987 return ConstantInt::get(V->getType(), ~(*C));
8988
8989 return nullptr;
8990}
8991
8992/// Match non-obvious integer minimum and maximum sequences.
8994 Value *CmpLHS, Value *CmpRHS,
8995 Value *TrueVal, Value *FalseVal,
8996 Value *&LHS, Value *&RHS,
8997 unsigned Depth) {
8998 // Assume success. If there's no match, callers should not use these anyway.
8999 LHS = TrueVal;
9000 RHS = FalseVal;
9001
9002 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9004 return SPR;
9005
9006 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
9008 return SPR;
9009
9010 // Look through 'not' ops to find disguised min/max.
9011 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9012 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9013 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9014 switch (Pred) {
9015 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9016 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9017 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9018 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9019 default: break;
9020 }
9021 }
9022
9023 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9024 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9025 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9026 switch (Pred) {
9027 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9028 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9029 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9030 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9031 default: break;
9032 }
9033 }
9034
9035 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9036 return {SPF_UNKNOWN, SPNB_NA, false};
9037
9038 const APInt *C1;
9039 if (!match(CmpRHS, m_APInt(C1)))
9040 return {SPF_UNKNOWN, SPNB_NA, false};
9041
9042 // An unsigned min/max can be written with a signed compare.
9043 const APInt *C2;
9044 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9045 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9046 // Is the sign bit set?
9047 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9048 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9049 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9050 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9051
9052 // Is the sign bit clear?
9053 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9054 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9055 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9056 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9057 }
9058
9059 return {SPF_UNKNOWN, SPNB_NA, false};
9060}
9061
9062bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9063 bool AllowPoison) {
9064 assert(X && Y && "Invalid operand");
9065
9066 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9067 if (!match(X, m_Neg(m_Specific(Y))))
9068 return false;
9069
9070 auto *BO = cast<BinaryOperator>(X);
9071 if (NeedNSW && !BO->hasNoSignedWrap())
9072 return false;
9073
9074 auto *Zero = cast<Constant>(BO->getOperand(0));
9075 if (!AllowPoison && !Zero->isNullValue())
9076 return false;
9077
9078 return true;
9079 };
9080
9081 // X = -Y or Y = -X
9082 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9083 return true;
9084
9085 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9086 Value *A, *B;
9087 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9088 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9089 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9091}
9092
9093bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9094 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9095 Value *A, *B, *C;
9096 CmpPredicate Pred1, Pred2;
9097 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9098 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9099 return false;
9100
9101 // They must both have samesign flag or not.
9102 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9103 return false;
9104
9105 if (B == C)
9106 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9107
9108 // Try to infer the relationship from constant ranges.
9109 const APInt *RHSC1, *RHSC2;
9110 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9111 return false;
9112
9113 // Sign bits of two RHSCs should match.
9114 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9115 return false;
9116
9117 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9118 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9119
9120 return CR1.inverse() == CR2;
9121}
9122
9124 SelectPatternNaNBehavior NaNBehavior,
9125 bool Ordered) {
9126 switch (Pred) {
9127 default:
9128 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9129 case ICmpInst::ICMP_UGT:
9130 case ICmpInst::ICMP_UGE:
9131 return {SPF_UMAX, SPNB_NA, false};
9132 case ICmpInst::ICMP_SGT:
9133 case ICmpInst::ICMP_SGE:
9134 return {SPF_SMAX, SPNB_NA, false};
9135 case ICmpInst::ICMP_ULT:
9136 case ICmpInst::ICMP_ULE:
9137 return {SPF_UMIN, SPNB_NA, false};
9138 case ICmpInst::ICMP_SLT:
9139 case ICmpInst::ICMP_SLE:
9140 return {SPF_SMIN, SPNB_NA, false};
9141 case FCmpInst::FCMP_UGT:
9142 case FCmpInst::FCMP_UGE:
9143 case FCmpInst::FCMP_OGT:
9144 case FCmpInst::FCMP_OGE:
9145 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9146 case FCmpInst::FCMP_ULT:
9147 case FCmpInst::FCMP_ULE:
9148 case FCmpInst::FCMP_OLT:
9149 case FCmpInst::FCMP_OLE:
9150 return {SPF_FMINNUM, NaNBehavior, Ordered};
9151 }
9152}
9153
9154std::optional<std::pair<CmpPredicate, Constant *>>
9157 "Only for relational integer predicates.");
9158 if (isa<UndefValue>(C))
9159 return std::nullopt;
9160
9161 Type *Type = C->getType();
9162 bool IsSigned = ICmpInst::isSigned(Pred);
9163
9165 bool WillIncrement =
9166 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9167
9168 // Check if the constant operand can be safely incremented/decremented
9169 // without overflowing/underflowing.
9170 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9171 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9172 return false;
9173
9174 if (!Pred.hasSameSign())
9175 return true;
9176
9177 // Crossing the corresponding boundary in the other ordering changes the
9178 // sign bit, and therefore changes the poison domain.
9179 return WillIncrement ? !C->isMaxValue(!IsSigned)
9180 : !C->isMinValue(!IsSigned);
9181 };
9182
9183 Constant *SafeReplacementConstant = nullptr;
9184 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9185 // Bail out if the constant can't be safely incremented/decremented.
9186 if (!ConstantIsOk(CI))
9187 return std::nullopt;
9188 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9189 unsigned NumElts = FVTy->getNumElements();
9190 for (unsigned i = 0; i != NumElts; ++i) {
9191 Constant *Elt = C->getAggregateElement(i);
9192 if (!Elt)
9193 return std::nullopt;
9194
9195 if (isa<UndefValue>(Elt))
9196 continue;
9197
9198 // Bail out if we can't determine if this constant is min/max or if we
9199 // know that this constant is min/max.
9200 auto *CI = dyn_cast<ConstantInt>(Elt);
9201 if (!CI || !ConstantIsOk(CI))
9202 return std::nullopt;
9203
9204 if (!SafeReplacementConstant)
9205 SafeReplacementConstant = CI;
9206 }
9207 } else if (isa<VectorType>(C->getType())) {
9208 // Handle scalable splat
9209 Value *SplatC = C->getSplatValue();
9210 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9211 // Bail out if the constant can't be safely incremented/decremented.
9212 if (!CI || !ConstantIsOk(CI))
9213 return std::nullopt;
9214 } else {
9215 // ConstantExpr?
9216 return std::nullopt;
9217 }
9218
9219 // It may not be safe to change a compare predicate in the presence of
9220 // undefined elements, so replace those elements with the first safe constant
9221 // that we found.
9222 // TODO: in case of poison, it is safe; let's replace undefs only.
9223 if (C->containsUndefOrPoisonElement()) {
9224 assert(SafeReplacementConstant && "Replacement constant not set");
9225 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9226 }
9227
9229 Pred.hasSameSign());
9230
9231 // Increment or decrement the constant.
9232 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9233 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9234
9235 return std::make_pair(NewPred, NewC);
9236}
9237
9239 FastMathFlags FMF,
9240 Value *CmpLHS, Value *CmpRHS,
9241 Value *TrueVal, Value *FalseVal,
9242 Value *&LHS, Value *&RHS,
9243 unsigned Depth) {
9244 if (CmpInst::isFPPredicate(Pred)) {
9245 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9246 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9247 // purpose of identifying min/max. Disregard vector constants with undefined
9248 // elements because those can not be back-propagated for analysis.
9249 Value *OutputZeroVal = nullptr;
9250 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9251 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9252 OutputZeroVal = TrueVal;
9253 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9254 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9255 OutputZeroVal = FalseVal;
9256
9257 if (OutputZeroVal) {
9258 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9259 CmpLHS = OutputZeroVal;
9260 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9261 CmpRHS = OutputZeroVal;
9262 }
9263 }
9264
9265 LHS = CmpLHS;
9266 RHS = CmpRHS;
9267
9268 // Signed zero may return inconsistent results between implementations.
9269 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9270 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9271 // Therefore, we behave conservatively and only proceed if at least one of the
9272 // operands is known to not be zero or if we don't care about signed zero.
9273 if (CmpInst::isFPPredicate(Pred)) {
9274 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9275 !isKnownNonZero(CmpRHS))
9276 return {SPF_UNKNOWN, SPNB_NA, false};
9277 }
9278
9279 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9280 bool Ordered = false;
9281
9282 // When given one NaN and one non-NaN input:
9283 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9284 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9285 // ordered comparison fails), which could be NaN or non-NaN.
9286 // so here we discover exactly what NaN behavior is required/accepted.
9287 if (CmpInst::isFPPredicate(Pred)) {
9288 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9289 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9290
9291 if (LHSSafe && RHSSafe) {
9292 // Both operands are known non-NaN.
9293 NaNBehavior = SPNB_RETURNS_ANY;
9294 Ordered = CmpInst::isOrdered(Pred);
9295 } else if (CmpInst::isOrdered(Pred)) {
9296 // An ordered comparison will return false when given a NaN, so it
9297 // returns the RHS.
9298 Ordered = true;
9299 if (LHSSafe)
9300 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9301 NaNBehavior = SPNB_RETURNS_NAN;
9302 else if (RHSSafe)
9303 NaNBehavior = SPNB_RETURNS_OTHER;
9304 else
9305 // Completely unsafe.
9306 return {SPF_UNKNOWN, SPNB_NA, false};
9307 } else {
9308 Ordered = false;
9309 // An unordered comparison will return true when given a NaN, so it
9310 // returns the LHS.
9311 if (LHSSafe)
9312 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9313 NaNBehavior = SPNB_RETURNS_OTHER;
9314 else if (RHSSafe)
9315 NaNBehavior = SPNB_RETURNS_NAN;
9316 else
9317 // Completely unsafe.
9318 return {SPF_UNKNOWN, SPNB_NA, false};
9319 }
9320 }
9321
9322 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9323 std::swap(CmpLHS, CmpRHS);
9324 Pred = CmpInst::getSwappedPredicate(Pred);
9325 if (NaNBehavior == SPNB_RETURNS_NAN)
9326 NaNBehavior = SPNB_RETURNS_OTHER;
9327 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9328 NaNBehavior = SPNB_RETURNS_NAN;
9329 Ordered = !Ordered;
9330 }
9331
9332 // ([if]cmp X, Y) ? X : Y
9333 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9334 return getSelectPattern(Pred, NaNBehavior, Ordered);
9335
9336 if (isKnownNegation(TrueVal, FalseVal)) {
9337 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9338 // match against either LHS or sign-preserving operations on LHS, like
9339 // sext(LHS), or binary ops that do not wrap in signed sense.
9340 auto CmpLHSOrSExt =
9341 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9342 auto MaybeSExtOrMulCmpLHS =
9343 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9344 m_NSWShl(CmpLHSOrSExt, m_Value()));
9345 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9346 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9347 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9348 // Set the return values. If the compare uses the negated value (-X >s 0),
9349 // swap the return values because the negated value is always 'RHS'.
9350 LHS = TrueVal;
9351 RHS = FalseVal;
9352 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9353 std::swap(LHS, RHS);
9354
9355 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9356 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9357 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9358 return {SPF_ABS, SPNB_NA, false};
9359
9360 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9361 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9362 return {SPF_ABS, SPNB_NA, false};
9363
9364 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9365 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9366 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9367 return {SPF_NABS, SPNB_NA, false};
9368 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9369 // Set the return values. If the compare uses the negated value (-X >s 0),
9370 // swap the return values because the negated value is always 'RHS'.
9371 LHS = FalseVal;
9372 RHS = TrueVal;
9373 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9374 std::swap(LHS, RHS);
9375
9376 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9377 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9378 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9379 return {SPF_NABS, SPNB_NA, false};
9380
9381 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9382 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9383 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9384 return {SPF_ABS, SPNB_NA, false};
9385 }
9386 }
9387
9388 if (CmpInst::isIntPredicate(Pred))
9389 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9390
9391 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9392 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9393 // semantics than minNum. Be conservative in such case.
9394 if (NaNBehavior != SPNB_RETURNS_ANY ||
9395 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9396 !isKnownNonZero(CmpRHS)))
9397 return {SPF_UNKNOWN, SPNB_NA, false};
9398
9399 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9400}
9401
9403 Instruction::CastOps *CastOp) {
9404 const DataLayout &DL = CmpI->getDataLayout();
9405
9406 Constant *CastedTo = nullptr;
9407 switch (*CastOp) {
9408 case Instruction::ZExt:
9409 if (CmpI->isUnsigned())
9410 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9411 break;
9412 case Instruction::SExt:
9413 if (CmpI->isSigned())
9414 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9415 break;
9416 case Instruction::Trunc:
9417 Constant *CmpConst;
9418 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9419 CmpConst->getType() == SrcTy) {
9420 // Here we have the following case:
9421 //
9422 // %cond = cmp iN %x, CmpConst
9423 // %tr = trunc iN %x to iK
9424 // %narrowsel = select i1 %cond, iK %t, iK C
9425 //
9426 // We can always move trunc after select operation:
9427 //
9428 // %cond = cmp iN %x, CmpConst
9429 // %widesel = select i1 %cond, iN %x, iN CmpConst
9430 // %tr = trunc iN %widesel to iK
9431 //
9432 // Note that C could be extended in any way because we don't care about
9433 // upper bits after truncation. It can't be abs pattern, because it would
9434 // look like:
9435 //
9436 // select i1 %cond, x, -x.
9437 //
9438 // So only min/max pattern could be matched. Such match requires widened C
9439 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9440 // CmpConst == C is checked below.
9441 CastedTo = CmpConst;
9442 } else {
9443 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9444 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9445 }
9446 break;
9447 case Instruction::FPTrunc:
9448 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9449 break;
9450 case Instruction::FPExt:
9451 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9452 break;
9453 case Instruction::FPToUI:
9454 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9455 break;
9456 case Instruction::FPToSI:
9457 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9458 break;
9459 case Instruction::UIToFP:
9460 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9461 break;
9462 case Instruction::SIToFP:
9463 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9464 break;
9465 default:
9466 break;
9467 }
9468
9469 if (!CastedTo)
9470 return nullptr;
9471
9472 // Make sure the cast doesn't lose any information.
9473 Constant *CastedBack =
9474 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9475 if (CastedBack && CastedBack != C)
9476 return nullptr;
9477
9478 return CastedTo;
9479}
9480
9481/// Helps to match a select pattern in case of a type mismatch.
9482///
9483/// The function processes the case when type of true and false values of a
9484/// select instruction differs from type of the cmp instruction operands because
9485/// of a cast instruction. The function checks if it is legal to move the cast
9486/// operation after "select". If yes, it returns the new second value of
9487/// "select" (with the assumption that cast is moved):
9488/// 1. As operand of cast instruction when both values of "select" are same cast
9489/// instructions.
9490/// 2. As restored constant (by applying reverse cast operation) when the first
9491/// value of the "select" is a cast operation and the second value is a
9492/// constant. It is implemented in lookThroughCastConst().
9493/// 3. As one operand is cast instruction and the other is not. The operands in
9494/// sel(cmp) are in different type integer.
9495/// NOTE: We return only the new second value because the first value could be
9496/// accessed as operand of cast instruction.
9498 Instruction::CastOps *CastOp) {
9499 auto *Cast1 = dyn_cast<CastInst>(V1);
9500 if (!Cast1)
9501 return nullptr;
9502
9503 *CastOp = Cast1->getOpcode();
9504 Type *SrcTy = Cast1->getSrcTy();
9505 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9506 // If V1 and V2 are both the same cast from the same type, look through V1.
9507 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9508 return Cast2->getOperand(0);
9509 return nullptr;
9510 }
9511
9512 auto *C = dyn_cast<Constant>(V2);
9513 if (C)
9514 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9515
9516 Value *CastedTo = nullptr;
9517 if (*CastOp == Instruction::Trunc) {
9518 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9519 // Here we have the following case:
9520 // %y_ext = sext iK %y to iN
9521 // %cond = cmp iN %x, %y_ext
9522 // %tr = trunc iN %x to iK
9523 // %narrowsel = select i1 %cond, iK %tr, iK %y
9524 //
9525 // We can always move trunc after select operation:
9526 // %y_ext = sext iK %y to iN
9527 // %cond = cmp iN %x, %y_ext
9528 // %widesel = select i1 %cond, iN %x, iN %y_ext
9529 // %tr = trunc iN %widesel to iK
9530 assert(V2->getType() == Cast1->getType() &&
9531 "V2 and Cast1 should be the same type.");
9532 CastedTo = CmpI->getOperand(1);
9533 }
9534 }
9535
9536 return CastedTo;
9537}
9539 Instruction::CastOps *CastOp,
9540 unsigned Depth) {
9542 return {SPF_UNKNOWN, SPNB_NA, false};
9543
9545 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9546
9547 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9548 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9549
9550 Value *TrueVal = SI->getTrueValue();
9551 Value *FalseVal = SI->getFalseValue();
9552
9553 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9554 SI->getFastMathFlagsOrNone(),
9555 CastOp, Depth);
9556}
9557
9559 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9560 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9561 CmpInst::Predicate Pred = CmpI->getPredicate();
9562 Value *CmpLHS = CmpI->getOperand(0);
9563 Value *CmpRHS = CmpI->getOperand(1);
9564 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9565 FMF.setNoNaNs();
9566
9567 // Bail out early.
9568 if (CmpI->isEquality())
9569 return {SPF_UNKNOWN, SPNB_NA, false};
9570
9571 // Deal with type mismatches.
9572 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9573 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9574 // If this is a potential fmin/fmax with a cast to integer, then ignore
9575 // -0.0 because there is no corresponding integer value.
9576 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9577 FMF.setNoSignedZeros();
9578 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9579 cast<CastInst>(TrueVal)->getOperand(0), C,
9580 LHS, RHS, Depth);
9581 }
9582 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9583 // If this is a potential fmin/fmax with a cast to integer, then ignore
9584 // -0.0 because there is no corresponding integer value.
9585 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9586 FMF.setNoSignedZeros();
9587 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9588 C, cast<CastInst>(FalseVal)->getOperand(0),
9589 LHS, RHS, Depth);
9590 }
9591 }
9592 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9593 LHS, RHS, Depth);
9594}
9595
9597 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9598 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9599 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9600 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9601 if (SPF == SPF_FMINNUM)
9602 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9603 if (SPF == SPF_FMAXNUM)
9604 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9605 llvm_unreachable("unhandled!");
9606}
9607
9609 switch (SPF) {
9611 return Intrinsic::umin;
9613 return Intrinsic::umax;
9615 return Intrinsic::smin;
9617 return Intrinsic::smax;
9618 default:
9619 llvm_unreachable("Unexpected SPF");
9620 }
9621}
9622
9624 if (SPF == SPF_SMIN) return SPF_SMAX;
9625 if (SPF == SPF_UMIN) return SPF_UMAX;
9626 if (SPF == SPF_SMAX) return SPF_SMIN;
9627 if (SPF == SPF_UMAX) return SPF_UMIN;
9628 llvm_unreachable("unhandled!");
9629}
9630
9632 switch (MinMaxID) {
9633 case Intrinsic::smax: return Intrinsic::smin;
9634 case Intrinsic::smin: return Intrinsic::smax;
9635 case Intrinsic::umax: return Intrinsic::umin;
9636 case Intrinsic::umin: return Intrinsic::umax;
9637 // Please note that next four intrinsics may produce the same result for
9638 // original and inverted case even if X != Y due to NaN is handled specially.
9639 case Intrinsic::maximum: return Intrinsic::minimum;
9640 case Intrinsic::minimum: return Intrinsic::maximum;
9641 case Intrinsic::maxnum: return Intrinsic::minnum;
9642 case Intrinsic::minnum: return Intrinsic::maxnum;
9643 case Intrinsic::maximumnum:
9644 return Intrinsic::minimumnum;
9645 case Intrinsic::minimumnum:
9646 return Intrinsic::maximumnum;
9647 default: llvm_unreachable("Unexpected intrinsic");
9648 }
9649}
9650
9652 switch (SPF) {
9655 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9656 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9657 default: llvm_unreachable("Unexpected flavor");
9658 }
9659}
9660
9661std::pair<Intrinsic::ID, bool>
9663 // Check if VL contains select instructions that can be folded into a min/max
9664 // vector intrinsic and return the intrinsic if it is possible.
9665 // TODO: Support floating point min/max.
9666 bool AllCmpSingleUse = true;
9667 SelectPatternResult SelectPattern;
9668 SelectPattern.Flavor = SPF_UNKNOWN;
9669 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9670 Value *LHS, *RHS;
9671 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9672 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9673 return false;
9674 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9675 SelectPattern.Flavor != CurrentPattern.Flavor)
9676 return false;
9677 SelectPattern = CurrentPattern;
9678 AllCmpSingleUse &=
9680 return true;
9681 })) {
9682 switch (SelectPattern.Flavor) {
9683 case SPF_SMIN:
9684 return {Intrinsic::smin, AllCmpSingleUse};
9685 case SPF_UMIN:
9686 return {Intrinsic::umin, AllCmpSingleUse};
9687 case SPF_SMAX:
9688 return {Intrinsic::smax, AllCmpSingleUse};
9689 case SPF_UMAX:
9690 return {Intrinsic::umax, AllCmpSingleUse};
9691 case SPF_FMAXNUM:
9692 return {Intrinsic::maxnum, AllCmpSingleUse};
9693 case SPF_FMINNUM:
9694 return {Intrinsic::minnum, AllCmpSingleUse};
9695 default:
9696 llvm_unreachable("unexpected select pattern flavor");
9697 }
9698 }
9699 return {Intrinsic::not_intrinsic, false};
9700}
9701
9702template <typename InstTy>
9703static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9704 Value *&Init, Value *&OtherOp) {
9705 // Handle the case of a simple two-predecessor recurrence PHI.
9706 // There's a lot more that could theoretically be done here, but
9707 // this is sufficient to catch some interesting cases.
9708 // TODO: Expand list -- gep, uadd.sat etc.
9709 if (PN->getNumIncomingValues() != 2)
9710 return false;
9711
9712 for (unsigned I = 0; I != 2; ++I) {
9713 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9714 Operation && Operation->getNumOperands() >= 2) {
9715 Value *LHS = Operation->getOperand(0);
9716 Value *RHS = Operation->getOperand(1);
9717 if (LHS != PN && RHS != PN)
9718 continue;
9719
9720 Inst = Operation;
9721 Init = PN->getIncomingValue(!I);
9722 OtherOp = (LHS == PN) ? RHS : LHS;
9723 return true;
9724 }
9725 }
9726 return false;
9727}
9728
9729template <typename InstTy>
9730static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9731 Value *&Init, Value *&OtherOp0,
9732 Value *&OtherOp1) {
9733 if (PN->getNumIncomingValues() != 2)
9734 return false;
9735
9736 for (unsigned I = 0; I != 2; ++I) {
9737 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9738 Operation && Operation->getNumOperands() >= 3) {
9739 Value *Op0 = Operation->getOperand(0);
9740 Value *Op1 = Operation->getOperand(1);
9741 Value *Op2 = Operation->getOperand(2);
9742
9743 if (Op0 != PN && Op1 != PN && Op2 != PN)
9744 continue;
9745
9746 Inst = Operation;
9747 Init = PN->getIncomingValue(!I);
9748 if (Op0 == PN) {
9749 OtherOp0 = Op1;
9750 OtherOp1 = Op2;
9751 } else if (Op1 == PN) {
9752 OtherOp0 = Op0;
9753 OtherOp1 = Op2;
9754 } else {
9755 OtherOp0 = Op0;
9756 OtherOp1 = Op1;
9757 }
9758 return true;
9759 }
9760 }
9761 return false;
9762}
9764 Value *&Start, Value *&Step) {
9765 // We try to match a recurrence of the form:
9766 // %iv = [Start, %entry], [%iv.next, %backedge]
9767 // %iv.next = binop %iv, Step
9768 // Or:
9769 // %iv = [Start, %entry], [%iv.next, %backedge]
9770 // %iv.next = binop Step, %iv
9771 return matchTwoInputRecurrence(P, BO, Start, Step);
9772}
9773
9775 Value *&Start, Value *&Step) {
9776 BinaryOperator *BO = nullptr;
9777 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9778 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9779}
9780
9782 PHINode *&P, Value *&Init,
9783 Value *&OtherOp) {
9784 // Binary intrinsics only supported for now.
9785 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9786 I->getType() != I->getArgOperand(1)->getType())
9787 return false;
9788
9789 IntrinsicInst *II = nullptr;
9790 P = dyn_cast<PHINode>(I->getArgOperand(0));
9791 if (!P)
9792 P = dyn_cast<PHINode>(I->getArgOperand(1));
9793
9794 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9795}
9796
9798 PHINode *&P, Value *&Init,
9799 Value *&OtherOp0,
9800 Value *&OtherOp1) {
9801 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9802 I->getType() != I->getArgOperand(1)->getType() ||
9803 I->getType() != I->getArgOperand(2)->getType())
9804 return false;
9805 IntrinsicInst *II = nullptr;
9806 P = dyn_cast<PHINode>(I->getArgOperand(0));
9807 if (!P) {
9808 P = dyn_cast<PHINode>(I->getArgOperand(1));
9809 if (!P)
9810 P = dyn_cast<PHINode>(I->getArgOperand(2));
9811 }
9812 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9813 II == I;
9814}
9815
9816/// Return true if "icmp Pred LHS RHS" is always true.
9818 const Value *RHS) {
9819 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9820 return true;
9821
9822 switch (Pred) {
9823 default:
9824 return false;
9825
9826 case CmpInst::ICMP_SLE: {
9827 const APInt *C;
9828
9829 // LHS s<= LHS +_{nsw} C if C >= 0
9830 // LHS s<= LHS | C if C >= 0
9831 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9833 return !C->isNegative();
9834
9835 // LHS s<= smax(LHS, V) for any V
9837 return true;
9838
9839 // smin(RHS, V) s<= RHS for any V
9841 return true;
9842
9843 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9844 const Value *X;
9845 const APInt *CLHS, *CRHS;
9846 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9848 return CLHS->sle(*CRHS);
9849
9850 return false;
9851 }
9852
9853 case CmpInst::ICMP_ULE: {
9854 // LHS u<= LHS +_{nuw} V for any V
9855 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9857 return true;
9858
9859 // LHS u<= LHS | V for any V
9860 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9861 return true;
9862
9863 // LHS u<= umax(LHS, V) for any V
9865 return true;
9866
9867 // RHS >> V u<= RHS for any V
9868 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9869 return true;
9870
9871 // RHS u/ C_ugt_1 u<= RHS
9872 const APInt *C;
9873 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9874 return true;
9875
9876 // RHS & V u<= RHS for any V
9878 return true;
9879
9880 // umin(RHS, V) u<= RHS for any V
9882 return true;
9883
9884 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9885 const Value *X;
9886 const APInt *CLHS, *CRHS;
9887 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9889 return CLHS->ule(*CRHS);
9890
9891 return false;
9892 }
9893 }
9894}
9895
9896/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9897/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9898static std::optional<bool>
9900 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9901 switch (Pred) {
9902 default:
9903 return std::nullopt;
9904
9905 case CmpInst::ICMP_SLT:
9906 case CmpInst::ICMP_SLE:
9907 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9909 return true;
9910 return std::nullopt;
9911
9912 case CmpInst::ICMP_SGT:
9913 case CmpInst::ICMP_SGE:
9914 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9916 return true;
9917 return std::nullopt;
9918
9919 case CmpInst::ICMP_ULT:
9920 case CmpInst::ICMP_ULE:
9921 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9923 return true;
9924 return std::nullopt;
9925
9926 case CmpInst::ICMP_UGT:
9927 case CmpInst::ICMP_UGE:
9928 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9930 return true;
9931 return std::nullopt;
9932 }
9933}
9934
9935/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9936/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9937/// Otherwise, return std::nullopt if we can't infer anything.
9938static std::optional<bool>
9940 CmpPredicate RPred, const ConstantRange &RCR) {
9941 auto CRImpliesPred = [&](ConstantRange CR,
9942 CmpInst::Predicate Pred) -> std::optional<bool> {
9943 // If all true values for lhs and true for rhs, lhs implies rhs
9944 if (CR.icmp(Pred, RCR))
9945 return true;
9946
9947 // If there is no overlap, lhs implies not rhs
9948 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9949 return false;
9950
9951 return std::nullopt;
9952 };
9953 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9954 RPred))
9955 return Res;
9956 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9958 : LPred.dropSameSign();
9960 : RPred.dropSameSign();
9961 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9962 RPred);
9963 }
9964 return std::nullopt;
9965}
9966
9967/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9968/// is true. Return false if LHS implies RHS is false. Otherwise, return
9969/// std::nullopt if we can't infer anything.
9970static std::optional<bool>
9971isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9972 CmpPredicate RPred, const Value *R0, const Value *R1,
9973 const DataLayout &DL, bool LHSIsTrue) {
9974 // The rest of the logic assumes the LHS condition is true. If that's not the
9975 // case, invert the predicate to make it so.
9976 if (!LHSIsTrue)
9977 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9978
9979 // We can have non-canonical operands, so try to normalize any common operand
9980 // to L0/R0.
9981 if (L0 == R1) {
9982 std::swap(R0, R1);
9983 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9984 }
9985 if (R0 == L1) {
9986 std::swap(L0, L1);
9987 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9988 }
9989 if (L1 == R1) {
9990 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9991 if (L0 != R0 || match(L0, m_ImmConstant())) {
9992 std::swap(L0, L1);
9993 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9994 std::swap(R0, R1);
9995 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9996 }
9997 }
9998
9999 // See if we can infer anything if operand-0 matches and we have at least one
10000 // constant.
10001 const APInt *Unused;
10002 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10003 // Potential TODO: We could also further use the constant range of L0/R0 to
10004 // further constraint the constant ranges. At the moment this leads to
10005 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10006 // C1` (see discussion: D58633).
10007 SimplifyQuery SQ(DL);
10012
10013 // Even if L1/R1 are not both constant, we can still sometimes deduce
10014 // relationship from a single constant. For example X u> Y implies X != 0.
10015 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10016 return R;
10017 // If both L1/R1 were exact constant ranges and we didn't get anything
10018 // here, we won't be able to deduce this.
10019 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10020 return std::nullopt;
10021 }
10022
10023 // Can we infer anything when the two compares have matching operands?
10024 if (L0 == R0 && L1 == R1)
10025 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10026
10027 // It only really makes sense in the context of signed comparison for "X - Y
10028 // must be positive if X >= Y and no overflow".
10029 // Take SGT as an example: L0:x > L1:y and C >= 0
10030 // ==> R0:(x -nsw y) < R1:(-C) is false
10031 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10032 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10033 SignedLPred == ICmpInst::ICMP_SGE) &&
10034 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10035 if (match(R1, m_NonPositive()) &&
10036 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10037 return false;
10038 }
10039
10040 // Take SLT as an example: L0:x < L1:y and C <= 0
10041 // ==> R0:(x -nsw y) < R1:(-C) is true
10042 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10043 SignedLPred == ICmpInst::ICMP_SLE) &&
10044 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10045 if (match(R1, m_NonNegative()) &&
10046 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10047 return true;
10048 }
10049
10050 // a - b == NonZero -> a != b
10051 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10052 const APInt *L1C;
10053 Value *A, *B;
10054 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10055 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10056 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10057 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10062 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10063 }
10064
10065 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10066 if (L0 == R0 &&
10067 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10068 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10069 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10070 return CmpPredicate::getMatching(LPred, RPred).has_value();
10071
10072 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10073 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10074
10075 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10076 // Example: L0 u< 13 => (L0 & 16) == 0
10077 const APInt *LC, *RC, *MaskC;
10078 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10079 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10081 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10082 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10083 return true;
10084 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10085 ConstantRange(*RC)))
10086 return false;
10087 }
10088
10089 return std::nullopt;
10090}
10091
10092/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10093/// is true. Return false if LHS implies RHS is false. Otherwise, return
10094/// std::nullopt if we can't infer anything.
10095static std::optional<bool>
10097 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10098 const DataLayout &DL, bool LHSIsTrue) {
10099 // The rest of the logic assumes the LHS condition is true. If that's not the
10100 // case, invert the predicate to make it so.
10101 if (!LHSIsTrue)
10102 LPred = FCmpInst::getInversePredicate(LPred);
10103
10104 // We can have non-canonical operands, so try to normalize any common operand
10105 // to L0/R0.
10106 if (L0 == R1) {
10107 std::swap(R0, R1);
10108 RPred = FCmpInst::getSwappedPredicate(RPred);
10109 }
10110 if (R0 == L1) {
10111 std::swap(L0, L1);
10112 LPred = FCmpInst::getSwappedPredicate(LPred);
10113 }
10114 if (L1 == R1) {
10115 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10116 if (L0 != R0 || match(L0, m_ImmConstant())) {
10117 std::swap(L0, L1);
10118 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10119 std::swap(R0, R1);
10120 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10121 }
10122 }
10123
10124 // Can we infer anything when the two compares have matching operands?
10125 if (L0 == R0 && L1 == R1) {
10126 if ((LPred & RPred) == LPred)
10127 return true;
10128 if ((LPred & ~RPred) == LPred)
10129 return false;
10130 }
10131
10132 // See if we can infer anything if operand-0 matches and we have at least one
10133 // constant.
10134 const APFloat *L1C, *R1C;
10135 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10136 if (std::optional<ConstantFPRange> DomCR =
10138 if (std::optional<ConstantFPRange> ImpliedCR =
10140 if (ImpliedCR->contains(*DomCR))
10141 return true;
10142 }
10143 if (std::optional<ConstantFPRange> ImpliedCR =
10145 FCmpInst::getInversePredicate(RPred), *R1C)) {
10146 if (ImpliedCR->contains(*DomCR))
10147 return false;
10148 }
10149 }
10150 }
10151
10152 return std::nullopt;
10153}
10154
10155/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10156/// false. Otherwise, return std::nullopt if we can't infer anything. We
10157/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10158/// instruction.
10159static std::optional<bool>
10161 const Value *RHSOp0, const Value *RHSOp1,
10162 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10163 // The LHS must be an 'or', 'and', or a 'select' instruction.
10164 assert((LHS->getOpcode() == Instruction::And ||
10165 LHS->getOpcode() == Instruction::Or ||
10166 LHS->getOpcode() == Instruction::Select) &&
10167 "Expected LHS to be 'and', 'or', or 'select'.");
10168
10169 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10170
10171 // If the result of an 'or' is false, then we know both legs of the 'or' are
10172 // false. Similarly, if the result of an 'and' is true, then we know both
10173 // legs of the 'and' are true.
10174 const Value *ALHS, *ARHS;
10175 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10176 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10177 // FIXME: Make this non-recursion.
10178 if (std::optional<bool> Implication = isImpliedCondition(
10179 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10180 return Implication;
10181 if (std::optional<bool> Implication = isImpliedCondition(
10182 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10183 return Implication;
10184 return std::nullopt;
10185 }
10186 return std::nullopt;
10187}
10188
10189std::optional<bool>
10191 const Value *RHSOp0, const Value *RHSOp1,
10192 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10193 // Bail out when we hit the limit.
10195 return std::nullopt;
10196
10197 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10198 // example.
10199 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10200 return std::nullopt;
10201
10202 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10203 "Expected integer type only!");
10204
10205 // Match not
10206 if (match(LHS, m_Not(m_Value(LHS))))
10207 LHSIsTrue = !LHSIsTrue;
10208
10209 // Both LHS and RHS are icmps.
10210 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10211 CmpPredicate LHSPred;
10212 Value *LHSOp0, *LHSOp1;
10213 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10214 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10215 RHSOp1, DL, LHSIsTrue);
10216 } else {
10217 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10218 "Expected floating point type only!");
10219 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10220 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10221 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10222 DL, LHSIsTrue);
10223 }
10224
10225 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10226 /// the RHS to be an icmp.
10227 /// FIXME: Add support for and/or/select on the RHS.
10228 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10229 if ((LHSI->getOpcode() == Instruction::And ||
10230 LHSI->getOpcode() == Instruction::Or ||
10231 LHSI->getOpcode() == Instruction::Select))
10232 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10233 Depth);
10234 }
10235 return std::nullopt;
10236}
10237
10238std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10239 const DataLayout &DL,
10240 bool LHSIsTrue, unsigned Depth) {
10241 // LHS ==> RHS by definition
10242 if (LHS == RHS)
10243 return LHSIsTrue;
10244
10245 // Match not
10246 bool InvertRHS = false;
10247 if (match(RHS, m_Not(m_Value(RHS)))) {
10248 if (LHS == RHS)
10249 return !LHSIsTrue;
10250 InvertRHS = true;
10251 }
10252
10253 CmpPredicate RHSPred;
10254 Value *RHSOp0, *RHSOp1;
10255 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10256 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10257 LHSIsTrue, Depth))
10258 return InvertRHS ? !*Implied : *Implied;
10259 return std::nullopt;
10260 }
10261 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10262 if (auto Implied = isImpliedCondition(
10263 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10264 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10265 return InvertRHS ? !*Implied : *Implied;
10266 return std::nullopt;
10267 }
10268
10270 return std::nullopt;
10271
10272 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10273 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10274 const Value *RHS1, *RHS2;
10275 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10276 if (std::optional<bool> Imp =
10277 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10278 if (*Imp == true)
10279 return !InvertRHS;
10280 if (std::optional<bool> Imp =
10281 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10282 if (*Imp == true)
10283 return !InvertRHS;
10284 }
10285 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10286 if (std::optional<bool> Imp =
10287 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10288 if (*Imp == false)
10289 return InvertRHS;
10290 if (std::optional<bool> Imp =
10291 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10292 if (*Imp == false)
10293 return InvertRHS;
10294 }
10295
10296 return std::nullopt;
10297}
10298
10299// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10300// condition dominating ContextI or nullptr, if no condition is found.
10301static std::pair<Value *, bool>
10303 if (!ContextI || !ContextI->getParent())
10304 return {nullptr, false};
10305
10306 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10307 // dominator tree (eg, from a SimplifyQuery) instead?
10308 const BasicBlock *ContextBB = ContextI->getParent();
10309 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10310 if (!PredBB)
10311 return {nullptr, false};
10312
10313 // We need a conditional branch in the predecessor.
10314 Value *PredCond;
10315 BasicBlock *TrueBB, *FalseBB;
10316 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10317 return {nullptr, false};
10318
10319 // The branch should get simplified. Don't bother simplifying this condition.
10320 if (TrueBB == FalseBB)
10321 return {nullptr, false};
10322
10323 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10324 "Predecessor block does not point to successor?");
10325
10326 // Is this condition implied by the predecessor condition?
10327 return {PredCond, TrueBB == ContextBB};
10328}
10329
10330std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10331 const Instruction *ContextI,
10332 const DataLayout &DL) {
10333 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10334 auto PredCond = getDomPredecessorCondition(ContextI);
10335 if (PredCond.first)
10336 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10337 return std::nullopt;
10338}
10339
10341 const Value *LHS,
10342 const Value *RHS,
10343 const Instruction *ContextI,
10344 const DataLayout &DL) {
10345 auto PredCond = getDomPredecessorCondition(ContextI);
10346 if (PredCond.first)
10347 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10348 PredCond.second);
10349 return std::nullopt;
10350}
10351
10353 APInt &Upper, const InstrInfoQuery &IIQ,
10354 bool PreferSignedRange) {
10355 unsigned Width = Lower.getBitWidth();
10356 const APInt *C;
10357 switch (BO.getOpcode()) {
10358 case Instruction::Sub:
10359 if (match(BO.getOperand(0), m_APInt(C))) {
10360 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10361 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10362
10363 // If the caller expects a signed compare, then try to use a signed range.
10364 // Otherwise if both no-wraps are set, use the unsigned range because it
10365 // is never larger than the signed range. Example:
10366 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10367 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10368 if (PreferSignedRange && HasNSW && HasNUW)
10369 HasNUW = false;
10370
10371 if (HasNUW) {
10372 // 'sub nuw c, x' produces [0, C].
10373 Upper = *C + 1;
10374 } else if (HasNSW) {
10375 if (C->isNegative()) {
10376 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10378 Upper = *C - APInt::getSignedMaxValue(Width);
10379 } else {
10380 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10381 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10382 Lower = *C - APInt::getSignedMaxValue(Width);
10384 }
10385 }
10386 }
10387 break;
10388 case Instruction::Add:
10389 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10390 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10391 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10392
10393 // If the caller expects a signed compare, then try to use a signed
10394 // range. Otherwise if both no-wraps are set, use the unsigned range
10395 // because it is never larger than the signed range. Example: "add nuw
10396 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10397 if (PreferSignedRange && HasNSW && HasNUW)
10398 HasNUW = false;
10399
10400 if (HasNUW) {
10401 // 'add nuw x, C' produces [C, UINT_MAX].
10402 Lower = *C;
10403 } else if (HasNSW) {
10404 if (C->isNegative()) {
10405 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10407 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10408 } else {
10409 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10410 Lower = APInt::getSignedMinValue(Width) + *C;
10411 Upper = APInt::getSignedMaxValue(Width) + 1;
10412 }
10413 }
10414 }
10415 break;
10416
10417 case Instruction::And:
10418 if (match(BO.getOperand(1), m_APInt(C)))
10419 // 'and x, C' produces [0, C].
10420 Upper = *C + 1;
10421 // X & -X is a power of two or zero. So we can cap the value at max power of
10422 // two.
10423 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10424 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10425 Upper = APInt::getSignedMinValue(Width) + 1;
10426 break;
10427
10428 case Instruction::Or:
10429 if (match(BO.getOperand(1), m_APInt(C)))
10430 // 'or x, C' produces [C, UINT_MAX].
10431 Lower = *C;
10432 break;
10433
10434 case Instruction::AShr:
10435 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10436 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10438 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10439 } else if (match(BO.getOperand(0), m_APInt(C))) {
10440 unsigned ShiftAmount = Width - 1;
10441 if (!C->isZero() && IIQ.isExact(&BO))
10442 ShiftAmount = C->countr_zero();
10443 if (C->isNegative()) {
10444 // 'ashr C, x' produces [C, C >> (Width-1)]
10445 Lower = *C;
10446 Upper = C->ashr(ShiftAmount) + 1;
10447 } else {
10448 // 'ashr C, x' produces [C >> (Width-1), C]
10449 Lower = C->ashr(ShiftAmount);
10450 Upper = *C + 1;
10451 }
10452 }
10453 break;
10454
10455 case Instruction::LShr:
10456 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10457 // 'lshr x, C' produces [0, UINT_MAX >> C].
10458 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10459 } else if (match(BO.getOperand(0), m_APInt(C))) {
10460 // 'lshr C, x' produces [C >> (Width-1), C].
10461 unsigned ShiftAmount = Width - 1;
10462 if (!C->isZero() && IIQ.isExact(&BO))
10463 ShiftAmount = C->countr_zero();
10464 Lower = C->lshr(ShiftAmount);
10465 Upper = *C + 1;
10466 }
10467 break;
10468
10469 case Instruction::Shl:
10470 if (match(BO.getOperand(0), m_APInt(C))) {
10471 if (IIQ.hasNoUnsignedWrap(&BO)) {
10472 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10473 Lower = *C;
10474 Upper = Lower.shl(Lower.countl_zero()) + 1;
10475 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10476 if (C->isNegative()) {
10477 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10478 unsigned ShiftAmount = C->countl_one() - 1;
10479 Lower = C->shl(ShiftAmount);
10480 Upper = *C + 1;
10481 } else {
10482 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10483 unsigned ShiftAmount = C->countl_zero() - 1;
10484 Lower = *C;
10485 Upper = C->shl(ShiftAmount) + 1;
10486 }
10487 } else {
10488 // If lowbit is set, value can never be zero.
10489 if ((*C)[0])
10490 Lower = APInt::getOneBitSet(Width, 0);
10491 // If we are shifting a constant the largest it can be is if the longest
10492 // sequence of consecutive ones is shifted to the highbits (breaking
10493 // ties for which sequence is higher). At the moment we take a liberal
10494 // upper bound on this by just popcounting the constant.
10495 // TODO: There may be a bitwise trick for it longest/highest
10496 // consecutative sequence of ones (naive method is O(Width) loop).
10497 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10498 }
10499 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10500 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10501 }
10502 break;
10503
10504 case Instruction::SDiv:
10505 if (match(BO.getOperand(1), m_APInt(C))) {
10506 APInt IntMin = APInt::getSignedMinValue(Width);
10507 APInt IntMax = APInt::getSignedMaxValue(Width);
10508 if (C->isAllOnes()) {
10509 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10510 // where C != -1 and C != 0 and C != 1
10511 Lower = IntMin + 1;
10512 Upper = IntMax + 1;
10513 } else if (C->countl_zero() < Width - 1) {
10514 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10515 // where C != -1 and C != 0 and C != 1
10516 Lower = IntMin.sdiv(*C);
10517 Upper = IntMax.sdiv(*C);
10518 if (Lower.sgt(Upper))
10520 Upper = Upper + 1;
10521 assert(Upper != Lower && "Upper part of range has wrapped!");
10522 }
10523 } else if (match(BO.getOperand(0), m_APInt(C))) {
10524 if (C->isMinSignedValue()) {
10525 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10526 Lower = *C;
10527 Upper = Lower.lshr(1) + 1;
10528 } else {
10529 // 'sdiv C, x' produces [-|C|, |C|].
10530 Upper = C->abs() + 1;
10531 Lower = (-Upper) + 1;
10532 }
10533 }
10534 break;
10535
10536 case Instruction::UDiv:
10537 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10538 // 'udiv x, C' produces [0, UINT_MAX / C].
10539 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10540 } else if (match(BO.getOperand(0), m_APInt(C))) {
10541 // 'udiv C, x' produces [0, C].
10542 Upper = *C + 1;
10543 }
10544 break;
10545
10546 case Instruction::SRem:
10547 if (match(BO.getOperand(1), m_APInt(C))) {
10548 // 'srem x, C' produces (-|C|, |C|).
10549 Upper = C->abs();
10550 Lower = (-Upper) + 1;
10551 } else if (match(BO.getOperand(0), m_APInt(C))) {
10552 if (C->isNegative()) {
10553 // 'srem -|C|, x' produces [-|C|, 0].
10554 Upper = 1;
10555 Lower = *C;
10556 } else {
10557 // 'srem |C|, x' produces [0, |C|].
10558 Upper = *C + 1;
10559 }
10560 }
10561 break;
10562
10563 case Instruction::URem:
10564 if (match(BO.getOperand(1), m_APInt(C)))
10565 // 'urem x, C' produces [0, C).
10566 Upper = *C;
10567 else if (match(BO.getOperand(0), m_APInt(C)))
10568 // 'urem C, x' produces [0, C].
10569 Upper = *C + 1;
10570 break;
10571
10572 default:
10573 break;
10574 }
10575}
10576
10578 bool UseInstrInfo) {
10579 unsigned Width = II.getType()->getScalarSizeInBits();
10580 const APInt *C;
10581 switch (II.getIntrinsicID()) {
10582 case Intrinsic::ctlz:
10583 case Intrinsic::cttz: {
10584 APInt Upper(Width, Width);
10585 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10586 Upper += 1;
10587 // Maximum of set/clear bits is the bit width.
10589 }
10590 case Intrinsic::ctpop:
10591 // Maximum of set/clear bits is the bit width.
10593 APInt(Width, Width) + 1);
10594 case Intrinsic::uadd_sat:
10595 // uadd.sat(x, C) produces [C, UINT_MAX].
10596 if (match(II.getOperand(0), m_APInt(C)) ||
10597 match(II.getOperand(1), m_APInt(C)))
10599 break;
10600 case Intrinsic::sadd_sat:
10601 if (match(II.getOperand(0), m_APInt(C)) ||
10602 match(II.getOperand(1), m_APInt(C))) {
10603 if (C->isNegative())
10604 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10606 APInt::getSignedMaxValue(Width) + *C +
10607 1);
10608
10609 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10611 APInt::getSignedMaxValue(Width) + 1);
10612 }
10613 break;
10614 case Intrinsic::usub_sat:
10615 // usub.sat(C, x) produces [0, C].
10616 if (match(II.getOperand(0), m_APInt(C)))
10617 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10618
10619 // usub.sat(x, C) produces [0, UINT_MAX - C].
10620 if (match(II.getOperand(1), m_APInt(C)))
10622 APInt::getMaxValue(Width) - *C + 1);
10623 break;
10624 case Intrinsic::ssub_sat:
10625 if (match(II.getOperand(0), m_APInt(C))) {
10626 if (C->isNegative())
10627 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10629 *C - APInt::getSignedMinValue(Width) +
10630 1);
10631
10632 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10634 APInt::getSignedMaxValue(Width) + 1);
10635 } else if (match(II.getOperand(1), m_APInt(C))) {
10636 if (C->isNegative())
10637 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10639 APInt::getSignedMaxValue(Width) + 1);
10640
10641 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10643 APInt::getSignedMaxValue(Width) - *C +
10644 1);
10645 }
10646 break;
10647 case Intrinsic::umin:
10648 case Intrinsic::umax:
10649 case Intrinsic::smin:
10650 case Intrinsic::smax:
10651 if (!match(II.getOperand(0), m_APInt(C)) &&
10652 !match(II.getOperand(1), m_APInt(C)))
10653 break;
10654
10655 switch (II.getIntrinsicID()) {
10656 case Intrinsic::umin:
10657 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10658 case Intrinsic::umax:
10660 case Intrinsic::smin:
10662 *C + 1);
10663 case Intrinsic::smax:
10665 APInt::getSignedMaxValue(Width) + 1);
10666 default:
10667 llvm_unreachable("Must be min/max intrinsic");
10668 }
10669 break;
10670 case Intrinsic::abs:
10671 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10672 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10673 if (match(II.getOperand(1), m_One()))
10675 APInt::getSignedMaxValue(Width) + 1);
10676
10678 APInt::getSignedMinValue(Width) + 1);
10679 case Intrinsic::vscale:
10680 if (!II.getParent() || !II.getFunction())
10681 break;
10682 return getVScaleRange(II.getFunction(), Width);
10683 case Intrinsic::read_register:
10684 case Intrinsic::read_volatile_register: {
10685 const Module *M = II.getModule();
10686 if (!M || !M->getTargetTriple().isRISCV())
10687 break;
10688 if (II.getFunction() && isReadVLENB(II))
10689 return getRISCVVLENBRange(II, Width);
10690 break;
10691 }
10692 default:
10693 break;
10694 }
10695
10696 return ConstantRange::getFull(Width);
10697}
10698
10700 const InstrInfoQuery &IIQ) {
10701 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10702 const Value *LHS = nullptr, *RHS = nullptr;
10704 if (R.Flavor == SPF_UNKNOWN)
10705 return ConstantRange::getFull(BitWidth);
10706
10707 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10708 // If the negation part of the abs (in RHS) has the NSW flag,
10709 // then the result of abs(X) is [0..SIGNED_MAX],
10710 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10711 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10715
10718 }
10719
10720 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10721 // The result of -abs(X) is <= 0.
10723 APInt(BitWidth, 1));
10724 }
10725
10726 const APInt *C;
10727 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10728 return ConstantRange::getFull(BitWidth);
10729
10730 switch (R.Flavor) {
10731 case SPF_UMIN:
10733 case SPF_UMAX:
10735 case SPF_SMIN:
10737 *C + 1);
10738 case SPF_SMAX:
10741 default:
10742 return ConstantRange::getFull(BitWidth);
10743 }
10744}
10745
10747 // The maximum representable value of a half is 65504. For floats the maximum
10748 // value is 3.4e38 which requires roughly 129 bits.
10749 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10750 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10751 return;
10752 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10753 Lower = APInt(BitWidth, -65504, true);
10754 Upper = APInt(BitWidth, 65505);
10755 }
10756
10757 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10758 // For a fptoui the lower limit is left as 0.
10759 Upper = APInt(BitWidth, 65505);
10760 }
10761}
10762
10764 const SimplifyQuery &SQ,
10765 unsigned Depth) {
10766 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10767
10769 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10770
10771 if (auto *C = dyn_cast<Constant>(V))
10772 return C->toConstantRange();
10773
10774 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10775 ConstantRange CR = ConstantRange::getFull(BitWidth);
10776 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10777 APInt Lower = APInt(BitWidth, 0);
10778 APInt Upper = APInt(BitWidth, 0);
10779 // TODO: Return ConstantRange.
10780 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10782 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10784 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10785 ConstantRange CRTrue =
10786 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10787 ConstantRange CRFalse =
10788 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10789 CR = CRTrue.unionWith(CRFalse);
10791 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10792 ConstantRange SrcCR =
10793 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10794 CR = SrcCR.truncate(BitWidth);
10795 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10796 ConstantRange SrcCR =
10797 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10798 CR = SrcCR.zeroExtend(BitWidth);
10799 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10800 ConstantRange SrcCR =
10801 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10802 CR = SrcCR.signExtend(BitWidth);
10803 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10804 APInt Lower = APInt(BitWidth, 0);
10805 APInt Upper = APInt(BitWidth, 0);
10806 // TODO: Return ConstantRange.
10809 } else if (const auto *A = dyn_cast<Argument>(V))
10810 if (std::optional<ConstantRange> Range = A->getRange())
10811 CR = *Range;
10812
10813 if (auto *I = dyn_cast<Instruction>(V)) {
10814 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10816
10817 Value *FrexpSrc;
10818 if (const auto *CB = dyn_cast<CallBase>(V)) {
10819 if (std::optional<ConstantRange> Range = CB->getRange())
10820 CR = CR.intersectWith(*Range);
10822 m_Value(FrexpSrc))))) {
10823 const fltSemantics &FltSem =
10824 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10825 // It should be possible to implement this for any type, but this logic
10826 // only computes the range assuming standard subnormal handling.
10827 if (APFloat::isIEEELikeFP(FltSem)) {
10829 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10830
10831 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10832 // constrain its range when the source can be neither.
10833 if (KnownSrc.isKnownNeverInfOrNaN()) {
10834 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10835
10836 // Offset to find the true minimum exponent value for a denormal.
10837 if (!KnownSrc.isKnownNeverSubnormal())
10838 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10839
10840 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10841
10842 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10844
10845 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10846 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10847
10848 MinExp = std::max(AdjustedMin, MinExp);
10849 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10850 MaxExp);
10851
10853 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10854 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10855 /*isSigned=*/true));
10856 }
10857 }
10858 }
10859 }
10860
10861 if (SQ.CtxI && SQ.AC) {
10862 // Try to restrict the range based on information from assumptions.
10863 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10864 if (!AssumeVH)
10865 continue;
10866 CallInst *I = cast<CallInst>(AssumeVH);
10867 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10868 "Got assumption for the wrong function!");
10869 assert(I->getIntrinsicID() == Intrinsic::assume &&
10870 "must be an assume intrinsic");
10871
10872 if (!isValidAssumeForContext(I, SQ))
10873 continue;
10874 Value *Arg = I->getArgOperand(0);
10875 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10876 // Currently we just use information from comparisons.
10877 if (!Cmp || Cmp->getOperand(0) != V)
10878 continue;
10879 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10880 ConstantRange RHS =
10881 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10882 SQ.getWithInstruction(I), Depth + 1);
10883 CR = CR.intersectWith(
10884 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10885 }
10886 }
10887
10888 return CR;
10889}
10890
10891static void
10893 function_ref<void(Value *)> InsertAffected) {
10894 assert(V != nullptr);
10895 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10896 InsertAffected(V);
10897 } else if (auto *I = dyn_cast<Instruction>(V)) {
10898 InsertAffected(V);
10899
10900 // Peek through unary operators to find the source of the condition.
10901 Value *Op;
10903 m_Trunc(m_Value(Op))))) {
10905 InsertAffected(Op);
10906 }
10907 }
10908}
10909
10911 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10912 auto AddAffected = [&InsertAffected](Value *V) {
10913 addValueAffectedByCondition(V, InsertAffected);
10914 };
10915
10916 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10917 if (IsAssume) {
10918 AddAffected(LHS);
10919 AddAffected(RHS);
10920 } else if (match(RHS, m_Constant()))
10921 AddAffected(LHS);
10922 };
10923
10924 SmallVector<Value *, 8> Worklist;
10926 Worklist.push_back(Cond);
10927 while (!Worklist.empty()) {
10928 Value *V = Worklist.pop_back_val();
10929 if (!Visited.insert(V).second)
10930 continue;
10931
10932 CmpPredicate Pred;
10933 Value *A, *B, *X;
10934
10935 if (IsAssume) {
10936 AddAffected(V);
10937 if (match(V, m_Not(m_Value(X))))
10938 AddAffected(X);
10939 }
10940
10941 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10942 // assume(A && B) is split to -> assume(A); assume(B);
10943 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10944 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10945 // enough information to be worth handling (intersection of information as
10946 // opposed to union).
10947 if (!IsAssume) {
10948 Worklist.push_back(A);
10949 Worklist.push_back(B);
10950 }
10951 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10952 bool HasRHSC = match(B, m_ConstantInt());
10953 if (ICmpInst::isEquality(Pred)) {
10954 AddAffected(A);
10955 if (IsAssume)
10956 AddAffected(B);
10957 if (HasRHSC) {
10958 Value *Y;
10959 // (X << C) or (X >>_s C) or (X >>_u C).
10960 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10961 AddAffected(X);
10962 // (X & C) or (X | C).
10963 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10964 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10965 AddAffected(X);
10966 AddAffected(Y);
10967 }
10968 // X - Y
10969 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10970 AddAffected(X);
10971 AddAffected(Y);
10972 }
10973 }
10974 } else {
10975 AddCmpOperands(A, B);
10976 if (HasRHSC) {
10977 // Handle (A + C1) u< C2, which is the canonical form of
10978 // A > C3 && A < C4.
10980 AddAffected(X);
10981
10982 if (ICmpInst::isUnsigned(Pred)) {
10983 Value *Y;
10984 // X & Y u> C -> X >u C && Y >u C
10985 // X | Y u< C -> X u< C && Y u< C
10986 // X nuw+ Y u< C -> X u< C && Y u< C
10987 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10988 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10989 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10990 AddAffected(X);
10991 AddAffected(Y);
10992 }
10993 // X nuw- Y u> C -> X u> C
10994 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10995 AddAffected(X);
10996 }
10997 }
10998
10999 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11000 // by computeKnownFPClass().
11002 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11003 InsertAffected(X);
11004 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11005 InsertAffected(X);
11006 }
11007 }
11008
11009 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11010 Value *SquareOp = nullptr;
11011 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11012 AddAffected(SquareOp);
11013 };
11014 AddNuwSquareOperand(A);
11015 AddNuwSquareOperand(B);
11016
11017 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11018 AddAffected(X);
11019 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11020 AddCmpOperands(A, B);
11021
11022 // fcmp fneg(x), y
11023 // fcmp fabs(x), y
11024 // fcmp fneg(fabs(x)), y
11025 if (match(A, m_FNeg(m_Value(A))))
11026 AddAffected(A);
11027 if (match(A, m_FAbs(m_Value(A))))
11028 AddAffected(A);
11029
11031 m_Value()))) {
11032 // Handle patterns that computeKnownFPClass() support.
11033 AddAffected(A);
11034 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11035 // Assume is checked here as X is already added above for assumes in
11036 // addValueAffectedByCondition
11037 AddAffected(X);
11038 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11039 // Assume is checked here to avoid issues with ephemeral values
11040 Worklist.push_back(X);
11041 }
11042 }
11043}
11044
11046 // (X >> C) or/add (X & mask(C) != 0)
11047 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11048 if (BO->getOpcode() == Instruction::Add ||
11049 BO->getOpcode() == Instruction::Or) {
11050 const Value *X;
11051 const APInt *C1, *C2;
11052 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11056 m_Zero())))) &&
11057 C2->popcount() == C1->getZExtValue())
11058 return X;
11059 }
11060 }
11061 return nullptr;
11062}
11063
11065 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11066}
11067
11070 unsigned MaxCount, bool AllowUndefOrPoison) {
11073 auto Push = [&](const Value *V) -> bool {
11074 Constant *C;
11075 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11076 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11077 return false;
11078 // Check existence first to avoid unnecessary allocations.
11079 if (Constants.contains(C))
11080 return true;
11081 if (Constants.size() == MaxCount)
11082 return false;
11083 Constants.insert(C);
11084 return true;
11085 }
11086
11087 if (auto *Inst = dyn_cast<Instruction>(V)) {
11088 if (Visited.insert(Inst).second)
11089 Worklist.push_back(Inst);
11090 return true;
11091 }
11092 return false;
11093 };
11094 if (!Push(V))
11095 return false;
11096 while (!Worklist.empty()) {
11097 const Instruction *CurInst = Worklist.pop_back_val();
11098 switch (CurInst->getOpcode()) {
11099 case Instruction::Select:
11100 if (!Push(CurInst->getOperand(1)))
11101 return false;
11102 if (!Push(CurInst->getOperand(2)))
11103 return false;
11104 break;
11105 case Instruction::PHI:
11106 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11107 // Fast path for recurrence PHI.
11108 if (IncomingValue == CurInst)
11109 continue;
11110 if (!Push(IncomingValue))
11111 return false;
11112 }
11113 break;
11114 default:
11115 return false;
11116 }
11117 }
11118 return true;
11119}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:362
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:366
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:354
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:379
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6155
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:452
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass 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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041