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