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 const SimplifyQuery &SQ, unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V.getValue()))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
317 KnownBits Known = Depth == 0 ? V.getKnownBits(SQ)
318 : computeKnownBits(V.getValue(), SQ, Depth);
319 return Known.isNonNegative() &&
320 (Known.isNonZero() || isKnownNonZero(V.getValue(), SQ, Depth));
321}
322
324 const SimplifyQuery &SQ, unsigned Depth) {
325 if (Depth == 0)
326 return V.getKnownBits(SQ).isNegative();
327 return computeKnownBits(V.getValue(), SQ, Depth).isNegative();
328}
329
330static bool isKnownNonEqual(const Value *V1, const Value *V2,
331 const APInt &DemandedElts, const SimplifyQuery &Q,
332 unsigned Depth);
333
334static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
335 const Value *RHS);
336
337bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
338 const SimplifyQuery &Q, unsigned Depth) {
339 // We don't support looking through casts.
340 if (V1 == V2 || V1->getType() != V2->getType())
341 return false;
342 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
343 APInt DemandedElts =
344 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
345 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
346}
347
348bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
349 const SimplifyQuery &SQ, unsigned Depth) {
350 KnownBits Known(Mask.getBitWidth());
352 return Mask.isSubsetOf(Known.Zero);
353}
354
355static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
356 const SimplifyQuery &Q, unsigned Depth);
357
358static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
359 unsigned Depth = 0) {
360 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
361 APInt DemandedElts =
362 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
363 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
364}
365
366unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
367 AssumptionCache *AC, const Instruction *CtxI,
368 const DominatorTree *DT, bool UseInstrInfo,
369 unsigned Depth) {
370 return ::ComputeNumSignBits(
371 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
372}
373
375 AssumptionCache *AC,
376 const Instruction *CtxI,
377 const DominatorTree *DT,
378 unsigned Depth) {
379 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
380 return V->getType()->getScalarSizeInBits() - SignBits + 1;
381}
382
383/// Try to detect the lerp pattern: a * (b - c) + c * d
384/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
385///
386/// In that particular case, we can use the following chain of reasoning:
387///
388/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
389///
390/// Since that is true for arbitrary a, b, c and d within our constraints, we
391/// can conclude that:
392///
393/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
394///
395/// Considering that any result of the lerp would be less or equal to U, it
396/// would have at least the number of leading 0s as in U.
397///
398/// While being quite a specific situation, it is fairly common in computer
399/// graphics in the shape of alpha blending.
400///
401/// Modifies given KnownOut in-place with the inferred information.
402static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
403 const APInt &DemandedElts,
404 KnownBits &KnownOut,
405 const SimplifyQuery &Q,
406 unsigned Depth) {
407
408 Type *Ty = Op0->getType();
409 const unsigned BitWidth = Ty->getScalarSizeInBits();
410
411 // Only handle scalar types for now
412 if (Ty->isVectorTy())
413 return;
414
415 // Try to match: a * (b - c) + c * d.
416 // When a == 1 => A == nullptr, the same applies to d/D as well.
417 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
418 const Instruction *SubBC = nullptr;
419
420 const auto MatchSubBC = [&]() {
421 // (b - c) can have two forms that interest us:
422 //
423 // 1. sub nuw %b, %c
424 // 2. xor %c, %b
425 //
426 // For the first case, nuw flag guarantees our requirement b >= c.
427 //
428 // The second case might happen when the analysis can infer that b is a mask
429 // for c and we can transform sub operation into xor (that is usually true
430 // for constant b's). Even though xor is symmetrical, canonicalization
431 // ensures that the constant will be the RHS. We have additional checks
432 // later on to ensure that this xor operation is equivalent to subtraction.
434 m_Xor(m_Value(C), m_Value(B))));
435 };
436
437 const auto MatchASubBC = [&]() {
438 // Cases:
439 // - a * (b - c)
440 // - (b - c) * a
441 // - (b - c) <- a implicitly equals 1
442 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
443 };
444
445 const auto MatchCD = [&]() {
446 // Cases:
447 // - d * c
448 // - c * d
449 // - c <- d implicitly equals 1
451 };
452
453 const auto Match = [&](const Value *LHS, const Value *RHS) {
454 // We do use m_Specific(C) in MatchCD, so we have to make sure that
455 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
456 // has to evaluate first and return true.
457 //
458 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
459 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
460 };
461
462 if (!Match(Op0, Op1) && !Match(Op1, Op0))
463 return;
464
465 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
466 // For some of the values we use the convention of leaving
467 // it nullptr to signify an implicit constant 1.
468 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
470 };
471
472 // Check that all operands are non-negative
473 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
474 if (!KnownA.isNonNegative())
475 return;
476
477 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
478 if (!KnownD.isNonNegative())
479 return;
480
481 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
482 if (!KnownB.isNonNegative())
483 return;
484
485 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
486 if (!KnownC.isNonNegative())
487 return;
488
489 // If we matched subtraction as xor, we need to actually check that xor
490 // is semantically equivalent to subtraction.
491 //
492 // For that to be true, b has to be a mask for c or that b's known
493 // ones cover all known and possible ones of c.
494 if (SubBC->getOpcode() == Instruction::Xor &&
495 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
496 return;
497
498 const APInt MaxA = KnownA.getMaxValue();
499 const APInt MaxD = KnownD.getMaxValue();
500 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
501 const APInt MaxB = KnownB.getMaxValue();
502
503 // We can't infer leading zeros info if the upper-bound estimate wraps.
504 bool Overflow;
505 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
506
507 if (Overflow)
508 return;
509
510 // If we know that x <= y and both are positive than x has at least the same
511 // number of leading zeros as y.
512 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
513 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
514}
515
516static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
517 bool NSW, bool NUW,
518 const APInt &DemandedElts,
519 KnownBits &KnownOut, KnownBits &Known2,
520 const SimplifyQuery &Q, unsigned Depth) {
521 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
522
523 // If one operand is unknown and we have no nowrap information,
524 // the result will be unknown independently of the second operand.
525 if (KnownOut.isUnknown() && !NSW && !NUW)
526 return;
527
528 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
529 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
530
531 if (!Add && NSW && !KnownOut.isNonNegative() &&
533 .value_or(false) ||
534 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
535 KnownOut.makeNonNegative();
536
537 if (Add)
538 // Try to match lerp pattern and combine results
539 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
540}
541
542static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
543 bool NUW, const APInt &DemandedElts,
544 KnownBits &Known, KnownBits &Known2,
545 const SimplifyQuery &Q, unsigned Depth) {
546 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
547 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
548
549 bool isKnownNegative = false;
550 bool isKnownNonNegative = false;
551 // If the multiplication is known not to overflow, compute the sign bit.
552 if (NSW) {
553 if (Op0 == Op1) {
554 // The product of a number with itself is non-negative.
555 isKnownNonNegative = true;
556 } else {
557 bool isKnownNonNegativeOp1 = Known.isNonNegative();
558 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
559 bool isKnownNegativeOp1 = Known.isNegative();
560 bool isKnownNegativeOp0 = Known2.isNegative();
561 // The product of two numbers with the same sign is non-negative.
562 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
563 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
564 if (!isKnownNonNegative && NUW) {
565 // mul nuw nsw with a factor > 1 is non-negative.
566 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
567 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
568 KnownBits::sgt(Known2, One).value_or(false);
569 }
570
571 // The product of a negative number and a non-negative number is either
572 // negative or zero.
575 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
576 Known2.isNonZero()) ||
577 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
578 }
579 }
580
581 bool SelfMultiply = Op0 == Op1;
582 if (SelfMultiply)
583 SelfMultiply &=
584 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
585 Known = KnownBits::mul(Known, Known2, SelfMultiply);
586
587 if (SelfMultiply) {
588 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
589 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
590 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
591
592 if (OutValidBits < TyBits) {
593 APInt KnownZeroMask =
594 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
595 Known.Zero |= KnownZeroMask;
596 }
597 }
598
599 // Only make use of no-wrap flags if we failed to compute the sign bit
600 // directly. This matters if the multiplication always overflows, in
601 // which case we prefer to follow the result of the direct computation,
602 // though as the program is invoking undefined behaviour we can choose
603 // whatever we like here.
604 if (isKnownNonNegative && !Known.isNegative())
605 Known.makeNonNegative();
606 else if (isKnownNegative && !Known.isNonNegative())
607 Known.makeNegative();
608}
609
611 KnownBits &Known) {
612 unsigned BitWidth = Known.getBitWidth();
613 unsigned NumRanges = Ranges.getNumOperands() / 2;
614 assert(NumRanges >= 1);
615
616 Known.setAllConflict();
617
618 for (unsigned i = 0; i < NumRanges; ++i) {
620 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
622 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
623 ConstantRange Range(Lower->getValue(), Upper->getValue());
624 // BitWidth must equal the Ranges BitWidth for the correct number of high
625 // bits to be set.
626 assert(BitWidth == Range.getBitWidth() &&
627 "Known bit width must match range bit width!");
628
629 // The first CommonPrefixBits of all values in Range are equal.
630 unsigned CommonPrefixBits =
631 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
632 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
633 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
634 Known.One &= UnsignedMax & Mask;
635 Known.Zero &= ~UnsignedMax & Mask;
636 }
637}
638
639static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
640 // The instruction defining an assumption's condition itself is always
641 // considered ephemeral to that assumption (even if it has other
642 // non-ephemeral users). See r246696's test case for an example.
643 if (is_contained(I->operands(), E))
644 return true;
645
646 const auto *EI = dyn_cast<Instruction>(E);
647 if (!EI)
648 return false;
649
650 if (EI == I)
651 return true;
652
655 Visited.insert(EI);
656 WorkList.push_back(EI);
657 bool ReachesI = false;
658 while (!WorkList.empty()) {
659 const Instruction *V = WorkList.pop_back_val();
660 for (const User *U : V->users()) {
661 const auto *UI = cast<Instruction>(U);
662 if (UI == I) {
663 ReachesI = true;
664 continue;
665 }
666 if (UI->mayHaveSideEffects() || UI->isTerminator())
667 return false;
668 if (Visited.insert(UI).second)
669 WorkList.push_back(UI);
670 }
671 }
672 return ReachesI;
673}
674
675// Is this an intrinsic that cannot be speculated but also cannot trap?
677 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
678 return CI->isAssumeLikeIntrinsic();
679
680 return false;
681}
682
684 const Instruction *CtxI,
685 const DominatorTree *DT,
686 bool AllowEphemerals) {
687 // There are two restrictions on the use of an assume:
688 // 1. The assume must dominate the context (or the control flow must
689 // reach the assume whenever it reaches the context).
690 // 2. The context must not be in the assume's set of ephemeral values
691 // (otherwise we will use the assume to prove that the condition
692 // feeding the assume is trivially true, thus causing the removal of
693 // the assume).
694
695 if (Inv->getParent() == CtxI->getParent()) {
696 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
697 // in the BB.
698 if (Inv->comesBefore(CtxI))
699 return true;
700
701 // Don't let an assume affect itself - this would cause the problems
702 // `isEphemeralValueOf` is trying to prevent, and it would also make
703 // the loop below go out of bounds.
704 if (!AllowEphemerals && Inv == CtxI)
705 return false;
706
707 // The context comes first, but they're both in the same block.
708 // Make sure there is nothing in between that might interrupt
709 // the control flow, not even CtxI itself.
710 // We limit the scan distance between the assume and its context instruction
711 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
712 // it can be adjusted if needed (could be turned into a cl::opt).
713 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
715 return false;
716
717 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
718 }
719
720 // Inv and CtxI are in different blocks.
721 if (DT) {
722 if (DT->dominates(Inv, CtxI))
723 return true;
724 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
725 Inv->getParent()->isEntryBlock()) {
726 // We don't have a DT, but this trivially dominates.
727 return true;
728 }
729
730 return false;
731}
732
735 unsigned &NumChecked) {
736 for (const Instruction &I : make_range(Begin, End)) {
737 if (NumChecked++ > MaxInstrsToCheckForFree)
738 return false;
739 if (auto *CB = dyn_cast<CallBase>(&I)) {
740 if (!CB->hasFnAttr(Attribute::NoFree))
741 return false;
742 } else if (I.maySynchronize()) {
743 return false;
744 }
745 }
746 return true;
747}
748
750 const Instruction *CtxI,
751 const DominatorTree *DT) {
752 const BasicBlock *CtxBB = CtxI->getParent();
753 const BasicBlock *AssumeBB = Assume->getParent();
754 unsigned NumChecked = 0;
755 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
756 if (CtxBB == AssumeBB) {
757 if (Assume != CtxI && !Assume->comesBefore(CtxI))
758 return false;
759 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
760 }
761 if (DT && !DT->dominates(Assume, CtxI))
762 return false;
763 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
764 return false;
765 if (pred_empty(CtxBB))
766 return false;
767
768 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
769 // backedges returning to CtxBB are enqueued and checked correctly.
772 while (!Worklist.empty()) {
773 const BasicBlock *CurBB = Worklist.pop_back_val();
774 if (!Visited.insert(CurBB).second)
775 continue;
776
777 if (CurBB == AssumeBB) {
778 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
779 return false;
780 continue;
781 }
782 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
783 "Blocks between Assume and CtxI must be dominated by AssumeBB");
784
785 if (pred_empty(CurBB))
786 return false;
787
788 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
789 // instructions from CtxIter to the end of CtxBB (instructions before
790 // CtxIter were checked above). Otherwise, check the entire block.
791 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
792 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
793 return false;
794 append_range(Worklist, predecessors(CurBB));
795 }
796 return true;
797}
798
799// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
800// we still have enough information about `RHS` to conclude non-zero. For
801// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
802// so the extra compile time may not be worth it, but possibly a second API
803// should be created for use outside of loops.
804static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
805 // v u> y implies v != 0.
806 if (Pred == ICmpInst::ICMP_UGT)
807 return true;
808
809 // Special-case v != 0 to also handle v != null.
810 if (Pred == ICmpInst::ICMP_NE)
811 return match(RHS, m_Zero());
812
813 // All other predicates - rely on generic ConstantRange handling.
814 const APInt *C;
815 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
816 if (match(RHS, m_APInt(C))) {
818 return !TrueValues.contains(Zero);
819 }
820
822 if (VC == nullptr)
823 return false;
824
825 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
826 ++ElemIdx) {
828 Pred, VC->getElementAsAPInt(ElemIdx));
829 if (TrueValues.contains(Zero))
830 return false;
831 }
832 return true;
833}
834
835static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
836 Value *&ValOut, Instruction *&CtxIOut,
837 const PHINode **PhiOut = nullptr) {
838 ValOut = U->get();
839 if (ValOut == PHI)
840 return;
841 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
842 if (PhiOut)
843 *PhiOut = PHI;
844 Value *V;
845 // If the Use is a select of this phi, compute analysis on other arm to break
846 // recursion.
847 // TODO: Min/Max
848 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
849 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
850 ValOut = V;
851
852 // Same for select, if this phi is 2-operand phi, compute analysis on other
853 // incoming value to break recursion.
854 // TODO: We could handle any number of incoming edges as long as we only have
855 // two unique values.
856 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
857 IncPhi && IncPhi->getNumIncomingValues() == 2) {
858 for (int Idx = 0; Idx < 2; ++Idx) {
859 if (IncPhi->getIncomingValue(Idx) == PHI) {
860 ValOut = IncPhi->getIncomingValue(1 - Idx);
861 if (PhiOut)
862 *PhiOut = IncPhi;
863 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
864 break;
865 }
866 }
867 }
868}
869
870static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
871 // Use of assumptions is context-sensitive. If we don't have a context, we
872 // cannot use them!
873 if (!Q.AC || !Q.CtxI)
874 return false;
875
876 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
877 if (!Elem.Assume)
878 continue;
879
880 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
881 assert(I->getFunction() == Q.CtxI->getFunction() &&
882 "Got assumption for the wrong function!");
883
884 if (Elem.Index != AssumptionCache::ExprResultIdx) {
886 I->getOperandBundleAt(Elem.Index)) &&
888 return true;
889 continue;
890 }
891
892 // Warning: This loop can end up being somewhat performance sensitive.
893 // We're running this loop for once for each value queried resulting in a
894 // runtime of ~O(#assumes * #values).
895
896 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
898 return true;
899
900 Value *RHS;
901 CmpPredicate Pred;
902 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
903 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
904 continue;
905
907 return true;
908 }
909
910 return false;
911}
912
915 const SimplifyQuery &Q) {
916 if (RHS->getType()->isPointerTy()) {
917 // Handle comparison of pointer to null explicitly, as it will not be
918 // covered by the m_APInt() logic below.
919 if (LHS == V && match(RHS, m_Zero())) {
920 switch (Pred) {
922 Known.setAllZero();
923 break;
926 Known.makeNonNegative();
927 break;
929 Known.makeNegative();
930 break;
931 default:
932 break;
933 }
934 }
935 return;
936 }
937
938 unsigned BitWidth = Known.getBitWidth();
939 auto m_V =
941
942 Value *Y;
943 const APInt *Mask, *C;
944 if (!match(RHS, m_APInt(C)))
945 return;
946
947 uint64_t ShAmt;
948 switch (Pred) {
950 // assume(V = C)
951 if (match(LHS, m_V)) {
952 Known = Known.unionWith(KnownBits::makeConstant(*C));
953 // assume(V & Mask = C)
954 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
955 // For one bits in Mask, we can propagate bits from C to V.
956 Known.One |= *C;
957 if (match(Y, m_APInt(Mask)))
958 Known.Zero |= ~*C & *Mask;
959 // assume(V | Mask = C)
960 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
961 // For zero bits in Mask, we can propagate bits from C to V.
962 Known.Zero |= ~*C;
963 if (match(Y, m_APInt(Mask)))
964 Known.One |= *C & ~*Mask;
965 // assume(V << ShAmt = C)
966 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
967 ShAmt < BitWidth) {
968 // For those bits in C that are known, we can propagate them to known
969 // bits in V shifted to the right by ShAmt.
971 RHSKnown >>= ShAmt;
972 Known = Known.unionWith(RHSKnown);
973 // assume(V >> ShAmt = C)
974 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
975 ShAmt < BitWidth) {
976 // For those bits in RHS that are known, we can propagate them to known
977 // bits in V shifted to the right by C.
979 RHSKnown <<= ShAmt;
980 Known = Known.unionWith(RHSKnown);
981 }
982 break;
983 case ICmpInst::ICMP_NE: {
984 // assume (V & B != 0) where B is a power of 2
985 const APInt *BPow2;
986 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
987 Known.One |= *BPow2;
988 break;
989 }
990 default: {
991 const APInt *Offset = nullptr;
992 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
994 if (Offset)
995 LHSRange = LHSRange.sub(*Offset);
996 Known = Known.unionWith(LHSRange.toKnownBits());
997 }
998 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
999 // X & Y u> C -> X u> C && Y u> C
1000 // X nuw- Y u> C -> X u> C
1001 if (match(LHS, m_c_And(m_V, m_Value())) ||
1002 match(LHS, m_NUWSub(m_V, m_Value())))
1003 Known.One.setHighBits(
1004 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1005 }
1006 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1007 // X | Y u< C -> X u< C && Y u< C
1008 // X nuw+ Y u< C -> X u< C && Y u< C
1009 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1010 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1011 Known.Zero.setHighBits(
1012 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1013 }
1014 }
1015 } break;
1016 }
1017}
1018
1021 const SimplifyQuery &SQ, bool Invert) {
1022 ICmpInst::Predicate Pred =
1023 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1024 Value *LHS = Cmp->getOperand(0);
1025 Value *RHS = Cmp->getOperand(1);
1026
1027 // Handle icmp pred (trunc V), C
1028 if (match(LHS, m_Trunc(m_Specific(V)))) {
1029 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1030 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1032 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1033 else
1034 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1035 return;
1036 }
1037
1038 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1039}
1040
1042 KnownBits &Known, const SimplifyQuery &SQ,
1043 bool Invert, unsigned Depth) {
1044 Value *A, *B;
1047 KnownBits Known2(Known.getBitWidth());
1048 KnownBits Known3(Known.getBitWidth());
1049 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1050 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1051 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1053 Known2 = Known2.unionWith(Known3);
1054 else
1055 Known2 = Known2.intersectWith(Known3);
1056 Known = Known.unionWith(Known2);
1057 return;
1058 }
1059
1060 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1061 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1062 return;
1063 }
1064
1065 if (match(Cond, m_Trunc(m_Specific(V)))) {
1066 KnownBits DstKnown(1);
1067 if (Invert) {
1068 DstKnown.setAllZero();
1069 } else {
1070 DstKnown.setAllOnes();
1071 }
1073 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1074 return;
1075 }
1076 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1077 return;
1078 }
1079
1081 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1082}
1083
1085 const SimplifyQuery &Q, unsigned Depth) {
1086 // Handle injected condition.
1087 if (Q.CC && Q.CC->AffectedValues.contains(V))
1089
1090 if (!Q.CtxI)
1091 return;
1092
1093 if (Q.DC && Q.DT) {
1094 // Handle dominating conditions.
1095 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1096 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1097 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1098 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1099 /*Invert*/ false, Depth);
1100
1101 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1102 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1103 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1104 /*Invert*/ true, Depth);
1105 }
1106
1107 if (Known.hasConflict())
1108 Known.resetAll();
1109 }
1110
1111 if (!Q.AC)
1112 return;
1113
1114 unsigned BitWidth = Known.getBitWidth();
1115
1116 // Note that the patterns below need to be kept in sync with the code
1117 // in AssumptionCache::updateAffectedValues.
1118
1119 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1120 if (!Elem.Assume)
1121 continue;
1122
1123 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1124 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1125 "Got assumption for the wrong function!");
1126
1127 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1128 auto OBU = I->getOperandBundleAt(Elem.Index);
1129 switch (getBundleAttrFromOBU(OBU)) {
1130 case BundleAttr::Align: {
1131 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1132 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1134 Known.Zero |= (*Alignment - 1) & ~*Offset;
1135 Known.One |= (*Alignment - 1) & *Offset;
1136 }
1137 } break;
1138
1139 case BundleAttr::Range: {
1140 auto [Val, Range] = getAssumeRangeInfo(OBU);
1141 if (Val == V && isValidAssumeForContext(I, Q))
1142 Known = Known.unionWith(Range.toKnownBits());
1143 } break;
1144
1145 default:
1146 break;
1147 }
1148 continue;
1149 }
1150
1151 // Warning: This loop can end up being somewhat performance sensitive.
1152 // We're running this loop for once for each value queried resulting in a
1153 // runtime of ~O(#assumes * #values).
1154
1155 Value *Arg = I->getArgOperand(0);
1156
1157 if (Arg == V && isValidAssumeForContext(I, Q)) {
1158 assert(BitWidth == 1 && "assume operand is not i1?");
1159 (void)BitWidth;
1160 Known.setAllOnes();
1161 return;
1162 }
1163 if (match(Arg, m_Not(m_Specific(V))) &&
1165 assert(BitWidth == 1 && "assume operand is not i1?");
1166 (void)BitWidth;
1167 Known.setAllZero();
1168 return;
1169 }
1170 auto *Trunc = dyn_cast<TruncInst>(Arg);
1171 if (Trunc && Trunc->getOperand(0) == V &&
1173 if (Trunc->hasNoUnsignedWrap()) {
1175 return;
1176 }
1177 Known.One.setBit(0);
1178 return;
1179 }
1180
1181 // The remaining tests are all recursive, so bail out if we hit the limit.
1183 continue;
1184
1185 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1186 if (!Cmp)
1187 continue;
1188
1189 if (!isValidAssumeForContext(I, Q))
1190 continue;
1191
1192 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1193 }
1194
1195 // Conflicting assumption: Undefined behavior will occur on this execution
1196 // path.
1197 if (Known.hasConflict())
1198 Known.resetAll();
1199}
1200
1201/// Compute known bits from a shift operator, including those with a
1202/// non-constant shift amount. Known is the output of this function. Known2 is a
1203/// pre-allocated temporary with the same bit width as Known and on return
1204/// contains the known bit of the shift value source. KF is an
1205/// operator-specific function that, given the known-bits and a shift amount,
1206/// compute the implied known-bits of the shift operator's result respectively
1207/// for that shift amount. The results from calling KF are conservatively
1208/// combined for all permitted shift amounts.
1210 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1211 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1212 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1213 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1214 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1215 // To limit compile-time impact, only query isKnownNonZero() if we know at
1216 // least something about the shift amount.
1217 bool ShAmtNonZero =
1218 Known.isNonZero() ||
1219 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1220 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1221 Known = KF(Known2, Known, ShAmtNonZero);
1222}
1223
1224static KnownBits
1225getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1226 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1227 const SimplifyQuery &Q, unsigned Depth) {
1228 unsigned BitWidth = KnownLHS.getBitWidth();
1229 KnownBits KnownOut(BitWidth);
1230 bool IsAnd = false;
1231 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1232 Value *X = nullptr, *Y = nullptr;
1233
1234 switch (I->getOpcode()) {
1235 case Instruction::And:
1236 KnownOut = KnownLHS & KnownRHS;
1237 IsAnd = true;
1238 // and(x, -x) 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: instcombine often reassociates independent `and` which can hide
1242 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1243 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1244 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1245 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1246 KnownOut = KnownLHS.blsi();
1247 else
1248 KnownOut = KnownRHS.blsi();
1249 }
1250 break;
1251 case Instruction::Or:
1252 KnownOut = KnownLHS | KnownRHS;
1253 break;
1254 case Instruction::Xor:
1255 KnownOut = KnownLHS ^ KnownRHS;
1256 // xor(x, x-1) is common idioms that will clear all but lowest set
1257 // bit. If we have a single known bit in x, we can clear all bits
1258 // above it.
1259 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1260 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1261 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1262 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1263 if (HasKnownOne &&
1265 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1266 KnownOut = XBits.blsmsk();
1267 }
1268 break;
1269 default:
1270 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1271 }
1272
1273 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1274 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1275 // here we handle the more general case of adding any odd number by
1276 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1277 // TODO: This could be generalized to clearing any bit set in y where the
1278 // following bit is known to be unset in y.
1279 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1283 KnownBits KnownY(BitWidth);
1284 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1285 if (KnownY.countMinTrailingOnes() > 0) {
1286 if (IsAnd)
1287 KnownOut.Zero.setBit(0);
1288 else
1289 KnownOut.One.setBit(0);
1290 }
1291 }
1292 return KnownOut;
1293}
1294
1296 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1297 unsigned Depth,
1298 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1299 KnownBitsFunc) {
1300 APInt DemandedEltsLHS, DemandedEltsRHS;
1302 DemandedElts, DemandedEltsLHS,
1303 DemandedEltsRHS);
1304
1305 const auto ComputeForSingleOpFunc =
1306 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1307 return KnownBitsFunc(
1308 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1309 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1310 };
1311
1312 if (DemandedEltsRHS.isZero())
1313 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1314 if (DemandedEltsLHS.isZero())
1315 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1316
1317 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1318 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1319}
1320
1321// Public so this can be used in `SimplifyDemandedUseBits`.
1323 const KnownBits &KnownLHS,
1324 const KnownBits &KnownRHS,
1325 const SimplifyQuery &SQ,
1326 unsigned Depth) {
1327 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1328 APInt DemandedElts =
1329 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1330
1331 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1332 Depth);
1333}
1334
1336 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1337 // Without vscale_range, we only know that vscale is non-zero.
1338 if (!Attr.isValid())
1340
1341 unsigned AttrMin = Attr.getVScaleRangeMin();
1342 // Minimum is larger than vscale width, result is always poison.
1343 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1344 return ConstantRange::getEmpty(BitWidth);
1345
1346 APInt Min(BitWidth, AttrMin);
1347 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1348 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1350
1351 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1352}
1353
1354/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1355/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1356/// target's VLEN range. Callers must ensure the target is RISC-V.
1357static bool isReadVLENB(const IntrinsicInst &II) {
1358 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1359 if (!MAV)
1360 return false;
1361 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1362 if (!MD || MD->getNumOperands() != 1)
1363 return false;
1364 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1365 return RegName && RegName->getString() == "vlenb";
1366}
1367
1368/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1369/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1370/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1371/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1372/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1373/// attribute, when present, pins the subtarget's VLEN in units of
1374/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1375/// RVVBytesPerBlock.
1377 unsigned Width) {
1378 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1379 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1380
1381 const Function *F = II.getFunction();
1382 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1383 ConstantRange VScale = getVScaleRange(F, Width);
1384 Range = Range.intersectWith(
1386 }
1387 return Range;
1388}
1389
1391 Value *Arm, bool Invert,
1392 const SimplifyQuery &Q, unsigned Depth) {
1393 // If we have a constant arm, we are done.
1394 if (Known.isConstant())
1395 return;
1396
1397 // See what condition implies about the bits of the select arm.
1398 KnownBits CondRes(Known.getBitWidth());
1399 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1400 // If we don't get any information from the condition, no reason to
1401 // proceed.
1402 if (CondRes.isUnknown())
1403 return;
1404
1405 // We can have conflict if the condition is dead. I.e if we have
1406 // (x | 64) < 32 ? (x | 64) : y
1407 // we will have conflict at bit 6 from the condition/the `or`.
1408 // In that case just return. Its not particularly important
1409 // what we do, as this select is going to be simplified soon.
1410 CondRes = CondRes.unionWith(Known);
1411 if (CondRes.hasConflict())
1412 return;
1413
1414 // Finally make sure the information we found is valid. This is relatively
1415 // expensive so it's left for the very end.
1416 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1417 return;
1418
1419 // Finally, we know we get information from the condition and its valid,
1420 // so return it.
1421 Known = std::move(CondRes);
1422}
1423
1424// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1425// Returns the input and lower/upper bounds.
1426static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1427 const APInt *&CLow, const APInt *&CHigh) {
1429 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1430 "Input should be a Select!");
1431
1432 const Value *LHS = nullptr, *RHS = nullptr;
1434 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1435 return false;
1436
1437 if (!match(RHS, m_APInt(CLow)))
1438 return false;
1439
1440 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1442 if (getInverseMinMaxFlavor(SPF) != SPF2)
1443 return false;
1444
1445 if (!match(RHS2, m_APInt(CHigh)))
1446 return false;
1447
1448 if (SPF == SPF_SMIN)
1449 std::swap(CLow, CHigh);
1450
1451 In = LHS2;
1452 return CLow->sle(*CHigh);
1453}
1454
1456 const APInt *&CLow,
1457 const APInt *&CHigh) {
1458 assert((II->getIntrinsicID() == Intrinsic::smin ||
1459 II->getIntrinsicID() == Intrinsic::smax) &&
1460 "Must be smin/smax");
1461
1462 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1463 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1464 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1465 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1466 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1467 return false;
1468
1469 if (II->getIntrinsicID() == Intrinsic::smin)
1470 std::swap(CLow, CHigh);
1471 return CLow->sle(*CHigh);
1472}
1473
1475 KnownBits &Known) {
1476 const APInt *CLow, *CHigh;
1477 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1478 Known = Known.unionWith(
1479 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1480}
1481
1483 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1484 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1485 unsigned Depth) {
1486 // Change the context instruction to the "edge" that flows into the phi. This
1487 // is important because that is where the value is actually "evaluated" even
1488 // though it is used later somewhere else. (see also D69571).
1490 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1491
1492 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1493 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1494
1495 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1496 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1497}
1498
1500 const APInt &DemandedElts,
1502 const SimplifyQuery &Q,
1503 unsigned Depth) {
1504 unsigned BitWidth = Known.getBitWidth();
1505
1506 KnownBits Known2(BitWidth);
1507 switch (I->getOpcode()) {
1508 default: break;
1509 case Instruction::Load:
1510 if (MDNode *MD =
1511 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1513 break;
1514 case Instruction::And:
1515 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1516 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1517
1518 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1519 break;
1520 case Instruction::Or:
1521 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1522 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1523
1524 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1525 break;
1526 case Instruction::Xor:
1527 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1528 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1529
1530 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1531 break;
1532 case Instruction::Mul: {
1535 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1536 DemandedElts, Known, Known2, Q, Depth);
1537 break;
1538 }
1539 case Instruction::UDiv: {
1540 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1541 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1542 Known =
1544 break;
1545 }
1546 case Instruction::SDiv: {
1547 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1548 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1549 Known =
1551 break;
1552 }
1553 case Instruction::Select: {
1554 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1555 KnownBits Res(Known.getBitWidth());
1556 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1557 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1558 return Res;
1559 };
1560 // Only known if known in both the LHS and RHS.
1561 Known =
1562 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1563 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1564 break;
1565 }
1566 case Instruction::FPToSI: {
1567 // fptosi is poison if the rounded value doesn't fit in the result type,
1568 // so we can assume the conversion is well-defined and rounds towards
1569 // zero. +-Inf can never fit in an integer type, so it is always poison,
1570 // like NaN. Negative subnormals and negative zero round to 0. That
1571 // leaves negative normals as the only class that can produce a defined
1572 // negative result.
1573 KnownFPClass SrcFPClass = computeKnownFPClass(
1574 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1575 if (SrcFPClass.isKnownNever(fcNegNormal))
1576 Known.makeNonNegative();
1577 break;
1578 }
1579 case Instruction::FPTrunc:
1580 case Instruction::FPExt:
1581 case Instruction::FPToUI:
1582 case Instruction::SIToFP:
1583 case Instruction::UIToFP:
1584 break; // Can't work with floating point.
1585 case Instruction::PtrToInt:
1586 case Instruction::PtrToAddr:
1587 case Instruction::IntToPtr:
1588 // Fall through and handle them the same as zext/trunc.
1589 [[fallthrough]];
1590 case Instruction::ZExt:
1591 case Instruction::Trunc: {
1592 Type *SrcTy = I->getOperand(0)->getType();
1593
1594 unsigned SrcBitWidth;
1595 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1596 // which fall through here.
1597 Type *ScalarTy = SrcTy->getScalarType();
1598 SrcBitWidth = ScalarTy->isPointerTy() ?
1599 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1600 Q.DL.getTypeSizeInBits(ScalarTy);
1601
1602 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1603 Known = Known.anyextOrTrunc(SrcBitWidth);
1604 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1605 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1606 Inst && Inst->hasNonNeg() && !Known.isNegative())
1607 Known.makeNonNegative();
1608 Known = Known.zextOrTrunc(BitWidth);
1609 break;
1610 }
1611 case Instruction::BitCast: {
1612 Type *SrcTy = I->getOperand(0)->getType();
1613 if (SrcTy->isIntOrPtrTy() &&
1614 // TODO: For now, not handling conversions like:
1615 // (bitcast i64 %x to <2 x i32>)
1616 !I->getType()->isVectorTy()) {
1617 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1618 break;
1619 }
1620
1621 const Value *V;
1622 // Handle bitcast from floating point to integer.
1623 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1624 V->getType()->isFPOrFPVectorTy()) {
1625 Type *FPType = V->getType()->getScalarType();
1626 KnownFPClass Result =
1627 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1628
1629 Known = Result.toKnownBits(FPType->getFltSemantics());
1630
1631 break;
1632 }
1633
1634 // Handle cast from vector integer type to scalar or vector integer.
1635 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1636 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1637 !I->getType()->isIntOrIntVectorTy() ||
1638 isa<ScalableVectorType>(I->getType()))
1639 break;
1640
1641 unsigned NumElts = DemandedElts.getBitWidth();
1642 bool IsLE = Q.DL.isLittleEndian();
1643 // Look through a cast from narrow vector elements to wider type.
1644 // Examples: v4i32 -> v2i64, v3i8 -> v24
1645 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1646 if (BitWidth % SubBitWidth == 0) {
1647 // Known bits are automatically intersected across demanded elements of a
1648 // vector. So for example, if a bit is computed as known zero, it must be
1649 // zero across all demanded elements of the vector.
1650 //
1651 // For this bitcast, each demanded element of the output is sub-divided
1652 // across a set of smaller vector elements in the source vector. To get
1653 // the known bits for an entire element of the output, compute the known
1654 // bits for each sub-element sequentially. This is done by shifting the
1655 // one-set-bit demanded elements parameter across the sub-elements for
1656 // consecutive calls to computeKnownBits. We are using the demanded
1657 // elements parameter as a mask operator.
1658 //
1659 // The known bits of each sub-element are then inserted into place
1660 // (dependent on endian) to form the full result of known bits.
1661 unsigned SubScale = BitWidth / SubBitWidth;
1662 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1663 for (unsigned i = 0; i != NumElts; ++i) {
1664 if (DemandedElts[i])
1665 SubDemandedElts.setBit(i * SubScale);
1666 }
1667
1668 KnownBits KnownSrc(SubBitWidth);
1669 for (unsigned i = 0; i != SubScale; ++i) {
1670 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1671 Depth + 1);
1672 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1673 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1674 }
1675 }
1676 // Look through a cast from wider vector elements to narrow type.
1677 // Examples: v2i64 -> v4i32
1678 if (SubBitWidth % BitWidth == 0) {
1679 unsigned SubScale = SubBitWidth / BitWidth;
1680 KnownBits KnownSrc(SubBitWidth);
1681 APInt SubDemandedElts =
1682 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1683 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1684 Depth + 1);
1685
1686 Known.setAllConflict();
1687 for (unsigned i = 0; i != NumElts; ++i) {
1688 if (DemandedElts[i]) {
1689 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1690 unsigned Offset = (Shifts % SubScale) * BitWidth;
1691 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1692 if (Known.isUnknown())
1693 break;
1694 }
1695 }
1696 }
1697 break;
1698 }
1699 case Instruction::SExt: {
1700 // Compute the bits in the result that are not present in the input.
1701 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1702
1703 Known = Known.trunc(SrcBitWidth);
1704 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1705 // If the sign bit of the input is known set or clear, then we know the
1706 // top bits of the result.
1707 Known = Known.sext(BitWidth);
1708 break;
1709 }
1710 case Instruction::Shl: {
1713 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1714 bool ShAmtNonZero) {
1715 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1716 };
1717 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1718 KF);
1719 // X << X is even: X is either zero or shifts by at least one bit. Both
1720 // uses must observe the same value, so X must not be undef.
1721 if (I->getOperand(0) == I->getOperand(1) &&
1722 isGuaranteedNotToBeUndef(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
1723 Depth + 1))
1724 Known.Zero.setBit(0);
1725
1726 // Trailing zeros of a right-shifted constant never decrease.
1727 const APInt *C;
1728 if (match(I->getOperand(0), m_APInt(C)))
1729 Known.Zero.setLowBits(C->countr_zero());
1730
1731 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1732 // lands at bit Y, when BitWidth is a power of 2.
1733 const APInt *YC;
1734 Value *X = I->getOperand(0);
1735 if (isPowerOf2_32(BitWidth) &&
1736 match(I->getOperand(1),
1738 m_SpecificInt(BitWidth - 1)))) &&
1739 YC->ult(BitWidth - 1)) {
1740 unsigned Y = YC->getZExtValue();
1741 Known.One.setBit(Y);
1742 Known.Zero.setBitsFrom(Y + 1);
1743 }
1744 break;
1745 }
1746 case Instruction::LShr: {
1747 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1748 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1749 bool ShAmtNonZero) {
1750 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1751 };
1752 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1753 KF);
1754 // Leading zeros of a left-shifted constant never decrease.
1755 const APInt *C;
1756 if (match(I->getOperand(0), m_APInt(C)))
1757 Known.Zero.setHighBits(C->countl_zero());
1758 break;
1759 }
1760 case Instruction::AShr: {
1761 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1762 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1763 bool ShAmtNonZero) {
1764 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1765 };
1766 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1767 KF);
1768 break;
1769 }
1770 case Instruction::Sub: {
1773 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1774 DemandedElts, Known, Known2, Q, Depth);
1775 break;
1776 }
1777 case Instruction::Add: {
1780 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1781 DemandedElts, Known, Known2, Q, Depth);
1782 break;
1783 }
1784 case Instruction::SRem:
1785 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1786 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1787 Known = KnownBits::srem(Known, Known2);
1788 break;
1789
1790 case Instruction::URem:
1791 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1792 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1793 Known = KnownBits::urem(Known, Known2);
1794 break;
1795 case Instruction::Alloca:
1796 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1797 break;
1798 case Instruction::GetElementPtr: {
1799 // Analyze all of the subscripts of this getelementptr instruction
1800 // to determine if we can prove known low zero bits.
1801 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1802 // Accumulate the constant indices in a separate variable
1803 // to minimize the number of calls to computeForAddSub.
1804 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1805 APInt AccConstIndices(IndexWidth, 0);
1806
1807 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1808 if (IndexWidth == BitWidth) {
1809 // Note that inbounds does *not* guarantee nsw for the addition, as only
1810 // the offset is signed, while the base address is unsigned.
1811 Known = KnownBits::add(Known, IndexBits);
1812 } else {
1813 // If the index width is smaller than the pointer width, only add the
1814 // value to the low bits.
1815 assert(IndexWidth < BitWidth &&
1816 "Index width can't be larger than pointer width");
1817 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1818 }
1819 };
1820
1822 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1823 // TrailZ can only become smaller, short-circuit if we hit zero.
1824 if (Known.isUnknown())
1825 break;
1826
1827 Value *Index = I->getOperand(i);
1828
1829 // Handle case when index is zero.
1830 Constant *CIndex = dyn_cast<Constant>(Index);
1831 if (CIndex && CIndex->isNullValue())
1832 continue;
1833
1834 if (StructType *STy = GTI.getStructTypeOrNull()) {
1835 // Handle struct member offset arithmetic.
1836
1837 assert(CIndex &&
1838 "Access to structure field must be known at compile time");
1839
1840 if (CIndex->getType()->isVectorTy())
1841 Index = CIndex->getSplatValue();
1842
1843 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1844 const StructLayout *SL = Q.DL.getStructLayout(STy);
1845 uint64_t Offset = SL->getElementOffset(Idx);
1846 AccConstIndices += Offset;
1847 continue;
1848 }
1849
1850 // Handle array index arithmetic.
1851 Type *IndexedTy = GTI.getIndexedType();
1852 if (!IndexedTy->isSized()) {
1853 Known.resetAll();
1854 break;
1855 }
1856
1857 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1858 uint64_t StrideInBytes = Stride.getKnownMinValue();
1859 if (!Stride.isScalable()) {
1860 // Fast path for constant offset.
1861 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1862 AccConstIndices +=
1863 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1864 continue;
1865 }
1866 }
1867
1868 KnownBits IndexBits =
1869 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1870 KnownBits ScalingFactor(IndexWidth);
1871 // Multiply by current sizeof type.
1872 // &A[i] == A + i * sizeof(*A[i]).
1873 if (Stride.isScalable()) {
1874 // For scalable types the only thing we know about sizeof is
1875 // that this is a multiple of the minimum size.
1876 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1877 } else {
1878 ScalingFactor =
1879 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1880 }
1881 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1882 }
1883 if (!Known.isUnknown() && !AccConstIndices.isZero())
1884 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1885 break;
1886 }
1887 case Instruction::PHI: {
1888 const PHINode *P = cast<PHINode>(I);
1889 BinaryOperator *BO = nullptr;
1890 Value *Start = nullptr, *Step = nullptr;
1891 KnownBits &KnownStart = Known2;
1892 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1893 // Handle the case of a simple two-predecessor recurrence PHI.
1894 // There's a lot more that could theoretically be done here, but
1895 // this is sufficient to catch some interesting cases.
1896 unsigned Opcode = BO->getOpcode();
1897
1898 switch (Opcode) {
1899 // If this is a shift recurrence, we know the bits being shifted in. We
1900 // can combine that with information about the start value of the
1901 // recurrence to conclude facts about the result. If this is a udiv
1902 // recurrence, we know that the result can never exceed either the
1903 // numerator or the start value, whichever is greater.
1904 case Instruction::LShr:
1905 case Instruction::AShr:
1906 case Instruction::Shl:
1907 case Instruction::UDiv:
1908 if (BO->getOperand(0) != I)
1909 break;
1910 [[fallthrough]];
1911
1912 // For a urem recurrence, the result can never exceed the start value. The
1913 // phi could either be the numerator or the denominator.
1914 case Instruction::URem: {
1915 // We have matched a recurrence of the form:
1916 // %iv = [R, %entry], [%iv.next, %backedge]
1917 // %iv.next = shift_op %iv, L
1918
1919 // Recurse with the phi context to avoid concern about whether facts
1920 // inferred hold at original context instruction. TODO: It may be
1921 // correct to use the original context. IF warranted, explore and
1922 // add sufficient tests to cover.
1924 RecQ.CtxI = P;
1925 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1926 switch (Opcode) {
1927 case Instruction::Shl:
1928 // A shl recurrence will only increase the tailing zeros
1929 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1930 break;
1931 case Instruction::LShr:
1932 case Instruction::UDiv:
1933 case Instruction::URem:
1934 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1935 // the start value.
1936 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1937 break;
1938 case Instruction::AShr:
1939 // An ashr recurrence will extend the initial sign bit
1940 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1941 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1942 break;
1943 }
1944 break;
1945 }
1946
1947 case Instruction::And: {
1948 // Bits that are zero in the start value stay zero, and bits that are
1949 // one in both the start value and the step stay one.
1950 KnownBits KnownStep(BitWidth);
1951 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1952 KnownStart, KnownStep, Q, Depth);
1953 Known.Zero |= KnownStart.Zero;
1954 Known.One |= KnownStart.One & KnownStep.One;
1955 break;
1956 }
1957
1958 case Instruction::Or: {
1959 // Bits that are zero in both the start value and the step stay zero,
1960 // and bits that are one in the start value stay one.
1961 KnownBits KnownStep(BitWidth);
1962 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1963 KnownStart, KnownStep, Q, Depth);
1964 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
1965 Known.One |= KnownStart.One;
1966 break;
1967 }
1968
1969 // Check for operations that have the property that if
1970 // both their operands have low zero bits, the result
1971 // will have low zero bits.
1972 case Instruction::Add:
1973 case Instruction::Sub:
1974 case Instruction::Mul: {
1975 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1976 // zero bits.
1977 KnownBits KnownStep(BitWidth);
1978 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1979 KnownStart, KnownStep, Q, Depth);
1980
1981 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1982 KnownStep.countMinTrailingZeros()));
1983
1984 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1985 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1986 break;
1987
1988 switch (Opcode) {
1989 // If initial value of recurrence is nonnegative, and we are adding
1990 // a nonnegative number with nsw, the result can only be nonnegative
1991 // or poison value regardless of the number of times we execute the
1992 // add in phi recurrence. If initial value is negative and we are
1993 // adding a negative number with nsw, the result can only be
1994 // negative or poison value. Similar arguments apply to sub and mul.
1995 //
1996 // (add non-negative, non-negative) --> non-negative
1997 // (add negative, negative) --> negative
1998 case Instruction::Add: {
1999 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2000 Known.makeNonNegative();
2001 else if (KnownStart.isNegative() && KnownStep.isNegative())
2002 Known.makeNegative();
2003 break;
2004 }
2005
2006 // (sub nsw non-negative, negative) --> non-negative
2007 // (sub nsw negative, non-negative) --> negative
2008 case Instruction::Sub: {
2009 if (BO->getOperand(0) != I)
2010 break;
2011 if (KnownStart.isNonNegative() && KnownStep.isNegative())
2012 Known.makeNonNegative();
2013 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
2014 Known.makeNegative();
2015 break;
2016 }
2017
2018 // (mul nsw non-negative, non-negative) --> non-negative
2019 case Instruction::Mul:
2020 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2021 Known.makeNonNegative();
2022 break;
2023
2024 default:
2025 break;
2026 }
2027 break;
2028 }
2029
2030 default:
2031 break;
2032 }
2033 } else {
2034 IntrinsicInst *II = nullptr;
2035 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2036 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2037 //
2038 // %iv.next = <II>(%iv, <Step>)
2039 // or
2040 // %iv.next = <II>(<Step>, %iv)
2041 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2042 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2043 KnownBits KnownStep(BitWidth);
2045 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2046
2047 if (IntrinsicID == Intrinsic::umin) {
2048 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2049 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2050 KnownStep.countMinLeadingOnes()));
2051 } else {
2052 // umax
2053 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2054 KnownStep.countMinLeadingZeros()));
2055 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2056 }
2057 }
2058 }
2059 }
2060
2061 // Unreachable blocks may have zero-operand PHI nodes.
2062 if (P->getNumIncomingValues() == 0)
2063 break;
2064
2065 // Otherwise take the unions of the known bit sets of the operands,
2066 // taking conservative care to avoid excessive recursion.
2067 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2068 // Skip if every incoming value references to ourself.
2069 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2070 break;
2071
2072 Known.setAllConflict();
2073 for (const Use &U : P->operands()) {
2074 Value *IncValue;
2075 const PHINode *CtxPhi;
2076 Instruction *CtxI;
2077 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2078 // Skip direct self references.
2079 if (IncValue == P)
2080 continue;
2081
2082 // Change the context instruction to the "edge" that flows into the
2083 // phi. This is important because that is where the value is actually
2084 // "evaluated" even though it is used later somewhere else. (see also
2085 // D69571).
2087
2088 Known2 = KnownBits(BitWidth);
2089
2090 // Recurse, but cap the recursion to one level, because we don't
2091 // want to waste time spinning around in loops.
2092 // TODO: See if we can base recursion limiter on number of incoming phi
2093 // edges so we don't overly clamp analysis.
2094 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2096
2097 // See if we can further use a conditional branch into the phi
2098 // to help us determine the range of the value.
2099 if (!Known2.isConstant()) {
2100 CmpPredicate Pred;
2101 const APInt *RHSC;
2102 BasicBlock *TrueSucc, *FalseSucc;
2103 // TODO: Use RHS Value and compute range from its known bits.
2104 if (match(RecQ.CtxI,
2105 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2106 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2107 // Check for cases of duplicate successors.
2108 if ((TrueSucc == CtxPhi->getParent()) !=
2109 (FalseSucc == CtxPhi->getParent())) {
2110 // If we're using the false successor, invert the predicate.
2111 if (FalseSucc == CtxPhi->getParent())
2112 Pred = CmpInst::getInversePredicate(Pred);
2113 // Get the knownbits implied by the incoming phi condition.
2114 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2115 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2116 // We can have conflicts here if we are analyzing deadcode (its
2117 // impossible for us reach this BB based the icmp).
2118 if (KnownUnion.hasConflict()) {
2119 // No reason to continue analyzing in a known dead region, so
2120 // just resetAll and break. This will cause us to also exit the
2121 // outer loop.
2122 Known.resetAll();
2123 break;
2124 }
2125 Known2 = KnownUnion;
2126 }
2127 }
2128 }
2129
2130 Known = Known.intersectWith(Known2);
2131 // If all bits have been ruled out, there's no need to check
2132 // more operands.
2133 if (Known.isUnknown())
2134 break;
2135 }
2136 }
2137 break;
2138 }
2139 case Instruction::Call:
2140 case Instruction::Invoke: {
2141 // If range metadata is attached to this call, set known bits from that,
2142 // and then intersect with known bits based on other properties of the
2143 // function.
2144 if (MDNode *MD =
2145 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2147
2148 const auto *CB = cast<CallBase>(I);
2149
2150 if (std::optional<ConstantRange> Range = CB->getRange())
2151 Known = Known.unionWith(Range->toKnownBits());
2152
2153 if (const Value *RV = CB->getReturnedArgOperand()) {
2154 if (RV->getType() == I->getType()) {
2155 computeKnownBits(RV, Known2, Q, Depth + 1);
2156 Known = Known.unionWith(Known2);
2157 // If the function doesn't return properly for all input values
2158 // (e.g. unreachable exits) then there might be conflicts between the
2159 // argument value and the range metadata. Simply discard the known bits
2160 // in case of conflicts.
2161 if (Known.hasConflict())
2162 Known.resetAll();
2163 }
2164 }
2165 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2166 switch (II->getIntrinsicID()) {
2167 default:
2168 break;
2169 case Intrinsic::abs: {
2170 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2171 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2172 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2173 break;
2174 }
2175 case Intrinsic::bitreverse:
2176 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2177 Known = Known.unionWith(Known2.reverseBits());
2178 break;
2179 case Intrinsic::bswap:
2180 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2181 Known = Known.unionWith(Known2.byteSwap());
2182 break;
2183 case Intrinsic::ctlz: {
2184 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2185 // If we have a known 1, its position is our upper bound.
2186 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2187 // If this call is poison for 0 input, the result will be less than 2^n.
2188 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2189 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2190 unsigned LowBits = llvm::bit_width(PossibleLZ);
2191 Known.Zero.setBitsFrom(LowBits);
2192 break;
2193 }
2194 case Intrinsic::cttz: {
2195 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2196 // If we have a known 1, its position is our upper bound.
2197 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2198 // If this call is poison for 0 input, the result will be less than 2^n.
2199 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2200 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2201 unsigned LowBits = llvm::bit_width(PossibleTZ);
2202 Known.Zero.setBitsFrom(LowBits);
2203 break;
2204 }
2205 case Intrinsic::ctpop: {
2206 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2207 // We can bound the space the count needs. Also, bits known to be zero
2208 // can't contribute to the population.
2209 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2210 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2211 Known.Zero.setBitsFrom(LowBits);
2212 // TODO: we could bound KnownOne using the lower bound on the number
2213 // of bits which might be set provided by popcnt KnownOne2.
2214 break;
2215 }
2216 case Intrinsic::fshr:
2217 case Intrinsic::fshl: {
2218 const APInt *SA;
2219 if (!match(I->getOperand(2), m_APInt(SA)))
2220 break;
2221
2222 KnownBits Known3(BitWidth);
2223 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2224 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2225 Known = II->getIntrinsicID() == Intrinsic::fshl
2226 ? KnownBits::fshl(Known2, Known3, *SA)
2227 : KnownBits::fshr(Known2, Known3, *SA);
2228 break;
2229 }
2230 case Intrinsic::clmul:
2231 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2232 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2233 Known = KnownBits::clmul(Known, Known2);
2234 break;
2235 case Intrinsic::pext:
2236 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2237 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2238 Known = KnownBits::pext(Known, Known2);
2239 break;
2240 case Intrinsic::pdep:
2241 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2242 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2243 Known = KnownBits::pdep(Known, Known2);
2244 break;
2245 case Intrinsic::smulh:
2246 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2247 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2248 Known = KnownBits::mulhs(Known, Known2);
2249 break;
2250 case Intrinsic::umulh:
2251 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2252 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2253 Known = KnownBits::mulhu(Known, Known2);
2254 break;
2255 case Intrinsic::uadd_sat:
2256 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2257 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2258 Known = KnownBits::uadd_sat(Known, Known2);
2259 break;
2260 case Intrinsic::usub_sat:
2261 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2262 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2263 Known = KnownBits::usub_sat(Known, Known2);
2264 break;
2265 case Intrinsic::sadd_sat:
2266 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2267 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2268 Known = KnownBits::sadd_sat(Known, Known2);
2269 break;
2270 case Intrinsic::ssub_sat:
2271 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2272 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2273 Known = KnownBits::ssub_sat(Known, Known2);
2274 break;
2275 // Vec reverse preserves bits from input vec.
2276 case Intrinsic::vector_reverse:
2277 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2278 Depth + 1);
2279 break;
2280 // for min/max/and/or reduce, any bit common to each element in the
2281 // input vec is set in the output.
2282 case Intrinsic::vector_reduce_and:
2283 case Intrinsic::vector_reduce_or:
2284 case Intrinsic::vector_reduce_umax:
2285 case Intrinsic::vector_reduce_umin:
2286 case Intrinsic::vector_reduce_smax:
2287 case Intrinsic::vector_reduce_smin:
2288 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2289 break;
2290 case Intrinsic::vector_reduce_xor: {
2291 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2292 // The zeros common to all vecs are zero in the output.
2293 // If the number of elements is odd, then the common ones remain. If the
2294 // number of elements is even, then the common ones becomes zeros.
2295 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2296 // Even, so the ones become zeros.
2297 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2298 if (EvenCnt)
2299 Known.Zero |= Known.One;
2300 // Maybe even element count so need to clear ones.
2301 if (VecTy->isScalableTy() || EvenCnt)
2302 Known.One.clearAllBits();
2303 break;
2304 }
2305 case Intrinsic::vector_reduce_add: {
2306 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2307 if (!VecTy)
2308 break;
2309 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2310 Known = Known.reduceAdd(VecTy->getNumElements());
2311 break;
2312 }
2313 case Intrinsic::umin:
2314 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2315 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2316 Known = KnownBits::umin(Known, Known2);
2317 break;
2318 case Intrinsic::umax:
2319 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2320 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2321 Known = KnownBits::umax(Known, Known2);
2322 break;
2323 case Intrinsic::smin:
2324 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2325 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2326 Known = KnownBits::smin(Known, Known2);
2328 break;
2329 case Intrinsic::smax:
2330 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2331 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2332 Known = KnownBits::smax(Known, Known2);
2334 break;
2335 case Intrinsic::ptrmask: {
2336 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2337
2338 const Value *Mask = I->getOperand(1);
2339 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2340 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2341 // TODO: 1-extend would be more precise.
2342 Known &= Known2.anyextOrTrunc(BitWidth);
2343 break;
2344 }
2345 case Intrinsic::x86_sse42_crc32_64_64:
2346 Known.Zero.setBitsFrom(32);
2347 break;
2348 case Intrinsic::x86_ssse3_phadd_d_128:
2349 case Intrinsic::x86_ssse3_phadd_w_128:
2350 case Intrinsic::x86_avx2_phadd_d:
2351 case Intrinsic::x86_avx2_phadd_w: {
2353 I, DemandedElts, Q, Depth,
2354 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2355 return KnownBits::add(KnownLHS, KnownRHS);
2356 });
2357 break;
2358 }
2359 case Intrinsic::x86_ssse3_phadd_sw_128:
2360 case Intrinsic::x86_avx2_phadd_sw: {
2362 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2363 break;
2364 }
2365 case Intrinsic::x86_ssse3_phsub_d_128:
2366 case Intrinsic::x86_ssse3_phsub_w_128:
2367 case Intrinsic::x86_avx2_phsub_d:
2368 case Intrinsic::x86_avx2_phsub_w: {
2370 I, DemandedElts, Q, Depth,
2371 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2372 return KnownBits::sub(KnownLHS, KnownRHS);
2373 });
2374 break;
2375 }
2376 case Intrinsic::x86_ssse3_phsub_sw_128:
2377 case Intrinsic::x86_avx2_phsub_sw: {
2379 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2380 break;
2381 }
2382 case Intrinsic::riscv_vsetvli:
2383 case Intrinsic::riscv_vsetvlimax: {
2384 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2385 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2387 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2388 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2389 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2390 uint64_t MaxVLEN =
2391 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2392 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2393
2394 // Result of vsetvli must be not larger than AVL.
2395 if (HasAVL)
2396 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2397 MaxVL = std::min(MaxVL, CI->getZExtValue());
2398
2399 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2400 if (BitWidth > KnownZeroFirstBit)
2401 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2402 break;
2403 }
2404 case Intrinsic::amdgcn_mbcnt_hi:
2405 case Intrinsic::amdgcn_mbcnt_lo: {
2406 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2407 // most 31 + src1.
2408 KnownBits MbcntKnown(BitWidth);
2409 MbcntKnown.Zero.setBitsFrom(
2410 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2411 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2412 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2413 break;
2414 }
2415 case Intrinsic::vscale: {
2416 if (!II->getParent() || !II->getFunction())
2417 break;
2418
2419 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2420 break;
2421 }
2422 case Intrinsic::stepvector: {
2423 auto *VecTy = cast<VectorType>(II->getType());
2424 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2425 if (!isUIntN(BitWidth, MinNumElts))
2426 break;
2427
2428 bool Overflow = false;
2429 APInt MaxNumElts(BitWidth, MinNumElts);
2430 if (VecTy->isScalableTy()) {
2431 if (!II->getParent() || !II->getFunction())
2432 break;
2433 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2435 .umul_ov(MaxNumElts, Overflow);
2436 }
2437
2438 // Give up if the lane count could wrap. Stepvector truncates lane
2439 // indices that do not fit in the element type.
2440 if (Overflow)
2441 break;
2442
2443 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2444 break;
2445 }
2446 }
2447 }
2448 break;
2449 }
2450 case Instruction::ShuffleVector: {
2451 if (auto *Splat = getSplatValue(I)) {
2453 break;
2454 }
2455
2456 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2457 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2458 if (!Shuf) {
2459 Known.resetAll();
2460 return;
2461 }
2462 // For undef elements, we don't know anything about the common state of
2463 // the shuffle result.
2464 APInt DemandedLHS, DemandedRHS;
2465 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2466 Known.resetAll();
2467 return;
2468 }
2469 Known.setAllConflict();
2470 if (!!DemandedLHS) {
2471 const Value *LHS = Shuf->getOperand(0);
2472 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2473 // If we don't know any bits, early out.
2474 if (Known.isUnknown())
2475 break;
2476 }
2477 if (!!DemandedRHS) {
2478 const Value *RHS = Shuf->getOperand(1);
2479 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2480 Known = Known.intersectWith(Known2);
2481 }
2482 break;
2483 }
2484 case Instruction::InsertElement: {
2485 if (isa<ScalableVectorType>(I->getType())) {
2486 Known.resetAll();
2487 return;
2488 }
2489 const Value *Vec = I->getOperand(0);
2490 const Value *Elt = I->getOperand(1);
2491 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2492 unsigned NumElts = DemandedElts.getBitWidth();
2493 APInt DemandedVecElts = DemandedElts;
2494 bool NeedsElt = true;
2495 // If we know the index we are inserting too, clear it from Vec check.
2496 if (CIdx && CIdx->getValue().ult(NumElts)) {
2497 DemandedVecElts.clearBit(CIdx->getZExtValue());
2498 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2499 }
2500
2501 Known.setAllConflict();
2502 if (NeedsElt) {
2503 computeKnownBits(Elt, Known, Q, Depth + 1);
2504 // If we don't know any bits, early out.
2505 if (Known.isUnknown())
2506 break;
2507 }
2508
2509 if (!DemandedVecElts.isZero()) {
2510 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2511 Known = Known.intersectWith(Known2);
2512 }
2513 break;
2514 }
2515 case Instruction::ExtractElement: {
2516 // Look through extract element. If the index is non-constant or
2517 // out-of-range demand all elements, otherwise just the extracted element.
2518 const Value *Vec = I->getOperand(0);
2519 const Value *Idx = I->getOperand(1);
2520 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2521 if (isa<ScalableVectorType>(Vec->getType())) {
2522 // FIXME: there's probably *something* we can do with scalable vectors
2523 Known.resetAll();
2524 break;
2525 }
2526 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2527 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2528 if (CIdx && CIdx->getValue().ult(NumElts))
2529 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2530 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2531 break;
2532 }
2533 case Instruction::ExtractValue:
2534 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2536 if (EVI->getNumIndices() != 1) break;
2537 if (EVI->getIndices()[0] == 0) {
2538 switch (II->getIntrinsicID()) {
2539 default: break;
2540 case Intrinsic::uadd_with_overflow:
2541 case Intrinsic::sadd_with_overflow:
2543 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2544 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2545 break;
2546 case Intrinsic::usub_with_overflow:
2547 case Intrinsic::ssub_with_overflow:
2549 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2550 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2551 break;
2552 case Intrinsic::umul_with_overflow:
2553 case Intrinsic::smul_with_overflow:
2554 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2555 false, DemandedElts, Known, Known2, Q, Depth);
2556 break;
2557 }
2558 }
2559 }
2560 break;
2561 case Instruction::Freeze:
2562 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2563 Depth + 1))
2564 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2565 break;
2566 }
2567}
2568
2569/// Determine which bits of V are known to be either zero or one and return
2570/// them.
2571KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2572 const SimplifyQuery &Q, unsigned Depth) {
2573 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2574 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2575 return Known;
2576}
2577
2578/// Determine which bits of V are known to be either zero or one and return
2579/// them.
2581 unsigned Depth) {
2582 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2584 return Known;
2585}
2586
2587/// Determine which bits of V are known to be either zero or one and return
2588/// them in the Known bit set.
2589///
2590/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2591/// we cannot optimize based on the assumption that it is zero without changing
2592/// it to be an explicit zero. If we don't change it to zero, other code could
2593/// optimized based on the contradictory assumption that it is non-zero.
2594/// Because instcombine aggressively folds operations with undef args anyway,
2595/// this won't lose us code quality.
2596///
2597/// This function is defined on values with integer type, values with pointer
2598/// type, and vectors of integers. In the case
2599/// where V is a vector, known zero, and known one values are the
2600/// same width as the vector element, and the bit is set only if it is true
2601/// for all of the demanded elements in the vector specified by DemandedElts.
2602void computeKnownBits(const Value *V, const APInt &DemandedElts,
2603 KnownBits &Known, const SimplifyQuery &Q,
2604 unsigned Depth) {
2605 if (!DemandedElts) {
2606 // No demanded elts, better to assume we don't know anything.
2607 Known.resetAll();
2608 return;
2609 }
2610
2611 assert(V && "No Value?");
2612 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2613
2614#ifndef NDEBUG
2615 Type *Ty = V->getType();
2616 unsigned BitWidth = Known.getBitWidth();
2617
2618 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2619 "Not integer or pointer type!");
2620
2621 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2622 assert(
2623 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2624 "DemandedElt width should equal the fixed vector number of elements");
2625 } else {
2626 assert(DemandedElts == APInt(1, 1) &&
2627 "DemandedElt width should be 1 for scalars or scalable vectors");
2628 }
2629
2630 Type *ScalarTy = Ty->getScalarType();
2631 if (ScalarTy->isPointerTy()) {
2632 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2633 "V and Known should have same BitWidth");
2634 } else {
2635 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2636 "V and Known should have same BitWidth");
2637 }
2638#endif
2639
2640 const APInt *C;
2641 if (match(V, m_APInt(C))) {
2642 // We know all of the bits for a scalar constant or a splat vector constant!
2644 return;
2645 }
2646 // Null and aggregate-zero are all-zeros.
2648 Known.setAllZero();
2649 return;
2650 }
2651 // Handle a constant vector by taking the intersection of the known bits of
2652 // each element.
2654 assert(!isa<ScalableVectorType>(V->getType()));
2655 // We know that CDV must be a vector of integers. Take the intersection of
2656 // each element.
2657 Known.setAllConflict();
2658 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2659 if (!DemandedElts[i])
2660 continue;
2661 APInt Elt = CDV->getElementAsAPInt(i);
2662 Known.Zero &= ~Elt;
2663 Known.One &= Elt;
2664 }
2665 if (Known.hasConflict())
2666 Known.resetAll();
2667 return;
2668 }
2669
2670 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2671 assert(!isa<ScalableVectorType>(V->getType()));
2672 // We know that CV must be a vector of integers. Take the intersection of
2673 // each element.
2674 Known.setAllConflict();
2675 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2676 if (!DemandedElts[i])
2677 continue;
2678 Constant *Element = CV->getAggregateElement(i);
2679 if (isa<PoisonValue>(Element))
2680 continue;
2681 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2682 if (!ElementCI) {
2683 Known.resetAll();
2684 return;
2685 }
2686 const APInt &Elt = ElementCI->getValue();
2687 Known.Zero &= ~Elt;
2688 Known.One &= Elt;
2689 }
2690 if (Known.hasConflict())
2691 Known.resetAll();
2692 return;
2693 }
2694
2695 // Start out not knowing anything.
2696 Known.resetAll();
2697
2698 // We can't imply anything about undefs.
2699 if (isa<UndefValue>(V))
2700 return;
2701
2702 // There's no point in looking through other users of ConstantData for
2703 // assumptions. Confirm that we've handled them all.
2704 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2705
2706 if (const auto *A = dyn_cast<Argument>(V))
2707 if (std::optional<ConstantRange> Range = A->getRange())
2708 Known = Range->toKnownBits();
2709
2710 // All recursive calls that increase depth must come after this.
2712 return;
2713
2714 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2715 // the bits of its aliasee.
2716 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2717 if (!GA->isInterposable())
2718 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2719 return;
2720 }
2721
2722 if (const Operator *I = dyn_cast<Operator>(V))
2723 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2724 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2725 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2726 Known = CR->toKnownBits();
2727 }
2728
2729 // Aligned pointers have trailing zeros - refine Known.Zero set
2730 if (isa<PointerType>(V->getType())) {
2731 Align Alignment = V->getPointerAlignment(Q.DL);
2732 Known.Zero.setLowBits(Log2(Alignment));
2733 }
2734
2735 // computeKnownBitsFromContext strictly refines Known.
2736 // Therefore, we run them after computeKnownBitsFromOperator.
2737
2738 // Check whether we can determine known bits from context such as assumes.
2740}
2741
2742/// Try to detect a recurrence that the value of the induction variable is
2743/// always a power of two (or zero).
2744static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2745 SimplifyQuery &Q, unsigned Depth) {
2746 BinaryOperator *BO = nullptr;
2747 Value *Start = nullptr, *Step = nullptr;
2748 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2749 return false;
2750
2751 // Initial value must be a power of two.
2752 for (const Use &U : PN->operands()) {
2753 if (U.get() == Start) {
2754 // Initial value comes from a different BB, need to adjust context
2755 // instruction for analysis.
2756 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2757 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2758 return false;
2759 }
2760 }
2761
2762 // Except for Mul, the induction variable must be on the left side of the
2763 // increment expression, otherwise its value can be arbitrary.
2764 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2765 return false;
2766
2767 Q.CtxI = BO->getParent()->getTerminator();
2768 switch (BO->getOpcode()) {
2769 case Instruction::Mul:
2770 // Power of two is closed under multiplication.
2771 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2772 Q.IIQ.hasNoSignedWrap(BO)) &&
2773 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2774 case Instruction::SDiv:
2775 // Start value must not be signmask for signed division, so simply being a
2776 // power of two is not sufficient, and it has to be a constant.
2777 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2778 return false;
2779 [[fallthrough]];
2780 case Instruction::UDiv:
2781 // Divisor must be a power of two.
2782 // If OrZero is false, cannot guarantee induction variable is non-zero after
2783 // division, same for Shr, unless it is exact division.
2784 return (OrZero || Q.IIQ.isExact(BO)) &&
2785 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2786 case Instruction::Shl:
2787 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2788 case Instruction::AShr:
2789 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2790 return false;
2791 [[fallthrough]];
2792 case Instruction::LShr:
2793 return OrZero || Q.IIQ.isExact(BO);
2794 default:
2795 return false;
2796 }
2797}
2798
2799/// Return true if we can infer that \p V is known to be a power of 2 from
2800/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2801static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2802 const Value *Cond,
2803 bool CondIsTrue) {
2804 CmpPredicate Pred;
2805 const APInt *RHSC;
2806 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2807 return false;
2808 if (!CondIsTrue)
2809 Pred = ICmpInst::getInversePredicate(Pred);
2810 // ctpop(V) u< 2
2811 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2812 return true;
2813 // ctpop(V) == 1
2814 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2815}
2816
2817/// Return true if the given value is known to have exactly one
2818/// bit set when defined. For vectors return true if every element is known to
2819/// be a power of two when defined. Supports values with integer or pointer
2820/// types and vectors of integers.
2821bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2822 const SimplifyQuery &Q, unsigned Depth) {
2823 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2824
2825 if (isa<Constant>(V))
2826 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2827
2828 // i1 is by definition a power of 2 or zero.
2829 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2830 return true;
2831
2832 // Try to infer from assumptions.
2833 if (Q.AC && Q.CtxI) {
2834 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2835 if (!AssumeVH)
2836 continue;
2837 CallInst *I = cast<CallInst>(AssumeVH);
2838 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2839 /*CondIsTrue=*/true) &&
2841 return true;
2842 }
2843 }
2844
2845 // Handle dominating conditions.
2846 if (Q.DC && Q.CtxI && Q.DT) {
2847 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2848 Value *Cond = BI->getCondition();
2849
2850 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2852 /*CondIsTrue=*/true) &&
2853 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2854 return true;
2855
2856 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2858 /*CondIsTrue=*/false) &&
2859 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2860 return true;
2861 }
2862 }
2863
2864 auto *I = dyn_cast<Instruction>(V);
2865 if (!I)
2866 return false;
2867
2868 if (Q.CtxI && match(V, m_VScale())) {
2869 const Function *F = Q.CtxI->getFunction();
2870 // The vscale_range indicates vscale is a power-of-two.
2871 return F->hasFnAttribute(Attribute::VScaleRange);
2872 }
2873
2874 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2875 // it is shifted off the end then the result is undefined.
2876 if (match(I, m_Shl(m_One(), m_Value())))
2877 return true;
2878
2879 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2880 // the bottom. If it is shifted off the bottom then the result is undefined.
2881 if (match(I, m_LShr(m_SignMask(), m_Value())))
2882 return true;
2883
2884 // The remaining tests are all recursive, so bail out if we hit the limit.
2886 return false;
2887
2888 switch (I->getOpcode()) {
2889 case Instruction::ZExt:
2890 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2891 case Instruction::Trunc:
2892 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2893 case Instruction::Shl:
2894 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2895 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2896 return false;
2897 case Instruction::LShr:
2898 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2899 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2900 return false;
2901 case Instruction::UDiv:
2903 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2904 return false;
2905 case Instruction::Mul:
2906 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2907 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2908 (OrZero || isKnownNonZero(I, Q, Depth));
2909 case Instruction::And:
2910 // A power of two and'd with anything is a power of two or zero.
2911 if (OrZero &&
2912 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2913 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2914 return true;
2915 // X & (-X) is always a power of two or zero.
2916 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2917 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2918 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2919 return false;
2920 case Instruction::Add: {
2921 // Adding a power-of-two or zero to the same power-of-two or zero yields
2922 // either the original power-of-two, a larger power-of-two or zero.
2924 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2925 Q.IIQ.hasNoSignedWrap(VOBO)) {
2926 if (match(I->getOperand(0),
2927 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2928 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2929 return true;
2930 if (match(I->getOperand(1),
2931 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2932 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2933 return true;
2934
2935 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2936 KnownBits LHSBits(BitWidth);
2937 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2938
2939 KnownBits RHSBits(BitWidth);
2940 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2941 // If i8 V is a power of two or zero:
2942 // ZeroBits: 1 1 1 0 1 1 1 1
2943 // ~ZeroBits: 0 0 0 1 0 0 0 0
2944 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2945 // If OrZero isn't set, we cannot give back a zero result.
2946 // Make sure either the LHS or RHS has a bit set.
2947 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2948 return true;
2949 }
2950
2951 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2952 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2953 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2954 return true;
2955 return false;
2956 }
2957 case Instruction::Select:
2958 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2959 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2960 case Instruction::PHI: {
2961 // A PHI node is power of two if all incoming values are power of two, or if
2962 // it is an induction variable where in each step its value is a power of
2963 // two.
2964 auto *PN = cast<PHINode>(I);
2966
2967 // Check if it is an induction variable and always power of two.
2968 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2969 return true;
2970
2971 // Recursively check all incoming values. Limit recursion to 2 levels, so
2972 // that search complexity is limited to number of operands^2.
2973 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2974 return llvm::all_of(PN->operands(), [&](const Use &U) {
2975 // Value is power of 2 if it is coming from PHI node itself by induction.
2976 if (U.get() == PN)
2977 return true;
2978
2979 // Change the context instruction to the incoming block where it is
2980 // evaluated.
2981 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
2982 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2983 });
2984 }
2985 case Instruction::Invoke:
2986 case Instruction::Call: {
2987 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2988 switch (II->getIntrinsicID()) {
2989 case Intrinsic::umax:
2990 case Intrinsic::smax:
2991 case Intrinsic::umin:
2992 case Intrinsic::smin:
2993 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2994 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2995 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2996 // thus dont change pow2/non-pow2 status.
2997 case Intrinsic::bitreverse:
2998 case Intrinsic::bswap:
2999 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3000 case Intrinsic::fshr:
3001 case Intrinsic::fshl:
3002 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
3003 if (II->getArgOperand(0) == II->getArgOperand(1))
3004 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3005 break;
3006 case Intrinsic::riscv_vsetvlimax:
3007 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
3008 // for any valid vtype, so it is a power of two regardless of OrZero.
3009 return true;
3010 case Intrinsic::read_register:
3011 case Intrinsic::read_volatile_register: {
3012 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
3013 // of two, so it is a power of two regardless of OrZero.
3014 const Module *M = II->getModule();
3015 if (!M || !M->getTargetTriple().isRISCV())
3016 break;
3017 return isReadVLENB(*II);
3018 }
3019 default:
3020 break;
3021 }
3022 }
3023 return false;
3024 }
3025 default:
3026 return false;
3027 }
3028}
3029
3030/// Test whether a GEP's result is known to be non-null.
3031///
3032/// Uses properties inherent in a GEP to try to determine whether it is known
3033/// to be non-null.
3034///
3035/// Currently this routine does not support vector GEPs.
3036static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3037 unsigned Depth) {
3038 const Function *F = nullptr;
3039 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3040 F = I->getFunction();
3041
3042 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3043 // may be null iff the base pointer is null and the offset is zero.
3044 if (!GEP->hasNoUnsignedWrap() &&
3045 !(GEP->isInBounds() &&
3046 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3047 return false;
3048
3049 // FIXME: Support vector-GEPs.
3050 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3051
3052 // If the base pointer is non-null, we cannot walk to a null address with an
3053 // inbounds GEP in address space zero.
3054 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3055 return true;
3056
3057 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3058 // If so, then the GEP cannot produce a null pointer, as doing so would
3059 // inherently violate the inbounds contract within address space zero.
3061 GTI != GTE; ++GTI) {
3062 // Struct types are easy -- they must always be indexed by a constant.
3063 if (StructType *STy = GTI.getStructTypeOrNull()) {
3064 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3065 unsigned ElementIdx = OpC->getZExtValue();
3066 const StructLayout *SL = Q.DL.getStructLayout(STy);
3067 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3068 if (ElementOffset > 0)
3069 return true;
3070 continue;
3071 }
3072
3073 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3074 if (GTI.getSequentialElementStride(Q.DL).isZero())
3075 continue;
3076
3077 // Fast path the constant operand case both for efficiency and so we don't
3078 // increment Depth when just zipping down an all-constant GEP.
3079 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3080 if (!OpC->isZero())
3081 return true;
3082 continue;
3083 }
3084
3085 // We post-increment Depth here because while isKnownNonZero increments it
3086 // as well, when we pop back up that increment won't persist. We don't want
3087 // to recurse 10k times just because we have 10k GEP operands. We don't
3088 // bail completely out because we want to handle constant GEPs regardless
3089 // of depth.
3091 continue;
3092
3093 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3094 return true;
3095 }
3096
3097 return false;
3098}
3099
3101 const Instruction *CtxI,
3102 const DominatorTree *DT) {
3103 assert(!isa<Constant>(V) && "Called for constant?");
3104
3105 if (!CtxI || !DT)
3106 return false;
3107
3108 unsigned NumUsesExplored = 0;
3109 for (auto &U : V->uses()) {
3110 // Avoid massive lists
3111 if (NumUsesExplored >= DomConditionsMaxUses)
3112 break;
3113 NumUsesExplored++;
3114
3115 const Instruction *UI = cast<Instruction>(U.getUser());
3116 // If the value is used as an argument to a call or invoke, then argument
3117 // attributes may provide an answer about null-ness.
3118 if (V->getType()->isPointerTy()) {
3119 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3120 if (CB->isArgOperand(&U) &&
3121 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3122 /*AllowUndefOrPoison=*/false) &&
3123 DT->dominates(CB, CtxI))
3124 return true;
3125 }
3126 }
3127
3128 // If the value is used as a load/store, then the pointer must be non null.
3129 if (V == getLoadStorePointerOperand(UI)) {
3132 DT->dominates(UI, CtxI))
3133 return true;
3134 }
3135
3136 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3137 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3138 isValidAssumeForContext(UI, CtxI, DT))
3139 return true;
3140
3141 // Consider only compare instructions uniquely controlling a branch
3142 Value *RHS;
3143 CmpPredicate Pred;
3144 bool NonNullIfTrue;
3145 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3146 if (cmpExcludesZero(Pred, RHS))
3147 NonNullIfTrue = true;
3149 NonNullIfTrue = false;
3150 else
3151 continue;
3152 } else if (UI->getType()->isIntegerTy(1) &&
3153 match(UI, m_Trunc(m_Specific(V)))) {
3154 NonNullIfTrue = true;
3155 } else
3156 continue;
3157
3160 for (const auto *CmpU : UI->users()) {
3161 assert(WorkList.empty() && "Should be!");
3162 if (Visited.insert(CmpU).second)
3163 WorkList.push_back(CmpU);
3164
3165 while (!WorkList.empty()) {
3166 auto *Curr = WorkList.pop_back_val();
3167
3168 // If a user is an AND, add all its users to the work list. We only
3169 // propagate "pred != null" condition through AND because it is only
3170 // correct to assume that all conditions of AND are met in true branch.
3171 // TODO: Support similar logic of OR and EQ predicate?
3172 if (NonNullIfTrue)
3173 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3174 for (const auto *CurrU : Curr->users())
3175 if (Visited.insert(CurrU).second)
3176 WorkList.push_back(CurrU);
3177 continue;
3178 }
3179
3180 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3181 BasicBlock *NonNullSuccessor =
3182 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3183 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3184 if (DT->dominates(Edge, CtxI->getParent()))
3185 return true;
3186 } else if (NonNullIfTrue && isGuard(Curr) &&
3187 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3188 return true;
3189 }
3190 }
3191 }
3192 }
3193
3194 return false;
3195}
3196
3197/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3198/// ensure that the value it's attached to is never Value? 'RangeType' is
3199/// is the type of the value described by the range.
3200static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3201 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3202 assert(NumRanges >= 1);
3203 for (unsigned i = 0; i < NumRanges; ++i) {
3205 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3207 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3208 ConstantRange Range(Lower->getValue(), Upper->getValue());
3209 if (Range.contains(Value))
3210 return false;
3211 }
3212 return true;
3213}
3214
3215/// Try to detect a recurrence that monotonically increases/decreases from a
3216/// non-zero starting value. These are common as induction variables.
3217static bool isNonZeroRecurrence(const PHINode *PN) {
3218 BinaryOperator *BO = nullptr;
3219 Value *Start = nullptr, *Step = nullptr;
3220 const APInt *StartC, *StepC;
3221 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3222 !match(Start, m_APInt(StartC)) || StartC->isZero())
3223 return false;
3224
3225 switch (BO->getOpcode()) {
3226 case Instruction::Add:
3227 // Starting from non-zero and stepping away from zero can never wrap back
3228 // to zero.
3229 return BO->hasNoUnsignedWrap() ||
3230 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3231 StartC->isNegative() == StepC->isNegative());
3232 case Instruction::Mul:
3233 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3234 match(Step, m_APInt(StepC)) && !StepC->isZero();
3235 case Instruction::Shl:
3236 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3237 case Instruction::AShr:
3238 case Instruction::LShr:
3239 return BO->isExact();
3240 case Instruction::Or:
3241 return true;
3242 default:
3243 return false;
3244 }
3245}
3246
3247static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3249 m_Specific(Op1), m_Zero()))) ||
3251 m_Specific(Op0), m_Zero())));
3252}
3253
3254/// Return true if "addr(P) + Off" cannot be zero. The object P points to
3255/// cannot cross the unsigned address space boundary, including the address one
3256/// past its end, so an offset that stays within the object cannot wrap around
3257/// to zero. This holds even if the object starts at the zero address, which is
3258/// all that null_pointer_is_valid permits, so a non-zero offset is enough.
3260 Value *Y) {
3261 const APInt *Off;
3262 if (!match(Y, m_APInt(Off)) || Off->isZero())
3263 return false;
3264
3265 // ptrtoaddr always produces the address. ptrtoint only does so when its
3266 // result is at least as wide as the address: a narrower result is truncated
3267 // and may wrap to zero, while bits above the address can only make the
3268 // result more non-zero.
3269 Value *P;
3270 if (!match(X, m_PtrToAddr(m_Value(P))) &&
3271 !(match(X, m_PtrToInt(m_Value(P))) &&
3272 X->getType()->getScalarSizeInBits() >=
3273 Q.DL.getAddressSizeInBits(P->getType())))
3274 return false;
3275
3276 // A vector of pointers has no single object whose size can be taken, and
3277 // getPointerDereferenceableBytes() requires a plain pointer.
3278 if (!P->getType()->isPointerTy())
3279 return false;
3280
3281 bool CanBeNull;
3282 uint64_t DerefBytes = P->getPointerDereferenceableBytes(
3283 Q.DL, CanBeNull, /*CanBeFreed=*/nullptr);
3284 if (CanBeNull || DerefBytes == 0 || !Off->ule(DerefBytes))
3285 return false;
3286
3287 return true;
3288}
3289
3290static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3291 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3292 bool NUW, unsigned Depth) {
3294 return true;
3295
3296 // (X + (X != 0)) is non zero
3297 if (matchOpWithOpEqZero(X, Y))
3298 return true;
3299
3300 if (NUW)
3301 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3302 isKnownNonZero(X, DemandedElts, Q, Depth);
3303
3304 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3305 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3306
3307 // If X and Y are both non-negative (as signed values) then their sum is not
3308 // zero unless both X and Y are zero.
3309 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3310 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3311 isKnownNonZero(X, DemandedElts, Q, Depth))
3312 return true;
3313
3314 // If X and Y are both negative (as signed values) then their sum is not
3315 // zero unless both X and Y equal INT_MIN.
3316 if (XKnown.isNegative() && YKnown.isNegative()) {
3318 // The sign bit of X is set. If some other bit is set then X is not equal
3319 // to INT_MIN.
3320 if (XKnown.One.intersects(Mask))
3321 return true;
3322 // The sign bit of Y is set. If some other bit is set then Y is not equal
3323 // to INT_MIN.
3324 if (YKnown.One.intersects(Mask))
3325 return true;
3326 }
3327
3328 // The sum of a non-negative number and a power of two is not zero.
3329 if (XKnown.isNonNegative() &&
3330 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3331 return true;
3332 if (YKnown.isNonNegative() &&
3333 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3334 return true;
3335
3336 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3337}
3338
3339static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3340 unsigned BitWidth, Value *X, Value *Y,
3341 unsigned Depth) {
3342 // (X - (X != 0)) is non zero
3343 // ((X != 0) - X) is non zero
3344 if (matchOpWithOpEqZero(X, Y))
3345 return true;
3346
3347 // TODO: Move this case into isKnownNonEqual().
3348 if (auto *C = dyn_cast<Constant>(X))
3349 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3350 return true;
3351
3352 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3353}
3354
3355static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3356 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3357 bool NUW, unsigned Depth) {
3358 // If X and Y are non-zero then so is X * Y as long as the multiplication
3359 // does not overflow.
3360 if (NSW || NUW)
3361 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3362 isKnownNonZero(Y, DemandedElts, Q, Depth);
3363
3364 // If either X or Y is odd, then if the other is non-zero the result can't
3365 // be zero.
3366 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3367 if (XKnown.One[0])
3368 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3369
3370 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3371 if (YKnown.One[0])
3372 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3373
3374 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3375 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3376 // the lowest known One of X and Y. If they are non-zero, the result
3377 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3378 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3379 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3380 BitWidth;
3381}
3382
3383static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3384 const SimplifyQuery &Q, const KnownBits &KnownVal,
3385 unsigned Depth) {
3386 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3387 switch (I->getOpcode()) {
3388 case Instruction::Shl:
3389 return Lhs.shl(Rhs);
3390 case Instruction::LShr:
3391 return Lhs.lshr(Rhs);
3392 case Instruction::AShr:
3393 return Lhs.ashr(Rhs);
3394 default:
3395 llvm_unreachable("Unknown Shift Opcode");
3396 }
3397 };
3398
3399 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3400 switch (I->getOpcode()) {
3401 case Instruction::Shl:
3402 return Lhs.lshr(Rhs);
3403 case Instruction::LShr:
3404 case Instruction::AShr:
3405 return Lhs.shl(Rhs);
3406 default:
3407 llvm_unreachable("Unknown Shift Opcode");
3408 }
3409 };
3410
3411 if (KnownVal.isUnknown())
3412 return false;
3413
3414 KnownBits KnownCnt =
3415 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3416 APInt MaxShift = KnownCnt.getMaxValue();
3417 unsigned NumBits = KnownVal.getBitWidth();
3418 if (MaxShift.uge(NumBits))
3419 return false;
3420
3421 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3422 return true;
3423
3424 // If all of the bits shifted out are known to be zero, and Val is known
3425 // non-zero then at least one non-zero bit must remain.
3426 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3427 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3428 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3429 return true;
3430
3431 return false;
3432}
3433
3435 const APInt &DemandedElts,
3436 const SimplifyQuery &Q, unsigned Depth) {
3437 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3438 switch (I->getOpcode()) {
3439 case Instruction::Alloca:
3440 // Alloca never returns null, malloc might.
3441 return I->getType()->getPointerAddressSpace() == 0;
3442 case Instruction::GetElementPtr:
3443 if (I->getType()->isPointerTy())
3445 break;
3446 case Instruction::BitCast: {
3447 // We need to be a bit careful here. We can only peek through the bitcast
3448 // if the scalar size of elements in the operand are smaller than and a
3449 // multiple of the size they are casting too. Take three cases:
3450 //
3451 // 1) Unsafe:
3452 // bitcast <2 x i16> %NonZero to <4 x i8>
3453 //
3454 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3455 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3456 // guranteed (imagine just sign bit set in the 2 i16 elements).
3457 //
3458 // 2) Unsafe:
3459 // bitcast <4 x i3> %NonZero to <3 x i4>
3460 //
3461 // Even though the scalar size of the src (`i3`) is smaller than the
3462 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3463 // its possible for the `3 x i4` elements to be zero because there are
3464 // some elements in the destination that don't contain any full src
3465 // element.
3466 //
3467 // 3) Safe:
3468 // bitcast <4 x i8> %NonZero to <2 x i16>
3469 //
3470 // This is always safe as non-zero in the 4 i8 elements implies
3471 // non-zero in the combination of any two adjacent ones. Since i8 is a
3472 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3473 // This all implies the 2 i16 elements are non-zero.
3474 Type *FromTy = I->getOperand(0)->getType();
3475 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3476 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3477 return isKnownNonZero(I->getOperand(0), Q, Depth);
3478 } break;
3479 case Instruction::IntToPtr:
3480 // Note that we have to take special care to avoid looking through
3481 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3482 // as casts that can alter the value, e.g., AddrSpaceCasts.
3483 if (!isa<ScalableVectorType>(I->getType()) &&
3484 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3485 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3486 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3487 break;
3488 case Instruction::PtrToAddr:
3489 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3490 // so we can directly forward.
3491 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3492 case Instruction::PtrToInt:
3493 // For inttoptr, make sure the result size is >= the address size. If the
3494 // address is non-zero, any larger value is also non-zero.
3495 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3496 I->getType()->getScalarSizeInBits())
3497 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3498 break;
3499 case Instruction::Trunc:
3500 // nuw/nsw trunc preserves zero/non-zero status of input.
3501 if (auto *TI = dyn_cast<TruncInst>(I))
3502 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3503 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3504 break;
3505
3506 // Iff x - y != 0, then x ^ y != 0
3507 // Therefore we can do the same exact checks
3508 case Instruction::Xor:
3509 case Instruction::Sub:
3510 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3511 I->getOperand(1), Depth);
3512 case Instruction::Or:
3513 // (X | (X != 0)) is non zero
3514 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3515 return true;
3516 // X | Y != 0 if X != Y.
3517 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3518 Depth))
3519 return true;
3520 // X | Y != 0 if X != 0 or Y != 0.
3521 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3522 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3523 case Instruction::SExt:
3524 case Instruction::ZExt:
3525 // ext X != 0 if X != 0.
3526 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3527
3528 case Instruction::Shl: {
3529 // shl nsw/nuw can't remove any non-zero bits.
3531 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3532 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3533
3534 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3535 // if the lowest bit is shifted off the end.
3537 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3538 if (Known.One[0])
3539 return true;
3540
3541 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3542 }
3543 case Instruction::LShr:
3544 case Instruction::AShr: {
3545 // shr exact can only shift out zero bits.
3547 if (BO->isExact())
3548 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3549
3550 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3551 // defined if the sign bit is shifted off the end.
3553 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3554 if (Known.isNegative())
3555 return true;
3556
3557 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3558 // position >= C, because the sum >= max(A, B).
3559 Value *A, *B;
3560 const APInt *C;
3561 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3562 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3563 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3564 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3565 if (!KnownA.One.lshr(*C).isZero())
3566 return true;
3567 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3568 if (!KnownB.One.lshr(*C).isZero())
3569 return true;
3570 }
3571
3572 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3573 }
3574 case Instruction::UDiv:
3575 case Instruction::SDiv: {
3576 // X / Y
3577 // div exact can only produce a zero if the dividend is zero.
3578 if (cast<PossiblyExactOperator>(I)->isExact())
3579 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3580
3581 KnownBits XKnown =
3582 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3583 // If X is fully unknown we won't be able to figure anything out so don't
3584 // both computing knownbits for Y.
3585 if (XKnown.isUnknown())
3586 return false;
3587
3588 KnownBits YKnown =
3589 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3590 if (I->getOpcode() == Instruction::SDiv) {
3591 // For signed division need to compare abs value of the operands.
3592 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3593 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3594 }
3595 // If X u>= Y then div is non zero (0/0 is UB).
3596 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3597 // If X is total unknown or X u< Y we won't be able to prove non-zero
3598 // with compute known bits so just return early.
3599 return XUgeY && *XUgeY;
3600 }
3601 case Instruction::Add: {
3602 // X + Y.
3603
3604 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3605 // non-zero.
3607 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3608 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3609 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3610 }
3611 case Instruction::Mul: {
3613 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3614 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3615 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3616 }
3617 case Instruction::Select: {
3618 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3619
3620 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3621 // then see if the select condition implies the arm is non-zero. For example
3622 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3623 // dominated by `X != 0`.
3624 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3625 Value *Op;
3626 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3627 // Op is trivially non-zero.
3628 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3629 return true;
3630
3631 // The condition of the select dominates the true/false arm. Check if the
3632 // condition implies that a given arm is non-zero.
3633 Value *X;
3634 CmpPredicate Pred;
3635 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3636 return false;
3637
3638 if (!IsTrueArm)
3639 Pred = ICmpInst::getInversePredicate(Pred);
3640
3641 return cmpExcludesZero(Pred, X);
3642 };
3643
3644 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3645 SelectArmIsNonZero(/* IsTrueArm */ false))
3646 return true;
3647 break;
3648 }
3649 case Instruction::PHI: {
3650 auto *PN = cast<PHINode>(I);
3652 return true;
3653
3654 // Check if all incoming values are non-zero using recursion.
3656 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3657 return llvm::all_of(PN->operands(), [&](const Use &U) {
3658 if (U.get() == PN)
3659 return true;
3660 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3661 // Check if the branch on the phi excludes zero.
3662 CmpPredicate Pred;
3663 Value *X;
3664 BasicBlock *TrueSucc, *FalseSucc;
3665 if (match(RecQ.CtxI,
3666 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3667 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3668 // Check for cases of duplicate successors.
3669 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3670 // If we're using the false successor, invert the predicate.
3671 if (FalseSucc == PN->getParent())
3672 Pred = CmpInst::getInversePredicate(Pred);
3673 if (cmpExcludesZero(Pred, X))
3674 return true;
3675 }
3676 }
3677 // Finally recurse on the edge and check it directly.
3678 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3679 });
3680 }
3681 case Instruction::InsertElement: {
3682 if (isa<ScalableVectorType>(I->getType()))
3683 break;
3684
3685 const Value *Vec = I->getOperand(0);
3686 const Value *Elt = I->getOperand(1);
3687 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3688
3689 unsigned NumElts = DemandedElts.getBitWidth();
3690 APInt DemandedVecElts = DemandedElts;
3691 bool SkipElt = false;
3692 // If we know the index we are inserting too, clear it from Vec check.
3693 if (CIdx && CIdx->getValue().ult(NumElts)) {
3694 DemandedVecElts.clearBit(CIdx->getZExtValue());
3695 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3696 }
3697
3698 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3699 // are non-zero.
3700 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3701 (DemandedVecElts.isZero() ||
3702 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3703 }
3704 case Instruction::ExtractElement:
3705 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3706 const Value *Vec = EEI->getVectorOperand();
3707 const Value *Idx = EEI->getIndexOperand();
3708 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3709 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3710 unsigned NumElts = VecTy->getNumElements();
3711 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3712 if (CIdx && CIdx->getValue().ult(NumElts))
3713 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3714 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3715 }
3716 }
3717 break;
3718 case Instruction::ShuffleVector: {
3719 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3720 if (!Shuf)
3721 break;
3722 APInt DemandedLHS, DemandedRHS;
3723 // For undef elements, we don't know anything about the common state of
3724 // the shuffle result.
3725 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3726 break;
3727 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3728 return (DemandedRHS.isZero() ||
3729 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3730 (DemandedLHS.isZero() ||
3731 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3732 }
3733 case Instruction::Freeze:
3734 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3735 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3736 Depth);
3737 case Instruction::Load: {
3738 auto *LI = cast<LoadInst>(I);
3739 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3740 // is never null.
3741 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3742 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3743 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3744 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3745 return true;
3746 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3748 }
3749
3750 // No need to fall through to computeKnownBits as range metadata is already
3751 // handled in isKnownNonZero.
3752 return false;
3753 }
3754 case Instruction::ExtractValue: {
3755 const WithOverflowInst *WO;
3757 switch (WO->getBinaryOp()) {
3758 default:
3759 break;
3760 case Instruction::Add:
3761 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3762 WO->getArgOperand(1),
3763 /*NSW=*/false,
3764 /*NUW=*/false, Depth);
3765 case Instruction::Sub:
3766 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3767 WO->getArgOperand(1), Depth);
3768 case Instruction::Mul:
3769 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3770 WO->getArgOperand(1),
3771 /*NSW=*/false, /*NUW=*/false, Depth);
3772 break;
3773 }
3774 }
3775 break;
3776 }
3777 case Instruction::Call:
3778 case Instruction::Invoke: {
3779 const auto *Call = cast<CallBase>(I);
3780 if (I->getType()->isPointerTy()) {
3781 if (Call->isReturnNonNull())
3782 return true;
3783 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3784 Call, /*MustPreserveOffset=*/true))
3785 return isKnownNonZero(RP, Q, Depth);
3786 } else {
3787 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3789 if (std::optional<ConstantRange> Range = Call->getRange()) {
3790 const APInt ZeroValue(Range->getBitWidth(), 0);
3791 if (!Range->contains(ZeroValue))
3792 return true;
3793 }
3794 if (const Value *RV = Call->getReturnedArgOperand())
3795 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3796 return true;
3797 }
3798
3799 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3800 switch (II->getIntrinsicID()) {
3801 case Intrinsic::sshl_sat:
3802 case Intrinsic::ushl_sat:
3803 case Intrinsic::abs:
3804 case Intrinsic::bitreverse:
3805 case Intrinsic::bswap:
3806 case Intrinsic::ctpop:
3807 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3808 // NB: We don't do usub_sat here as in any case we can prove its
3809 // non-zero, we will fold it to `sub nuw` in InstCombine.
3810 case Intrinsic::ssub_sat:
3811 // For most types, if x != y then ssub.sat x, y != 0. But
3812 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3813 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3814 if (BitWidth == 1)
3815 return false;
3816 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3817 II->getArgOperand(1), Depth);
3818 case Intrinsic::sadd_sat:
3819 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3820 II->getArgOperand(1),
3821 /*NSW=*/true, /* NUW=*/false, Depth);
3822 // Vec reverse preserves zero/non-zero status from input vec.
3823 case Intrinsic::vector_reverse:
3824 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3825 Q, Depth);
3826 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3827 case Intrinsic::vector_reduce_or:
3828 case Intrinsic::vector_reduce_umax:
3829 case Intrinsic::vector_reduce_umin:
3830 case Intrinsic::vector_reduce_smax:
3831 case Intrinsic::vector_reduce_smin:
3832 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3833 case Intrinsic::umax:
3834 case Intrinsic::uadd_sat:
3835 // umax(X, (X != 0)) is non zero
3836 // X +usat (X != 0) is non zero
3837 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3838 return true;
3839
3840 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3841 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3842 case Intrinsic::smax: {
3843 // If either arg is strictly positive the result is non-zero. Otherwise
3844 // the result is non-zero if both ops are non-zero.
3845 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3846 const KnownBits &OpKnown) {
3847 if (!OpNonZero.has_value())
3848 OpNonZero = OpKnown.isNonZero() ||
3849 isKnownNonZero(Op, DemandedElts, Q, Depth);
3850 return *OpNonZero;
3851 };
3852 // Avoid re-computing isKnownNonZero.
3853 std::optional<bool> Op0NonZero, Op1NonZero;
3854 KnownBits Op1Known =
3855 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3856 if (Op1Known.isNonNegative() &&
3857 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3858 return true;
3859 KnownBits Op0Known =
3860 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3861 if (Op0Known.isNonNegative() &&
3862 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3863 return true;
3864 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3865 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3866 }
3867 case Intrinsic::smin: {
3868 // If either arg is negative the result is non-zero. Otherwise
3869 // the result is non-zero if both ops are non-zero.
3870 KnownBits Op1Known =
3871 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3872 if (Op1Known.isNegative())
3873 return true;
3874 KnownBits Op0Known =
3875 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3876 if (Op0Known.isNegative())
3877 return true;
3878
3879 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3880 return true;
3881 }
3882 [[fallthrough]];
3883 case Intrinsic::umin:
3884 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3885 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3886 case Intrinsic::cttz:
3887 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3888 .Zero[0];
3889 case Intrinsic::ctlz:
3890 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3891 .isNonNegative();
3892 case Intrinsic::fshr:
3893 case Intrinsic::fshl:
3894 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3895 if (II->getArgOperand(0) == II->getArgOperand(1))
3896 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3897 break;
3898 case Intrinsic::vscale:
3899 return true;
3900 case Intrinsic::experimental_get_vector_length:
3901 return isKnownNonZero(I->getOperand(0), Q, Depth);
3902 default:
3903 break;
3904 }
3905 break;
3906 }
3907
3908 return false;
3909 }
3910 }
3911
3913 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3914 return Known.One != 0;
3915}
3916
3917/// Return true if the given value is known to be non-zero when defined. For
3918/// vectors, return true if every demanded element is known to be non-zero when
3919/// defined. For pointers, if the context instruction and dominator tree are
3920/// specified, perform context-sensitive analysis and return true if the
3921/// pointer couldn't possibly be null at the specified instruction.
3922/// Supports values with integer or pointer type and vectors of integers.
3923bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3924 const SimplifyQuery &Q, unsigned Depth) {
3925 Type *Ty = V->getType();
3926
3927#ifndef NDEBUG
3928 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3929
3930 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3931 assert(
3932 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3933 "DemandedElt width should equal the fixed vector number of elements");
3934 } else {
3935 assert(DemandedElts == APInt(1, 1) &&
3936 "DemandedElt width should be 1 for scalars");
3937 }
3938#endif
3939
3940 if (auto *C = dyn_cast<Constant>(V)) {
3941 if (C->isNullValue())
3942 return false;
3943 if (isa<ConstantInt>(C))
3944 // Must be non-zero due to null test above.
3945 return true;
3946
3947 // For constant vectors, check that all elements are poison or known
3948 // non-zero to determine that the whole vector is known non-zero.
3949 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3950 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3951 if (!DemandedElts[i])
3952 continue;
3953 Constant *Elt = C->getAggregateElement(i);
3954 if (!Elt || Elt->isNullValue())
3955 return false;
3956 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3957 return false;
3958 }
3959 return true;
3960 }
3961
3962 // Constant ptrauth can be null, iff the base pointer can be.
3963 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3964 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3965
3966 // A global variable is non null unless extern weak or an absolute symbol
3967 // reference. An alias is also excluded, as it may resolve to a weak
3968 // undefined symbol and thus to the null address. Where null is a valid
3969 // address an allocation may start there, so nothing can be assumed; that
3970 // covers both null_pointer_is_valid and address spaces other than zero.
3971 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3973 GV->getType()->getAddressSpace()) &&
3974 !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3975 !isa<GlobalAlias>(GV))
3976 return true;
3977 }
3978
3979 // For constant expressions, fall through to the Operator code below.
3980 if (!isa<ConstantExpr>(V))
3981 return false;
3982 }
3983
3984 if (const auto *A = dyn_cast<Argument>(V))
3985 if (std::optional<ConstantRange> Range = A->getRange()) {
3986 const APInt ZeroValue(Range->getBitWidth(), 0);
3987 if (!Range->contains(ZeroValue))
3988 return true;
3989 }
3990
3991 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3992 return true;
3993
3994 // Some of the tests below are recursive, so bail out if we hit the limit.
3996 return false;
3997
3998 // Check for pointer simplifications.
3999
4000 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
4001 // A byval, inalloca may not be null in a non-default addres space. A
4002 // nonnull argument is assumed never 0.
4003 if (const Argument *A = dyn_cast<Argument>(V)) {
4004 if (((A->hasPassPointeeByValueCopyAttr() &&
4005 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
4006 A->hasNonNullAttr()))
4007 return true;
4008 }
4009 }
4010
4011 if (const auto *I = dyn_cast<Operator>(V))
4012 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
4013 return true;
4014
4015 if (!isa<Constant>(V) &&
4017 return true;
4018
4019 if (const Value *Stripped = stripNullTest(V))
4020 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
4021
4022 return false;
4023}
4024
4026 unsigned Depth) {
4027 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4028 APInt DemandedElts =
4029 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4030 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
4031}
4032
4033/// If the pair of operators are the same invertible function, return the
4034/// the operands of the function corresponding to each input. Otherwise,
4035/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
4036/// every input value to exactly one output value. This is equivalent to
4037/// saying that Op1 and Op2 are equal exactly when the specified pair of
4038/// operands are equal, (except that Op1 and Op2 may be poison more often.)
4039static std::optional<std::pair<Value*, Value*>>
4041 const Operator *Op2) {
4042 if (Op1->getOpcode() != Op2->getOpcode())
4043 return std::nullopt;
4044
4045 auto getOperands = [&](unsigned OpNum) -> auto {
4046 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
4047 };
4048
4049 switch (Op1->getOpcode()) {
4050 default:
4051 break;
4052 case Instruction::Or:
4053 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
4054 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
4055 break;
4056 [[fallthrough]];
4057 case Instruction::Xor:
4058 case Instruction::Add: {
4059 Value *Other;
4060 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
4061 return std::make_pair(Op1->getOperand(1), Other);
4062 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
4063 return std::make_pair(Op1->getOperand(0), Other);
4064 break;
4065 }
4066 case Instruction::Sub:
4067 if (Op1->getOperand(0) == Op2->getOperand(0))
4068 return getOperands(1);
4069 if (Op1->getOperand(1) == Op2->getOperand(1))
4070 return getOperands(0);
4071 break;
4072 case Instruction::Mul: {
4073 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4074 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4075 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4076 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4077 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4078 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4079 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4080 break;
4081
4082 // Assume operand order has been canonicalized
4083 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4084 isa<ConstantInt>(Op1->getOperand(1)) &&
4085 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4086 return getOperands(0);
4087 break;
4088 }
4089 case Instruction::Shl: {
4090 // Same as multiplies, with the difference that we don't need to check
4091 // for a non-zero multiply. Shifts always multiply by non-zero.
4092 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4093 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4094 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4095 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4096 break;
4097
4098 if (Op1->getOperand(1) == Op2->getOperand(1))
4099 return getOperands(0);
4100 break;
4101 }
4102 case Instruction::AShr:
4103 case Instruction::LShr: {
4104 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4105 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4106 if (!PEO1->isExact() || !PEO2->isExact())
4107 break;
4108
4109 if (Op1->getOperand(1) == Op2->getOperand(1))
4110 return getOperands(0);
4111 break;
4112 }
4113 case Instruction::SExt:
4114 case Instruction::ZExt:
4115 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4116 return getOperands(0);
4117 break;
4118 case Instruction::PHI: {
4119 const PHINode *PN1 = cast<PHINode>(Op1);
4120 const PHINode *PN2 = cast<PHINode>(Op2);
4121
4122 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4123 // are a single invertible function of the start values? Note that repeated
4124 // application of an invertible function is also invertible
4125 BinaryOperator *BO1 = nullptr;
4126 Value *Start1 = nullptr, *Step1 = nullptr;
4127 BinaryOperator *BO2 = nullptr;
4128 Value *Start2 = nullptr, *Step2 = nullptr;
4129 if (PN1->getParent() != PN2->getParent() ||
4130 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4131 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4132 break;
4133
4135 cast<Operator>(BO2));
4136 if (!Values)
4137 break;
4138
4139 // We have to be careful of mutually defined recurrences here. Ex:
4140 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4141 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4142 // The invertibility of these is complicated, and not worth reasoning
4143 // about (yet?).
4144 if (Values->first != PN1 || Values->second != PN2)
4145 break;
4146
4147 return std::make_pair(Start1, Start2);
4148 }
4149 }
4150 return std::nullopt;
4151}
4152
4153/// Return true if V1 == (binop V2, X), where X is known non-zero.
4154/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4155/// implies V2 != V1.
4156static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4157 const APInt &DemandedElts,
4158 const SimplifyQuery &Q, unsigned Depth) {
4160 if (!BO)
4161 return false;
4162 switch (BO->getOpcode()) {
4163 default:
4164 break;
4165 case Instruction::Or:
4166 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4167 break;
4168 [[fallthrough]];
4169 case Instruction::Xor:
4170 case Instruction::Add:
4171 Value *Op = nullptr;
4172 if (V2 == BO->getOperand(0))
4173 Op = BO->getOperand(1);
4174 else if (V2 == BO->getOperand(1))
4175 Op = BO->getOperand(0);
4176 else
4177 return false;
4178 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4179 }
4180 return false;
4181}
4182
4183/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4184/// the multiplication is nuw or nsw.
4185static bool isNonEqualMul(const Value *V1, const Value *V2,
4186 const APInt &DemandedElts, const SimplifyQuery &Q,
4187 unsigned Depth) {
4188 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4189 const APInt *C;
4190 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4191 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4192 !C->isZero() && !C->isOne() &&
4193 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4194 }
4195 return false;
4196}
4197
4198/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4199/// the shift is nuw or nsw.
4200static bool isNonEqualShl(const Value *V1, const Value *V2,
4201 const APInt &DemandedElts, const SimplifyQuery &Q,
4202 unsigned Depth) {
4203 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4204 const APInt *C;
4205 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4206 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4207 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4208 }
4209 return false;
4210}
4211
4212static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4213 const APInt &DemandedElts, const SimplifyQuery &Q,
4214 unsigned Depth) {
4215 // Check two PHIs are in same block.
4216 if (PN1->getParent() != PN2->getParent())
4217 return false;
4218
4220 bool UsedFullRecursion = false;
4221 for (const BasicBlock *IncomBB : PN1->blocks()) {
4222 if (!VisitedBBs.insert(IncomBB).second)
4223 continue; // Don't reprocess blocks that we have dealt with already.
4224 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4225 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4226 const APInt *C1, *C2;
4227 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4228 continue;
4229
4230 // Only one pair of phi operands is allowed for full recursion.
4231 if (UsedFullRecursion)
4232 return false;
4233
4235 RecQ.CtxI = IncomBB->getTerminator();
4236 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4237 return false;
4238 UsedFullRecursion = true;
4239 }
4240 return true;
4241}
4242
4243static bool isNonEqualSelect(const Value *V1, const Value *V2,
4244 const APInt &DemandedElts, const SimplifyQuery &Q,
4245 unsigned Depth) {
4246 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4247 if (!SI1)
4248 return false;
4249
4250 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4251 const Value *Cond1 = SI1->getCondition();
4252 const Value *Cond2 = SI2->getCondition();
4253 if (Cond1 == Cond2)
4254 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4255 DemandedElts, Q, Depth + 1) &&
4256 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4257 DemandedElts, Q, Depth + 1);
4258 }
4259 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4260 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4261}
4262
4263// Check to see if A is both a GEP and is the incoming value for a PHI in the
4264// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4265// one of them being the recursive GEP A and the other a ptr at same base and at
4266// the same/higher offset than B we are only incrementing the pointer further in
4267// loop if offset of recursive GEP is greater than 0.
4269 const SimplifyQuery &Q) {
4270 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4271 return false;
4272
4273 auto *GEPA = dyn_cast<GEPOperator>(A);
4274 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4275 return false;
4276
4277 // Handle 2 incoming PHI values with one being a recursive GEP.
4278 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4279 if (!PN || PN->getNumIncomingValues() != 2)
4280 return false;
4281
4282 // Search for the recursive GEP as an incoming operand, and record that as
4283 // Step.
4284 Value *Start = nullptr;
4285 Value *Step = const_cast<Value *>(A);
4286 if (PN->getIncomingValue(0) == Step)
4287 Start = PN->getIncomingValue(1);
4288 else if (PN->getIncomingValue(1) == Step)
4289 Start = PN->getIncomingValue(0);
4290 else
4291 return false;
4292
4293 // Other incoming node base should match the B base.
4294 // StartOffset >= OffsetB && StepOffset > 0?
4295 // StartOffset <= OffsetB && StepOffset < 0?
4296 // Is non-equal if above are true.
4297 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4298 // optimisation to inbounds GEPs only.
4299 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4300 APInt StartOffset(IndexWidth, 0);
4301 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4302 APInt StepOffset(IndexWidth, 0);
4303 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4304
4305 // Check if Base Pointer of Step matches the PHI.
4306 if (Step != PN)
4307 return false;
4308 APInt OffsetB(IndexWidth, 0);
4309 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4310 return Start == B &&
4311 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4312 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4313}
4314
4315static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4316 const SimplifyQuery &Q, unsigned Depth) {
4317 if (!Q.CtxI)
4318 return false;
4319
4320 // Try to infer NonEqual based on information from dominating conditions.
4321 if (Q.DC && Q.DT) {
4322 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4323 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4324 Value *Cond = BI->getCondition();
4325 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4326 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4328 /*LHSIsTrue=*/true, Depth)
4329 .value_or(false))
4330 return true;
4331
4332 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4333 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4335 /*LHSIsTrue=*/false, Depth)
4336 .value_or(false))
4337 return true;
4338 }
4339
4340 return false;
4341 };
4342
4343 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4344 IsKnownNonEqualFromDominatingCondition(V2))
4345 return true;
4346 }
4347
4348 if (!Q.AC)
4349 return false;
4350
4351 // Try to infer NonEqual based on information from assumptions.
4352 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4353 if (!AssumeVH)
4354 continue;
4355 CallInst *I = cast<CallInst>(AssumeVH);
4356
4357 assert(I->getFunction() == Q.CtxI->getFunction() &&
4358 "Got assumption for the wrong function!");
4359 assert(I->getIntrinsicID() == Intrinsic::assume &&
4360 "must be an assume intrinsic");
4361
4362 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4363 /*LHSIsTrue=*/true, Depth)
4364 .value_or(false) &&
4366 return true;
4367 }
4368
4369 return false;
4370}
4371
4372static bool isNonEqualURem(const Value *X, const Value *Rem,
4373 const SimplifyQuery &Q) {
4374 const Value *Y;
4375 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4376 return false;
4377
4378 // For a defined urem, X != X urem Y exactly when X u>= Y.
4379 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4381 return true;
4382
4383 std::optional<bool> Implied =
4385 return Implied && *Implied;
4386}
4387
4388/// Return true if it is known that V1 != V2.
4389static bool isKnownNonEqual(const Value *V1, const Value *V2,
4390 const APInt &DemandedElts, const SimplifyQuery &Q,
4391 unsigned Depth) {
4392 if (V1 == V2)
4393 return false;
4394 if (V1->getType() != V2->getType())
4395 // We can't look through casts yet.
4396 return false;
4397
4399 return false;
4400
4401 // See if we can recurse through (exactly one of) our operands. This
4402 // requires our operation be 1-to-1 and map every input value to exactly
4403 // one output value. Such an operation is invertible.
4404 auto *O1 = dyn_cast<Operator>(V1);
4405 auto *O2 = dyn_cast<Operator>(V2);
4406 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4407 if (auto Values = getInvertibleOperands(O1, O2))
4408 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4409 Depth + 1);
4410
4411 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4412 const PHINode *PN2 = cast<PHINode>(V2);
4413 // FIXME: This is missing a generalization to handle the case where one is
4414 // a PHI and another one isn't.
4415 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4416 return true;
4417 };
4418 }
4419
4420 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4421 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4422 return true;
4423
4424 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4425 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4426 return true;
4427
4428 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4429 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4430 return true;
4431
4432 if (V1->getType()->isIntOrIntVectorTy()) {
4433 // Are any known bits in V1 contradictory to known bits in V2? If V1
4434 // has a known zero where V2 has a known one, they must not be equal.
4435 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4436 if (!Known1.isUnknown()) {
4437 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4438 if (Known1.Zero.intersects(Known2.One) ||
4439 Known2.Zero.intersects(Known1.One))
4440 return true;
4441 }
4442 }
4443
4444 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4445 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4446 return true;
4447
4450 return true;
4451
4452 Value *A, *B;
4453 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4454 // Check PtrToInt type matches the pointer size.
4455 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4457 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4458
4459 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4460 return true;
4461
4462 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4463 return true;
4464
4465 return false;
4466}
4467
4468/// For vector constants, loop over the elements and find the constant with the
4469/// minimum number of sign bits. Return 0 if the value is not a vector constant
4470/// or if any element was not analyzed; otherwise, return the count for the
4471/// element with the minimum number of sign bits.
4473 const APInt &DemandedElts,
4474 unsigned TyBits) {
4475 const auto *CV = dyn_cast<Constant>(V);
4476 if (!CV || !isa<FixedVectorType>(CV->getType()))
4477 return 0;
4478
4479 unsigned MinSignBits = TyBits;
4480 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4481 for (unsigned i = 0; i != NumElts; ++i) {
4482 if (!DemandedElts[i])
4483 continue;
4484 // If we find a non-ConstantInt, bail out.
4485 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4486 if (!Elt)
4487 return 0;
4488
4489 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4490 }
4491
4492 return MinSignBits;
4493}
4494
4495static unsigned ComputeNumSignBitsImpl(const Value *V,
4496 const APInt &DemandedElts,
4497 const SimplifyQuery &Q, unsigned Depth);
4498
4499static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4500 const SimplifyQuery &Q, unsigned Depth) {
4501 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4502 assert(Result > 0 && "At least one sign bit needs to be present!");
4503 return Result;
4504}
4505
4506/// Return the number of times the sign bit of the register is replicated into
4507/// the other bits. We know that at least 1 bit is always equal to the sign bit
4508/// (itself), but other cases can give us information. For example, immediately
4509/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4510/// other, so we return 3. For vectors, return the number of sign bits for the
4511/// vector element with the minimum number of known sign bits of the demanded
4512/// elements in the vector specified by DemandedElts.
4513static unsigned ComputeNumSignBitsImpl(const Value *V,
4514 const APInt &DemandedElts,
4515 const SimplifyQuery &Q, unsigned Depth) {
4516 Type *Ty = V->getType();
4517#ifndef NDEBUG
4518 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4519
4520 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4521 assert(
4522 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4523 "DemandedElt width should equal the fixed vector number of elements");
4524 } else {
4525 assert(DemandedElts == APInt(1, 1) &&
4526 "DemandedElt width should be 1 for scalars");
4527 }
4528#endif
4529
4530 // We return the minimum number of sign bits that are guaranteed to be present
4531 // in V, so for undef we have to conservatively return 1. We don't have the
4532 // same behavior for poison though -- that's a FIXME today.
4533
4534 Type *ScalarTy = Ty->getScalarType();
4535 unsigned TyBits = ScalarTy->isPointerTy() ?
4536 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4537 Q.DL.getTypeSizeInBits(ScalarTy);
4538
4539 unsigned Tmp, Tmp2;
4540 unsigned FirstAnswer = 1;
4541
4542 // Note that ConstantInt is handled by the general computeKnownBits case
4543 // below.
4544
4546 return 1;
4547
4548 if (auto *U = dyn_cast<Operator>(V)) {
4549 switch (Operator::getOpcode(V)) {
4550 default: break;
4551 case Instruction::BitCast: {
4552 Value *Src = U->getOperand(0);
4553 Type *SrcTy = Src->getType();
4554
4555 // Skip if the source type is not an integer or integer vector type
4556 // This ensures we only process integer-like types
4557 if (!SrcTy->isIntOrIntVectorTy())
4558 break;
4559
4560 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4561
4562 // Bitcast 'large element' scalar/vector to 'small element' vector.
4563 if ((SrcBits % TyBits) != 0)
4564 break;
4565
4566 // Only proceed if the destination type is a fixed-size vector
4567 if (isa<FixedVectorType>(Ty)) {
4568 // Fast case - sign splat can be simply split across the small elements.
4569 // This works for both vector and scalar sources
4570 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4571 if (Tmp == SrcBits)
4572 return TyBits;
4573 }
4574 break;
4575 }
4576 case Instruction::SExt:
4577 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4578 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4579 Tmp;
4580
4581 case Instruction::SDiv: {
4582 const APInt *Denominator;
4583 // sdiv X, C -> adds log(C) sign bits.
4584 if (match(U->getOperand(1), m_APInt(Denominator))) {
4585
4586 // Ignore non-positive denominator.
4587 if (!Denominator->isStrictlyPositive())
4588 break;
4589
4590 // Calculate the incoming numerator bits.
4591 unsigned NumBits =
4592 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4593
4594 // Add floor(log(C)) bits to the numerator bits.
4595 return std::min(TyBits, NumBits + Denominator->logBase2());
4596 }
4597 break;
4598 }
4599
4600 case Instruction::SRem: {
4601 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4602
4603 const APInt *Denominator;
4604 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4605 // positive constant. This let us put a lower bound on the number of sign
4606 // bits.
4607 if (match(U->getOperand(1), m_APInt(Denominator))) {
4608
4609 // Ignore non-positive denominator.
4610 if (Denominator->isStrictlyPositive()) {
4611 // Calculate the leading sign bit constraints by examining the
4612 // denominator. Given that the denominator is positive, there are two
4613 // cases:
4614 //
4615 // 1. The numerator is positive. The result range is [0,C) and
4616 // [0,C) u< (1 << ceilLogBase2(C)).
4617 //
4618 // 2. The numerator is negative. Then the result range is (-C,0] and
4619 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4620 //
4621 // Thus a lower bound on the number of sign bits is `TyBits -
4622 // ceilLogBase2(C)`.
4623
4624 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4625 Tmp = std::max(Tmp, ResBits);
4626 }
4627 }
4628 return Tmp;
4629 }
4630
4631 case Instruction::AShr: {
4632 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4633 // ashr X, C -> adds C sign bits. Vectors too.
4634 const APInt *ShAmt;
4635 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4636 if (ShAmt->uge(TyBits))
4637 break; // Bad shift.
4638 unsigned ShAmtLimited = ShAmt->getZExtValue();
4639 Tmp += ShAmtLimited;
4640 if (Tmp > TyBits) Tmp = TyBits;
4641 }
4642 return Tmp;
4643 }
4644 case Instruction::Shl: {
4645 const APInt *ShAmt;
4646 Value *X = nullptr;
4647 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4648 // shl destroys sign bits.
4649 if (ShAmt->uge(TyBits))
4650 break; // Bad shift.
4651 // We can look through a zext (more or less treating it as a sext) if
4652 // all extended bits are shifted out.
4653 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4654 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4655 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4656 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4657 } else
4658 Tmp =
4659 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4660 if (ShAmt->uge(Tmp))
4661 break; // Shifted all sign bits out.
4662 Tmp2 = ShAmt->getZExtValue();
4663 return Tmp - Tmp2;
4664 }
4665 break;
4666 }
4667 case Instruction::And:
4668 case Instruction::Or:
4669 case Instruction::Xor: // NOT is handled here.
4670 // Logical binary ops preserve the number of sign bits at the worst.
4671 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4672 if (Tmp != 1) {
4673 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4674 FirstAnswer = std::min(Tmp, Tmp2);
4675 // We computed what we know about the sign bits as our first
4676 // answer. Now proceed to the generic code that uses
4677 // computeKnownBits, and pick whichever answer is better.
4678 }
4679 break;
4680
4681 case Instruction::Select: {
4682 // If we have a clamp pattern, we know that the number of sign bits will
4683 // be the minimum of the clamp min/max range.
4684 const Value *X;
4685 const APInt *CLow, *CHigh;
4686 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4687 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4688
4689 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4690 if (Tmp == 1)
4691 break;
4692 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4693 return std::min(Tmp, Tmp2);
4694 }
4695
4696 case Instruction::Add:
4697 // Add can have at most one carry bit. Thus we know that the output
4698 // is, at worst, one more bit than the inputs.
4699 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4700 if (Tmp == 1) break;
4701
4702 // Special case decrementing a value (ADD X, -1):
4703 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4704 if (CRHS->isAllOnesValue()) {
4705 KnownBits Known(TyBits);
4706 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4707
4708 // If the input is known to be 0 or 1, the output is 0/-1, which is
4709 // all sign bits set.
4710 if ((Known.Zero | 1).isAllOnes())
4711 return TyBits;
4712
4713 // If we are subtracting one from a positive number, there is no carry
4714 // out of the result.
4715 if (Known.isNonNegative())
4716 return Tmp;
4717 }
4718
4719 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4720 if (Tmp2 == 1)
4721 break;
4722 return std::min(Tmp, Tmp2) - 1;
4723
4724 case Instruction::Sub:
4725 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4726 if (Tmp2 == 1)
4727 break;
4728
4729 // Handle NEG.
4730 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4731 if (CLHS->isNullValue()) {
4732 KnownBits Known(TyBits);
4733 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4734 // If the input is known to be 0 or 1, the output is 0/-1, which is
4735 // all sign bits set.
4736 if ((Known.Zero | 1).isAllOnes())
4737 return TyBits;
4738
4739 // If the input is known to be positive (the sign bit is known clear),
4740 // the output of the NEG has the same number of sign bits as the
4741 // input.
4742 if (Known.isNonNegative())
4743 return Tmp2;
4744
4745 // Otherwise, we treat this like a SUB.
4746 }
4747
4748 // Sub can have at most one carry bit. Thus we know that the output
4749 // is, at worst, one more bit than the inputs.
4750 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4751 if (Tmp == 1)
4752 break;
4753 return std::min(Tmp, Tmp2) - 1;
4754
4755 case Instruction::Mul: {
4756 // The output of the Mul can be at most twice the valid bits in the
4757 // inputs.
4758 unsigned SignBitsOp0 =
4759 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4760 if (SignBitsOp0 == 1)
4761 break;
4762 unsigned SignBitsOp1 =
4763 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4764 if (SignBitsOp1 == 1)
4765 break;
4766 unsigned OutValidBits =
4767 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4768 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4769 }
4770
4771 case Instruction::PHI: {
4772 const PHINode *PN = cast<PHINode>(U);
4773 unsigned NumIncomingValues = PN->getNumIncomingValues();
4774 // Don't analyze large in-degree PHIs.
4775 if (NumIncomingValues > 4) break;
4776 // Unreachable blocks may have zero-operand PHI nodes.
4777 if (NumIncomingValues == 0) break;
4778
4779 // Take the minimum of all incoming values. This can't infinitely loop
4780 // because of our depth threshold.
4782 Tmp = TyBits;
4783 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4784 if (Tmp == 1) return Tmp;
4785 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4786 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4787 DemandedElts, RecQ, Depth + 1));
4788 }
4789 return Tmp;
4790 }
4791
4792 case Instruction::Trunc: {
4793 // If the input contained enough sign bits that some remain after the
4794 // truncation, then we can make use of that. Otherwise we don't know
4795 // anything.
4796 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4797 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4798 if (Tmp > (OperandTyBits - TyBits))
4799 return Tmp - (OperandTyBits - TyBits);
4800
4801 return 1;
4802 }
4803
4804 case Instruction::ExtractElement:
4805 // Look through extract element. At the moment we keep this simple and
4806 // skip tracking the specific element. But at least we might find
4807 // information valid for all elements of the vector (for example if vector
4808 // is sign extended, shifted, etc).
4809 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4810
4811 case Instruction::ShuffleVector: {
4812 // Collect the minimum number of sign bits that are shared by every vector
4813 // element referenced by the shuffle.
4814 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4815 if (!Shuf) {
4816 // FIXME: Add support for shufflevector constant expressions.
4817 return 1;
4818 }
4819 APInt DemandedLHS, DemandedRHS;
4820 // For undef elements, we don't know anything about the common state of
4821 // the shuffle result.
4822 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4823 return 1;
4824 Tmp = std::numeric_limits<unsigned>::max();
4825 if (!!DemandedLHS) {
4826 const Value *LHS = Shuf->getOperand(0);
4827 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4828 }
4829 // If we don't know anything, early out and try computeKnownBits
4830 // fall-back.
4831 if (Tmp == 1)
4832 break;
4833 if (!!DemandedRHS) {
4834 const Value *RHS = Shuf->getOperand(1);
4835 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4836 Tmp = std::min(Tmp, Tmp2);
4837 }
4838 // If we don't know anything, early out and try computeKnownBits
4839 // fall-back.
4840 if (Tmp == 1)
4841 break;
4842 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4843 return Tmp;
4844 }
4845 case Instruction::Call: {
4846 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4847 switch (II->getIntrinsicID()) {
4848 default:
4849 break;
4850 case Intrinsic::abs:
4851 Tmp =
4852 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4853 if (Tmp == 1)
4854 break;
4855
4856 // Absolute value reduces number of sign bits by at most 1.
4857 return Tmp - 1;
4858 case Intrinsic::smin:
4859 case Intrinsic::smax: {
4860 const APInt *CLow, *CHigh;
4861 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4862 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4863 }
4864 }
4865 }
4866 }
4867 }
4868 }
4869
4870 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4871 // use this information.
4872
4873 // If we can examine all elements of a vector constant successfully, we're
4874 // done (we can't do any better than that). If not, keep trying.
4875 if (unsigned VecSignBits =
4876 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4877 return VecSignBits;
4878
4879 KnownBits Known(TyBits);
4880 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4881
4882 // If we know that the sign bit is either zero or one, determine the number of
4883 // identical bits in the top of the input value.
4884 return std::max(FirstAnswer, Known.countMinSignBits());
4885}
4886
4888 const TargetLibraryInfo *TLI) {
4889 const Function *F = CB.getCalledFunction();
4890 if (!F)
4892
4893 if (F->isIntrinsic())
4894 return F->getIntrinsicID();
4895
4896 // We are going to infer semantics of a library function based on mapping it
4897 // to an LLVM intrinsic. Check that the library function is available from
4898 // this callbase and in this environment.
4899 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4901
4902 LibFunc Func = TLI->getLibFunc(CB);
4903 if (Func == NotLibFunc)
4905
4906 switch (Func) {
4907 default:
4908 break;
4909 case LibFunc_sin:
4910 case LibFunc_sinf:
4911 case LibFunc_sinl:
4912 return Intrinsic::sin;
4913 case LibFunc_cos:
4914 case LibFunc_cosf:
4915 case LibFunc_cosl:
4916 return Intrinsic::cos;
4917 case LibFunc_tan:
4918 case LibFunc_tanf:
4919 case LibFunc_tanl:
4920 return Intrinsic::tan;
4921 case LibFunc_asin:
4922 case LibFunc_asinf:
4923 case LibFunc_asinl:
4924 return Intrinsic::asin;
4925 case LibFunc_acos:
4926 case LibFunc_acosf:
4927 case LibFunc_acosl:
4928 return Intrinsic::acos;
4929 case LibFunc_atan:
4930 case LibFunc_atanf:
4931 case LibFunc_atanl:
4932 return Intrinsic::atan;
4933 case LibFunc_atan2:
4934 case LibFunc_atan2f:
4935 case LibFunc_atan2l:
4936 return Intrinsic::atan2;
4937 case LibFunc_sinh:
4938 case LibFunc_sinhf:
4939 case LibFunc_sinhl:
4940 return Intrinsic::sinh;
4941 case LibFunc_cosh:
4942 case LibFunc_coshf:
4943 case LibFunc_coshl:
4944 return Intrinsic::cosh;
4945 case LibFunc_tanh:
4946 case LibFunc_tanhf:
4947 case LibFunc_tanhl:
4948 return Intrinsic::tanh;
4949 case LibFunc_exp:
4950 case LibFunc_expf:
4951 case LibFunc_expl:
4952 return Intrinsic::exp;
4953 case LibFunc_exp2:
4954 case LibFunc_exp2f:
4955 case LibFunc_exp2l:
4956 return Intrinsic::exp2;
4957 case LibFunc_exp10:
4958 case LibFunc_exp10f:
4959 case LibFunc_exp10l:
4960 return Intrinsic::exp10;
4961 case LibFunc_log:
4962 case LibFunc_logf:
4963 case LibFunc_logl:
4964 return Intrinsic::log;
4965 case LibFunc_log10:
4966 case LibFunc_log10f:
4967 case LibFunc_log10l:
4968 return Intrinsic::log10;
4969 case LibFunc_log2:
4970 case LibFunc_log2f:
4971 case LibFunc_log2l:
4972 return Intrinsic::log2;
4973 case LibFunc_fabs:
4974 case LibFunc_fabsf:
4975 case LibFunc_fabsl:
4976 return Intrinsic::fabs;
4977 case LibFunc_fmin:
4978 case LibFunc_fminf:
4979 case LibFunc_fminl:
4980 return Intrinsic::minnum;
4981 case LibFunc_fmax:
4982 case LibFunc_fmaxf:
4983 case LibFunc_fmaxl:
4984 return Intrinsic::maxnum;
4985 case LibFunc_copysign:
4986 case LibFunc_copysignf:
4987 case LibFunc_copysignl:
4988 return Intrinsic::copysign;
4989 case LibFunc_floor:
4990 case LibFunc_floorf:
4991 case LibFunc_floorl:
4992 return Intrinsic::floor;
4993 case LibFunc_ceil:
4994 case LibFunc_ceilf:
4995 case LibFunc_ceill:
4996 return Intrinsic::ceil;
4997 case LibFunc_trunc:
4998 case LibFunc_truncf:
4999 case LibFunc_truncl:
5000 return Intrinsic::trunc;
5001 case LibFunc_rint:
5002 case LibFunc_rintf:
5003 case LibFunc_rintl:
5004 return Intrinsic::rint;
5005 case LibFunc_nearbyint:
5006 case LibFunc_nearbyintf:
5007 case LibFunc_nearbyintl:
5008 return Intrinsic::nearbyint;
5009 case LibFunc_round:
5010 case LibFunc_roundf:
5011 case LibFunc_roundl:
5012 return Intrinsic::round;
5013 case LibFunc_roundeven:
5014 case LibFunc_roundevenf:
5015 case LibFunc_roundevenl:
5016 return Intrinsic::roundeven;
5017 case LibFunc_pow:
5018 case LibFunc_powf:
5019 case LibFunc_powl:
5020 return Intrinsic::pow;
5021 case LibFunc_sqrt:
5022 case LibFunc_sqrtf:
5023 case LibFunc_sqrtl:
5024 return Intrinsic::sqrt;
5025 }
5026
5028}
5029
5030/// Given an exploded icmp instruction, return true if the comparison only
5031/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
5032/// the result of the comparison is true when the input value is signed.
5034 bool &TrueIfSigned) {
5035 switch (Pred) {
5036 case ICmpInst::ICMP_SLT: // True if LHS s< 0
5037 TrueIfSigned = true;
5038 return RHS.isZero();
5039 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
5040 TrueIfSigned = true;
5041 return RHS.isAllOnes();
5042 case ICmpInst::ICMP_SGT: // True if LHS s> -1
5043 TrueIfSigned = false;
5044 return RHS.isAllOnes();
5045 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
5046 TrueIfSigned = false;
5047 return RHS.isZero();
5048 case ICmpInst::ICMP_UGT:
5049 // True if LHS u> RHS and RHS == sign-bit-mask - 1
5050 TrueIfSigned = true;
5051 return RHS.isMaxSignedValue();
5052 case ICmpInst::ICMP_UGE:
5053 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5054 TrueIfSigned = true;
5055 return RHS.isMinSignedValue();
5056 case ICmpInst::ICMP_ULT:
5057 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5058 TrueIfSigned = false;
5059 return RHS.isMinSignedValue();
5060 case ICmpInst::ICMP_ULE:
5061 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
5062 TrueIfSigned = false;
5063 return RHS.isMaxSignedValue();
5064 default:
5065 return false;
5066 }
5067}
5068
5070 bool CondIsTrue,
5071 const Instruction *CtxI,
5072 KnownFPClass &KnownFromContext,
5073 unsigned Depth = 0) {
5074 Value *A, *B;
5076 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5077 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5078 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5079 Depth + 1);
5080 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5081 Depth + 1);
5082 return;
5083 }
5085 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5086 Depth + 1);
5087 return;
5088 }
5089 CmpPredicate Pred;
5090 Value *LHS;
5091 uint64_t ClassVal = 0;
5092 const APFloat *CRHS;
5093 const APInt *RHS;
5094 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5095 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5096 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5097 LHS != V);
5098 if (CmpVal == V)
5099 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5101 m_Specific(V), m_ConstantInt(ClassVal)))) {
5102 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5103 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5104 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5105 m_APInt(RHS)))) {
5106 bool TrueIfSigned;
5107 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5108 return;
5109 if (TrueIfSigned == CondIsTrue)
5110 KnownFromContext.signBitMustBeOne();
5111 else
5112 KnownFromContext.signBitMustBeZero();
5113 }
5114}
5115
5116/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5117/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5118/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5119/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5120/// exponent range is [-149, -2], but the 0 edge case is above this range).
5121static std::tuple<int, int, int>
5123 if (!Q.CtxI || !Q.DC || !Q.DT)
5125
5126 // Intersect the bounds implied by every dominating condition, keeping the
5127 // tightest maximum. A value may participate in multiple compares
5128 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5129 int MaxExp = APFloat::IEK_Inf;
5130 int MaxExpNonZero = APFloat::IEK_Inf;
5131
5132 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5133 CmpPredicate Pred;
5134 const APFloat *LimitC;
5135 if (!match(BI->getCondition(),
5136 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5137 continue;
5138
5139 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5140 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5141 continue;
5142
5143 // If fabs(x) <= K, implies the exponent min exp range.
5144 // if fabs(x) >= K, swap the successor
5145 bool IsLessEqual =
5146 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5147 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5148 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5149
5150 bool KnownStrictlyLess =
5151 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5152 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5153
5154 BasicBlockEdge Edge1(BI->getParent(),
5155 BI->getSuccessor(IsLessEqual ? 0 : 1));
5156 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5157 // frexp returns an exponent one greater than ilogb.
5158 int Exp = ilogb(*LimitC) + 1;
5159
5160 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5161 // exponent drops by one when K is exact power of two.
5162 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5163 --Exp;
5164
5165 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5166 // may exclude.
5167
5168 // TODO: Figure out lower bound to detect no-underflow.
5169 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5170 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5171 }
5172 }
5173
5174 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5175}
5176
5178 const SimplifyQuery &Q) {
5179 KnownFPClass KnownFromContext;
5180
5181 if (Q.CC && Q.CC->AffectedValues.contains(V))
5183 KnownFromContext);
5184
5185 if (!Q.CtxI)
5186 return KnownFromContext;
5187
5188 if (Q.DC && Q.DT) {
5189 // Handle dominating conditions.
5190 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5191 Value *Cond = BI->getCondition();
5192
5193 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5194 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5195 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5196 KnownFromContext);
5197
5198 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5199 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5200 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5201 KnownFromContext);
5202 }
5203 }
5204
5205 if (!Q.AC)
5206 return KnownFromContext;
5207
5208 // Try to restrict the floating-point classes based on information from
5209 // assumptions.
5210 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5211 if (!AssumeVH)
5212 continue;
5213 CallInst *I = cast<CallInst>(AssumeVH);
5214
5215 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5216 "Got assumption for the wrong function!");
5217 assert(I->getIntrinsicID() == Intrinsic::assume &&
5218 "must be an assume intrinsic");
5219
5220 if (!isValidAssumeForContext(I, Q))
5221 continue;
5222
5223 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5224 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5225 }
5226
5227 return KnownFromContext;
5228}
5229
5231 Value *Arm, bool Invert,
5232 const SimplifyQuery &SQ,
5233 unsigned Depth) {
5234
5235 KnownFPClass KnownSrc;
5237 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5238 Depth + 1);
5239 KnownSrc = KnownSrc.unionWith(Known);
5240 if (KnownSrc.isUnknown())
5241 return;
5242
5243 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5244 Known = KnownSrc;
5245}
5246
5247void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5248 FPClassTest InterestedClasses, KnownFPClass &Known,
5249 const SimplifyQuery &Q, unsigned Depth);
5250
5252 FPClassTest InterestedClasses,
5253 const SimplifyQuery &Q, unsigned Depth) {
5254 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5255 APInt DemandedElts =
5256 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5257 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5258}
5259
5261 const APInt &DemandedElts,
5262 FPClassTest InterestedClasses,
5264 const SimplifyQuery &Q,
5265 unsigned Depth) {
5266 if ((InterestedClasses &
5268 return;
5269
5270 KnownFPClass KnownSrc;
5271 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5272 KnownSrc, Q, Depth + 1);
5273
5274 const fltSemantics &DstTy = Op->getType()->getScalarType()->getFltSemantics();
5275 const fltSemantics &SrcTy =
5276 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5277
5278 const auto *I = dyn_cast<Instruction>(Op);
5279 const Function *F = I ? I->getFunction() : nullptr;
5280 DenormalMode DstMode =
5281 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
5282 DenormalMode SrcMode =
5283 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
5284
5285 Known = KnownFPClass::fptrunc(KnownSrc, DstTy, SrcTy, DstMode, SrcMode);
5286}
5287
5289 switch (IID) {
5290 case Intrinsic::minimum:
5292 case Intrinsic::maximum:
5294 case Intrinsic::minimumnum:
5296 case Intrinsic::maximumnum:
5298 case Intrinsic::minnum:
5300 case Intrinsic::maxnum:
5302 default:
5303 llvm_unreachable("not a floating-point min-max intrinsic");
5304 }
5305}
5306
5307/// \return true if this is a floating point value that is known to have a
5308/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5309static bool isAbsoluteValueULEOne(const Value *V) {
5310 // TODO: Handle frexp
5311 // TODO: Other rounding intrinsics?
5312 // TODO: Try computeKnownExponentRangeFromContext
5313
5314 // fabs(x - floor(x)) <= 1
5315 const Value *SubFloorX;
5316 if (match(V, m_FSub(m_Value(SubFloorX),
5318 return true;
5319
5322}
5323
5324void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5325 FPClassTest InterestedClasses, KnownFPClass &Known,
5326 const SimplifyQuery &Q, unsigned Depth) {
5327 assert(Known.isUnknown() && "should not be called with known information");
5328
5329 if (!DemandedElts) {
5330 // No demanded elts, better to assume we don't know anything.
5331 Known.resetAll();
5332 return;
5333 }
5334
5335 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5336
5337 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5338 Known = KnownFPClass(CFP->getValueAPF());
5339 return;
5340 }
5341
5343 Known.setKnownFPClasses(fcPosZero);
5344 return;
5345 }
5346
5347 if (isa<PoisonValue>(V)) {
5349 return;
5350 }
5351
5352 // Try to handle fixed width vector constants
5353 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5354 const Constant *CV = dyn_cast<Constant>(V);
5355 if (VFVTy && CV) {
5357
5358 // For vectors, verify that each element is not NaN.
5359 unsigned NumElts = VFVTy->getNumElements();
5360 for (unsigned i = 0; i != NumElts; ++i) {
5361 if (!DemandedElts[i])
5362 continue;
5363
5364 Constant *Elt = CV->getAggregateElement(i);
5365 if (!Elt) {
5366 Known = KnownFPClass();
5367 return;
5368 }
5369 if (isa<PoisonValue>(Elt))
5370 continue;
5371 auto *CElt = dyn_cast<ConstantFP>(Elt);
5372 if (!CElt) {
5373 Known = KnownFPClass();
5374 return;
5375 }
5376
5377 Known |= KnownFPClass(CElt->getValueAPF());
5378 }
5379 return;
5380 }
5381
5382 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5384 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5385 Known |= KnownFPClass(CDS->getElementAsAPFloat(I));
5386 return;
5387 }
5388
5389 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5390 // TODO: Handle complex aggregates
5392 for (const Use &Op : CA->operands()) {
5393 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5394 if (!CFP) {
5395 Known = KnownFPClass();
5396 return;
5397 }
5398
5399 Known |= KnownFPClass(CFP->getValueAPF());
5400 }
5401
5402 return;
5403 }
5404
5405 FPClassTest KnownNotFromFlags = fcNone;
5406 if (const auto *CB = dyn_cast<CallBase>(V))
5407 KnownNotFromFlags |= CB->getRetNoFPClass();
5408 else if (const auto *Arg = dyn_cast<Argument>(V))
5409 KnownNotFromFlags |= Arg->getNoFPClass();
5410
5411 const Operator *Op = dyn_cast<Operator>(V);
5413 if (FPOp->hasNoNaNs())
5414 KnownNotFromFlags |= fcNan;
5415 if (FPOp->hasNoInfs())
5416 KnownNotFromFlags |= fcInf;
5417 }
5418
5419 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5420 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5421
5422 // We no longer need to find out about these bits from inputs if we can
5423 // assume this from flags/attributes.
5424 InterestedClasses &= ~KnownNotFromFlags;
5425
5426 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5427 Known.knownNot(KnownNotFromFlags);
5428 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5429 if (*AssumedClasses.getSignBit())
5430 Known.signBitMustBeOne();
5431 else
5432 Known.signBitMustBeZero();
5433 }
5434 });
5435
5436 if (!Op)
5437 return;
5438
5439 // All recursive calls that increase depth must come after this.
5441 return;
5442
5443 const unsigned Opc = Op->getOpcode();
5444 switch (Opc) {
5445 case Instruction::FNeg: {
5446 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5447 Known, Q, Depth + 1);
5448 Known.fneg();
5449 break;
5450 }
5451 case Instruction::Select: {
5452 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5453 KnownFPClass Res;
5454 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5455 Depth + 1);
5456 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5457 Depth);
5458 return Res;
5459 };
5460 // Only known if known in both the LHS and RHS.
5461 Known =
5462 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5463 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5464 break;
5465 }
5466 case Instruction::Load: {
5467 const MDNode *NoFPClass =
5468 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5469 if (!NoFPClass)
5470 break;
5471
5472 ConstantInt *MaskVal =
5474 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5475 break;
5476 }
5477 case Instruction::Call: {
5478 const CallInst *II = cast<CallInst>(Op);
5479 const Intrinsic::ID IID = II->getIntrinsicID();
5480 switch (IID) {
5481 case Intrinsic::fabs: {
5482 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5483 // If we only care about the sign bit we don't need to inspect the
5484 // operand.
5485 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5486 InterestedClasses, Known, Q, Depth + 1);
5487 }
5488
5489 Known.fabs();
5490 break;
5491 }
5492 case Intrinsic::copysign: {
5493 KnownFPClass KnownSign;
5494
5495 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5496 Known, Q, Depth + 1);
5497 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5498 KnownSign, Q, Depth + 1);
5499 Known.copysign(KnownSign);
5500 break;
5501 }
5502 case Intrinsic::fma:
5503 case Intrinsic::fmuladd: {
5504 if ((InterestedClasses & (fcNegative | fcNan)) == fcNone)
5505 break;
5506
5507 const bool IsFMA = IID == Intrinsic::fma;
5508
5509 // FIXME: This should check isGuaranteedNotToBeUndef
5510 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5511 FPClassTest InterestedSquared = InterestedClasses;
5512 FPClassTest InterestedAddend = InterestedClasses;
5513 // Only fma(+inf, +inf, -inf) and fma(-inf, -inf, -inf) produce NaN when
5514 // squaring.
5515 if (InterestedClasses & fcQNan) {
5516 InterestedSquared |= fcSNan | fcInf;
5517 InterestedAddend |= fcSNan | fcNegInf;
5518 }
5519
5520 KnownFPClass KnownSrc, KnownAddend;
5521 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5522 InterestedAddend, KnownAddend, Q, Depth + 1);
5523 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5524 InterestedSquared, KnownSrc, Q, Depth + 1);
5525
5526 const Function *F = II->getFunction();
5527 const fltSemantics &FltSem =
5528 II->getType()->getScalarType()->getFltSemantics();
5530 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5531
5532 if ((KnownNotFromFlags & fcNan) == fcNan) {
5533 KnownSrc.knownNot(fcNan);
5534 KnownAddend.knownNot(fcNan);
5535 }
5536
5537 if ((KnownNotFromFlags & fcInf) == fcInf) {
5538 KnownSrc.knownNot(fcInf);
5539 KnownAddend.knownNot(fcInf);
5540 }
5541
5542 Known = IsFMA
5543 ? KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode)
5544 : KnownFPClass::fmuladd_square(KnownSrc, KnownAddend, Mode);
5545 break;
5546 }
5547
5548 KnownFPClass KnownSrc[3];
5549 for (int I = 0; I != 3; ++I) {
5550 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5551 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5552 if (KnownSrc[I].isUnknown())
5553 return;
5554
5555 if ((KnownNotFromFlags & fcNan) == fcNan)
5556 KnownSrc[I].knownNot(fcNan);
5557 if ((KnownNotFromFlags & fcInf) == fcInf)
5558 KnownSrc[I].knownNot(fcInf);
5559 }
5560
5561 const Function *F = II->getFunction();
5562 const fltSemantics &FltSem =
5563 II->getType()->getScalarType()->getFltSemantics();
5565 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5566 Known =
5567 IsFMA ? KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode)
5568 : KnownFPClass::fmuladd(KnownSrc[0], KnownSrc[1], KnownSrc[2],
5569 Mode);
5570 break;
5571 }
5572 case Intrinsic::sqrt:
5573 case Intrinsic::experimental_constrained_sqrt: {
5574 KnownFPClass KnownSrc;
5575 FPClassTest InterestedSrcs = InterestedClasses;
5576 if (InterestedClasses & fcQNan)
5578 // Subnormals may flush to zero.
5579 if (InterestedClasses & fcZero)
5580 InterestedSrcs |= fcSubnormal;
5581
5582 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5583 KnownSrc, Q, Depth + 1);
5584
5586
5587 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5588 if (!HasNSZ) {
5589 const Function *F = II->getFunction();
5590 const fltSemantics &FltSem =
5591 II->getType()->getScalarType()->getFltSemantics();
5592 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5593 }
5594
5595 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5596 if (HasNSZ)
5597 Known.knownNot(fcNegZero);
5598
5599 break;
5600 }
5601 case Intrinsic::sin: {
5602 KnownFPClass KnownSrc;
5603 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5604 KnownSrc, Q, Depth + 1);
5605 Known = KnownFPClass::sin(KnownSrc);
5606 break;
5607 }
5608 case Intrinsic::cos: {
5609 KnownFPClass KnownSrc;
5610 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5611 KnownSrc, Q, Depth + 1);
5612 Known = KnownFPClass::cos(KnownSrc);
5613 break;
5614 }
5615 case Intrinsic::tan: {
5616 KnownFPClass KnownSrc;
5617 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5618 KnownSrc, Q, Depth + 1);
5619 Known = KnownFPClass::tan(KnownSrc);
5620 break;
5621 }
5622 case Intrinsic::sinh: {
5623 KnownFPClass KnownSrc;
5624 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5625 KnownSrc, Q, Depth + 1);
5626 Known = KnownFPClass::sinh(KnownSrc);
5627 break;
5628 }
5629 case Intrinsic::cosh: {
5630 KnownFPClass KnownSrc;
5631 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5632 KnownSrc, Q, Depth + 1);
5633 Known = KnownFPClass::cosh(KnownSrc);
5634 break;
5635 }
5636 case Intrinsic::tanh: {
5637 KnownFPClass KnownSrc;
5638 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5639 KnownSrc, Q, Depth + 1);
5640 Known = KnownFPClass::tanh(KnownSrc);
5641 break;
5642 }
5643 case Intrinsic::asin: {
5644 KnownFPClass KnownSrc;
5645 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5646 KnownSrc, Q, Depth + 1);
5647 Known = KnownFPClass::asin(KnownSrc);
5648 break;
5649 }
5650 case Intrinsic::acos: {
5651 KnownFPClass KnownSrc;
5652 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5653 KnownSrc, Q, Depth + 1);
5654 Known = KnownFPClass::acos(KnownSrc);
5655 break;
5656 }
5657 case Intrinsic::atan: {
5658 KnownFPClass KnownSrc;
5659 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5660 KnownSrc, Q, Depth + 1);
5661 Known = KnownFPClass::atan(KnownSrc);
5662 break;
5663 }
5664 case Intrinsic::atan2: {
5665 FPClassTest InterestedY = InterestedClasses;
5666 FPClassTest InterestedX = InterestedClasses;
5667
5668 // We can rule out negative values if y cannot have a negative value.
5669 if ((InterestedClasses & fcNegFinite) != fcNone)
5670 InterestedY |= fcNegative;
5671
5672 // We can rule out positive values if y cannot have a positive value.
5673 if ((InterestedClasses & fcPosFinite) != fcNone)
5674 InterestedY |= fcPositive | fcNegSubnormal;
5675
5676 // We can rule out zero and subnormal if x cannot have a positive value.
5677 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5678 InterestedX |= fcPositive | fcNegSubnormal;
5679
5680 KnownFPClass KnownY, KnownX;
5681 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5682 KnownY, Q, Depth + 1);
5683 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5684 KnownX, Q, Depth + 1);
5685
5686 const Function *F = II->getFunction();
5688 F ? F->getDenormalMode(
5689 II->getType()->getScalarType()->getFltSemantics())
5691 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5692 break;
5693 }
5694 case Intrinsic::maxnum:
5695 case Intrinsic::minnum:
5696 case Intrinsic::minimum:
5697 case Intrinsic::maximum:
5698 case Intrinsic::minimumnum:
5699 case Intrinsic::maximumnum: {
5700 KnownFPClass KnownLHS, KnownRHS;
5701 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5702 KnownLHS, Q, Depth + 1);
5703 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5704 KnownRHS, Q, Depth + 1);
5705
5706 const Function *F = II->getFunction();
5707
5709 F ? F->getDenormalMode(
5710 II->getType()->getScalarType()->getFltSemantics())
5712
5713 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5714 Mode);
5715 break;
5716 }
5717 case Intrinsic::canonicalize: {
5718 KnownFPClass KnownSrc;
5719 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5720 KnownSrc, Q, Depth + 1);
5721
5722 const Function *F = II->getFunction();
5723 DenormalMode DenormMode =
5724 F ? F->getDenormalMode(
5725 II->getType()->getScalarType()->getFltSemantics())
5727 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5728 break;
5729 }
5730 case Intrinsic::vector_reduce_fmax:
5731 case Intrinsic::vector_reduce_fmin:
5732 case Intrinsic::vector_reduce_fmaximum:
5733 case Intrinsic::vector_reduce_fminimum:
5734 case Intrinsic::vector_reduce_fmaximumnum:
5735 case Intrinsic::vector_reduce_fminimumnum: {
5736 // reduce min/max will choose an element from one of the vector elements,
5737 // so we can infer and class information that is common to all elements.
5738 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5739 InterestedClasses, Q, Depth + 1);
5740 // Can only propagate sign if output is never NaN.
5741 if (!Known.isKnownNeverNaN())
5742 Known.setSignBit(std::nullopt);
5743 break;
5744 }
5745 // reverse preserves all characteristics of the input vec's element.
5746 case Intrinsic::vector_reverse:
5748 II->getArgOperand(0), DemandedElts.reverseBits(),
5749 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5750 break;
5751 case Intrinsic::trunc:
5752 case Intrinsic::floor:
5753 case Intrinsic::ceil:
5754 case Intrinsic::rint:
5755 case Intrinsic::nearbyint:
5756 case Intrinsic::round:
5757 case Intrinsic::roundeven: {
5758 KnownFPClass KnownSrc;
5759 FPClassTest InterestedSrcs = InterestedClasses;
5760
5761 // Negative round ups towards zero produce negative zero.
5762 if (InterestedSrcs & fcNegFinite)
5763 InterestedSrcs |= fcNegFinite;
5764
5765 // Negative subnormals may flush to positive zero.
5766 if (InterestedSrcs & fcPosFinite)
5767 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
5768
5769 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5770 KnownSrc, Q, Depth + 1);
5771
5772 const Function *F = II->getFunction();
5774 F ? F->getDenormalMode(
5775 II->getType()->getScalarType()->getFltSemantics())
5777 const bool IsMultiUnitFPType =
5778 V->getType()->getScalarType()->isMultiUnitFPType();
5779
5780 switch (IID) {
5781 case Intrinsic::trunc:
5782 Known = KnownFPClass::trunc(KnownSrc, Mode);
5783 break;
5784 case Intrinsic::floor:
5785 Known = KnownFPClass::floor(KnownSrc, IsMultiUnitFPType, Mode);
5786 break;
5787 case Intrinsic::ceil:
5788 Known = KnownFPClass::ceil(KnownSrc, IsMultiUnitFPType, Mode);
5789 break;
5790 default:
5791 Known =
5792 KnownFPClass::roundToIntegral(KnownSrc, IsMultiUnitFPType, Mode);
5793 break;
5794 }
5795 break;
5796 }
5797 case Intrinsic::exp:
5798 case Intrinsic::exp2:
5799 case Intrinsic::exp10:
5800 case Intrinsic::amdgcn_exp2: {
5801 KnownFPClass KnownSrc;
5802 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5803 KnownSrc, Q, Depth + 1);
5804
5805 Known = KnownFPClass::exp(KnownSrc);
5806
5807 Type *EltTy = II->getType()->getScalarType();
5808 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5809 Known.knownNot(fcSubnormal);
5810
5811 break;
5812 }
5813 case Intrinsic::fptrunc_round: {
5814 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5815 Q, Depth);
5816 break;
5817 }
5818 case Intrinsic::log:
5819 case Intrinsic::log10:
5820 case Intrinsic::log2:
5821 case Intrinsic::experimental_constrained_log:
5822 case Intrinsic::experimental_constrained_log10:
5823 case Intrinsic::experimental_constrained_log2:
5824 case Intrinsic::amdgcn_log: {
5825 FPClassTest InterestedSrcs = fcNone;
5826
5827 // log(negative) produces NaN.
5828 if ((InterestedClasses & fcNan) != fcNone)
5829 InterestedSrcs |= fcNan | fcNegative;
5830
5831 // log(logical-zero) produces negative infinity.
5832 if ((InterestedClasses & fcNegInf) != fcNone)
5833 InterestedSrcs |= fcZero | fcSubnormal;
5834
5835 // log(x) < -0.0 if x < +1.0
5836 if ((InterestedClasses & fcNegNormal) != fcNone)
5837 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5838
5839 // log(x) >= +0.0 if x >= +1.0
5840 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5841 InterestedSrcs |= fcPosNormal;
5842
5843 // log(x) is positive infinity iff x is positive infinity.
5844 if ((InterestedClasses & fcPosInf) != fcNone)
5845 InterestedSrcs |= fcPosInf;
5846
5847 KnownFPClass KnownSrc;
5848 if (InterestedSrcs != fcNone)
5849 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5850 KnownSrc, Q, Depth + 1);
5851 const Function *F = II->getFunction();
5853 F ? F->getDenormalMode(
5854 II->getType()->getScalarType()->getFltSemantics())
5856 const bool IsMultiUnitFPType =
5857 V->getType()->getScalarType()->isMultiUnitFPType();
5858 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
5859 break;
5860 }
5861 case Intrinsic::pow: {
5862 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5863 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5864 if (!WantNaN && !WantNegative)
5865 break;
5866
5867 FPClassTest InterestedLHS = fcNone;
5868 FPClassTest InterestedRHS = fcNone;
5869 if (WantNaN) {
5870 // pow may return NaN if one of the arguments is NaN. NaN may also be
5871 // produced from a negative, non-zero finite base and a non-integer
5872 // exponent.
5873 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5874 InterestedRHS |= fcNan;
5875 }
5876 if (WantNegative) {
5877 // A negative value is returned when a negative base is raised to an odd
5878 // integer power. Only normal values can be odd integers.
5879 InterestedLHS |= fcNegative;
5880 InterestedRHS |= fcNormal;
5881 }
5882
5883 KnownFPClass KnownLHS;
5884 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5885 KnownLHS, Q, Depth + 1);
5886
5887 // If the LHS is unknown, then querying the RHS is only useful for rare
5888 // edge cases.
5889 if (KnownLHS.isUnknown())
5890 break;
5891
5892 KnownFPClass KnownRHS;
5893 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5894 KnownRHS, Q, Depth + 1);
5895 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5896 break;
5897 }
5898 case Intrinsic::powi: {
5899 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5900 break;
5901
5902 // The exponent is always a scalar, even when raising a vector to a power.
5903 const Value *Exp = II->getArgOperand(1);
5904 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5905 KnownBits ExponentKnownBits(BitWidth);
5906 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5907
5908 FPClassTest InterestedSrcs = fcNone;
5909 if (InterestedClasses & fcNan)
5910 InterestedSrcs |= fcNan;
5911 if (!ExponentKnownBits.isZero()) {
5912 if (InterestedClasses & fcInf)
5913 InterestedSrcs |= fcFinite | fcInf;
5914 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5915 InterestedSrcs |= fcNegative;
5916 }
5917
5918 KnownFPClass KnownSrc;
5919 if (InterestedSrcs != fcNone)
5920 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5921 KnownSrc, Q, Depth + 1);
5922
5923 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5924 break;
5925 }
5926 case Intrinsic::ldexp: {
5927 KnownFPClass KnownSrc;
5928 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5929 KnownSrc, Q, Depth + 1);
5930 // Can refine inf/zero handling based on the exponent operand.
5931 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5932
5933 const Value *ExpArg = II->getArgOperand(1);
5934 ConstantRange ExpKnownRange =
5935 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5936 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5937 : ConstantRange::getFull(
5938 ExpArg->getType()->getScalarSizeInBits());
5939
5940 const fltSemantics &Flt =
5941 II->getType()->getScalarType()->getFltSemantics();
5942
5943 const Function *F = II->getFunction();
5945 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5946
5947 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5948 ExpKnownRange.getSignedMax(), Flt, Mode);
5949 break;
5950 }
5951 case Intrinsic::arithmetic_fence: {
5952 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5953 Known, Q, Depth + 1);
5954 break;
5955 }
5956 case Intrinsic::experimental_constrained_sitofp:
5957 case Intrinsic::experimental_constrained_uitofp:
5958 // Cannot produce nan
5959 Known.knownNot(fcNan);
5960
5961 // sitofp and uitofp turn into +0.0 for zero.
5962 Known.knownNot(fcNegZero);
5963
5964 // Integers cannot be subnormal
5965 Known.knownNot(fcSubnormal);
5966
5967 if (IID == Intrinsic::experimental_constrained_uitofp)
5968 Known.signBitMustBeZero();
5969
5970 // TODO: Copy inf handling from instructions
5971 break;
5972
5973 case Intrinsic::amdgcn_fract: {
5974 Known.knownNot(fcInf);
5975
5976 if (InterestedClasses & fcNan) {
5977 KnownFPClass KnownSrc;
5978 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5979 InterestedClasses, KnownSrc, Q, Depth + 1);
5980
5981 if (KnownSrc.isKnownNeverInfOrNaN())
5982 Known.knownNot(fcNan);
5983 else if (KnownSrc.isKnownNever(fcSNan))
5984 Known.knownNot(fcSNan);
5985 }
5986
5987 break;
5988 }
5989 case Intrinsic::amdgcn_rcp: {
5990 KnownFPClass KnownSrc;
5991 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5992 KnownSrc, Q, Depth + 1);
5993
5994 Known.propagateNonNaN(KnownSrc);
5995
5996 Type *EltTy = II->getType()->getScalarType();
5997
5998 // f32 denormal always flushed.
5999 if (EltTy->isFloatTy()) {
6000 Known.knownNot(fcSubnormal);
6001 KnownSrc.knownNot(fcSubnormal);
6002 }
6003
6004 if (KnownSrc.isKnownNever(fcNegative))
6005 Known.knownNot(fcNegative);
6006 if (KnownSrc.isKnownNever(fcPositive))
6007 Known.knownNot(fcPositive);
6008
6009 if (const Function *F = II->getFunction()) {
6010 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6011 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6012 Known.knownNot(fcPosInf);
6013 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6014 Known.knownNot(fcNegInf);
6015 }
6016
6017 break;
6018 }
6019 case Intrinsic::amdgcn_rsq: {
6020 KnownFPClass KnownSrc;
6021 // The only negative value that can be returned is -inf for -0 inputs.
6023
6024 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6025 KnownSrc, Q, Depth + 1);
6026
6027 // Negative -> nan
6028 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
6029 Known.knownNot(fcNan);
6030 else if (KnownSrc.isKnownNever(fcSNan))
6031 Known.knownNot(fcSNan);
6032
6033 // +inf -> +0
6034 if (KnownSrc.isKnownNeverPosInfinity())
6035 Known.knownNot(fcPosZero);
6036
6037 Type *EltTy = II->getType()->getScalarType();
6038
6039 // f32 denormal always flushed.
6040 if (EltTy->isFloatTy())
6041 Known.knownNot(fcPosSubnormal);
6042
6043 if (const Function *F = II->getFunction()) {
6044 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6045
6046 // -0 -> -inf
6047 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6048 Known.knownNot(fcNegInf);
6049
6050 // +0 -> +inf
6051 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6052 Known.knownNot(fcPosInf);
6053 }
6054
6055 break;
6056 }
6057 case Intrinsic::amdgcn_trig_preop: {
6058 // Always returns a value [0, 1)
6059 Known.knownNot(fcNan | fcInf | fcNegative);
6060 break;
6061 }
6062 case Intrinsic::convert_from_arbitrary_fp: {
6063 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
6064 StringRef FormatStr = cast<MDString>(MD)->getString();
6065
6066 const fltSemantics *SrcSemantics =
6068 if (!SrcSemantics)
6069 break;
6070
6071 const fltSemantics DstSemantics =
6072 II->getType()->getScalarType()->getFltSemantics();
6073
6074 if (!APFloat::semanticsHasNaN(*SrcSemantics))
6075 Known.knownNot(fcNan);
6076
6077 // fcInf can only be cleared if the source format has no Inf encoding
6078 // and the dst max exp can accommodate src max exp.
6079 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
6080 APFloat::semanticsMaxExponent(*SrcSemantics) <=
6081 APFloat::semanticsMaxExponent(DstSemantics))
6082 Known.knownNot(fcInf);
6083
6084 // Check and clear all neg flags for formats that do not have signed
6085 // representation.
6086 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
6087 Known.knownNot(fcNegative);
6088
6089 // Check if format has no zero at all (Float8E8M0FNU), or no negative
6090 // zero.
6091 if (!APFloat::semanticsHasZero(*SrcSemantics))
6092 Known.knownNot(fcZero);
6093 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
6094 Known.knownNot(fcNegZero);
6095
6096 // If src lands normally in dest, the result can never be subnormal.
6097 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6098 Known.knownNot(fcSubnormal);
6099 break;
6100 }
6101 default:
6102 break;
6103 }
6104
6105 break;
6106 }
6107 case Instruction::FAdd:
6108 case Instruction::FSub: {
6109 KnownFPClass KnownLHS, KnownRHS;
6110 bool WantNegative =
6111 Op->getOpcode() == Instruction::FAdd &&
6112 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6113 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6114 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6115
6116 if (!WantNaN && !WantNegative && !WantNegZero)
6117 break;
6118
6119 FPClassTest InterestedSrcs = InterestedClasses;
6120 if (WantNegative)
6121 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6122 if (InterestedClasses & fcNan)
6123 InterestedSrcs |= fcInf;
6124 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6125 KnownRHS, Q, Depth + 1);
6126
6127 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6128 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6129 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6130 Depth + 1);
6131 if (Self)
6132 KnownLHS = KnownRHS;
6133
6134 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6135 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6136 WantNegZero || Opc == Instruction::FSub) {
6137
6138 // FIXME: Context function should always be passed in separately
6139 const Function *F = cast<Instruction>(Op)->getFunction();
6140 const fltSemantics &FltSem =
6141 Op->getType()->getScalarType()->getFltSemantics();
6143 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6144
6145 if (Self && Opc == Instruction::FAdd) {
6146 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6147 } else {
6148 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6149 // there's no point.
6150
6151 if (!Self) {
6152 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6153 KnownLHS, Q, Depth + 1);
6154 }
6155
6156 Known = Opc == Instruction::FAdd
6157 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6158 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6159 }
6160 }
6161
6162 break;
6163 }
6164 case Instruction::FMul: {
6165 const Function *F = cast<Instruction>(Op)->getFunction();
6167 F ? F->getDenormalMode(
6168 Op->getType()->getScalarType()->getFltSemantics())
6170
6171 Value *LHS = Op->getOperand(0);
6172 Value *RHS = Op->getOperand(1);
6173 // X * X is always non-negative or a NaN.
6174 // FIXME: Should check isGuaranteedNotToBeUndef
6175 if (LHS == RHS) {
6176 KnownFPClass KnownSrc;
6177 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6178 Depth + 1);
6179 Known = KnownFPClass::square(KnownSrc, Mode);
6180 break;
6181 }
6182
6183 KnownFPClass KnownLHS, KnownRHS;
6184
6185 const APFloat *CRHS;
6186 if (match(RHS, m_APFloat(CRHS))) {
6187 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6188 Depth + 1);
6189 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6190 } else {
6191 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6192 Depth + 1);
6193 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6194 // additional not-nan if the addend is known-not negative infinity if the
6195 // multiply is known-not infinity.
6196
6197 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6198 Depth + 1);
6199 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6200 }
6201
6202 /// Propgate no-infs if the other source is known smaller than one, such
6203 /// that this cannot introduce overflow.
6204 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6205 Known.knownNot(fcInf);
6206 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6207 Known.knownNot(fcInf);
6208
6209 break;
6210 }
6211 case Instruction::FDiv: {
6212 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6213
6214 const Function *F = cast<Instruction>(Op)->getFunction();
6215 const fltSemantics &FltSem =
6216 Op->getType()->getScalarType()->getFltSemantics();
6218 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6219
6220 if (Op->getOperand(0) == Op->getOperand(1) &&
6221 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6222 // X / X is always exactly 1.0 or a NaN.
6223 Known.setKnownFPClasses(fcNan | fcPosNormal);
6224
6225 if (!WantNan)
6226 break;
6227
6228 KnownFPClass KnownSrc;
6229 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6230 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6231 Depth + 1);
6232
6233 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6234 break;
6235 }
6236
6237 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6238 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6239 if (!WantNan && !WantNegative && !WantPositive)
6240 break;
6241
6242 KnownFPClass KnownLHS, KnownRHS;
6243 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6244 Q, Depth + 1);
6245
6246 bool KnowSomethingUseful =
6247 KnownRHS.isKnownNever(fcSNan) ||
6250
6251 if (KnowSomethingUseful)
6252 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6253 Q, Depth + 1);
6254
6255 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6256 break;
6257 }
6258 case Instruction::FRem: {
6259 FPClassTest InterestedLHS = fcNone;
6260 FPClassTest InterestedRHS = fcNone;
6261
6262 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6263 if (InterestedClasses & fcNan) {
6264 InterestedLHS |= fcNan | fcInf;
6265 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6266 }
6267
6268 // The sign for frem is the same as the first operand.
6269 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6270 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6271 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6272 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6273
6274 // A negative zero result requires a negative finite first operand.
6275 if (InterestedClasses & fcNegZero)
6276 InterestedLHS |= fcNegFinite;
6277
6278 // A positive zero result can additionally come from a negative finite
6279 // result being flushed to positive zero.
6280 if (InterestedClasses & fcPosZero)
6281 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6282
6283 const Function *F = cast<Instruction>(Op)->getFunction();
6285 F ? F->getDenormalMode(
6286 Op->getType()->getScalarType()->getFltSemantics())
6288
6289 if (Op->getOperand(0) == Op->getOperand(1) &&
6290 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6291 // X % X is always exactly [+-]0.0 or a NaN.
6292 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6293 KnownFPClass KnownSrc;
6294 if (InterestedSrcs != fcNone)
6295 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6296 KnownSrc, Q, Depth + 1);
6297 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6298 break;
6299 }
6300
6301 KnownFPClass KnownLHS;
6302 if (InterestedLHS != fcNone)
6303 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6304 KnownLHS, Q, Depth + 1);
6305
6306 KnownFPClass KnownRHS;
6307 // RHS is only useful for refining NaN classes.
6308 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6309 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6310 KnownRHS, Q, Depth + 1);
6311
6312 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6313
6314 break;
6315 }
6316 case Instruction::FPExt: {
6317 KnownFPClass KnownSrc;
6318 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6319 KnownSrc, Q, Depth + 1);
6320
6321 const fltSemantics &DstTy =
6322 Op->getType()->getScalarType()->getFltSemantics();
6323 const fltSemantics &SrcTy =
6324 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6325
6326 const auto *I = dyn_cast<Instruction>(Op);
6327 const Function *F = I ? I->getFunction() : nullptr;
6328 DenormalMode DstMode =
6329 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
6330 DenormalMode SrcMode =
6331 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
6332
6333 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy, DstMode, SrcMode);
6334 break;
6335 }
6336 case Instruction::FPTrunc: {
6337 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6338 Depth);
6339 break;
6340 }
6341 case Instruction::SIToFP:
6342 case Instruction::UIToFP: {
6343 // Cannot produce nan
6344 Known.knownNot(fcNan);
6345
6346 // Integers cannot be subnormal
6347 Known.knownNot(fcSubnormal);
6348
6349 // sitofp and uitofp turn into +0.0 for zero.
6350 Known.knownNot(fcNegZero);
6351
6352 // UIToFP is always non-negative regardless of known bits.
6353 if (Op->getOpcode() == Instruction::UIToFP)
6354 Known.signBitMustBeZero();
6355
6356 // Only compute known bits if we can learn something useful from them.
6357 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6358 break;
6359
6360 KnownBits IntKnown =
6361 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6362
6363 // If the integer is non-zero, the result cannot be +0.0
6364 if (IntKnown.isNonZero())
6365 Known.knownNot(fcPosZero);
6366
6367 if (Op->getOpcode() == Instruction::SIToFP) {
6368 // If the signed integer is known non-negative, the result is
6369 // non-negative. If the signed integer is known negative, the result is
6370 // negative.
6371 if (IntKnown.isNonNegative()) {
6372 Known.signBitMustBeZero();
6373 } else if (IntKnown.isNegative()) {
6374 Known.signBitMustBeOne();
6375 }
6376 }
6377
6378 // Guard kept for ilogb()
6379 if (InterestedClasses & fcInf) {
6380 // Get width of largest magnitude integer known.
6381 // This still works for a signed minimum value because the largest FP
6382 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6383 int IntSize = IntKnown.getBitWidth();
6384 if (Op->getOpcode() == Instruction::UIToFP)
6385 IntSize -= IntKnown.countMinLeadingZeros();
6386 else if (Op->getOpcode() == Instruction::SIToFP)
6387 IntSize -= IntKnown.countMinSignBits();
6388
6389 // If the exponent of the largest finite FP value can hold the largest
6390 // integer, the result of the cast must be finite.
6391 Type *FPTy = Op->getType()->getScalarType();
6392 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6393 Known.knownNot(fcInf);
6394 }
6395
6396 break;
6397 }
6398 case Instruction::ExtractElement: {
6399 // Look through extract element. If the index is non-constant or
6400 // out-of-range demand all elements, otherwise just the extracted element.
6401 const Value *Vec = Op->getOperand(0);
6402
6403 APInt DemandedVecElts;
6404 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6405 unsigned NumElts = VecTy->getNumElements();
6406 DemandedVecElts = APInt::getAllOnes(NumElts);
6407 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6408 if (CIdx && CIdx->getValue().ult(NumElts))
6409 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6410 } else {
6411 DemandedVecElts = APInt(1, 1);
6412 }
6413
6414 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6415 Q, Depth + 1);
6416 }
6417 case Instruction::InsertElement: {
6418 if (isa<ScalableVectorType>(Op->getType()))
6419 return;
6420
6421 const Value *Vec = Op->getOperand(0);
6422 const Value *Elt = Op->getOperand(1);
6423 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6424 unsigned NumElts = DemandedElts.getBitWidth();
6425 APInt DemandedVecElts = DemandedElts;
6426 bool NeedsElt = true;
6427 // If we know the index we are inserting to, clear it from Vec check.
6428 if (CIdx && CIdx->getValue().ult(NumElts)) {
6429 DemandedVecElts.clearBit(CIdx->getZExtValue());
6430 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6431 }
6432
6433 // Do we demand the inserted element?
6434 if (NeedsElt) {
6435 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6436 // If we don't know any bits, early out.
6437 if (Known.isUnknown())
6438 break;
6439 } else {
6441 }
6442
6443 // Do we need anymore elements from Vec?
6444 if (!DemandedVecElts.isZero()) {
6445 KnownFPClass Known2;
6446 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6447 Depth + 1);
6448 Known |= Known2;
6449 }
6450
6451 break;
6452 }
6453 case Instruction::ShuffleVector: {
6454 // Handle vector splat idiom
6455 if (Value *Splat = getSplatValue(V)) {
6456 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6457 break;
6458 }
6459
6460 // For undef elements, we don't know anything about the common state of
6461 // the shuffle result.
6462 APInt DemandedLHS, DemandedRHS;
6463 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6464 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6465 return;
6466
6467 if (!!DemandedLHS) {
6468 const Value *LHS = Shuf->getOperand(0);
6469 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6470 Depth + 1);
6471
6472 // If we don't know any bits, early out.
6473 if (Known.isUnknown())
6474 break;
6475 } else {
6477 }
6478
6479 if (!!DemandedRHS) {
6480 KnownFPClass Known2;
6481 const Value *RHS = Shuf->getOperand(1);
6482 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6483 Depth + 1);
6484 Known |= Known2;
6485 }
6486
6487 break;
6488 }
6489 case Instruction::ExtractValue: {
6490 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6491 ArrayRef<unsigned> Indices = Extract->getIndices();
6492 const Value *Src = Extract->getAggregateOperand();
6493 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6494 Indices[0] == 0) {
6495 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6496 switch (II->getIntrinsicID()) {
6497 case Intrinsic::frexp: {
6498 FPClassTest InterestedSrcs = InterestedClasses;
6499
6500 // Positive subnormals and negative subnormals could become positive
6501 // zero.
6502 if (InterestedClasses & fcPosZero)
6503 InterestedSrcs |= fcSubnormal;
6504
6505 // Negative subnormals could become negative zero.
6506 if (InterestedClasses & fcNegZero)
6507 InterestedSrcs |= fcNegSubnormal;
6508
6509 if (InterestedClasses & fcPosNormal)
6510 InterestedSrcs |= fcPosSubnormal;
6511
6512 if (InterestedClasses & fcNegNormal)
6513 InterestedSrcs |= fcNegSubnormal;
6514
6515 KnownFPClass KnownSrc;
6516 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6517 InterestedSrcs, KnownSrc, Q, Depth + 1);
6518
6519 const Function *F = cast<Instruction>(Op)->getFunction();
6520 const fltSemantics &FltSem =
6521 Op->getType()->getScalarType()->getFltSemantics();
6522
6524 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6525 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6526 return;
6527 }
6528 default:
6529 break;
6530 }
6531 }
6532 }
6533
6534 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6535 Depth + 1);
6536 break;
6537 }
6538 case Instruction::PHI: {
6539 const PHINode *P = cast<PHINode>(Op);
6540 // Unreachable blocks may have zero-operand PHI nodes.
6541 if (P->getNumIncomingValues() == 0)
6542 break;
6543
6544 // Otherwise take the unions of the known bit sets of the operands,
6545 // taking conservative care to avoid excessive recursion.
6546 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6547
6548 if (Depth < PhiRecursionLimit) {
6549 // Skip if every incoming value references to ourself.
6550 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6551 break;
6552
6553 bool First = true;
6554
6555 for (const Use &U : P->operands()) {
6556 Value *IncValue;
6557 Instruction *CtxI;
6558 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6559 // Skip direct self references.
6560 if (IncValue == P)
6561 continue;
6562
6563 KnownFPClass KnownSrc;
6564 // Recurse, but cap the recursion to two levels, because we don't want
6565 // to waste time spinning around in loops. We need at least depth 2 to
6566 // detect known sign bits.
6567 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6569 PhiRecursionLimit);
6570
6571 if (First) {
6572 Known = KnownSrc;
6573 First = false;
6574 } else {
6575 Known |= KnownSrc;
6576 }
6577
6578 if (Known.getKnownFPClasses() == fcAllFlags)
6579 break;
6580 }
6581 }
6582
6583 // Look for the case of a for loop which has a positive
6584 // initial value and is incremented by a squared value.
6585 // This will propagate sign information out of such loops.
6586 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6587 break;
6588 for (unsigned I = 0; I < 2; I++) {
6589 Value *RecurValue = P->getIncomingValue(1 - I);
6591 if (!II)
6592 continue;
6593 Value *R, *L, *Init;
6594 PHINode *PN;
6596 PN == P) {
6597 switch (II->getIntrinsicID()) {
6598 case Intrinsic::fma:
6599 case Intrinsic::fmuladd: {
6600 KnownFPClass KnownStart;
6601 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6602 Q, Depth + 1);
6603 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6604 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6606 break;
6607 }
6608 }
6609 }
6610 }
6611 break;
6612 }
6613 case Instruction::BitCast: {
6614 const Value *Src;
6615 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6616 !Src->getType()->isIntOrIntVectorTy())
6617 break;
6618
6619 const Type *Ty = Op->getType();
6620
6621 Value *CastLHS, *CastRHS;
6622
6623 // Match bitcast(umax(bitcast(a), bitcast(b)))
6624 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6625 m_BitCast(m_Value(CastRHS)))) &&
6626 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6627 KnownFPClass KnownLHS, KnownRHS;
6628 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6629 Depth + 1);
6630 if (!KnownRHS.isUnknown()) {
6631 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6632 Q, Depth + 1);
6633 Known = KnownLHS | KnownRHS;
6634 }
6635
6636 return;
6637 }
6638
6639 const Type *EltTy = Ty->getScalarType();
6640 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6641 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6642
6644 break;
6645 }
6646 default:
6647 break;
6648 }
6649}
6650
6652 const APInt &DemandedElts,
6653 FPClassTest InterestedClasses,
6654 const SimplifyQuery &SQ,
6655 unsigned Depth) {
6656 KnownFPClass KnownClasses;
6657 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6658 Depth);
6659 return KnownClasses;
6660}
6661
6663 FPClassTest InterestedClasses,
6664 const SimplifyQuery &SQ,
6665 unsigned Depth) {
6667 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6668 return Known;
6669}
6670
6672 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6673 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6674 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6675 return computeKnownFPClass(V, InterestedClasses,
6676 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6677 Depth);
6678}
6679
6681llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6682 FastMathFlags FMF, FPClassTest InterestedClasses,
6683 const SimplifyQuery &SQ, unsigned Depth) {
6684 if (FMF.noNaNs())
6685 InterestedClasses &= ~fcNan;
6686 if (FMF.noInfs())
6687 InterestedClasses &= ~fcInf;
6688
6689 KnownFPClass Result =
6690 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6691
6692 if (FMF.noNaNs())
6693 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6694 if (FMF.noInfs())
6695 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6696 return Result;
6697}
6698
6700 FPClassTest InterestedClasses,
6701 const SimplifyQuery &SQ,
6702 unsigned Depth) {
6703 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6704 APInt DemandedElts =
6705 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6706 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6707 Depth);
6708}
6709
6711 unsigned Depth) {
6713 return Known.isKnownNever(fcNegZero);
6714}
6715
6717 unsigned Depth) {
6720 return Known.cannotBeOrderedLessThanZero();
6721}
6722
6724 unsigned Depth) {
6726 return Known.isKnownNeverInfinity();
6727}
6728
6729/// Return true if the floating-point value can never contain a NaN or infinity.
6731 unsigned Depth) {
6733 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6734}
6735
6736/// Return true if the floating-point scalar value is not a NaN or if the
6737/// floating-point vector value has no NaN elements. Return false if a value
6738/// could ever be NaN.
6740 unsigned Depth) {
6742 return Known.isKnownNeverNaN();
6743}
6744
6745/// Return false if we can prove that the specified FP value's sign bit is 0.
6746/// Return true if we can prove that the specified FP value's sign bit is 1.
6747/// Otherwise return std::nullopt.
6748std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6749 const SimplifyQuery &SQ,
6750 unsigned Depth) {
6752 return Known.getSignBit();
6753}
6754
6756 auto *User = cast<Instruction>(U.getUser());
6757 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6758 if (FPOp->hasNoSignedZeros())
6759 return true;
6760 }
6761
6762 switch (User->getOpcode()) {
6763 case Instruction::FPToSI:
6764 case Instruction::FPToUI:
6765 return true;
6766 case Instruction::FRem:
6767 // frem(x, +-0.0) == NaN, and more generally frem(x, y) == frem(x, -y).
6768 return U.getOperandNo() == 1;
6769 case Instruction::FCmp:
6770 // fcmp treats both positive and negative zero as equal.
6771 return true;
6772 case Instruction::Call:
6773 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6774 switch (II->getIntrinsicID()) {
6775 case Intrinsic::fabs:
6776 case Intrinsic::exp:
6777 case Intrinsic::exp2:
6778 case Intrinsic::exp10:
6779 case Intrinsic::log:
6780 case Intrinsic::log2:
6781 case Intrinsic::log10:
6782 case Intrinsic::cos:
6783 case Intrinsic::acos:
6784 case Intrinsic::cosh:
6785 case Intrinsic::fptosi_sat:
6786 case Intrinsic::fptoui_sat:
6787 case Intrinsic::lround:
6788 case Intrinsic::llround:
6789 case Intrinsic::lrint:
6790 case Intrinsic::llrint:
6791 return true;
6792 case Intrinsic::copysign:
6793 return U.getOperandNo() == 0;
6794 case Intrinsic::pow:
6795 // pow(x, +-0.0) == +1.0 or NaN
6796 return U.getOperandNo() == 1;
6797 case Intrinsic::is_fpclass: {
6798 auto Test =
6799 static_cast<FPClassTest>(
6800 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6803 }
6804 default:
6805 return false;
6806 }
6807 }
6808 return false;
6809 default:
6810 return false;
6811 }
6812}
6813
6815 auto *User = cast<Instruction>(U.getUser());
6816 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6817 if (FPOp->hasNoNaNs())
6818 return true;
6819 }
6820
6821 switch (User->getOpcode()) {
6822 case Instruction::FPToSI:
6823 case Instruction::FPToUI:
6824 return true;
6825 // Proper FP math operations ignore the sign bit of NaN.
6826 case Instruction::FAdd:
6827 case Instruction::FSub:
6828 case Instruction::FMul:
6829 case Instruction::FDiv:
6830 case Instruction::FRem:
6831 case Instruction::FPTrunc:
6832 case Instruction::FPExt:
6833 case Instruction::FCmp:
6834 return true;
6835 // Bitwise FP operations should preserve the sign bit of NaN.
6836 case Instruction::FNeg:
6837 case Instruction::Select:
6838 case Instruction::PHI:
6839 return false;
6840 case Instruction::Ret:
6841 return User->getFunction()->getAttributes().getRetNoFPClass() &
6843 case Instruction::Call:
6844 case Instruction::Invoke: {
6845 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6846 switch (II->getIntrinsicID()) {
6847 case Intrinsic::fabs:
6848 return true;
6849 case Intrinsic::copysign:
6850 return U.getOperandNo() == 0;
6851 // Other proper FP math intrinsics ignore the sign bit of NaN.
6852 case Intrinsic::maxnum:
6853 case Intrinsic::minnum:
6854 case Intrinsic::maximum:
6855 case Intrinsic::minimum:
6856 case Intrinsic::maximumnum:
6857 case Intrinsic::minimumnum:
6858 case Intrinsic::canonicalize:
6859 case Intrinsic::fma:
6860 case Intrinsic::fmuladd:
6861 case Intrinsic::sqrt:
6862 case Intrinsic::pow:
6863 case Intrinsic::powi:
6864 case Intrinsic::fptoui_sat:
6865 case Intrinsic::fptosi_sat:
6866 case Intrinsic::is_fpclass:
6867 return true;
6868 default:
6869 return false;
6870 }
6871 }
6872
6873 FPClassTest NoFPClass =
6874 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6875 return NoFPClass & FPClassTest::fcNan;
6876 }
6877 default:
6878 return false;
6879 }
6880}
6881
6883 FastMathFlags FMF) {
6884 if (isa<PoisonValue>(V))
6885 return true;
6886 if (isa<UndefValue>(V))
6887 return false;
6888
6889 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6890 return true;
6891
6893 if (!I)
6894 return false;
6895
6896 switch (I->getOpcode()) {
6897 case Instruction::SIToFP:
6898 case Instruction::UIToFP:
6899 // TODO: Could check nofpclass(inf) on incoming argument
6900 if (FMF.noInfs())
6901 return true;
6902
6903 // Need to check int size cannot produce infinity, which computeKnownFPClass
6904 // knows how to do already.
6905 return isKnownNeverInfinity(I, SQ);
6906 case Instruction::Call: {
6907 const CallInst *CI = cast<CallInst>(I);
6908 switch (CI->getIntrinsicID()) {
6909 case Intrinsic::trunc:
6910 case Intrinsic::floor:
6911 case Intrinsic::ceil:
6912 case Intrinsic::rint:
6913 case Intrinsic::nearbyint:
6914 case Intrinsic::round:
6915 case Intrinsic::roundeven:
6916 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6917 default:
6918 break;
6919 }
6920
6921 break;
6922 }
6923 default:
6924 break;
6925 }
6926
6927 return false;
6928}
6929
6931
6932 // All byte-wide stores are splatable, even of arbitrary variables.
6933 if (V->getType()->isIntegerTy(8))
6934 return V;
6935
6936 LLVMContext &Ctx = V->getContext();
6937
6938 // Undef don't care.
6939 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6940 if (isa<UndefValue>(V))
6941 return UndefInt8;
6942
6943 // Return poison for zero-sized type.
6944 if (DL.getTypeStoreSize(V->getType()).isZero())
6945 return PoisonValue::get(Type::getInt8Ty(Ctx));
6946
6948 if (!C) {
6949 // Conceptually, we could handle things like:
6950 // %a = zext i8 %X to i16
6951 // %b = shl i16 %a, 8
6952 // %c = or i16 %a, %b
6953 // but until there is an example that actually needs this, it doesn't seem
6954 // worth worrying about.
6955 return nullptr;
6956 }
6957
6958 // Handle 'null' ConstantArrayZero etc.
6959 if (C->isNullValue())
6961
6962 // Constant floating-point values can be handled as integer values if the
6963 // corresponding integer value is "byteable". An important case is 0.0.
6964 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6965 Type *ScalarTy = CFP->getType()->getScalarType();
6966 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6967 return isBytewiseValue(
6968 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6969
6970 // Don't handle long double formats, which have strange constraints.
6971 return nullptr;
6972 }
6973
6974 // We can handle constant integers that are multiple of 8 bits.
6975 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6976 if (CI->getBitWidth() % 8 == 0) {
6977 if (!CI->getValue().isSplat(8))
6978 return nullptr;
6979 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6980 }
6981 }
6982
6983 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6984 if (CE->getOpcode() == Instruction::IntToPtr) {
6985 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6986 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6988 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6989 return isBytewiseValue(Op, DL);
6990 }
6991 }
6992 }
6993
6994 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6995 if (LHS == RHS)
6996 return LHS;
6997 if (!LHS || !RHS)
6998 return nullptr;
6999 if (LHS == UndefInt8)
7000 return RHS;
7001 if (RHS == UndefInt8)
7002 return LHS;
7003 return nullptr;
7004 };
7005
7007 Value *Val = UndefInt8;
7008 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
7009 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
7010 return nullptr;
7011 return Val;
7012 }
7013
7015 Value *Val = UndefInt8;
7016 for (Value *Op : C->operands())
7017 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
7018 return nullptr;
7019 return Val;
7020 }
7021
7022 // Don't try to handle the handful of other constants.
7023 return nullptr;
7024}
7025
7026// This is the recursive version of BuildSubAggregate. It takes a few different
7027// arguments. Idxs is the index within the nested struct From that we are
7028// looking at now (which is of type IndexedType). IdxSkip is the number of
7029// indices from Idxs that should be left out when inserting into the resulting
7030// struct. To is the result struct built so far, new insertvalue instructions
7031// build on that.
7032static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
7034 unsigned IdxSkip,
7035 BasicBlock::iterator InsertBefore) {
7036 StructType *STy = dyn_cast<StructType>(IndexedType);
7037 if (STy) {
7038 // Save the original To argument so we can modify it
7039 Value *OrigTo = To;
7040 // General case, the type indexed by Idxs is a struct
7041 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
7042 // Process each struct element recursively
7043 Idxs.push_back(i);
7044 Value *PrevTo = To;
7045 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
7046 InsertBefore);
7047 Idxs.pop_back();
7048 if (!To) {
7049 // Couldn't find any inserted value for this index? Cleanup
7050 while (PrevTo != OrigTo) {
7052 PrevTo = Del->getAggregateOperand();
7053 Del->eraseFromParent();
7054 }
7055 // Stop processing elements
7056 break;
7057 }
7058 }
7059 // If we successfully found a value for each of our subaggregates
7060 if (To)
7061 return To;
7062 }
7063 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
7064 // the struct's elements had a value that was inserted directly. In the latter
7065 // case, perhaps we can't determine each of the subelements individually, but
7066 // we might be able to find the complete struct somewhere.
7067
7068 // Find the value that is at that particular spot
7069 Value *V = FindInsertedValue(From, Idxs);
7070
7071 if (!V)
7072 return nullptr;
7073
7074 // Insert the value in the new (sub) aggregate
7075 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
7076 InsertBefore);
7077}
7078
7079// This helper takes a nested struct and extracts a part of it (which is again a
7080// struct) into a new value. For example, given the struct:
7081// { a, { b, { c, d }, e } }
7082// and the indices "1, 1" this returns
7083// { c, d }.
7084//
7085// It does this by inserting an insertvalue for each element in the resulting
7086// struct, as opposed to just inserting a single struct. This will only work if
7087// each of the elements of the substruct are known (ie, inserted into From by an
7088// insertvalue instruction somewhere).
7089//
7090// All inserted insertvalue instructions are inserted before InsertBefore
7092 BasicBlock::iterator InsertBefore) {
7093 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
7094 idx_range);
7095 Value *To = PoisonValue::get(IndexedType);
7096 SmallVector<unsigned, 10> Idxs(idx_range);
7097 unsigned IdxSkip = Idxs.size();
7098
7099 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
7100}
7101
7102/// Given an aggregate and a sequence of indices, see if the scalar value
7103/// indexed is already around as a register, for example if it was inserted
7104/// directly into the aggregate.
7105///
7106/// If InsertBefore is not null, this function will duplicate (modified)
7107/// insertvalues when a part of a nested struct is extracted.
7108Value *
7110 std::optional<BasicBlock::iterator> InsertBefore) {
7111 // Nothing to index? Just return V then (this is useful at the end of our
7112 // recursion).
7113 if (idx_range.empty())
7114 return V;
7115 // We have indices, so V should have an indexable type.
7116 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
7117 "Not looking at a struct or array?");
7118 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
7119 "Invalid indices for type?");
7120
7121 if (Constant *C = dyn_cast<Constant>(V)) {
7122 C = C->getAggregateElement(idx_range[0]);
7123 if (!C) return nullptr;
7124 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7125 }
7126
7128 // Loop the indices for the insertvalue instruction in parallel with the
7129 // requested indices
7130 const unsigned *req_idx = idx_range.begin();
7131 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7132 i != e; ++i, ++req_idx) {
7133 if (req_idx == idx_range.end()) {
7134 // We can't handle this without inserting insertvalues
7135 if (!InsertBefore)
7136 return nullptr;
7137
7138 // The requested index identifies a part of a nested aggregate. Handle
7139 // this specially. For example,
7140 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7141 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7142 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7143 // This can be changed into
7144 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7145 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7146 // which allows the unused 0,0 element from the nested struct to be
7147 // removed.
7148 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7149 *InsertBefore);
7150 }
7151
7152 // This insert value inserts something else than what we are looking for.
7153 // See if the (aggregate) value inserted into has the value we are
7154 // looking for, then.
7155 if (*req_idx != *i)
7156 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7157 InsertBefore);
7158 }
7159 // If we end up here, the indices of the insertvalue match with those
7160 // requested (though possibly only partially). Now we recursively look at
7161 // the inserted value, passing any remaining indices.
7162 return FindInsertedValue(I->getInsertedValueOperand(),
7163 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7164 }
7165
7167 // If we're extracting a value from an aggregate that was extracted from
7168 // something else, we can extract from that something else directly instead.
7169 // However, we will need to chain I's indices with the requested indices.
7170
7171 // Calculate the number of indices required
7172 unsigned size = I->getNumIndices() + idx_range.size();
7173 // Allocate some space to put the new indices in
7175 Idxs.reserve(size);
7176 // Add indices from the extract value instruction
7177 Idxs.append(I->idx_begin(), I->idx_end());
7178
7179 // Add requested indices
7180 Idxs.append(idx_range.begin(), idx_range.end());
7181
7182 assert(Idxs.size() == size
7183 && "Number of indices added not correct?");
7184
7185 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7186 }
7187 // Otherwise, we don't know (such as, extracting from a function return value
7188 // or load instruction)
7189 return nullptr;
7190}
7191
7192// If V refers to an initialized global constant, set Slice either to
7193// its initializer if the size of its elements equals ElementSize, or,
7194// for ElementSize == 8, to its representation as an array of unsiged
7195// char. Return true on success.
7196// Offset is in the unit "nr of ElementSize sized elements".
7199 unsigned ElementSize, uint64_t Offset) {
7200 assert(V && "V should not be null.");
7201 assert((ElementSize % 8) == 0 &&
7202 "ElementSize expected to be a multiple of the size of a byte.");
7203 unsigned ElementSizeInBytes = ElementSize / 8;
7204
7205 // Drill down into the pointer expression V, ignoring any intervening
7206 // casts, and determine the identity of the object it references along
7207 // with the cumulative byte offset into it.
7208 const GlobalVariable *GV =
7210 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7211 // Fail if V is not based on constant global object.
7212 return false;
7213
7214 const DataLayout &DL = GV->getDataLayout();
7215 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7216
7218 /*AllowNonInbounds*/ true))
7219 // Fail if a constant offset could not be determined.
7220 return false;
7221
7222 uint64_t StartIdx = Off.getLimitedValue();
7223 if (StartIdx == UINT64_MAX)
7224 // Fail if the constant offset is excessive.
7225 return false;
7226
7227 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7228 // elements. Simply bail out if that isn't possible.
7229 if ((StartIdx % ElementSizeInBytes) != 0)
7230 return false;
7231
7232 Offset += StartIdx / ElementSizeInBytes;
7233 ConstantDataArray *Array = nullptr;
7234 ArrayType *ArrayTy = nullptr;
7235
7236 if (GV->getInitializer()->isNullValue()) {
7237 Type *GVTy = GV->getValueType();
7238 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7239 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7240
7241 Slice.Array = nullptr;
7242 Slice.Offset = 0;
7243 // Return an empty Slice for undersized constants to let callers
7244 // transform even undefined library calls into simpler, well-defined
7245 // expressions. This is preferable to making the calls although it
7246 // prevents sanitizers from detecting such calls.
7247 Slice.Length = Length < Offset ? 0 : Length - Offset;
7248 return true;
7249 }
7250
7251 auto *Init = const_cast<Constant *>(GV->getInitializer());
7252 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7253 Type *InitElTy = ArrayInit->getElementType();
7254 if (InitElTy->isIntegerTy(ElementSize)) {
7255 // If Init is an initializer for an array of the expected type
7256 // and size, use it as is.
7257 Array = ArrayInit;
7258 ArrayTy = ArrayInit->getType();
7259 }
7260 }
7261
7262 if (!Array) {
7263 if (ElementSize != 8)
7264 // TODO: Handle conversions to larger integral types.
7265 return false;
7266
7267 // Otherwise extract the portion of the initializer starting
7268 // at Offset as an array of bytes, and reset Offset.
7270 if (!Init)
7271 return false;
7272
7273 Offset = 0;
7275 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7276 }
7277
7278 uint64_t NumElts = ArrayTy->getArrayNumElements();
7279 if (Offset > NumElts)
7280 return false;
7281
7282 Slice.Array = Array;
7283 Slice.Offset = Offset;
7284 Slice.Length = NumElts - Offset;
7285 return true;
7286}
7287
7288/// Extract bytes from the initializer of the constant array V, which need
7289/// not be a nul-terminated string. On success, store the bytes in Str and
7290/// return true. When TrimAtNul is set, Str will contain only the bytes up
7291/// to but not including the first nul. Return false on failure.
7293 bool TrimAtNul) {
7295 if (!getConstantDataArrayInfo(V, Slice, 8))
7296 return false;
7297
7298 if (Slice.Array == nullptr) {
7299 if (TrimAtNul) {
7300 // Return a nul-terminated string even for an empty Slice. This is
7301 // safe because all existing SimplifyLibcalls callers require string
7302 // arguments and the behavior of the functions they fold is undefined
7303 // otherwise. Folding the calls this way is preferable to making
7304 // the undefined library calls, even though it prevents sanitizers
7305 // from reporting such calls.
7306 Str = StringRef();
7307 return true;
7308 }
7309 if (Slice.Length == 1) {
7310 Str = StringRef("", 1);
7311 return true;
7312 }
7313 // We cannot instantiate a StringRef as we do not have an appropriate string
7314 // of 0s at hand.
7315 return false;
7316 }
7317
7318 // Start out with the entire array in the StringRef.
7319 Str = Slice.Array->getAsString();
7320 // Skip over 'offset' bytes.
7321 Str = Str.substr(Slice.Offset);
7322
7323 if (TrimAtNul) {
7324 // Trim off the \0 and anything after it. If the array is not nul
7325 // terminated, we just return the whole end of string. The client may know
7326 // some other way that the string is length-bound.
7327 Str = Str.substr(0, Str.find('\0'));
7328 }
7329 return true;
7330}
7331
7332// These next two are very similar to the above, but also look through PHI
7333// nodes.
7334// TODO: See if we can integrate these two together.
7335
7336/// If we can compute the length of the string pointed to by
7337/// the specified pointer, return 'len+1'. If we can't, return 0.
7340 unsigned CharSize) {
7341 // Look through noop bitcast instructions.
7342 V = V->stripPointerCasts();
7343
7344 // If this is a PHI node, there are two cases: either we have already seen it
7345 // or we haven't.
7346 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7347 if (!PHIs.insert(PN).second)
7348 return ~0ULL; // already in the set.
7349
7350 // If it was new, see if all the input strings are the same length.
7351 uint64_t LenSoFar = ~0ULL;
7352 for (Value *IncValue : PN->incoming_values()) {
7353 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7354 if (Len == 0) return 0; // Unknown length -> unknown.
7355
7356 if (Len == ~0ULL) continue;
7357
7358 if (Len != LenSoFar && LenSoFar != ~0ULL)
7359 return 0; // Disagree -> unknown.
7360 LenSoFar = Len;
7361 }
7362
7363 // Success, all agree.
7364 return LenSoFar;
7365 }
7366
7367 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7368 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7369 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7370 if (Len1 == 0) return 0;
7371 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7372 if (Len2 == 0) return 0;
7373 if (Len1 == ~0ULL) return Len2;
7374 if (Len2 == ~0ULL) return Len1;
7375 if (Len1 != Len2) return 0;
7376 return Len1;
7377 }
7378
7379 // Otherwise, see if we can read the string.
7381 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7382 return 0;
7383
7384 if (Slice.Array == nullptr)
7385 // Zeroinitializer (including an empty one).
7386 return 1;
7387
7388 // Search for the first nul character. Return a conservative result even
7389 // when there is no nul. This is safe since otherwise the string function
7390 // being folded such as strlen is undefined, and can be preferable to
7391 // making the undefined library call.
7392 unsigned NullIndex = 0;
7393 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7394 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7395 break;
7396 }
7397
7398 return NullIndex + 1;
7399}
7400
7401/// If we can compute the length of the string pointed to by
7402/// the specified pointer, return 'len+1'. If we can't, return 0.
7403uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7404 if (!V->getType()->isPointerTy())
7405 return 0;
7406
7408 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7409 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7410 // an empty string as a length.
7411 return Len == ~0ULL ? 1 : Len;
7412}
7413
7414const Value *
7416 bool MustPreserveOffset,
7417 bool MustPreserveProvenance) {
7418 assert(Call &&
7419 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7420 if (const Value *RV = Call->getReturnedArgOperand())
7421 return RV;
7422 // This can be used only as a aliasing property.
7424 Call, MustPreserveOffset, MustPreserveProvenance))
7425 return Call->getArgOperand(0);
7426 return nullptr;
7427}
7428
7430 const CallBase *Call, bool MustPreserveOffset,
7431 bool MustPreserveProvenance) {
7432 switch (Call->getIntrinsicID()) {
7433 case Intrinsic::launder_invariant_group:
7434 case Intrinsic::aarch64_irg:
7435 case Intrinsic::aarch64_tagp:
7436 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7437 // input pointer (and thus preserves the byte offset, which is the property
7438 // the MustPreserveOffset flag selects). However, it will not necessarily
7439 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7440 // descriptor", which has "all loads return 0, all stores are dropped"
7441 // semantics. Given the context of this intrinsic list, no one should be
7442 // relying on such a strict bit-exact null mapping (and, at time of
7443 // writing, they are not), but we document this fact out of an abundance
7444 // of caution.
7445 case Intrinsic::amdgcn_make_buffer_rsrc:
7446 return !MustPreserveProvenance;
7447 case Intrinsic::ptrmask:
7448 return !MustPreserveOffset;
7449 case Intrinsic::threadlocal_address:
7450 // The underlying variable changes with thread ID. The Thread ID may change
7451 // at coroutine suspend points.
7452 return !Call->getParent()->getParent()->isPresplitCoroutine();
7453 default:
7454 return false;
7455 }
7456}
7457
7458/// \p PN defines a loop-variant pointer to an object. Check if the
7459/// previous iteration of the loop was referring to the same object as \p PN.
7461 const LoopInfo *LI) {
7462 // Find the loop-defined value.
7463 Loop *L = LI->getLoopFor(PN->getParent());
7464 if (PN->getNumIncomingValues() != 2)
7465 return true;
7466
7467 // Find the value from previous iteration.
7468 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7469 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7470 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7471 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7472 return true;
7473
7474 // If a new pointer is loaded in the loop, the pointer references a different
7475 // object in every iteration. E.g.:
7476 // for (i)
7477 // int *p = a[i];
7478 // ...
7479 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7480 if (!L->isLoopInvariant(Load->getPointerOperand()))
7481 return false;
7482 return true;
7483}
7484
7485const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7486 bool MustPreserveProvenance) {
7487 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7488 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7489 const Value *PtrOp = GEP->getPointerOperand();
7490 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7491 return V;
7492 V = PtrOp;
7493 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7494 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7495 Value *NewV = cast<Operator>(V)->getOperand(0);
7496 if (!NewV->getType()->isPointerTy())
7497 return V;
7498 V = NewV;
7499 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7500 if (GA->isInterposable())
7501 return V;
7502 V = GA->getAliasee();
7503 } else {
7504 if (auto *PHI = dyn_cast<PHINode>(V)) {
7505 // Look through single-arg phi nodes created by LCSSA.
7506 if (PHI->getNumIncomingValues() == 1) {
7507 V = PHI->getIncomingValue(0);
7508 continue;
7509 }
7510 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7511 // CaptureTracking can know about special capturing properties of some
7512 // intrinsics like launder.invariant.group, that can't be expressed with
7513 // the attributes, but have properties like returning aliasing pointer.
7514 // Because some analysis may assume that nocaptured pointer is not
7515 // returned from some special intrinsic (because function would have to
7516 // be marked with returns attribute), it is crucial to use this function
7517 // because it should be in sync with CaptureTracking. Not using it may
7518 // cause weird miscompilations where 2 aliasing pointers are assumed to
7519 // noalias.
7521 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7522 V = RP;
7523 continue;
7524 }
7525 }
7526
7527 return V;
7528 }
7529 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7530 }
7531 return V;
7532}
7533
7536 const LoopInfo *LI, unsigned MaxLookup) {
7539 Worklist.push_back(V);
7540 do {
7541 const Value *P = Worklist.pop_back_val();
7542 P = getUnderlyingObject(P, MaxLookup);
7543
7544 if (!Visited.insert(P).second)
7545 continue;
7546
7547 if (auto *SI = dyn_cast<SelectInst>(P)) {
7548 Worklist.push_back(SI->getTrueValue());
7549 Worklist.push_back(SI->getFalseValue());
7550 continue;
7551 }
7552
7553 if (auto *PN = dyn_cast<PHINode>(P)) {
7554 // If this PHI changes the underlying object in every iteration of the
7555 // loop, don't look through it. Consider:
7556 // int **A;
7557 // for (i) {
7558 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7559 // Curr = A[i];
7560 // *Prev, *Curr;
7561 //
7562 // Prev is tracking Curr one iteration behind so they refer to different
7563 // underlying objects.
7564 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7566 append_range(Worklist, PN->incoming_values());
7567 else
7568 Objects.push_back(P);
7569 continue;
7570 }
7571
7572 Objects.push_back(P);
7573 } while (!Worklist.empty());
7574}
7575
7577 bool MustPreserveProvenance) {
7578 const unsigned MaxVisited = 8;
7579
7582 Worklist.push_back(V);
7583 const Value *Object = nullptr;
7584 // Used as fallback if we can't find a common underlying object through
7585 // recursion.
7586 bool First = true;
7587 const Value *FirstObject =
7588 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7589 do {
7590 const Value *P = Worklist.pop_back_val();
7591 P = First ? FirstObject
7593 MustPreserveProvenance);
7594 First = false;
7595
7596 if (!Visited.insert(P).second)
7597 continue;
7598
7599 if (Visited.size() == MaxVisited)
7600 return FirstObject;
7601
7602 if (auto *SI = dyn_cast<SelectInst>(P)) {
7603 Worklist.push_back(SI->getTrueValue());
7604 Worklist.push_back(SI->getFalseValue());
7605 continue;
7606 }
7607
7608 if (auto *PN = dyn_cast<PHINode>(P)) {
7609 append_range(Worklist, PN->incoming_values());
7610 continue;
7611 }
7612
7613 if (!Object)
7614 Object = P;
7615 else if (Object != P)
7616 return FirstObject;
7617 } while (!Worklist.empty());
7618
7619 return Object ? Object : FirstObject;
7620}
7621
7622/// This is the function that does the work of looking through basic
7623/// ptrtoint+arithmetic+inttoptr sequences.
7624static const Value *getUnderlyingObjectFromInt(const Value *V) {
7625 do {
7626 if (const Operator *U = dyn_cast<Operator>(V)) {
7627 // If we find a ptrtoint, we can transfer control back to the
7628 // regular getUnderlyingObjectFromInt.
7629 if (U->getOpcode() == Instruction::PtrToInt)
7630 return U->getOperand(0);
7631 // If we find an add of a constant, a multiplied value, or a phi, it's
7632 // likely that the other operand will lead us to the base
7633 // object. We don't have to worry about the case where the
7634 // object address is somehow being computed by the multiply,
7635 // because our callers only care when the result is an
7636 // identifiable object.
7637 if (U->getOpcode() != Instruction::Add ||
7638 (!isa<ConstantInt>(U->getOperand(1)) &&
7639 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7640 !isa<PHINode>(U->getOperand(1))))
7641 return V;
7642 V = U->getOperand(0);
7643 } else {
7644 return V;
7645 }
7646 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7647 } while (true);
7648}
7649
7650/// This is a wrapper around getUnderlyingObjects and adds support for basic
7651/// ptrtoint+arithmetic+inttoptr sequences.
7652/// It returns false if unidentified object is found in getUnderlyingObjects.
7654 SmallVectorImpl<Value *> &Objects) {
7656 SmallVector<const Value *, 4> Working(1, V);
7657 bool AllObjectsIdentified = true;
7658 do {
7659 V = Working.pop_back_val();
7660
7662 getUnderlyingObjects(V, Objs);
7663
7664 for (const Value *V : Objs) {
7665 if (!Visited.insert(V).second)
7666 continue;
7667 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7668 const Value *O =
7669 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7670 if (O->getType()->isPointerTy()) {
7671 Working.push_back(O);
7672 continue;
7673 }
7674 }
7675 AllObjectsIdentified &= isIdentifiedObject(V);
7676 Objects.push_back(const_cast<Value *>(V));
7677 }
7678 } while (!Working.empty());
7679 return AllObjectsIdentified;
7680}
7681
7683 AllocaInst *Result = nullptr;
7685 SmallVector<Value *, 4> Worklist;
7686
7687 auto AddWork = [&](Value *V) {
7688 if (Visited.insert(V).second)
7689 Worklist.push_back(V);
7690 };
7691
7692 AddWork(V);
7693 do {
7694 V = Worklist.pop_back_val();
7695 assert(Visited.count(V));
7696
7697 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7698 if (Result && Result != AI)
7699 return nullptr;
7700 Result = AI;
7701 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7702 AddWork(CI->getOperand(0));
7703 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7704 for (Value *IncValue : PN->incoming_values())
7705 AddWork(IncValue);
7706 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7707 AddWork(SI->getTrueValue());
7708 AddWork(SI->getFalseValue());
7710 if (OffsetZero && !GEP->hasAllZeroIndices())
7711 return nullptr;
7712 AddWork(GEP->getPointerOperand());
7713 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7714 Value *Returned = CB->getReturnedArgOperand();
7715 if (Returned)
7716 AddWork(Returned);
7717 else
7718 return nullptr;
7719 } else {
7720 return nullptr;
7721 }
7722 } while (!Worklist.empty());
7723
7724 return Result;
7725}
7726
7728 if (auto *II = dyn_cast<IntrinsicInst>(I))
7729 return isTriviallyVectorizable(II->getIntrinsicID());
7730 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7731 return (!Shuffle || Shuffle->isSelect()) &&
7733}
7734
7736 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7737 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7738 bool IgnoreUBImplyingAttrs) {
7739 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7740 AC, DT, TLI, UseVariableInfo,
7741 IgnoreUBImplyingAttrs);
7742}
7743
7745 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7746 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7747 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7748#ifndef NDEBUG
7749 if (Inst->getOpcode() != Opcode) {
7750 // Check that the operands are actually compatible with the Opcode override.
7751 auto hasEqualReturnAndLeadingOperandTypes =
7752 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7753 if (Inst->getNumOperands() < NumLeadingOperands)
7754 return false;
7755 const Type *ExpectedType = Inst->getType();
7756 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7757 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7758 return false;
7759 return true;
7760 };
7762 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7763 assert(!Instruction::isUnaryOp(Opcode) ||
7764 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7765 }
7766#endif
7767
7768 switch (Opcode) {
7769 default:
7770 return true;
7771 case Instruction::UDiv:
7772 case Instruction::URem: {
7773 // x / y is undefined if y == 0.
7774 const APInt *V;
7775 if (match(Inst->getOperand(1), m_APInt(V)))
7776 return *V != 0;
7777 return false;
7778 }
7779 case Instruction::SDiv:
7780 case Instruction::SRem: {
7781 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7782 const APInt *Numerator, *Denominator;
7783 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7784 return false;
7785 // We cannot hoist this division if the denominator is 0.
7786 if (*Denominator == 0)
7787 return false;
7788 // It's safe to hoist if the denominator is not 0 or -1.
7789 if (!Denominator->isAllOnes())
7790 return true;
7791 // At this point we know that the denominator is -1. It is safe to hoist as
7792 // long we know that the numerator is not INT_MIN.
7793 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7794 return !Numerator->isMinSignedValue();
7795 // The numerator *might* be MinSignedValue.
7796 return false;
7797 }
7798 case Instruction::Load: {
7799 if (!UseVariableInfo)
7800 return false;
7801
7802 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7803 if (!LI)
7804 return false;
7805 if (mustSuppressSpeculation(*LI))
7806 return false;
7807 const DataLayout &DL = LI->getDataLayout();
7809 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7810 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7811 }
7812 case Instruction::Call: {
7813 auto *CI = dyn_cast<const CallInst>(Inst);
7814 if (!CI)
7815 return false;
7816 const Function *Callee = CI->getCalledFunction();
7817
7818 // The called function could have undefined behavior or side-effects, even
7819 // if marked readnone nounwind.
7820 if (!Callee || !Callee->isSpeculatable())
7821 return false;
7822 // Since the operands may be changed after hoisting, undefined behavior may
7823 // be triggered by some UB-implying attributes.
7824 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7825 }
7826 case Instruction::VAArg:
7827 case Instruction::Alloca:
7828 case Instruction::Invoke:
7829 case Instruction::CallBr:
7830 case Instruction::PHI:
7831 case Instruction::Store:
7832 case Instruction::Ret:
7833 case Instruction::UncondBr:
7834 case Instruction::CondBr:
7835 case Instruction::IndirectBr:
7836 case Instruction::Switch:
7837 case Instruction::Unreachable:
7838 case Instruction::Fence:
7839 case Instruction::AtomicRMW:
7840 case Instruction::AtomicCmpXchg:
7841 case Instruction::LandingPad:
7842 case Instruction::Resume:
7843 case Instruction::CatchSwitch:
7844 case Instruction::CatchPad:
7845 case Instruction::CatchRet:
7846 case Instruction::CleanupPad:
7847 case Instruction::CleanupRet:
7848 return false; // Misc instructions which have effects
7849 }
7850}
7851
7853 if (I.mayReadOrWriteMemory())
7854 // Memory dependency possible
7855 return true;
7857 // Can't move above a maythrow call or infinite loop. Or if an
7858 // inalloca alloca, above a stacksave call.
7859 return true;
7861 // 1) Can't reorder two inf-loop calls, even if readonly
7862 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7863 // safe to speculative execute. (Inverse of above)
7864 return true;
7865 return false;
7866}
7867
7868/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7882
7883/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7886 bool ForSigned,
7887 const SimplifyQuery &SQ) {
7888 ConstantRange CR1 =
7889 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7890 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7893 return CR1.intersectWith(CR2, RangeType);
7894}
7895
7897 const Value *RHS,
7898 const SimplifyQuery &SQ,
7899 bool IsNSW) {
7900 ConstantRange LHSRange =
7901 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7902 ConstantRange RHSRange =
7903 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7904
7905 // mul nsw of two non-negative numbers is also nuw.
7906 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7908
7909 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7910}
7911
7913 const Value *RHS,
7914 const SimplifyQuery &SQ) {
7915 // Multiplying n * m significant bits yields a result of n + m significant
7916 // bits. If the total number of significant bits does not exceed the
7917 // result bit width (minus 1), there is no overflow.
7918 // This means if we have enough leading sign bits in the operands
7919 // we can guarantee that the result does not overflow.
7920 // Ref: "Hacker's Delight" by Henry Warren
7921 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7922
7923 // Note that underestimating the number of sign bits gives a more
7924 // conservative answer.
7925 unsigned SignBits =
7926 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7927
7928 // First handle the easy case: if we have enough sign bits there's
7929 // definitely no overflow.
7930 if (SignBits > BitWidth + 1)
7932
7933 // There are two ambiguous cases where there can be no overflow:
7934 // SignBits == BitWidth + 1 and
7935 // SignBits == BitWidth
7936 // The second case is difficult to check, therefore we only handle the
7937 // first case.
7938 if (SignBits == BitWidth + 1) {
7939 // It overflows only when both arguments are negative and the true
7940 // product is exactly the minimum negative number.
7941 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7942 // For simplicity we just check if at least one side is not negative.
7943 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7944 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7945 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7947 }
7949}
7950
7953 const WithCache<const Value *> &RHS,
7954 const SimplifyQuery &SQ) {
7955 ConstantRange LHSRange =
7956 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7957 ConstantRange RHSRange =
7958 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7959 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7960}
7961
7962static OverflowResult
7965 const AddOperator *Add, const SimplifyQuery &SQ) {
7966 if (Add && Add->hasNoSignedWrap()) {
7968 }
7969
7970 // If LHS and RHS each have at least two sign bits, the addition will look
7971 // like
7972 //
7973 // XX..... +
7974 // YY.....
7975 //
7976 // If the carry into the most significant position is 0, X and Y can't both
7977 // be 1 and therefore the carry out of the addition is also 0.
7978 //
7979 // If the carry into the most significant position is 1, X and Y can't both
7980 // be 0 and therefore the carry out of the addition is also 1.
7981 //
7982 // Since the carry into the most significant position is always equal to
7983 // the carry out of the addition, there is no signed overflow.
7984 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7986
7987 ConstantRange LHSRange =
7988 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7989 ConstantRange RHSRange =
7990 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7991 OverflowResult OR =
7992 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7994 return OR;
7995
7996 // The remaining code needs Add to be available. Early returns if not so.
7997 if (!Add)
7999
8000 // If the sign of Add is the same as at least one of the operands, this add
8001 // CANNOT overflow. If this can be determined from the known bits of the
8002 // operands the above signedAddMayOverflow() check will have already done so.
8003 // The only other way to improve on the known bits is from an assumption, so
8004 // call computeKnownBitsFromContext() directly.
8005 bool LHSOrRHSKnownNonNegative =
8006 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
8007 bool LHSOrRHSKnownNegative =
8008 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
8009 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
8010 KnownBits AddKnown(LHSRange.getBitWidth());
8011 computeKnownBitsFromContext(Add, AddKnown, SQ);
8012 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
8013 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
8015 }
8016
8018}
8019
8021 const Value *RHS,
8022 const SimplifyQuery &SQ) {
8023 // X - (X % ?)
8024 // The remainder of a value can't have greater magnitude than itself,
8025 // so the subtraction can't overflow.
8026
8027 // X - (X -nuw ?)
8028 // In the minimal case, this would simplify to "?", so there's no subtract
8029 // at all. But if this analysis is used to peek through casts, for example,
8030 // then determining no-overflow may allow other transforms.
8031
8032 // TODO: There are other patterns like this.
8033 // See simplifyICmpWithBinOpOnLHS() for candidates.
8034 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
8035 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
8036 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8038
8039 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
8040 SQ.DL)) {
8041 if (*C)
8044 }
8045
8046 ConstantRange LHSRange =
8047 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8048 ConstantRange RHSRange =
8049 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8050 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
8051}
8052
8054 const Value *RHS,
8055 const SimplifyQuery &SQ) {
8056 // X - (X % ?)
8057 // The remainder of a value can't have greater magnitude than itself,
8058 // so the subtraction can't overflow.
8059
8060 // X - (X -nsw ?)
8061 // In the minimal case, this would simplify to "?", so there's no subtract
8062 // at all. But if this analysis is used to peek through casts, for example,
8063 // then determining no-overflow may allow other transforms.
8064 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
8065 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
8066 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8068
8069 // If LHS and RHS each have at least two sign bits, the subtraction
8070 // cannot overflow.
8071 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
8073
8074 ConstantRange LHSRange =
8075 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
8076 ConstantRange RHSRange =
8077 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
8078 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
8079}
8080
8082 const DominatorTree &DT) {
8083 SmallVector<const CondBrInst *, 2> GuardingBranches;
8085
8086 for (const User *U : WO->users()) {
8087 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
8088 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
8089
8090 if (EVI->getIndices()[0] == 0)
8091 Results.push_back(EVI);
8092 else {
8093 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
8094
8095 for (const auto *U : EVI->users())
8096 if (const auto *B = dyn_cast<CondBrInst>(U))
8097 GuardingBranches.push_back(B);
8098 }
8099 } else {
8100 // We are using the aggregate directly in a way we don't want to analyze
8101 // here (storing it to a global, say).
8102 return false;
8103 }
8104 }
8105
8106 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8107 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8108
8109 // Check if all users of the add are provably no-wrap.
8110 for (const auto *Result : Results) {
8111 // If the extractvalue itself is not executed on overflow, the we don't
8112 // need to check each use separately, since domination is transitive.
8113 if (DT.dominates(NoWrapEdge, Result->getParent()))
8114 continue;
8115
8116 for (const auto &RU : Result->uses())
8117 if (!DT.dominates(NoWrapEdge, RU))
8118 return false;
8119 }
8120
8121 return true;
8122 };
8123
8124 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8125}
8126
8127/// Shifts return poison if shiftwidth is larger than the bitwidth.
8128static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8129 auto *C = dyn_cast<Constant>(ShiftAmount);
8130 if (!C)
8131 return false;
8132
8133 // Shifts return poison if shiftwidth is larger than the bitwidth.
8135 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8136 unsigned NumElts = FVTy->getNumElements();
8137 for (unsigned i = 0; i < NumElts; ++i)
8138 ShiftAmounts.push_back(C->getAggregateElement(i));
8139 } else if (isa<ScalableVectorType>(C->getType()))
8140 return false; // Can't tell, just return false to be safe
8141 else
8142 ShiftAmounts.push_back(C);
8143
8144 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8145 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8146 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8147 });
8148
8149 return Safe;
8150}
8151
8153 bool ConsiderFlagsAndMetadata) {
8154
8155 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8156 Op->hasPoisonGeneratingAnnotations())
8157 return true;
8158
8159 unsigned Opcode = Op->getOpcode();
8160
8161 // Check whether opcode is a poison/undef-generating operation
8162 switch (Opcode) {
8163 case Instruction::Shl:
8164 case Instruction::AShr:
8165 case Instruction::LShr:
8166 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8167 case Instruction::FPToSI:
8168 case Instruction::FPToUI:
8169 // fptosi/ui yields poison if the resulting value does not fit in the
8170 // destination type.
8171 return true;
8172 case Instruction::Call:
8173 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8174 switch (II->getIntrinsicID()) {
8175 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8176 case Intrinsic::ctlz:
8177 case Intrinsic::cttz:
8178 case Intrinsic::abs:
8179 // We're not considering flags so it is safe to just return false.
8180 return false;
8181 case Intrinsic::sshl_sat:
8182 case Intrinsic::ushl_sat:
8183 if (!includesPoison(Kind) ||
8184 shiftAmountKnownInRange(II->getArgOperand(1)))
8185 return false;
8186 break;
8187 }
8188 }
8189 [[fallthrough]];
8190 case Instruction::CallBr:
8191 case Instruction::Invoke: {
8192 const auto *CB = cast<CallBase>(Op);
8193 return !CB->hasRetAttr(Attribute::NoUndef) &&
8194 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8195 }
8196 case Instruction::InsertElement:
8197 case Instruction::ExtractElement: {
8198 // If index exceeds the length of the vector, it returns poison
8199 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8200 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8201 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8202 if (includesPoison(Kind))
8203 return !Idx ||
8204 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8205 return false;
8206 }
8207 case Instruction::ShuffleVector: {
8209 ? cast<ConstantExpr>(Op)->getShuffleMask()
8210 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8211 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8212 }
8213 case Instruction::FNeg:
8214 case Instruction::PHI:
8215 case Instruction::Select:
8216 case Instruction::ExtractValue:
8217 case Instruction::InsertValue:
8218 case Instruction::Freeze:
8219 case Instruction::ICmp:
8220 case Instruction::FCmp:
8221 case Instruction::GetElementPtr:
8222 return false;
8223 case Instruction::AddrSpaceCast:
8224 return true;
8225 default: {
8226 const auto *CE = dyn_cast<ConstantExpr>(Op);
8227 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8228 return false;
8229 else if (Instruction::isBinaryOp(Opcode))
8230 return false;
8231 // Be conservative and return true.
8232 return true;
8233 }
8234 }
8235}
8236
8238 bool ConsiderFlagsAndMetadata) {
8239 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8240 ConsiderFlagsAndMetadata);
8241}
8242
8243bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8244 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8245 ConsiderFlagsAndMetadata);
8246}
8247
8248static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8249 unsigned Depth) {
8250 if (ValAssumedPoison == V)
8251 return true;
8252
8253 const unsigned MaxDepth = 2;
8254 if (Depth >= MaxDepth)
8255 return false;
8256
8257 if (const auto *I = dyn_cast<Instruction>(V)) {
8258 if (any_of(I->operands(), [=](const Use &Op) {
8259 return propagatesPoison(Op) &&
8260 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8261 }))
8262 return true;
8263
8264 // V = extractvalue V0, idx
8265 // V2 = extractvalue V0, idx2
8266 // V0's elements are all poison or not. (e.g., add_with_overflow)
8267 const WithOverflowInst *II;
8269 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8270 llvm::is_contained(II->args(), ValAssumedPoison)))
8271 return true;
8272 }
8273 return false;
8274}
8275
8276static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8277 unsigned Depth) {
8278 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8279 return true;
8280
8281 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8282 return true;
8283
8284 const unsigned MaxDepth = 2;
8285 if (Depth >= MaxDepth)
8286 return false;
8287
8288 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8289 if (I && !canCreatePoison(cast<Operator>(I))) {
8290 return all_of(I->operands(), [=](const Value *Op) {
8291 return impliesPoison(Op, V, Depth + 1);
8292 });
8293 }
8294 return false;
8295}
8296
8297bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8298 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8299}
8300
8301static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8302
8304 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8305 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8307 return false;
8308
8309 if (isa<MetadataAsValue>(V))
8310 return false;
8311
8312 if (const auto *A = dyn_cast<Argument>(V)) {
8313 if (A->hasAttribute(Attribute::NoUndef) ||
8314 A->hasAttribute(Attribute::Dereferenceable) ||
8315 A->hasAttribute(Attribute::DereferenceableOrNull))
8316 return true;
8317 }
8318
8319 if (auto *C = dyn_cast<Constant>(V)) {
8320 if (isa<PoisonValue>(C))
8321 return !includesPoison(Kind);
8322
8323 if (isa<UndefValue>(C))
8324 return !includesUndef(Kind);
8325
8328 return true;
8329
8330 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8331 if (isa<ConstantExpr>(C)) {
8332 // Scalable vectors can use a ConstantExpr to build a splat.
8333 if (Constant *SplatC = C->getSplatValue())
8334 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8335 return true;
8336 } else if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
8337 return all_of(CA->operands(), [&](const Use &Op) {
8338 return isGuaranteedNotToBeUndefOrPoison(Op.get(), AC, CtxI, DT,
8339 Depth + 1, Kind);
8340 });
8341 }
8342 }
8343 }
8344
8345 // Strip cast operations from a pointer value.
8346 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8347 // inbounds with zero offset. To guarantee that the result isn't poison, the
8348 // stripped pointer is checked as it has to be pointing into an allocated
8349 // object or be null `null` to ensure `inbounds` getelement pointers with a
8350 // zero offset could not produce poison.
8351 // It can strip off addrspacecast that do not change bit representation as
8352 // well. We believe that such addrspacecast is equivalent to no-op.
8353 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8354 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8355 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8356 return true;
8357
8358 auto OpCheck = [&](const Value *V) {
8359 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8360 };
8361
8362 if (auto *Opr = dyn_cast<Operator>(V)) {
8363 // If the value is a freeze instruction, then it can never
8364 // be undef or poison.
8365 if (isa<FreezeInst>(V))
8366 return true;
8367
8368 if (const auto *CB = dyn_cast<CallBase>(V)) {
8369 if (CB->hasRetAttr(Attribute::NoUndef) ||
8370 CB->hasRetAttr(Attribute::Dereferenceable) ||
8371 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8372 return true;
8373 }
8374
8375 if (!::canCreateUndefOrPoison(Opr, Kind,
8376 /*ConsiderFlagsAndMetadata=*/true)) {
8377 if (const auto *PN = dyn_cast<PHINode>(V)) {
8378 unsigned Num = PN->getNumIncomingValues();
8379 bool IsWellDefined = true;
8380 for (unsigned i = 0; i < Num; ++i) {
8381 if (PN == PN->getIncomingValue(i))
8382 continue;
8383 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8384 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8385 DT, Depth + 1, Kind)) {
8386 IsWellDefined = false;
8387 break;
8388 }
8389 }
8390 if (IsWellDefined)
8391 return true;
8392 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8393 : nullptr) {
8394 // For splats we only need to check the value being splatted.
8395 if (OpCheck(Splat))
8396 return true;
8397 } else if (all_of(Opr->operands(), OpCheck))
8398 return true;
8399 }
8400 }
8401
8402 if (auto *I = dyn_cast<LoadInst>(V))
8403 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8404 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8405 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8406 return true;
8407
8409 return true;
8410
8411 // CtxI may be null or a cloned instruction.
8412 if (!CtxI || !CtxI->getParent() || !DT)
8413 return false;
8414
8415 auto *DNode = DT->getNode(CtxI->getParent());
8416 if (!DNode)
8417 // Unreachable block
8418 return false;
8419
8420 // If V is used as a branch condition before reaching CtxI, V cannot be
8421 // undef or poison.
8422 // br V, BB1, BB2
8423 // BB1:
8424 // CtxI ; V cannot be undef or poison here
8425 auto *Dominator = DNode->getIDom();
8426 // This check is purely for compile time reasons: we can skip the IDom walk
8427 // if what we are checking for includes undef and the value is not an integer.
8428 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8429 while (Dominator) {
8430 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8431
8432 Value *Cond = nullptr;
8433 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8434 Cond = BI->getCondition();
8435 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8436 Cond = SI->getCondition();
8437 }
8438
8439 if (Cond) {
8440 if (Cond == V)
8441 return true;
8442 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8443 // For poison, we can analyze further
8444 auto *Opr = cast<Operator>(Cond);
8445 if (any_of(Opr->operands(), [V](const Use &U) {
8446 return V == U && propagatesPoison(U);
8447 }))
8448 return true;
8449 }
8450 }
8451
8452 Dominator = Dominator->getIDom();
8453 }
8454
8455 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8456 return true;
8457
8458 return false;
8459}
8460
8462 const Instruction *CtxI,
8463 const DominatorTree *DT,
8464 unsigned Depth) {
8465 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8467}
8468
8470 const Instruction *CtxI,
8471 const DominatorTree *DT, unsigned Depth) {
8472 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8474}
8475
8477 const Instruction *CtxI,
8478 const DominatorTree *DT, unsigned Depth) {
8479 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8481}
8482
8483/// Return true if undefined behavior would provably be executed on the path to
8484/// OnPathTo if Root produced a posion result. Note that this doesn't say
8485/// anything about whether OnPathTo is actually executed or whether Root is
8486/// actually poison. This can be used to assess whether a new use of Root can
8487/// be added at a location which is control equivalent with OnPathTo (such as
8488/// immediately before it) without introducing UB which didn't previously
8489/// exist. Note that a false result conveys no information.
8491 Instruction *OnPathTo,
8492 DominatorTree *DT) {
8493 // Basic approach is to assume Root is poison, propagate poison forward
8494 // through all users we can easily track, and then check whether any of those
8495 // users are provable UB and must execute before out exiting block might
8496 // exit.
8497
8498 // The set of all recursive users we've visited (which are assumed to all be
8499 // poison because of said visit)
8502 Worklist.push_back(Root);
8503 while (!Worklist.empty()) {
8504 const Instruction *I = Worklist.pop_back_val();
8505
8506 // If we know this must trigger UB on a path leading our target.
8507 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8508 return true;
8509
8510 // If we can't analyze propagation through this instruction, just skip it
8511 // and transitive users. Safe as false is a conservative result.
8512 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8513 return KnownPoison.contains(U) && propagatesPoison(U);
8514 }))
8515 continue;
8516
8517 if (KnownPoison.insert(I).second)
8518 for (const User *User : I->users())
8519 Worklist.push_back(cast<Instruction>(User));
8520 }
8521
8522 // Might be non-UB, or might have a path we couldn't prove must execute on
8523 // way to exiting bb.
8524 return false;
8525}
8526
8528 const SimplifyQuery &SQ) {
8529 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8530 Add, SQ);
8531}
8532
8535 const WithCache<const Value *> &RHS,
8536 const SimplifyQuery &SQ) {
8537 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8538}
8539
8541 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8542 // of time because it's possible for another thread to interfere with it for an
8543 // arbitrary length of time, but programs aren't allowed to rely on that.
8544
8545 // If there is no successor, then execution can't transfer to it.
8546 if (isa<ReturnInst>(I))
8547 return false;
8549 return false;
8550
8551 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8552 // Instruction::willReturn.
8553 //
8554 // FIXME: Move this check into Instruction::willReturn.
8555 if (isa<CatchPadInst>(I)) {
8556 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8557 default:
8558 // A catchpad may invoke exception object constructors and such, which
8559 // in some languages can be arbitrary code, so be conservative by default.
8560 return false;
8562 // For CoreCLR, it just involves a type test.
8563 return true;
8564 }
8565 }
8566
8567 // An instruction that returns without throwing must transfer control flow
8568 // to a successor.
8569 return !I->mayThrow() && I->willReturn();
8570}
8571
8573 // TODO: This is slightly conservative for invoke instruction since exiting
8574 // via an exception *is* normal control for them.
8575 for (const Instruction &I : *BB)
8577 return false;
8578 return true;
8579}
8580
8587
8590 assert(ScanLimit && "scan limit must be non-zero");
8591 for (const Instruction &I : Range) {
8592 if (--ScanLimit == 0)
8593 return false;
8595 return false;
8596 }
8597 return true;
8598}
8599
8601 const Loop *L) {
8602 // The loop header is guaranteed to be executed for every iteration.
8603 //
8604 // FIXME: Relax this constraint to cover all basic blocks that are
8605 // guaranteed to be executed at every iteration.
8606 if (I->getParent() != L->getHeader()) return false;
8607
8608 for (const Instruction &LI : *L->getHeader()) {
8609 if (&LI == I) return true;
8610 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8611 }
8612 llvm_unreachable("Instruction not contained in its own parent basic block.");
8613}
8614
8616 switch (IID) {
8617 // TODO: Add more intrinsics.
8618 case Intrinsic::sadd_with_overflow:
8619 case Intrinsic::ssub_with_overflow:
8620 case Intrinsic::smul_with_overflow:
8621 case Intrinsic::uadd_with_overflow:
8622 case Intrinsic::usub_with_overflow:
8623 case Intrinsic::umul_with_overflow:
8624 // If an input is a vector containing a poison element, the
8625 // two output vectors (calculated results, overflow bits)'
8626 // corresponding lanes are poison.
8627 return true;
8628 case Intrinsic::ctpop:
8629 case Intrinsic::ctlz:
8630 case Intrinsic::cttz:
8631 case Intrinsic::abs:
8632 case Intrinsic::smax:
8633 case Intrinsic::smin:
8634 case Intrinsic::umax:
8635 case Intrinsic::umin:
8636 case Intrinsic::scmp:
8637 case Intrinsic::smulh:
8638 case Intrinsic::umulh:
8639 case Intrinsic::is_fpclass:
8640 case Intrinsic::ptrmask:
8641 case Intrinsic::ucmp:
8642 case Intrinsic::bitreverse:
8643 case Intrinsic::bswap:
8644 case Intrinsic::sadd_sat:
8645 case Intrinsic::ssub_sat:
8646 case Intrinsic::sshl_sat:
8647 case Intrinsic::uadd_sat:
8648 case Intrinsic::usub_sat:
8649 case Intrinsic::ushl_sat:
8650 case Intrinsic::smul_fix:
8651 case Intrinsic::smul_fix_sat:
8652 case Intrinsic::umul_fix:
8653 case Intrinsic::umul_fix_sat:
8654 case Intrinsic::pow:
8655 case Intrinsic::powi:
8656 case Intrinsic::sin:
8657 case Intrinsic::sinh:
8658 case Intrinsic::cos:
8659 case Intrinsic::cosh:
8660 case Intrinsic::sincos:
8661 case Intrinsic::sincospi:
8662 case Intrinsic::tan:
8663 case Intrinsic::tanh:
8664 case Intrinsic::asin:
8665 case Intrinsic::acos:
8666 case Intrinsic::atan:
8667 case Intrinsic::atan2:
8668 case Intrinsic::canonicalize:
8669 case Intrinsic::sqrt:
8670 case Intrinsic::fma:
8671 case Intrinsic::fmuladd:
8672 case Intrinsic::exp:
8673 case Intrinsic::exp2:
8674 case Intrinsic::exp10:
8675 case Intrinsic::log:
8676 case Intrinsic::log2:
8677 case Intrinsic::log10:
8678 case Intrinsic::modf:
8679 case Intrinsic::floor:
8680 case Intrinsic::ceil:
8681 case Intrinsic::trunc:
8682 case Intrinsic::rint:
8683 case Intrinsic::nearbyint:
8684 case Intrinsic::round:
8685 case Intrinsic::roundeven:
8686 case Intrinsic::lrint:
8687 case Intrinsic::llrint:
8688 case Intrinsic::fshl:
8689 case Intrinsic::fshr:
8690 case Intrinsic::frexp:
8691 case Intrinsic::get_active_lane_mask:
8692 case Intrinsic::mask_beforefirst:
8693 return true;
8694 default:
8695 return false;
8696 }
8697}
8698
8699bool llvm::propagatesPoison(const Use &PoisonOp) {
8700 const Operator *I = cast<Operator>(PoisonOp.getUser());
8701 switch (I->getOpcode()) {
8702 case Instruction::Freeze:
8703 case Instruction::PHI:
8704 case Instruction::Invoke:
8705 return false;
8706 case Instruction::Select:
8707 return PoisonOp.getOperandNo() == 0;
8708 case Instruction::Call:
8709 if (auto *II = dyn_cast<IntrinsicInst>(I))
8710 return intrinsicPropagatesPoison(II->getIntrinsicID());
8711 return false;
8712 case Instruction::ICmp:
8713 case Instruction::FCmp:
8714 case Instruction::GetElementPtr:
8715 return true;
8716 default:
8718 return true;
8719
8720 // Be conservative and return false.
8721 return false;
8722 }
8723}
8724
8725/// Enumerates all operands of \p I that are guaranteed to not be undef or
8726/// poison. If the callback \p Handle returns true, stop processing and return
8727/// true. Otherwise, return false.
8728template <typename CallableT>
8730 const CallableT &Handle) {
8731 switch (I->getOpcode()) {
8732 case Instruction::Store:
8733 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8734 return true;
8735 break;
8736
8737 case Instruction::Load:
8738 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8739 return true;
8740 break;
8741
8742 // Since dereferenceable attribute imply noundef, atomic operations
8743 // also implicitly have noundef pointers too
8744 case Instruction::AtomicCmpXchg:
8746 return true;
8747 break;
8748
8749 case Instruction::AtomicRMW:
8750 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8751 return true;
8752 break;
8753
8754 case Instruction::Call:
8755 case Instruction::Invoke: {
8756 const CallBase *CB = cast<CallBase>(I);
8757 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8758 return true;
8759 for (unsigned i = 0; i < CB->arg_size(); ++i)
8760 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8761 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8762 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8763 Handle(CB->getArgOperand(i)))
8764 return true;
8765 break;
8766 }
8767 case Instruction::Ret:
8768 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8769 Handle(I->getOperand(0)))
8770 return true;
8771 break;
8772 case Instruction::Switch:
8773 if (Handle(cast<SwitchInst>(I)->getCondition()))
8774 return true;
8775 break;
8776 case Instruction::CondBr:
8777 if (Handle(cast<CondBrInst>(I)->getCondition()))
8778 return true;
8779 break;
8780 default:
8781 break;
8782 }
8783
8784 return false;
8785}
8786
8787/// Enumerates all operands of \p I that are guaranteed to not be poison.
8788template <typename CallableT>
8790 const CallableT &Handle) {
8791 if (handleGuaranteedWellDefinedOps(I, Handle))
8792 return true;
8793 switch (I->getOpcode()) {
8794 // Divisors of these operations are allowed to be partially undef.
8795 case Instruction::UDiv:
8796 case Instruction::SDiv:
8797 case Instruction::URem:
8798 case Instruction::SRem:
8799 return Handle(I->getOperand(1));
8800 default:
8801 return false;
8802 }
8803}
8804
8806 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8808 I, [&](const Value *V) { return KnownPoison.count(V); });
8809}
8810
8812 bool PoisonOnly) {
8813 // We currently only look for uses of values within the same basic
8814 // block, as that makes it easier to guarantee that the uses will be
8815 // executed given that Inst is executed.
8816 //
8817 // FIXME: Expand this to consider uses beyond the same basic block. To do
8818 // this, look out for the distinction between post-dominance and strong
8819 // post-dominance.
8820 const BasicBlock *BB = nullptr;
8822 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8823 BB = Inst->getParent();
8824 Begin = Inst->getIterator();
8825 Begin++;
8826 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8827 if (Arg->getParent()->isDeclaration())
8828 return false;
8829 BB = &Arg->getParent()->getEntryBlock();
8830 Begin = BB->begin();
8831 } else {
8832 return false;
8833 }
8834
8835 // Limit number of instructions we look at, to avoid scanning through large
8836 // blocks. The current limit is chosen arbitrarily.
8837 unsigned ScanLimit = 32;
8839
8840 if (!PoisonOnly) {
8841 // Since undef does not propagate eagerly, be conservative & just check
8842 // whether a value is directly passed to an instruction that must take
8843 // well-defined operands.
8844
8845 for (const auto &I : make_range(Begin, End)) {
8846 if (--ScanLimit == 0)
8847 break;
8848
8849 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8850 return WellDefinedOp == V;
8851 }))
8852 return true;
8853
8855 break;
8856 }
8857 return false;
8858 }
8859
8860 // Set of instructions that we have proved will yield poison if Inst
8861 // does.
8862 SmallPtrSet<const Value *, 16> YieldsPoison;
8864
8865 YieldsPoison.insert(V);
8866 Visited.insert(BB);
8867
8868 while (true) {
8869 for (const auto &I : make_range(Begin, End)) {
8870 if (--ScanLimit == 0)
8871 return false;
8872 if (mustTriggerUB(&I, YieldsPoison))
8873 return true;
8875 return false;
8876
8877 // If an operand is poison and propagates it, mark I as yielding poison.
8878 for (const Use &Op : I.operands()) {
8879 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8880 YieldsPoison.insert(&I);
8881 break;
8882 }
8883 }
8884
8885 // Special handling for select, which returns poison if its operand 0 is
8886 // poison (handled in the loop above) *or* if both its true/false operands
8887 // are poison (handled here).
8888 if (I.getOpcode() == Instruction::Select &&
8889 YieldsPoison.count(I.getOperand(1)) &&
8890 YieldsPoison.count(I.getOperand(2))) {
8891 YieldsPoison.insert(&I);
8892 }
8893 }
8894
8895 BB = BB->getSingleSuccessor();
8896 if (!BB || !Visited.insert(BB).second)
8897 break;
8898
8899 Begin = BB->getFirstNonPHIIt();
8900 End = BB->end();
8901 }
8902 return false;
8903}
8904
8906 return ::programUndefinedIfUndefOrPoison(Inst, false);
8907}
8908
8910 return ::programUndefinedIfUndefOrPoison(Inst, true);
8911}
8912
8913static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8914 if (FMF.noNaNs())
8915 return true;
8916
8917 if (auto *C = dyn_cast<ConstantFP>(V))
8918 return !C->isNaN();
8919
8920 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8921 if (!C->getElementType()->isFloatingPointTy())
8922 return false;
8923 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8924 if (C->getElementAsAPFloat(I).isNaN())
8925 return false;
8926 }
8927 return true;
8928 }
8929
8931 return true;
8932
8933 return false;
8934}
8935
8936static bool isKnownNonZero(const Value *V) {
8937 if (auto *C = dyn_cast<ConstantFP>(V))
8938 return !C->isZero();
8939
8940 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8941 if (!C->getElementType()->isFloatingPointTy())
8942 return false;
8943 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8944 if (C->getElementAsAPFloat(I).isZero())
8945 return false;
8946 }
8947 return true;
8948 }
8949
8950 return false;
8951}
8952
8953/// Match clamp pattern for float types without care about NaNs or signed zeros.
8954/// Given non-min/max outer cmp/select from the clamp pattern this
8955/// function recognizes if it can be substitued by a "canonical" min/max
8956/// pattern.
8958 Value *CmpLHS, Value *CmpRHS,
8959 Value *TrueVal, Value *FalseVal,
8960 Value *&LHS, Value *&RHS) {
8961 // Try to match
8962 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8963 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8964 // and return description of the outer Max/Min.
8965
8966 // First, check if select has inverse order:
8967 if (CmpRHS == FalseVal) {
8968 std::swap(TrueVal, FalseVal);
8969 Pred = CmpInst::getInversePredicate(Pred);
8970 }
8971
8972 // Assume success now. If there's no match, callers should not use these anyway.
8973 LHS = TrueVal;
8974 RHS = FalseVal;
8975
8976 const APFloat *FC1;
8977 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8978 return {SPF_UNKNOWN, SPNB_NA, false};
8979
8980 const APFloat *FC2;
8981 switch (Pred) {
8982 case CmpInst::FCMP_OLT:
8983 case CmpInst::FCMP_OLE:
8984 case CmpInst::FCMP_ULT:
8985 case CmpInst::FCMP_ULE:
8986 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8987 *FC1 < *FC2)
8988 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8989 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8990 *FC1 < *FC2)
8991 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8992 break;
8993 case CmpInst::FCMP_OGT:
8994 case CmpInst::FCMP_OGE:
8995 case CmpInst::FCMP_UGT:
8996 case CmpInst::FCMP_UGE:
8997 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8998 *FC1 > *FC2)
8999 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
9000 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
9001 *FC1 > *FC2)
9002 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
9003 break;
9004 default:
9005 break;
9006 }
9007
9008 return {SPF_UNKNOWN, SPNB_NA, false};
9009}
9010
9011/// Recognize variations of:
9012/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
9014 Value *CmpLHS, Value *CmpRHS,
9015 Value *TrueVal, Value *FalseVal) {
9016 // Swap the select operands and predicate to match the patterns below.
9017 if (CmpRHS != TrueVal) {
9018 Pred = ICmpInst::getSwappedPredicate(Pred);
9019 std::swap(TrueVal, FalseVal);
9020 }
9021 const APInt *C1;
9022 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
9023 const APInt *C2;
9024 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
9025 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9026 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
9027 return {SPF_SMAX, SPNB_NA, false};
9028
9029 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
9030 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9031 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
9032 return {SPF_SMIN, SPNB_NA, false};
9033
9034 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
9035 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9036 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
9037 return {SPF_UMAX, SPNB_NA, false};
9038
9039 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
9040 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9041 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
9042 return {SPF_UMIN, SPNB_NA, false};
9043 }
9044 return {SPF_UNKNOWN, SPNB_NA, false};
9045}
9046
9047/// If the input value is the result of a 'not' op, constant integer, or vector
9048/// splat of a constant integer, return the bitwise-not source value.
9049/// TODO: This could be extended to handle non-splat vector integer constants.
9051 Value *NotV;
9052 if (match(V, m_Not(m_Value(NotV))))
9053 return NotV;
9054
9055 const APInt *C;
9056 if (match(V, m_APInt(C)))
9057 return ConstantInt::get(V->getType(), ~(*C));
9058
9059 return nullptr;
9060}
9061
9062/// Match non-obvious integer minimum and maximum sequences.
9064 Value *CmpRHS, Value *TrueVal,
9065 Value *FalseVal, Value *&LHS,
9066 Value *&RHS) {
9067 // Assume success. If there's no match, callers should not use these anyway.
9068 LHS = TrueVal;
9069 RHS = FalseVal;
9070
9071 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9073 return SPR;
9074
9075 // Look through 'not' ops to find disguised min/max.
9076 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9077 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9078 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9079 switch (Pred) {
9080 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9081 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9082 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9083 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9084 default: break;
9085 }
9086 }
9087
9088 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9089 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9090 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9091 switch (Pred) {
9092 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9093 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9094 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9095 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9096 default: break;
9097 }
9098 }
9099
9100 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9101 return {SPF_UNKNOWN, SPNB_NA, false};
9102
9103 const APInt *C1;
9104 if (!match(CmpRHS, m_APInt(C1)))
9105 return {SPF_UNKNOWN, SPNB_NA, false};
9106
9107 // An unsigned min/max can be written with a signed compare.
9108 const APInt *C2;
9109 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9110 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9111 // Is the sign bit set?
9112 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9113 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9114 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9115 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9116
9117 // Is the sign bit clear?
9118 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9119 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9120 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9121 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9122 }
9123
9124 return {SPF_UNKNOWN, SPNB_NA, false};
9125}
9126
9127bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9128 bool AllowPoison) {
9129 assert(X && Y && "Invalid operand");
9130
9131 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9132 if (!match(X, m_Neg(m_Specific(Y))))
9133 return false;
9134
9135 auto *BO = cast<BinaryOperator>(X);
9136 if (NeedNSW && !BO->hasNoSignedWrap())
9137 return false;
9138
9139 auto *Zero = cast<Constant>(BO->getOperand(0));
9140 if (!AllowPoison && !Zero->isNullValue())
9141 return false;
9142
9143 return true;
9144 };
9145
9146 // X = -Y or Y = -X
9147 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9148 return true;
9149
9150 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9151 Value *A, *B;
9152 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9153 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9154 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9156}
9157
9158bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9159 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9160 Value *A, *B, *C;
9161 CmpPredicate Pred1, Pred2;
9162 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9163 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9164 return false;
9165
9166 // They must both have samesign flag or not.
9167 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9168 return false;
9169
9170 if (B == C)
9171 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9172
9173 // Try to infer the relationship from constant ranges.
9174 const APInt *RHSC1, *RHSC2;
9175 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9176 return false;
9177
9178 // Sign bits of two RHSCs should match.
9179 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9180 return false;
9181
9182 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9183 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9184
9185 return CR1.inverse() == CR2;
9186}
9187
9189 SelectPatternNaNBehavior NaNBehavior,
9190 bool Ordered) {
9191 switch (Pred) {
9192 default:
9193 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9194 case ICmpInst::ICMP_UGT:
9195 case ICmpInst::ICMP_UGE:
9196 return {SPF_UMAX, SPNB_NA, false};
9197 case ICmpInst::ICMP_SGT:
9198 case ICmpInst::ICMP_SGE:
9199 return {SPF_SMAX, SPNB_NA, false};
9200 case ICmpInst::ICMP_ULT:
9201 case ICmpInst::ICMP_ULE:
9202 return {SPF_UMIN, SPNB_NA, false};
9203 case ICmpInst::ICMP_SLT:
9204 case ICmpInst::ICMP_SLE:
9205 return {SPF_SMIN, SPNB_NA, false};
9206 case FCmpInst::FCMP_UGT:
9207 case FCmpInst::FCMP_UGE:
9208 case FCmpInst::FCMP_OGT:
9209 case FCmpInst::FCMP_OGE:
9210 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9211 case FCmpInst::FCMP_ULT:
9212 case FCmpInst::FCMP_ULE:
9213 case FCmpInst::FCMP_OLT:
9214 case FCmpInst::FCMP_OLE:
9215 return {SPF_FMINNUM, NaNBehavior, Ordered};
9216 }
9217}
9218
9219std::optional<std::pair<CmpPredicate, Constant *>>
9222 "Only for relational integer predicates.");
9223 if (isa<UndefValue>(C))
9224 return std::nullopt;
9225
9226 Type *Type = C->getType();
9227 bool IsSigned = ICmpInst::isSigned(Pred);
9228
9230 bool WillIncrement =
9231 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9232
9233 // Check if the constant operand can be safely incremented/decremented
9234 // without overflowing/underflowing.
9235 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9236 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9237 return false;
9238
9239 if (!Pred.hasSameSign())
9240 return true;
9241
9242 // Crossing the corresponding boundary in the other ordering changes the
9243 // sign bit, and therefore changes the poison domain.
9244 return WillIncrement ? !C->isMaxValue(!IsSigned)
9245 : !C->isMinValue(!IsSigned);
9246 };
9247
9248 Constant *SafeReplacementConstant = nullptr;
9249 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9250 // Bail out if the constant can't be safely incremented/decremented.
9251 if (!ConstantIsOk(CI))
9252 return std::nullopt;
9253 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9254 unsigned NumElts = FVTy->getNumElements();
9255 for (unsigned i = 0; i != NumElts; ++i) {
9256 Constant *Elt = C->getAggregateElement(i);
9257 if (!Elt)
9258 return std::nullopt;
9259
9260 if (isa<UndefValue>(Elt))
9261 continue;
9262
9263 // Bail out if we can't determine if this constant is min/max or if we
9264 // know that this constant is min/max.
9265 auto *CI = dyn_cast<ConstantInt>(Elt);
9266 if (!CI || !ConstantIsOk(CI))
9267 return std::nullopt;
9268
9269 if (!SafeReplacementConstant)
9270 SafeReplacementConstant = CI;
9271 }
9272 } else if (isa<VectorType>(C->getType())) {
9273 // Handle scalable splat
9274 Value *SplatC = C->getSplatValue();
9275 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9276 // Bail out if the constant can't be safely incremented/decremented.
9277 if (!CI || !ConstantIsOk(CI))
9278 return std::nullopt;
9279 } else {
9280 // ConstantExpr?
9281 return std::nullopt;
9282 }
9283
9284 // It may not be safe to change a compare predicate in the presence of
9285 // undefined elements, so replace those elements with the first safe constant
9286 // that we found.
9287 // TODO: in case of poison, it is safe; let's replace undefs only.
9288 if (C->containsUndefOrPoisonElement()) {
9289 assert(SafeReplacementConstant && "Replacement constant not set");
9290 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9291 }
9292
9294 Pred.hasSameSign());
9295
9296 // Increment or decrement the constant.
9297 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9298 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9299
9300 return std::make_pair(NewPred, NewC);
9301}
9302
9304 FastMathFlags FMF, Value *CmpLHS,
9305 Value *CmpRHS, Value *TrueVal,
9306 Value *FalseVal, Value *&LHS,
9307 Value *&RHS) {
9308 if (CmpInst::isFPPredicate(Pred)) {
9309 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9310 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9311 // purpose of identifying min/max. Disregard vector constants with undefined
9312 // elements because those can not be back-propagated for analysis.
9313 Value *OutputZeroVal = nullptr;
9314 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9315 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9316 OutputZeroVal = TrueVal;
9317 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9318 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9319 OutputZeroVal = FalseVal;
9320
9321 if (OutputZeroVal) {
9322 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9323 CmpLHS = OutputZeroVal;
9324 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9325 CmpRHS = OutputZeroVal;
9326 }
9327 }
9328
9329 LHS = CmpLHS;
9330 RHS = CmpRHS;
9331
9332 // Signed zero may return inconsistent results between implementations.
9333 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9334 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9335 // Therefore, we behave conservatively and only proceed if at least one of the
9336 // operands is known to not be zero or if we don't care about signed zero.
9337 if (CmpInst::isFPPredicate(Pred)) {
9338 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9339 !isKnownNonZero(CmpRHS))
9340 return {SPF_UNKNOWN, SPNB_NA, false};
9341 }
9342
9343 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9344 bool Ordered = false;
9345
9346 // When given one NaN and one non-NaN input:
9347 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9348 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9349 // ordered comparison fails), which could be NaN or non-NaN.
9350 // so here we discover exactly what NaN behavior is required/accepted.
9351 if (CmpInst::isFPPredicate(Pred)) {
9352 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9353 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9354
9355 if (LHSSafe && RHSSafe) {
9356 // Both operands are known non-NaN.
9357 NaNBehavior = SPNB_RETURNS_ANY;
9358 Ordered = CmpInst::isOrdered(Pred);
9359 } else if (CmpInst::isOrdered(Pred)) {
9360 // An ordered comparison will return false when given a NaN, so it
9361 // returns the RHS.
9362 Ordered = true;
9363 if (LHSSafe)
9364 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9365 NaNBehavior = SPNB_RETURNS_NAN;
9366 else if (RHSSafe)
9367 NaNBehavior = SPNB_RETURNS_OTHER;
9368 else
9369 // Completely unsafe.
9370 return {SPF_UNKNOWN, SPNB_NA, false};
9371 } else {
9372 Ordered = false;
9373 // An unordered comparison will return true when given a NaN, so it
9374 // returns the LHS.
9375 if (LHSSafe)
9376 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9377 NaNBehavior = SPNB_RETURNS_OTHER;
9378 else if (RHSSafe)
9379 NaNBehavior = SPNB_RETURNS_NAN;
9380 else
9381 // Completely unsafe.
9382 return {SPF_UNKNOWN, SPNB_NA, false};
9383 }
9384 }
9385
9386 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9387 std::swap(CmpLHS, CmpRHS);
9388 Pred = CmpInst::getSwappedPredicate(Pred);
9389 if (NaNBehavior == SPNB_RETURNS_NAN)
9390 NaNBehavior = SPNB_RETURNS_OTHER;
9391 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9392 NaNBehavior = SPNB_RETURNS_NAN;
9393 Ordered = !Ordered;
9394 }
9395
9396 // ([if]cmp X, Y) ? X : Y
9397 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9398 return getSelectPattern(Pred, NaNBehavior, Ordered);
9399
9400 if (isKnownNegation(TrueVal, FalseVal)) {
9401 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9402 // match against either LHS or sign-preserving operations on LHS, like
9403 // sext(LHS), or binary ops that do not wrap in signed sense.
9404 auto CmpLHSOrSExt =
9405 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9406 auto MaybeSExtOrMulCmpLHS =
9407 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9408 m_NSWShl(CmpLHSOrSExt, m_Value()));
9409 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9410 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9411 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9412 // Set the return values. If the compare uses the negated value (-X >s 0),
9413 // swap the return values because the negated value is always 'RHS'.
9414 LHS = TrueVal;
9415 RHS = FalseVal;
9416 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9417 std::swap(LHS, RHS);
9418
9419 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9420 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9421 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9422 return {SPF_ABS, SPNB_NA, false};
9423
9424 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9425 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9426 return {SPF_ABS, SPNB_NA, false};
9427
9428 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9429 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9430 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9431 return {SPF_NABS, SPNB_NA, false};
9432 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9433 // Set the return values. If the compare uses the negated value (-X >s 0),
9434 // swap the return values because the negated value is always 'RHS'.
9435 LHS = FalseVal;
9436 RHS = TrueVal;
9437 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9438 std::swap(LHS, RHS);
9439
9440 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9441 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9442 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9443 return {SPF_NABS, SPNB_NA, false};
9444
9445 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9446 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9447 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9448 return {SPF_ABS, SPNB_NA, false};
9449 }
9450 }
9451
9452 if (CmpInst::isIntPredicate(Pred))
9453 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9454
9455 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9456 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9457 // semantics than minNum. Be conservative in such case.
9458 if (NaNBehavior != SPNB_RETURNS_ANY ||
9459 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9460 !isKnownNonZero(CmpRHS)))
9461 return {SPF_UNKNOWN, SPNB_NA, false};
9462
9463 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9464}
9465
9467 Instruction::CastOps *CastOp) {
9468 const DataLayout &DL = CmpI->getDataLayout();
9469
9470 Constant *CastedTo = nullptr;
9471 switch (*CastOp) {
9472 case Instruction::ZExt:
9473 if (CmpI->isUnsigned())
9474 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9475 break;
9476 case Instruction::SExt:
9477 if (CmpI->isSigned())
9478 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9479 break;
9480 case Instruction::Trunc:
9481 Constant *CmpConst;
9482 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9483 CmpConst->getType() == SrcTy) {
9484 // Here we have the following case:
9485 //
9486 // %cond = cmp iN %x, CmpConst
9487 // %tr = trunc iN %x to iK
9488 // %narrowsel = select i1 %cond, iK %t, iK C
9489 //
9490 // We can always move trunc after select operation:
9491 //
9492 // %cond = cmp iN %x, CmpConst
9493 // %widesel = select i1 %cond, iN %x, iN CmpConst
9494 // %tr = trunc iN %widesel to iK
9495 //
9496 // Note that C could be extended in any way because we don't care about
9497 // upper bits after truncation. It can't be abs pattern, because it would
9498 // look like:
9499 //
9500 // select i1 %cond, x, -x.
9501 //
9502 // So only min/max pattern could be matched. Such match requires widened C
9503 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9504 // CmpConst == C is checked below.
9505 CastedTo = CmpConst;
9506 } else {
9507 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9508 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9509 }
9510 break;
9511 case Instruction::FPTrunc:
9512 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9513 break;
9514 case Instruction::FPExt:
9515 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9516 break;
9517 case Instruction::FPToUI:
9518 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9519 break;
9520 case Instruction::FPToSI:
9521 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9522 break;
9523 case Instruction::UIToFP:
9524 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9525 break;
9526 case Instruction::SIToFP:
9527 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9528 break;
9529 default:
9530 break;
9531 }
9532
9533 if (!CastedTo)
9534 return nullptr;
9535
9536 // Make sure the cast doesn't lose any information.
9537 Constant *CastedBack =
9538 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9539 if (CastedBack && CastedBack != C)
9540 return nullptr;
9541
9542 return CastedTo;
9543}
9544
9545/// Helps to match a select pattern in case of a type mismatch.
9546///
9547/// The function processes the case when type of true and false values of a
9548/// select instruction differs from type of the cmp instruction operands because
9549/// of a cast instruction. The function checks if it is legal to move the cast
9550/// operation after "select". If yes, it returns the new second value of
9551/// "select" (with the assumption that cast is moved):
9552/// 1. As operand of cast instruction when both values of "select" are same cast
9553/// instructions.
9554/// 2. As restored constant (by applying reverse cast operation) when the first
9555/// value of the "select" is a cast operation and the second value is a
9556/// constant. It is implemented in lookThroughCastConst().
9557/// 3. As one operand is cast instruction and the other is not. The operands in
9558/// sel(cmp) are in different type integer.
9559/// NOTE: We return only the new second value because the first value could be
9560/// accessed as operand of cast instruction.
9562 Instruction::CastOps *CastOp) {
9563 auto *Cast1 = dyn_cast<CastInst>(V1);
9564 if (!Cast1)
9565 return nullptr;
9566
9567 *CastOp = Cast1->getOpcode();
9568 Type *SrcTy = Cast1->getSrcTy();
9569 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9570 // If V1 and V2 are both the same cast from the same type, look through V1.
9571 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9572 return Cast2->getOperand(0);
9573 return nullptr;
9574 }
9575
9576 auto *C = dyn_cast<Constant>(V2);
9577 if (C)
9578 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9579
9580 Value *CastedTo = nullptr;
9581 if (*CastOp == Instruction::Trunc) {
9582 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9583 // Here we have the following case:
9584 // %y_ext = sext iK %y to iN
9585 // %cond = cmp iN %x, %y_ext
9586 // %tr = trunc iN %x to iK
9587 // %narrowsel = select i1 %cond, iK %tr, iK %y
9588 //
9589 // We can always move trunc after select operation:
9590 // %y_ext = sext iK %y to iN
9591 // %cond = cmp iN %x, %y_ext
9592 // %widesel = select i1 %cond, iN %x, iN %y_ext
9593 // %tr = trunc iN %widesel to iK
9594 assert(V2->getType() == Cast1->getType() &&
9595 "V2 and Cast1 should be the same type.");
9596 CastedTo = CmpI->getOperand(1);
9597 }
9598 }
9599
9600 return CastedTo;
9601}
9603 Instruction::CastOps *CastOp) {
9605 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9606
9607 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9608 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9609
9610 Value *TrueVal = SI->getTrueValue();
9611 Value *FalseVal = SI->getFalseValue();
9612
9614 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
9615}
9616
9618 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9619 FastMathFlags FMF, Instruction::CastOps *CastOp) {
9620 CmpInst::Predicate Pred = CmpI->getPredicate();
9621 Value *CmpLHS = CmpI->getOperand(0);
9622 Value *CmpRHS = CmpI->getOperand(1);
9623 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9624 FMF.setNoNaNs();
9625
9626 // Bail out early.
9627 if (CmpI->isEquality())
9628 return {SPF_UNKNOWN, SPNB_NA, false};
9629
9630 // Deal with type mismatches.
9631 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9632 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9633 // If this is a potential fmin/fmax with a cast to integer, then ignore
9634 // -0.0 because there is no corresponding integer value.
9635 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9636 FMF.setNoSignedZeros();
9637 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9638 cast<CastInst>(TrueVal)->getOperand(0), C,
9639 LHS, RHS);
9640 }
9641 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9642 // If this is a potential fmin/fmax with a cast to integer, then ignore
9643 // -0.0 because there is no corresponding integer value.
9644 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9645 FMF.setNoSignedZeros();
9646 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
9647 cast<CastInst>(FalseVal)->getOperand(0), LHS,
9648 RHS);
9649 }
9650 }
9651 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
9652 RHS);
9653}
9654
9656 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9657 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9658 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9659 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9660 if (SPF == SPF_FMINNUM)
9661 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9662 if (SPF == SPF_FMAXNUM)
9663 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9664 llvm_unreachable("unhandled!");
9665}
9666
9668 switch (SPF) {
9670 return Intrinsic::umin;
9672 return Intrinsic::umax;
9674 return Intrinsic::smin;
9676 return Intrinsic::smax;
9677 default:
9678 llvm_unreachable("Unexpected SPF");
9679 }
9680}
9681
9683 if (SPF == SPF_SMIN) return SPF_SMAX;
9684 if (SPF == SPF_UMIN) return SPF_UMAX;
9685 if (SPF == SPF_SMAX) return SPF_SMIN;
9686 if (SPF == SPF_UMAX) return SPF_UMIN;
9687 llvm_unreachable("unhandled!");
9688}
9689
9691 switch (MinMaxID) {
9692 case Intrinsic::smax: return Intrinsic::smin;
9693 case Intrinsic::smin: return Intrinsic::smax;
9694 case Intrinsic::umax: return Intrinsic::umin;
9695 case Intrinsic::umin: return Intrinsic::umax;
9696 // Please note that next four intrinsics may produce the same result for
9697 // original and inverted case even if X != Y due to NaN is handled specially.
9698 case Intrinsic::maximum: return Intrinsic::minimum;
9699 case Intrinsic::minimum: return Intrinsic::maximum;
9700 case Intrinsic::maxnum: return Intrinsic::minnum;
9701 case Intrinsic::minnum: return Intrinsic::maxnum;
9702 case Intrinsic::maximumnum:
9703 return Intrinsic::minimumnum;
9704 case Intrinsic::minimumnum:
9705 return Intrinsic::maximumnum;
9706 default: llvm_unreachable("Unexpected intrinsic");
9707 }
9708}
9709
9711 switch (SPF) {
9714 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9715 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9716 default: llvm_unreachable("Unexpected flavor");
9717 }
9718}
9719
9720std::pair<Intrinsic::ID, bool>
9722 // Check if VL contains select instructions that can be folded into a min/max
9723 // vector intrinsic and return the intrinsic if it is possible.
9724 // TODO: Support floating point min/max.
9725 bool AllCmpSingleUse = true;
9726 SelectPatternResult SelectPattern;
9727 SelectPattern.Flavor = SPF_UNKNOWN;
9728 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9729 Value *LHS, *RHS;
9730 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9731 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9732 return false;
9733 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9734 SelectPattern.Flavor != CurrentPattern.Flavor)
9735 return false;
9736 SelectPattern = CurrentPattern;
9737 AllCmpSingleUse &=
9739 return true;
9740 })) {
9741 switch (SelectPattern.Flavor) {
9742 case SPF_SMIN:
9743 return {Intrinsic::smin, AllCmpSingleUse};
9744 case SPF_UMIN:
9745 return {Intrinsic::umin, AllCmpSingleUse};
9746 case SPF_SMAX:
9747 return {Intrinsic::smax, AllCmpSingleUse};
9748 case SPF_UMAX:
9749 return {Intrinsic::umax, AllCmpSingleUse};
9750 case SPF_FMAXNUM:
9751 return {Intrinsic::maxnum, AllCmpSingleUse};
9752 case SPF_FMINNUM:
9753 return {Intrinsic::minnum, AllCmpSingleUse};
9754 default:
9755 llvm_unreachable("unexpected select pattern flavor");
9756 }
9757 }
9758 return {Intrinsic::not_intrinsic, false};
9759}
9760
9761template <typename InstTy>
9762static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9763 Value *&Init, Value *&OtherOp) {
9764 // Handle the case of a simple two-predecessor recurrence PHI.
9765 // There's a lot more that could theoretically be done here, but
9766 // this is sufficient to catch some interesting cases.
9767 // TODO: Expand list -- gep, uadd.sat etc.
9768 if (PN->getNumIncomingValues() != 2)
9769 return false;
9770
9771 for (unsigned I = 0; I != 2; ++I) {
9772 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9773 Operation && Operation->getNumOperands() >= 2) {
9774 Value *LHS = Operation->getOperand(0);
9775 Value *RHS = Operation->getOperand(1);
9776 if (LHS != PN && RHS != PN)
9777 continue;
9778
9779 Inst = Operation;
9780 Init = PN->getIncomingValue(!I);
9781 OtherOp = (LHS == PN) ? RHS : LHS;
9782 return true;
9783 }
9784 }
9785 return false;
9786}
9787
9788template <typename InstTy>
9789static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9790 Value *&Init, Value *&OtherOp0,
9791 Value *&OtherOp1) {
9792 if (PN->getNumIncomingValues() != 2)
9793 return false;
9794
9795 for (unsigned I = 0; I != 2; ++I) {
9796 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9797 Operation && Operation->getNumOperands() >= 3) {
9798 Value *Op0 = Operation->getOperand(0);
9799 Value *Op1 = Operation->getOperand(1);
9800 Value *Op2 = Operation->getOperand(2);
9801
9802 if (Op0 != PN && Op1 != PN && Op2 != PN)
9803 continue;
9804
9805 Inst = Operation;
9806 Init = PN->getIncomingValue(!I);
9807 if (Op0 == PN) {
9808 OtherOp0 = Op1;
9809 OtherOp1 = Op2;
9810 } else if (Op1 == PN) {
9811 OtherOp0 = Op0;
9812 OtherOp1 = Op2;
9813 } else {
9814 OtherOp0 = Op0;
9815 OtherOp1 = Op1;
9816 }
9817 return true;
9818 }
9819 }
9820 return false;
9821}
9823 Value *&Start, Value *&Step) {
9824 // We try to match a recurrence of the form:
9825 // %iv = [Start, %entry], [%iv.next, %backedge]
9826 // %iv.next = binop %iv, Step
9827 // Or:
9828 // %iv = [Start, %entry], [%iv.next, %backedge]
9829 // %iv.next = binop Step, %iv
9830 return matchTwoInputRecurrence(P, BO, Start, Step);
9831}
9832
9834 Value *&Start, Value *&Step) {
9835 BinaryOperator *BO = nullptr;
9836 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9837 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9838}
9839
9841 PHINode *&P, Value *&Init,
9842 Value *&OtherOp) {
9843 // Binary intrinsics only supported for now.
9844 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9845 I->getType() != I->getArgOperand(1)->getType())
9846 return false;
9847
9848 IntrinsicInst *II = nullptr;
9849 P = dyn_cast<PHINode>(I->getArgOperand(0));
9850 if (!P)
9851 P = dyn_cast<PHINode>(I->getArgOperand(1));
9852
9853 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9854}
9855
9857 PHINode *&P, Value *&Init,
9858 Value *&OtherOp0,
9859 Value *&OtherOp1) {
9860 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9861 I->getType() != I->getArgOperand(1)->getType() ||
9862 I->getType() != I->getArgOperand(2)->getType())
9863 return false;
9864 IntrinsicInst *II = nullptr;
9865 P = dyn_cast<PHINode>(I->getArgOperand(0));
9866 if (!P) {
9867 P = dyn_cast<PHINode>(I->getArgOperand(1));
9868 if (!P)
9869 P = dyn_cast<PHINode>(I->getArgOperand(2));
9870 }
9871 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9872 II == I;
9873}
9874
9875/// Return true if "icmp Pred LHS RHS" is always true.
9877 const Value *RHS) {
9878 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9879 return true;
9880
9881 switch (Pred) {
9882 default:
9883 return false;
9884
9885 case CmpInst::ICMP_SLE: {
9886 const APInt *C;
9887
9888 // LHS s<= LHS +_{nsw} C if C >= 0
9889 // LHS s<= LHS | C if C >= 0
9890 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9892 return !C->isNegative();
9893
9894 // LHS s<= smax(LHS, V) for any V
9896 return true;
9897
9898 // smin(RHS, V) s<= RHS for any V
9900 return true;
9901
9902 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9903 const Value *X;
9904 const APInt *CLHS, *CRHS;
9905 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9907 return CLHS->sle(*CRHS);
9908
9909 return false;
9910 }
9911
9912 case CmpInst::ICMP_ULE: {
9913 // LHS u<= LHS +_{nuw} V for any V
9914 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9916 return true;
9917
9918 // LHS u<= LHS | V for any V
9919 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9920 return true;
9921
9922 // LHS u<= umax(LHS, V) for any V
9924 return true;
9925
9926 // RHS >> V u<= RHS for any V
9927 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9928 return true;
9929
9930 // RHS u/ C_ugt_1 u<= RHS
9931 const APInt *C;
9932 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9933 return true;
9934
9935 // RHS & V u<= RHS for any V
9937 return true;
9938
9939 // umin(RHS, V) u<= RHS for any V
9941 return true;
9942
9943 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9944 const Value *X;
9945 const APInt *CLHS, *CRHS;
9946 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9948 return CLHS->ule(*CRHS);
9949
9950 return false;
9951 }
9952 }
9953}
9954
9955/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9956/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9957static std::optional<bool>
9959 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9960 switch (Pred) {
9961 default:
9962 return std::nullopt;
9963
9964 case CmpInst::ICMP_SLT:
9965 case CmpInst::ICMP_SLE:
9966 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9968 return true;
9969 return std::nullopt;
9970
9971 case CmpInst::ICMP_SGT:
9972 case CmpInst::ICMP_SGE:
9973 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9975 return true;
9976 return std::nullopt;
9977
9978 case CmpInst::ICMP_ULT:
9979 case CmpInst::ICMP_ULE:
9980 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9982 return true;
9983 return std::nullopt;
9984
9985 case CmpInst::ICMP_UGT:
9986 case CmpInst::ICMP_UGE:
9987 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9989 return true;
9990 return std::nullopt;
9991 }
9992}
9993
9994/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9995/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9996/// Otherwise, return std::nullopt if we can't infer anything.
9997static std::optional<bool>
9999 CmpPredicate RPred, const ConstantRange &RCR) {
10000 auto CRImpliesPred = [&](ConstantRange CR,
10001 CmpInst::Predicate Pred) -> std::optional<bool> {
10002 // If all true values for lhs and true for rhs, lhs implies rhs
10003 if (CR.icmp(Pred, RCR))
10004 return true;
10005
10006 // If there is no overlap, lhs implies not rhs
10007 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
10008 return false;
10009
10010 return std::nullopt;
10011 };
10012 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10013 RPred))
10014 return Res;
10015 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
10017 : LPred.dropSameSign();
10019 : RPred.dropSameSign();
10020 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10021 RPred);
10022 }
10023 return std::nullopt;
10024}
10025
10026/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10027/// is true. Return false if LHS implies RHS is false. Otherwise, return
10028/// std::nullopt if we can't infer anything.
10029static std::optional<bool>
10030isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
10031 CmpPredicate RPred, const Value *R0, const Value *R1,
10032 const DataLayout &DL, bool LHSIsTrue) {
10033 // The rest of the logic assumes the LHS condition is true. If that's not the
10034 // case, invert the predicate to make it so.
10035 if (!LHSIsTrue)
10036 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10037
10038 // We can have non-canonical operands, so try to normalize any common operand
10039 // to L0/R0.
10040 if (L0 == R1) {
10041 std::swap(R0, R1);
10042 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10043 }
10044 if (R0 == L1) {
10045 std::swap(L0, L1);
10046 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10047 }
10048 if (L1 == R1) {
10049 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10050 if (L0 != R0 || match(L0, m_ImmConstant())) {
10051 std::swap(L0, L1);
10052 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10053 std::swap(R0, R1);
10054 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10055 }
10056 }
10057
10058 // See if we can infer anything if operand-0 matches and we have at least one
10059 // constant.
10060 const APInt *Unused;
10061 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10062 // Potential TODO: We could also further use the constant range of L0/R0 to
10063 // further constraint the constant ranges. At the moment this leads to
10064 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10065 // C1` (see discussion: D58633).
10066 SimplifyQuery SQ(DL);
10071
10072 // Even if L1/R1 are not both constant, we can still sometimes deduce
10073 // relationship from a single constant. For example X u> Y implies X != 0.
10074 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10075 return R;
10076 // If both L1/R1 were exact constant ranges and we didn't get anything
10077 // here, we won't be able to deduce this.
10078 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10079 return std::nullopt;
10080 }
10081
10082 // Can we infer anything when the two compares have matching operands?
10083 if (L0 == R0 && L1 == R1)
10084 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10085
10086 // It only really makes sense in the context of signed comparison for "X - Y
10087 // must be positive if X >= Y and no overflow".
10088 // Take SGT as an example: L0:x > L1:y and C >= 0
10089 // ==> R0:(x -nsw y) < R1:(-C) is false
10090 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10091 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10092 SignedLPred == ICmpInst::ICMP_SGE) &&
10093 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10094 if (match(R1, m_NonPositive()) &&
10095 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10096 return false;
10097 }
10098
10099 // Take SLT as an example: L0:x < L1:y and C <= 0
10100 // ==> R0:(x -nsw y) < R1:(-C) is true
10101 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10102 SignedLPred == ICmpInst::ICMP_SLE) &&
10103 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10104 if (match(R1, m_NonNegative()) &&
10105 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10106 return true;
10107 }
10108
10109 // (a - b) pred C -> a != b, if 0 pred C is false
10110 // (ptrtoint(a) - ptrtoint(b)) pred C -> a != b, if 0 pred C is false
10111 Value *A, *B;
10112 if (ICmpInst::isEquality(RPred) && cmpExcludesZero(LPred, L1) &&
10113 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10114 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10119 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10120 }
10121
10122 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10123 if (L0 == R0 &&
10124 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10125 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10126 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10127 return CmpPredicate::getMatching(LPred, RPred).has_value();
10128
10129 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10130 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10131
10132 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10133 // Example: L0 u< 13 => (L0 & 16) == 0
10134 const APInt *LC, *RC, *MaskC;
10135 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10136 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10138 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10139 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10140 return true;
10141 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10142 ConstantRange(*RC)))
10143 return false;
10144 }
10145
10146 return std::nullopt;
10147}
10148
10149/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10150/// is true. Return false if LHS implies RHS is false. Otherwise, return
10151/// std::nullopt if we can't infer anything.
10152static std::optional<bool>
10154 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10155 const DataLayout &DL, bool LHSIsTrue) {
10156 // The rest of the logic assumes the LHS condition is true. If that's not the
10157 // case, invert the predicate to make it so.
10158 if (!LHSIsTrue)
10159 LPred = FCmpInst::getInversePredicate(LPred);
10160
10161 // We can have non-canonical operands, so try to normalize any common operand
10162 // to L0/R0.
10163 if (L0 == R1) {
10164 std::swap(R0, R1);
10165 RPred = FCmpInst::getSwappedPredicate(RPred);
10166 }
10167 if (R0 == L1) {
10168 std::swap(L0, L1);
10169 LPred = FCmpInst::getSwappedPredicate(LPred);
10170 }
10171 if (L1 == R1) {
10172 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10173 if (L0 != R0 || match(L0, m_ImmConstant())) {
10174 std::swap(L0, L1);
10175 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10176 std::swap(R0, R1);
10177 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10178 }
10179 }
10180
10181 // Can we infer anything when the two compares have matching operands?
10182 if (L0 == R0 && L1 == R1) {
10183 if ((LPred & RPred) == LPred)
10184 return true;
10185 if ((LPred & ~RPred) == LPred)
10186 return false;
10187 }
10188
10189 // See if we can infer anything if operand-0 matches and we have at least one
10190 // constant.
10191 const APFloat *L1C, *R1C;
10192 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10193 if (std::optional<ConstantFPRange> DomCR =
10195 if (std::optional<ConstantFPRange> ImpliedCR =
10197 if (ImpliedCR->contains(*DomCR))
10198 return true;
10199 }
10200 if (std::optional<ConstantFPRange> ImpliedCR =
10202 FCmpInst::getInversePredicate(RPred), *R1C)) {
10203 if (ImpliedCR->contains(*DomCR))
10204 return false;
10205 }
10206 }
10207 }
10208
10209 return std::nullopt;
10210}
10211
10212/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10213/// false. Otherwise, return std::nullopt if we can't infer anything. We
10214/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10215/// instruction.
10216static std::optional<bool>
10218 const Value *RHSOp0, const Value *RHSOp1,
10219 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10220 // The LHS must be an 'or', 'and', or a 'select' instruction.
10221 assert((LHS->getOpcode() == Instruction::And ||
10222 LHS->getOpcode() == Instruction::Or ||
10223 LHS->getOpcode() == Instruction::Select) &&
10224 "Expected LHS to be 'and', 'or', or 'select'.");
10225
10226 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10227
10228 // If the result of an 'or' is false, then we know both legs of the 'or' are
10229 // false. Similarly, if the result of an 'and' is true, then we know both
10230 // legs of the 'and' are true.
10231 const Value *ALHS, *ARHS;
10232 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10233 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10234 // FIXME: Make this non-recursion.
10235 if (std::optional<bool> Implication = isImpliedCondition(
10236 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10237 return Implication;
10238 if (std::optional<bool> Implication = isImpliedCondition(
10239 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10240 return Implication;
10241 return std::nullopt;
10242 }
10243 return std::nullopt;
10244}
10245
10246std::optional<bool>
10248 const Value *RHSOp0, const Value *RHSOp1,
10249 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10250 // Bail out when we hit the limit.
10252 return std::nullopt;
10253
10254 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10255 // example.
10256 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10257 return std::nullopt;
10258
10259 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10260 "Expected integer type only!");
10261
10262 // Match not
10263 if (match(LHS, m_Not(m_Value(LHS))))
10264 LHSIsTrue = !LHSIsTrue;
10265
10266 // Both LHS and RHS are icmps.
10267 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10268 CmpPredicate LHSPred;
10269 Value *LHSOp0, *LHSOp1;
10270 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10271 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10272 RHSOp1, DL, LHSIsTrue);
10273 } else {
10274 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10275 "Expected floating point type only!");
10276 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10277 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10278 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10279 DL, LHSIsTrue);
10280 }
10281
10282 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10283 /// the RHS to be an icmp.
10284 /// FIXME: Add support for and/or/select on the RHS.
10285 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10286 if ((LHSI->getOpcode() == Instruction::And ||
10287 LHSI->getOpcode() == Instruction::Or ||
10288 LHSI->getOpcode() == Instruction::Select))
10289 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10290 Depth);
10291 }
10292 return std::nullopt;
10293}
10294
10295std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10296 const DataLayout &DL,
10297 bool LHSIsTrue, unsigned Depth) {
10298 // LHS ==> RHS by definition
10299 if (LHS == RHS)
10300 return LHSIsTrue;
10301
10302 // Match not
10303 bool InvertRHS = false;
10304 if (match(RHS, m_Not(m_Value(RHS)))) {
10305 if (LHS == RHS)
10306 return !LHSIsTrue;
10307 InvertRHS = true;
10308 }
10309
10310 CmpPredicate RHSPred;
10311 Value *RHSOp0, *RHSOp1;
10312 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10313 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10314 LHSIsTrue, Depth))
10315 return InvertRHS ? !*Implied : *Implied;
10316 return std::nullopt;
10317 }
10318 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10319 if (auto Implied = isImpliedCondition(
10320 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10321 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10322 return InvertRHS ? !*Implied : *Implied;
10323 return std::nullopt;
10324 }
10325
10327 return std::nullopt;
10328
10329 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10330 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10331 const Value *RHS1, *RHS2;
10332 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10333 if (std::optional<bool> Imp =
10334 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10335 if (*Imp == true)
10336 return !InvertRHS;
10337 if (std::optional<bool> Imp =
10338 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10339 if (*Imp == true)
10340 return !InvertRHS;
10341 }
10342 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10343 if (std::optional<bool> Imp =
10344 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10345 if (*Imp == false)
10346 return InvertRHS;
10347 if (std::optional<bool> Imp =
10348 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10349 if (*Imp == false)
10350 return InvertRHS;
10351 }
10352
10353 return std::nullopt;
10354}
10355
10356// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10357// condition dominating ContextI or nullptr, if no condition is found.
10358static std::pair<Value *, bool>
10360 if (!ContextI || !ContextI->getParent())
10361 return {nullptr, false};
10362
10363 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10364 // dominator tree (eg, from a SimplifyQuery) instead?
10365 const BasicBlock *ContextBB = ContextI->getParent();
10366 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10367 if (!PredBB)
10368 return {nullptr, false};
10369
10370 // We need a conditional branch in the predecessor.
10371 Value *PredCond;
10372 BasicBlock *TrueBB, *FalseBB;
10373 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10374 return {nullptr, false};
10375
10376 // The branch should get simplified. Don't bother simplifying this condition.
10377 if (TrueBB == FalseBB)
10378 return {nullptr, false};
10379
10380 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10381 "Predecessor block does not point to successor?");
10382
10383 // Is this condition implied by the predecessor condition?
10384 return {PredCond, TrueBB == ContextBB};
10385}
10386
10387std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10388 const Instruction *ContextI,
10389 const DataLayout &DL) {
10390 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10391 auto PredCond = getDomPredecessorCondition(ContextI);
10392 if (PredCond.first)
10393 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10394 return std::nullopt;
10395}
10396
10398 const Value *LHS,
10399 const Value *RHS,
10400 const Instruction *ContextI,
10401 const DataLayout &DL) {
10402 auto PredCond = getDomPredecessorCondition(ContextI);
10403 if (PredCond.first)
10404 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10405 PredCond.second);
10406 return std::nullopt;
10407}
10408
10410 APInt &Upper, const InstrInfoQuery &IIQ,
10411 bool PreferSignedRange) {
10412 unsigned Width = Lower.getBitWidth();
10413 const APInt *C;
10414 switch (BO.getOpcode()) {
10415 case Instruction::Sub:
10416 if (match(BO.getOperand(0), m_APInt(C))) {
10417 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10418 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10419
10420 // If the caller expects a signed compare, then try to use a signed range.
10421 // Otherwise if both no-wraps are set, use the unsigned range because it
10422 // is never larger than the signed range. Example:
10423 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10424 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10425 if (PreferSignedRange && HasNSW && HasNUW)
10426 HasNUW = false;
10427
10428 if (HasNUW) {
10429 // 'sub nuw c, x' produces [0, C].
10430 Upper = *C + 1;
10431 } else if (HasNSW) {
10432 if (C->isNegative()) {
10433 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10435 Upper = *C - APInt::getSignedMaxValue(Width);
10436 } else {
10437 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10438 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10439 Lower = *C - APInt::getSignedMaxValue(Width);
10441 }
10442 }
10443 }
10444 break;
10445 case Instruction::Add:
10446 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10447 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10448 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10449
10450 // If the caller expects a signed compare, then try to use a signed
10451 // range. Otherwise if both no-wraps are set, use the unsigned range
10452 // because it is never larger than the signed range. Example: "add nuw
10453 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10454 if (PreferSignedRange && HasNSW && HasNUW)
10455 HasNUW = false;
10456
10457 if (HasNUW) {
10458 // 'add nuw x, C' produces [C, UINT_MAX].
10459 Lower = *C;
10460 } else if (HasNSW) {
10461 if (C->isNegative()) {
10462 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10464 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10465 } else {
10466 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10467 Lower = APInt::getSignedMinValue(Width) + *C;
10468 Upper = APInt::getSignedMaxValue(Width) + 1;
10469 }
10470 }
10471 }
10472 break;
10473
10474 case Instruction::And:
10475 if (match(BO.getOperand(1), m_APInt(C)))
10476 // 'and x, C' produces [0, C].
10477 Upper = *C + 1;
10478 // X & -X is a power of two or zero. So we can cap the value at max power of
10479 // two.
10480 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10481 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10482 Upper = APInt::getSignedMinValue(Width) + 1;
10483 break;
10484
10485 case Instruction::Or:
10486 if (match(BO.getOperand(1), m_APInt(C)))
10487 // 'or x, C' produces [C, UINT_MAX].
10488 Lower = *C;
10489 break;
10490
10491 case Instruction::AShr:
10492 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10493 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10495 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10496 } else if (match(BO.getOperand(0), m_APInt(C))) {
10497 unsigned ShiftAmount = Width - 1;
10498 if (!C->isZero() && IIQ.isExact(&BO))
10499 ShiftAmount = C->countr_zero();
10500 if (C->isNegative()) {
10501 // 'ashr C, x' produces [C, C >> (Width-1)]
10502 Lower = *C;
10503 Upper = C->ashr(ShiftAmount) + 1;
10504 } else {
10505 // 'ashr C, x' produces [C >> (Width-1), C]
10506 Lower = C->ashr(ShiftAmount);
10507 Upper = *C + 1;
10508 }
10509 }
10510 break;
10511
10512 case Instruction::LShr:
10513 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10514 // 'lshr x, C' produces [0, UINT_MAX >> C].
10515 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10516 } else if (match(BO.getOperand(0), m_APInt(C))) {
10517 // 'lshr C, x' produces [C >> (Width-1), C].
10518 unsigned ShiftAmount = Width - 1;
10519 if (!C->isZero() && IIQ.isExact(&BO))
10520 ShiftAmount = C->countr_zero();
10521 Lower = C->lshr(ShiftAmount);
10522 Upper = *C + 1;
10523 }
10524 break;
10525
10526 case Instruction::Shl:
10527 if (match(BO.getOperand(0), m_APInt(C))) {
10528 if (IIQ.hasNoUnsignedWrap(&BO)) {
10529 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10530 Lower = *C;
10531 Upper = Lower.shl(Lower.countl_zero()) + 1;
10532 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10533 if (C->isNegative()) {
10534 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10535 unsigned ShiftAmount = C->countl_one() - 1;
10536 Lower = C->shl(ShiftAmount);
10537 Upper = *C + 1;
10538 } else {
10539 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10540 unsigned ShiftAmount = C->countl_zero() - 1;
10541 Lower = *C;
10542 Upper = C->shl(ShiftAmount) + 1;
10543 }
10544 } else {
10545 // If lowbit is set, value can never be zero.
10546 if ((*C)[0])
10547 Lower = APInt::getOneBitSet(Width, 0);
10548 // If we are shifting a constant the largest it can be is if the longest
10549 // sequence of consecutive ones is shifted to the highbits (breaking
10550 // ties for which sequence is higher). At the moment we take a liberal
10551 // upper bound on this by just popcounting the constant.
10552 // TODO: There may be a bitwise trick for it longest/highest
10553 // consecutative sequence of ones (naive method is O(Width) loop).
10554 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10555 }
10556 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10557 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10558 }
10559 break;
10560
10561 case Instruction::SDiv:
10562 if (match(BO.getOperand(1), m_APInt(C))) {
10563 APInt IntMin = APInt::getSignedMinValue(Width);
10564 APInt IntMax = APInt::getSignedMaxValue(Width);
10565 if (C->isAllOnes()) {
10566 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10567 // where C != -1 and C != 0 and C != 1
10568 Lower = IntMin + 1;
10569 Upper = IntMax + 1;
10570 } else if (C->countl_zero() < Width - 1) {
10571 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10572 // where C != -1 and C != 0 and C != 1
10573 Lower = IntMin.sdiv(*C);
10574 Upper = IntMax.sdiv(*C);
10575 if (Lower.sgt(Upper))
10577 Upper = Upper + 1;
10578 assert(Upper != Lower && "Upper part of range has wrapped!");
10579 }
10580 } else if (match(BO.getOperand(0), m_APInt(C))) {
10581 if (C->isMinSignedValue()) {
10582 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10583 Lower = *C;
10584 Upper = Lower.lshr(1) + 1;
10585 } else {
10586 // 'sdiv C, x' produces [-|C|, |C|].
10587 Upper = C->abs() + 1;
10588 Lower = (-Upper) + 1;
10589 }
10590 }
10591 break;
10592
10593 case Instruction::UDiv:
10594 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10595 // 'udiv x, C' produces [0, UINT_MAX / C].
10596 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10597 } else if (match(BO.getOperand(0), m_APInt(C))) {
10598 // 'udiv C, x' produces [0, C].
10599 Upper = *C + 1;
10600 }
10601 break;
10602
10603 case Instruction::SRem:
10604 if (match(BO.getOperand(1), m_APInt(C))) {
10605 // 'srem x, C' produces (-|C|, |C|).
10606 Upper = C->abs();
10607 Lower = (-Upper) + 1;
10608 } else if (match(BO.getOperand(0), m_APInt(C))) {
10609 if (C->isNegative()) {
10610 // 'srem -|C|, x' produces [-|C|, 0].
10611 Upper = 1;
10612 Lower = *C;
10613 } else {
10614 // 'srem |C|, x' produces [0, |C|].
10615 Upper = *C + 1;
10616 }
10617 }
10618 break;
10619
10620 case Instruction::URem:
10621 if (match(BO.getOperand(1), m_APInt(C)))
10622 // 'urem x, C' produces [0, C).
10623 Upper = *C;
10624 else if (match(BO.getOperand(0), m_APInt(C)))
10625 // 'urem C, x' produces [0, C].
10626 Upper = *C + 1;
10627 break;
10628
10629 default:
10630 break;
10631 }
10632}
10633
10635 bool UseInstrInfo) {
10636 unsigned Width = II.getType()->getScalarSizeInBits();
10637 const APInt *C;
10638 switch (II.getIntrinsicID()) {
10639 case Intrinsic::ctlz:
10640 case Intrinsic::cttz: {
10641 APInt Upper(Width, Width);
10642 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10643 Upper += 1;
10644 // Maximum of set/clear bits is the bit width.
10646 }
10647 case Intrinsic::ctpop:
10648 // Maximum of set/clear bits is the bit width.
10650 APInt(Width, Width) + 1);
10651 case Intrinsic::uadd_sat:
10652 // uadd.sat(x, C) produces [C, UINT_MAX].
10653 if (match(II.getOperand(0), m_APInt(C)) ||
10654 match(II.getOperand(1), m_APInt(C)))
10656 break;
10657 case Intrinsic::sadd_sat:
10658 if (match(II.getOperand(0), m_APInt(C)) ||
10659 match(II.getOperand(1), m_APInt(C))) {
10660 if (C->isNegative())
10661 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10663 APInt::getSignedMaxValue(Width) + *C +
10664 1);
10665
10666 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10668 APInt::getSignedMaxValue(Width) + 1);
10669 }
10670 break;
10671 case Intrinsic::usub_sat:
10672 // usub.sat(C, x) produces [0, C].
10673 if (match(II.getOperand(0), m_APInt(C)))
10674 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10675
10676 // usub.sat(x, C) produces [0, UINT_MAX - C].
10677 if (match(II.getOperand(1), m_APInt(C)))
10679 APInt::getMaxValue(Width) - *C + 1);
10680 break;
10681 case Intrinsic::ssub_sat:
10682 if (match(II.getOperand(0), m_APInt(C))) {
10683 if (C->isNegative())
10684 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10686 *C - APInt::getSignedMinValue(Width) +
10687 1);
10688
10689 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10691 APInt::getSignedMaxValue(Width) + 1);
10692 } else if (match(II.getOperand(1), m_APInt(C))) {
10693 if (C->isNegative())
10694 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10696 APInt::getSignedMaxValue(Width) + 1);
10697
10698 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10700 APInt::getSignedMaxValue(Width) - *C +
10701 1);
10702 }
10703 break;
10704 case Intrinsic::umin:
10705 case Intrinsic::umax:
10706 case Intrinsic::smin:
10707 case Intrinsic::smax:
10708 if (!match(II.getOperand(0), m_APInt(C)) &&
10709 !match(II.getOperand(1), m_APInt(C)))
10710 break;
10711
10712 switch (II.getIntrinsicID()) {
10713 case Intrinsic::umin:
10714 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10715 case Intrinsic::umax:
10717 case Intrinsic::smin:
10719 *C + 1);
10720 case Intrinsic::smax:
10722 APInt::getSignedMaxValue(Width) + 1);
10723 default:
10724 llvm_unreachable("Must be min/max intrinsic");
10725 }
10726 break;
10727 case Intrinsic::abs:
10728 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10729 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10730 if (match(II.getOperand(1), m_One()))
10732 APInt::getSignedMaxValue(Width) + 1);
10733
10735 APInt::getSignedMinValue(Width) + 1);
10736 case Intrinsic::vscale:
10737 if (!II.getParent() || !II.getFunction())
10738 break;
10739 return getVScaleRange(II.getFunction(), Width);
10740 case Intrinsic::read_register:
10741 case Intrinsic::read_volatile_register: {
10742 const Module *M = II.getModule();
10743 if (!M || !M->getTargetTriple().isRISCV())
10744 break;
10745 if (II.getFunction() && isReadVLENB(II))
10746 return getRISCVVLENBRange(II, Width);
10747 break;
10748 }
10749 default:
10750 break;
10751 }
10752
10753 return ConstantRange::getFull(Width);
10754}
10755
10757 const InstrInfoQuery &IIQ) {
10758 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10759 const Value *LHS = nullptr, *RHS = nullptr;
10761 if (R.Flavor == SPF_UNKNOWN)
10762 return ConstantRange::getFull(BitWidth);
10763
10764 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10765 // If the negation part of the abs (in RHS) has the NSW flag,
10766 // then the result of abs(X) is [0..SIGNED_MAX],
10767 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10768 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10772
10775 }
10776
10777 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10778 // The result of -abs(X) is <= 0.
10780 APInt(BitWidth, 1));
10781 }
10782
10783 const APInt *C;
10784 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10785 return ConstantRange::getFull(BitWidth);
10786
10787 switch (R.Flavor) {
10788 case SPF_UMIN:
10790 case SPF_UMAX:
10792 case SPF_SMIN:
10794 *C + 1);
10795 case SPF_SMAX:
10798 default:
10799 return ConstantRange::getFull(BitWidth);
10800 }
10801}
10802
10804 // The maximum representable value of a half is 65504. For floats the maximum
10805 // value is 3.4e38 which requires roughly 129 bits.
10806 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10807 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10808 return;
10809 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10810 Lower = APInt(BitWidth, -65504, true);
10811 Upper = APInt(BitWidth, 65505);
10812 }
10813
10814 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10815 // For a fptoui the lower limit is left as 0.
10816 Upper = APInt(BitWidth, 65505);
10817 }
10818}
10819
10821 const SimplifyQuery &SQ,
10822 unsigned Depth) {
10823 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10824
10826 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10827
10828 if (auto *C = dyn_cast<Constant>(V))
10829 return C->toConstantRange();
10830
10831 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10832 ConstantRange CR = ConstantRange::getFull(BitWidth);
10833 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10834 APInt Lower = APInt(BitWidth, 0);
10835 APInt Upper = APInt(BitWidth, 0);
10836 // TODO: Return ConstantRange.
10837 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10839 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10841 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10842 ConstantRange CRTrue =
10843 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10844 ConstantRange CRFalse =
10845 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10846 CR = CRTrue.unionWith(CRFalse);
10848 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10849 ConstantRange SrcCR =
10850 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10851 CR = SrcCR.truncate(BitWidth);
10852 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10853 ConstantRange SrcCR =
10854 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10855 CR = SrcCR.zeroExtend(BitWidth);
10856 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10857 ConstantRange SrcCR =
10858 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10859 CR = SrcCR.signExtend(BitWidth);
10860 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10861 APInt Lower = APInt(BitWidth, 0);
10862 APInt Upper = APInt(BitWidth, 0);
10863 // TODO: Return ConstantRange.
10866 } else if (const auto *A = dyn_cast<Argument>(V))
10867 if (std::optional<ConstantRange> Range = A->getRange())
10868 CR = *Range;
10869
10870 if (auto *I = dyn_cast<Instruction>(V)) {
10871 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10873
10874 Value *FrexpSrc;
10875 if (const auto *CB = dyn_cast<CallBase>(V)) {
10876 if (std::optional<ConstantRange> Range = CB->getRange())
10877 CR = CR.intersectWith(*Range);
10879 m_Value(FrexpSrc))))) {
10880 const fltSemantics &FltSem =
10881 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10882 // It should be possible to implement this for any type, but this logic
10883 // only computes the range assuming standard subnormal handling.
10884 if (APFloat::isIEEELikeFP(FltSem)) {
10886 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10887
10888 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10889 // constrain its range when the source can be neither.
10890 if (KnownSrc.isKnownNeverInfOrNaN()) {
10891 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10892
10893 // Offset to find the true minimum exponent value for a denormal.
10894 if (!KnownSrc.isKnownNeverSubnormal())
10895 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10896
10897 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10898
10899 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10901
10902 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10903 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10904
10905 MinExp = std::max(AdjustedMin, MinExp);
10906 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10907 MaxExp);
10908
10910 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10911 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10912 /*isSigned=*/true));
10913 }
10914 }
10915 }
10916 }
10917
10918 if (SQ.CtxI && SQ.AC) {
10919 // Try to restrict the range based on information from assumptions.
10920 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10921 if (!AssumeVH)
10922 continue;
10923 CallInst *I = cast<CallInst>(AssumeVH);
10924 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10925 "Got assumption for the wrong function!");
10926 assert(I->getIntrinsicID() == Intrinsic::assume &&
10927 "must be an assume intrinsic");
10928
10929 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
10930 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
10931 if (getBundleAttrFromOBU(OBU) == BundleAttr::Range) {
10932 auto [Val, Range] = getAssumeRangeInfo(OBU);
10933 if (Val == V && isValidAssumeForContext(I, SQ))
10934 CR = CR.intersectWith(Range);
10935 }
10936 continue;
10937 }
10938
10939 if (!isValidAssumeForContext(I, SQ))
10940 continue;
10941 Value *Arg = I->getArgOperand(0);
10942 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10943 // Currently we just use information from comparisons.
10944 if (!Cmp || Cmp->getOperand(0) != V)
10945 continue;
10946 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10947 ConstantRange RHS =
10948 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10949 SQ.getWithInstruction(I), Depth + 1);
10950 CR = CR.intersectWith(
10951 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10952 }
10953 }
10954
10955 return CR;
10956}
10957
10958static void
10960 function_ref<void(Value *)> InsertAffected) {
10961 assert(V != nullptr);
10962 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10963 InsertAffected(V);
10964 } else if (auto *I = dyn_cast<Instruction>(V)) {
10965 InsertAffected(V);
10966
10967 // Peek through unary operators to find the source of the condition.
10968 Value *Op;
10970 m_Trunc(m_Value(Op))))) {
10972 InsertAffected(Op);
10973 }
10974 }
10975}
10976
10978 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10979 auto AddAffected = [&InsertAffected](Value *V) {
10980 addValueAffectedByCondition(V, InsertAffected);
10981 };
10982
10983 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10984 if (IsAssume) {
10985 AddAffected(LHS);
10986 AddAffected(RHS);
10987 } else if (match(RHS, m_Constant()))
10988 AddAffected(LHS);
10989 };
10990
10991 SmallVector<Value *, 8> Worklist;
10993 Worklist.push_back(Cond);
10994 while (!Worklist.empty()) {
10995 Value *V = Worklist.pop_back_val();
10996 if (!Visited.insert(V).second)
10997 continue;
10998
10999 CmpPredicate Pred;
11000 Value *A, *B, *X;
11001
11002 if (IsAssume) {
11003 AddAffected(V);
11004 if (match(V, m_Not(m_Value(X))))
11005 AddAffected(X);
11006 }
11007
11008 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
11009 // assume(A && B) is split to -> assume(A); assume(B);
11010 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
11011 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
11012 // enough information to be worth handling (intersection of information as
11013 // opposed to union).
11014 if (!IsAssume) {
11015 Worklist.push_back(A);
11016 Worklist.push_back(B);
11017 }
11018 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
11019 bool HasRHSC = match(B, m_ConstantInt());
11020 if (ICmpInst::isEquality(Pred)) {
11021 AddAffected(A);
11022 if (IsAssume)
11023 AddAffected(B);
11024 if (HasRHSC) {
11025 Value *Y;
11026 // (X << C) or (X >>_s C) or (X >>_u C).
11027 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
11028 AddAffected(X);
11029 // (X & C) or (X | C).
11030 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11031 match(A, m_Or(m_Value(X), m_Value(Y)))) {
11032 AddAffected(X);
11033 AddAffected(Y);
11034 }
11035 // X - Y
11036 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11037 AddAffected(X);
11038 AddAffected(Y);
11039 }
11040 }
11041 } else {
11042 AddCmpOperands(A, B);
11043 if (HasRHSC) {
11044 Value *Y;
11045 // Handle (A + C1) u< C2, which is the canonical form of
11046 // A > C3 && A < C4.
11048 AddAffected(X);
11049 // X - Y pred C, which implies X != Y if 0 pred C is false.
11050 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11051 AddAffected(X);
11052 AddAffected(Y);
11053 }
11054
11055 if (ICmpInst::isUnsigned(Pred)) {
11056 // X & Y u> C -> X >u C && Y >u C
11057 // X | Y u< C -> X u< C && Y u< C
11058 // X nuw+ Y u< C -> X u< C && Y u< C
11059 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11060 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11061 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11062 AddAffected(X);
11063 AddAffected(Y);
11064 }
11065 }
11066 }
11067
11068 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11069 // by computeKnownFPClass().
11071 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11072 InsertAffected(X);
11073 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11074 InsertAffected(X);
11075 }
11076 }
11077
11078 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11079 Value *SquareOp = nullptr;
11080 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11081 AddAffected(SquareOp);
11082 };
11083 AddNuwSquareOperand(A);
11084 AddNuwSquareOperand(B);
11085
11086 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11087 AddAffected(X);
11088 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11089 AddCmpOperands(A, B);
11090
11091 // fcmp fneg(x), y
11092 // fcmp fabs(x), y
11093 // fcmp fneg(fabs(x)), y
11094 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
11096 AddAffected(A);
11097 if (match(A, m_FAbs(m_Value(A))))
11098 AddAffected(A);
11099
11101 m_Value()))) {
11102 // Handle patterns that computeKnownFPClass() support.
11103 AddAffected(A);
11104 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11105 // Assume is checked here as X is already added above for assumes in
11106 // addValueAffectedByCondition
11107 AddAffected(X);
11108 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11109 // Assume is checked here to avoid issues with ephemeral values
11110 Worklist.push_back(X);
11111 }
11112 }
11113}
11114
11116 // (X >> C) or/add (X & mask(C) != 0)
11117 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11118 if (BO->getOpcode() == Instruction::Add ||
11119 BO->getOpcode() == Instruction::Or) {
11120 const Value *X;
11121 const APInt *C1, *C2;
11122 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11126 m_Zero())))) &&
11127 C2->popcount() == C1->getZExtValue())
11128 return X;
11129 }
11130 }
11131
11132 // select(cond, X, -X)
11133 {
11134 const Value *X;
11135 if (match(V, m_c_Select(m_Value(X), m_Neg(m_Deferred(X)))))
11136 return X;
11137 }
11138
11139 return nullptr;
11140}
11141
11143 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11144}
11145
11148 unsigned MaxCount, bool AllowUndefOrPoison) {
11151 auto Push = [&](const Value *V) -> bool {
11152 Constant *C;
11153 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11154 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11155 return false;
11156 // Check existence first to avoid unnecessary allocations.
11157 if (Constants.contains(C))
11158 return true;
11159 if (Constants.size() == MaxCount)
11160 return false;
11161 Constants.insert(C);
11162 return true;
11163 }
11164
11165 if (auto *Inst = dyn_cast<Instruction>(V)) {
11166 if (Visited.insert(Inst).second)
11167 Worklist.push_back(Inst);
11168 return true;
11169 }
11170 return false;
11171 };
11172 if (!Push(V))
11173 return false;
11174 while (!Worklist.empty()) {
11175 const Instruction *CurInst = Worklist.pop_back_val();
11176 switch (CurInst->getOpcode()) {
11177 case Instruction::Select:
11178 if (!Push(CurInst->getOperand(1)))
11179 return false;
11180 if (!Push(CurInst->getOperand(2)))
11181 return false;
11182 break;
11183 case Instruction::PHI:
11184 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11185 // Fast path for recurrence PHI.
11186 if (IncomingValue == CurInst)
11187 continue;
11188 if (!Push(IncomingValue))
11189 return false;
11190 }
11191 break;
11192 default:
11193 return false;
11194 }
11195 }
11196 return true;
11197}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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:665
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
SmallVector< MachineOperand, 4 > Cond
int64_t C1
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 bool isNonZeroAddrPlusOffset(const SimplifyQuery &Q, Value *X, Value *Y)
Return true if "addr(P) + Off" cannot be zero.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:367
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:342
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:363
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:338
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:334
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:371
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:359
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:384
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:375
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:6165
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1405
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
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
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:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
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:44
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:65
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.
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
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass ceil(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ceil.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static LLVM_ABI KnownFPClass fmuladd(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fptrunc and fptrunc_round.
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())
static LLVM_ABI KnownFPClass fmuladd_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd squared, squared, addend.
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.
void knownNot(FPClassMask RuleOut)
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 ...
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (rint, nearbyint, round, roundeven).
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
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 isKnownNever(FPClassMask Mask) const
Return true if it's known this can never be one of the mask entries.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
static LLVM_ABI KnownFPClass trunc(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for trunc.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode, bool IsMultiUnitFPType)
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass floor(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for floor.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
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:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
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().
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
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)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
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)
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.
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 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 bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
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 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 isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:246
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.
LLVM_ABI AssumeRangeInfo getAssumeRangeInfo(OperandBundleUse)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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 Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
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 Function * getFunction() const
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041