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