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
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1323 Value *Arm, bool Invert,
1324 const SimplifyQuery &Q, unsigned Depth) {
1325 // If we have a constant arm, we are done.
1326 if (Known.isConstant())
1327 return;
1328
1329 // See what condition implies about the bits of the select arm.
1330 KnownBits CondRes(Known.getBitWidth());
1331 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1332 // If we don't get any information from the condition, no reason to
1333 // proceed.
1334 if (CondRes.isUnknown())
1335 return;
1336
1337 // We can have conflict if the condition is dead. I.e if we have
1338 // (x | 64) < 32 ? (x | 64) : y
1339 // we will have conflict at bit 6 from the condition/the `or`.
1340 // In that case just return. Its not particularly important
1341 // what we do, as this select is going to be simplified soon.
1342 CondRes = CondRes.unionWith(Known);
1343 if (CondRes.hasConflict())
1344 return;
1345
1346 // Finally make sure the information we found is valid. This is relatively
1347 // expensive so it's left for the very end.
1348 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1349 return;
1350
1351 // Finally, we know we get information from the condition and its valid,
1352 // so return it.
1353 Known = std::move(CondRes);
1354}
1355
1356// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1357// Returns the input and lower/upper bounds.
1358static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1359 const APInt *&CLow, const APInt *&CHigh) {
1361 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1362 "Input should be a Select!");
1363
1364 const Value *LHS = nullptr, *RHS = nullptr;
1366 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1367 return false;
1368
1369 if (!match(RHS, m_APInt(CLow)))
1370 return false;
1371
1372 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1374 if (getInverseMinMaxFlavor(SPF) != SPF2)
1375 return false;
1376
1377 if (!match(RHS2, m_APInt(CHigh)))
1378 return false;
1379
1380 if (SPF == SPF_SMIN)
1381 std::swap(CLow, CHigh);
1382
1383 In = LHS2;
1384 return CLow->sle(*CHigh);
1385}
1386
1388 const APInt *&CLow,
1389 const APInt *&CHigh) {
1390 assert((II->getIntrinsicID() == Intrinsic::smin ||
1391 II->getIntrinsicID() == Intrinsic::smax) &&
1392 "Must be smin/smax");
1393
1394 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1395 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1396 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1397 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1398 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1399 return false;
1400
1401 if (II->getIntrinsicID() == Intrinsic::smin)
1402 std::swap(CLow, CHigh);
1403 return CLow->sle(*CHigh);
1404}
1405
1407 KnownBits &Known) {
1408 const APInt *CLow, *CHigh;
1409 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1410 Known = Known.unionWith(
1411 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1412}
1413
1415 const APInt &DemandedElts,
1417 const SimplifyQuery &Q,
1418 unsigned Depth) {
1419 unsigned BitWidth = Known.getBitWidth();
1420
1421 KnownBits Known2(BitWidth);
1422 switch (I->getOpcode()) {
1423 default: break;
1424 case Instruction::Load:
1425 if (MDNode *MD =
1426 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1428 break;
1429 case Instruction::And:
1430 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1431 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1432
1433 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1434 break;
1435 case Instruction::Or:
1436 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1437 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1438
1439 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1440 break;
1441 case Instruction::Xor:
1442 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1443 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1444
1445 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1446 break;
1447 case Instruction::Mul: {
1450 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1451 DemandedElts, Known, Known2, Q, Depth);
1452 break;
1453 }
1454 case Instruction::UDiv: {
1455 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1456 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1457 Known =
1459 break;
1460 }
1461 case Instruction::SDiv: {
1462 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1463 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1464 Known =
1466 break;
1467 }
1468 case Instruction::Select: {
1469 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1470 KnownBits Res(Known.getBitWidth());
1471 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1472 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1473 return Res;
1474 };
1475 // Only known if known in both the LHS and RHS.
1476 Known =
1477 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1478 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1479 break;
1480 }
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::FPToUI:
1484 case Instruction::FPToSI:
1485 case Instruction::SIToFP:
1486 case Instruction::UIToFP:
1487 break; // Can't work with floating point.
1488 case Instruction::PtrToInt:
1489 case Instruction::PtrToAddr:
1490 case Instruction::IntToPtr:
1491 // Fall through and handle them the same as zext/trunc.
1492 [[fallthrough]];
1493 case Instruction::ZExt:
1494 case Instruction::Trunc: {
1495 Type *SrcTy = I->getOperand(0)->getType();
1496
1497 unsigned SrcBitWidth;
1498 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1499 // which fall through here.
1500 Type *ScalarTy = SrcTy->getScalarType();
1501 SrcBitWidth = ScalarTy->isPointerTy() ?
1502 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1503 Q.DL.getTypeSizeInBits(ScalarTy);
1504
1505 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1506 Known = Known.anyextOrTrunc(SrcBitWidth);
1507 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1508 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1509 Inst && Inst->hasNonNeg() && !Known.isNegative())
1510 Known.makeNonNegative();
1511 Known = Known.zextOrTrunc(BitWidth);
1512 break;
1513 }
1514 case Instruction::BitCast: {
1515 Type *SrcTy = I->getOperand(0)->getType();
1516 if (SrcTy->isIntOrPtrTy() &&
1517 // TODO: For now, not handling conversions like:
1518 // (bitcast i64 %x to <2 x i32>)
1519 !I->getType()->isVectorTy()) {
1520 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1521 break;
1522 }
1523
1524 const Value *V;
1525 // Handle bitcast from floating point to integer.
1526 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1527 V->getType()->isFPOrFPVectorTy()) {
1528 Type *FPType = V->getType()->getScalarType();
1529 KnownFPClass Result =
1530 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1531
1532 Known = Result.toKnownBits(FPType->getFltSemantics());
1533
1534 break;
1535 }
1536
1537 // Handle cast from vector integer type to scalar or vector integer.
1538 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1539 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1540 !I->getType()->isIntOrIntVectorTy() ||
1541 isa<ScalableVectorType>(I->getType()))
1542 break;
1543
1544 unsigned NumElts = DemandedElts.getBitWidth();
1545 bool IsLE = Q.DL.isLittleEndian();
1546 // Look through a cast from narrow vector elements to wider type.
1547 // Examples: v4i32 -> v2i64, v3i8 -> v24
1548 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1549 if (BitWidth % SubBitWidth == 0) {
1550 // Known bits are automatically intersected across demanded elements of a
1551 // vector. So for example, if a bit is computed as known zero, it must be
1552 // zero across all demanded elements of the vector.
1553 //
1554 // For this bitcast, each demanded element of the output is sub-divided
1555 // across a set of smaller vector elements in the source vector. To get
1556 // the known bits for an entire element of the output, compute the known
1557 // bits for each sub-element sequentially. This is done by shifting the
1558 // one-set-bit demanded elements parameter across the sub-elements for
1559 // consecutive calls to computeKnownBits. We are using the demanded
1560 // elements parameter as a mask operator.
1561 //
1562 // The known bits of each sub-element are then inserted into place
1563 // (dependent on endian) to form the full result of known bits.
1564 unsigned SubScale = BitWidth / SubBitWidth;
1565 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1566 for (unsigned i = 0; i != NumElts; ++i) {
1567 if (DemandedElts[i])
1568 SubDemandedElts.setBit(i * SubScale);
1569 }
1570
1571 KnownBits KnownSrc(SubBitWidth);
1572 for (unsigned i = 0; i != SubScale; ++i) {
1573 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1574 Depth + 1);
1575 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1576 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1577 }
1578 }
1579 // Look through a cast from wider vector elements to narrow type.
1580 // Examples: v2i64 -> v4i32
1581 if (SubBitWidth % BitWidth == 0) {
1582 unsigned SubScale = SubBitWidth / BitWidth;
1583 KnownBits KnownSrc(SubBitWidth);
1584 APInt SubDemandedElts =
1585 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1586 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1587 Depth + 1);
1588
1589 Known.setAllConflict();
1590 for (unsigned i = 0; i != NumElts; ++i) {
1591 if (DemandedElts[i]) {
1592 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1593 unsigned Offset = (Shifts % SubScale) * BitWidth;
1594 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1595 if (Known.isUnknown())
1596 break;
1597 }
1598 }
1599 }
1600 break;
1601 }
1602 case Instruction::SExt: {
1603 // Compute the bits in the result that are not present in the input.
1604 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1605
1606 Known = Known.trunc(SrcBitWidth);
1607 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1608 // If the sign bit of the input is known set or clear, then we know the
1609 // top bits of the result.
1610 Known = Known.sext(BitWidth);
1611 break;
1612 }
1613 case Instruction::Shl: {
1616 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1617 bool ShAmtNonZero) {
1618 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1619 };
1620 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1621 KF);
1622 // Trailing zeros of a right-shifted constant never decrease.
1623 const APInt *C;
1624 if (match(I->getOperand(0), m_APInt(C)))
1625 Known.Zero.setLowBits(C->countr_zero());
1626
1627 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1628 // lands at bit Y, when BitWidth is a power of 2.
1629 const APInt *YC;
1630 Value *X = I->getOperand(0);
1631 if (isPowerOf2_32(BitWidth) &&
1632 match(I->getOperand(1),
1634 m_SpecificInt(BitWidth - 1)))) &&
1635 YC->ult(BitWidth - 1)) {
1636 unsigned Y = YC->getZExtValue();
1637 Known.One.setBit(Y);
1638 Known.Zero.setBitsFrom(Y + 1);
1639 }
1640 break;
1641 }
1642 case Instruction::LShr: {
1643 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1644 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1645 bool ShAmtNonZero) {
1646 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1647 };
1648 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1649 KF);
1650 // Leading zeros of a left-shifted constant never decrease.
1651 const APInt *C;
1652 if (match(I->getOperand(0), m_APInt(C)))
1653 Known.Zero.setHighBits(C->countl_zero());
1654 break;
1655 }
1656 case Instruction::AShr: {
1657 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1658 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1659 bool ShAmtNonZero) {
1660 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1661 };
1662 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1663 KF);
1664 break;
1665 }
1666 case Instruction::Sub: {
1669 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1670 DemandedElts, Known, Known2, Q, Depth);
1671 break;
1672 }
1673 case Instruction::Add: {
1676 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1677 DemandedElts, Known, Known2, Q, Depth);
1678 break;
1679 }
1680 case Instruction::SRem:
1681 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1682 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1683 Known = KnownBits::srem(Known, Known2);
1684 break;
1685
1686 case Instruction::URem:
1687 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1688 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1689 Known = KnownBits::urem(Known, Known2);
1690 break;
1691 case Instruction::Alloca:
1692 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1693 break;
1694 case Instruction::GetElementPtr: {
1695 // Analyze all of the subscripts of this getelementptr instruction
1696 // to determine if we can prove known low zero bits.
1697 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1698 // Accumulate the constant indices in a separate variable
1699 // to minimize the number of calls to computeForAddSub.
1700 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1701 APInt AccConstIndices(IndexWidth, 0);
1702
1703 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1704 if (IndexWidth == BitWidth) {
1705 // Note that inbounds does *not* guarantee nsw for the addition, as only
1706 // the offset is signed, while the base address is unsigned.
1707 Known = KnownBits::add(Known, IndexBits);
1708 } else {
1709 // If the index width is smaller than the pointer width, only add the
1710 // value to the low bits.
1711 assert(IndexWidth < BitWidth &&
1712 "Index width can't be larger than pointer width");
1713 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1714 }
1715 };
1716
1718 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1719 // TrailZ can only become smaller, short-circuit if we hit zero.
1720 if (Known.isUnknown())
1721 break;
1722
1723 Value *Index = I->getOperand(i);
1724
1725 // Handle case when index is zero.
1726 Constant *CIndex = dyn_cast<Constant>(Index);
1727 if (CIndex && CIndex->isNullValue())
1728 continue;
1729
1730 if (StructType *STy = GTI.getStructTypeOrNull()) {
1731 // Handle struct member offset arithmetic.
1732
1733 assert(CIndex &&
1734 "Access to structure field must be known at compile time");
1735
1736 if (CIndex->getType()->isVectorTy())
1737 Index = CIndex->getSplatValue();
1738
1739 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1740 const StructLayout *SL = Q.DL.getStructLayout(STy);
1741 uint64_t Offset = SL->getElementOffset(Idx);
1742 AccConstIndices += Offset;
1743 continue;
1744 }
1745
1746 // Handle array index arithmetic.
1747 Type *IndexedTy = GTI.getIndexedType();
1748 if (!IndexedTy->isSized()) {
1749 Known.resetAll();
1750 break;
1751 }
1752
1753 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1754 uint64_t StrideInBytes = Stride.getKnownMinValue();
1755 if (!Stride.isScalable()) {
1756 // Fast path for constant offset.
1757 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1758 AccConstIndices +=
1759 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1760 continue;
1761 }
1762 }
1763
1764 KnownBits IndexBits =
1765 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1766 KnownBits ScalingFactor(IndexWidth);
1767 // Multiply by current sizeof type.
1768 // &A[i] == A + i * sizeof(*A[i]).
1769 if (Stride.isScalable()) {
1770 // For scalable types the only thing we know about sizeof is
1771 // that this is a multiple of the minimum size.
1772 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1773 } else {
1774 ScalingFactor =
1775 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1776 }
1777 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1778 }
1779 if (!Known.isUnknown() && !AccConstIndices.isZero())
1780 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1781 break;
1782 }
1783 case Instruction::PHI: {
1784 const PHINode *P = cast<PHINode>(I);
1785 BinaryOperator *BO = nullptr;
1786 Value *R = nullptr, *L = nullptr;
1787 if (matchSimpleRecurrence(P, BO, R, L)) {
1788 // Handle the case of a simple two-predecessor recurrence PHI.
1789 // There's a lot more that could theoretically be done here, but
1790 // this is sufficient to catch some interesting cases.
1791 unsigned Opcode = BO->getOpcode();
1792
1793 switch (Opcode) {
1794 // If this is a shift recurrence, we know the bits being shifted in. We
1795 // can combine that with information about the start value of the
1796 // recurrence to conclude facts about the result. If this is a udiv
1797 // recurrence, we know that the result can never exceed either the
1798 // numerator or the start value, whichever is greater.
1799 case Instruction::LShr:
1800 case Instruction::AShr:
1801 case Instruction::Shl:
1802 case Instruction::UDiv:
1803 if (BO->getOperand(0) != I)
1804 break;
1805 [[fallthrough]];
1806
1807 // For a urem recurrence, the result can never exceed the start value. The
1808 // phi could either be the numerator or the denominator.
1809 case Instruction::URem: {
1810 // We have matched a recurrence of the form:
1811 // %iv = [R, %entry], [%iv.next, %backedge]
1812 // %iv.next = shift_op %iv, L
1813
1814 // Recurse with the phi context to avoid concern about whether facts
1815 // inferred hold at original context instruction. TODO: It may be
1816 // correct to use the original context. IF warranted, explore and
1817 // add sufficient tests to cover.
1819 RecQ.CxtI = P;
1820 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1821 switch (Opcode) {
1822 case Instruction::Shl:
1823 // A shl recurrence will only increase the tailing zeros
1824 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1825 break;
1826 case Instruction::LShr:
1827 case Instruction::UDiv:
1828 case Instruction::URem:
1829 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1830 // the start value.
1831 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1832 break;
1833 case Instruction::AShr:
1834 // An ashr recurrence will extend the initial sign bit
1835 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1836 Known.One.setHighBits(Known2.countMinLeadingOnes());
1837 break;
1838 }
1839 break;
1840 }
1841
1842 // Check for operations that have the property that if
1843 // both their operands have low zero bits, the result
1844 // will have low zero bits.
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::And:
1848 case Instruction::Or:
1849 case Instruction::Mul: {
1850 // Change the context instruction to the "edge" that flows into the
1851 // phi. This is important because that is where the value is actually
1852 // "evaluated" even though it is used later somewhere else. (see also
1853 // D69571).
1855
1856 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1857 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1858 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1859
1860 // Ok, we have a PHI of the form L op= R. Check for low
1861 // zero bits.
1862 RecQ.CxtI = RInst;
1863 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1864
1865 // We need to take the minimum number of known bits
1866 KnownBits Known3(BitWidth);
1867 RecQ.CxtI = LInst;
1868 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1869
1870 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1871 Known3.countMinTrailingZeros()));
1872
1873 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1874 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1875 break;
1876
1877 switch (Opcode) {
1878 // If initial value of recurrence is nonnegative, and we are adding
1879 // a nonnegative number with nsw, the result can only be nonnegative
1880 // or poison value regardless of the number of times we execute the
1881 // add in phi recurrence. If initial value is negative and we are
1882 // adding a negative number with nsw, the result can only be
1883 // negative or poison value. Similar arguments apply to sub and mul.
1884 //
1885 // (add non-negative, non-negative) --> non-negative
1886 // (add negative, negative) --> negative
1887 case Instruction::Add: {
1888 if (Known2.isNonNegative() && Known3.isNonNegative())
1889 Known.makeNonNegative();
1890 else if (Known2.isNegative() && Known3.isNegative())
1891 Known.makeNegative();
1892 break;
1893 }
1894
1895 // (sub nsw non-negative, negative) --> non-negative
1896 // (sub nsw negative, non-negative) --> negative
1897 case Instruction::Sub: {
1898 if (BO->getOperand(0) != I)
1899 break;
1900 if (Known2.isNonNegative() && Known3.isNegative())
1901 Known.makeNonNegative();
1902 else if (Known2.isNegative() && Known3.isNonNegative())
1903 Known.makeNegative();
1904 break;
1905 }
1906
1907 // (mul nsw non-negative, non-negative) --> non-negative
1908 case Instruction::Mul:
1909 if (Known2.isNonNegative() && Known3.isNonNegative())
1910 Known.makeNonNegative();
1911 break;
1912
1913 default:
1914 break;
1915 }
1916 break;
1917 }
1918
1919 default:
1920 break;
1921 }
1922 }
1923
1924 // Unreachable blocks may have zero-operand PHI nodes.
1925 if (P->getNumIncomingValues() == 0)
1926 break;
1927
1928 // Otherwise take the unions of the known bit sets of the operands,
1929 // taking conservative care to avoid excessive recursion.
1930 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1931 // Skip if every incoming value references to ourself.
1932 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1933 break;
1934
1935 Known.setAllConflict();
1936 for (const Use &U : P->operands()) {
1937 Value *IncValue;
1938 const PHINode *CxtPhi;
1939 Instruction *CxtI;
1940 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1941 // Skip direct self references.
1942 if (IncValue == P)
1943 continue;
1944
1945 // Change the context instruction to the "edge" that flows into the
1946 // phi. This is important because that is where the value is actually
1947 // "evaluated" even though it is used later somewhere else. (see also
1948 // D69571).
1950
1951 Known2 = KnownBits(BitWidth);
1952
1953 // Recurse, but cap the recursion to one level, because we don't
1954 // want to waste time spinning around in loops.
1955 // TODO: See if we can base recursion limiter on number of incoming phi
1956 // edges so we don't overly clamp analysis.
1957 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1959
1960 // See if we can further use a conditional branch into the phi
1961 // to help us determine the range of the value.
1962 if (!Known2.isConstant()) {
1963 CmpPredicate Pred;
1964 const APInt *RHSC;
1965 BasicBlock *TrueSucc, *FalseSucc;
1966 // TODO: Use RHS Value and compute range from its known bits.
1967 if (match(RecQ.CxtI,
1968 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1969 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1970 // Check for cases of duplicate successors.
1971 if ((TrueSucc == CxtPhi->getParent()) !=
1972 (FalseSucc == CxtPhi->getParent())) {
1973 // If we're using the false successor, invert the predicate.
1974 if (FalseSucc == CxtPhi->getParent())
1975 Pred = CmpInst::getInversePredicate(Pred);
1976 // Get the knownbits implied by the incoming phi condition.
1977 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
1978 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
1979 // We can have conflicts here if we are analyzing deadcode (its
1980 // impossible for us reach this BB based the icmp).
1981 if (KnownUnion.hasConflict()) {
1982 // No reason to continue analyzing in a known dead region, so
1983 // just resetAll and break. This will cause us to also exit the
1984 // outer loop.
1985 Known.resetAll();
1986 break;
1987 }
1988 Known2 = KnownUnion;
1989 }
1990 }
1991 }
1992
1993 Known = Known.intersectWith(Known2);
1994 // If all bits have been ruled out, there's no need to check
1995 // more operands.
1996 if (Known.isUnknown())
1997 break;
1998 }
1999 }
2000 break;
2001 }
2002 case Instruction::Call:
2003 case Instruction::Invoke: {
2004 // If range metadata is attached to this call, set known bits from that,
2005 // and then intersect with known bits based on other properties of the
2006 // function.
2007 if (MDNode *MD =
2008 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2010
2011 const auto *CB = cast<CallBase>(I);
2012
2013 if (std::optional<ConstantRange> Range = CB->getRange())
2014 Known = Known.unionWith(Range->toKnownBits());
2015
2016 if (const Value *RV = CB->getReturnedArgOperand()) {
2017 if (RV->getType() == I->getType()) {
2018 computeKnownBits(RV, Known2, Q, Depth + 1);
2019 Known = Known.unionWith(Known2);
2020 // If the function doesn't return properly for all input values
2021 // (e.g. unreachable exits) then there might be conflicts between the
2022 // argument value and the range metadata. Simply discard the known bits
2023 // in case of conflicts.
2024 if (Known.hasConflict())
2025 Known.resetAll();
2026 }
2027 }
2028 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2029 switch (II->getIntrinsicID()) {
2030 default:
2031 break;
2032 case Intrinsic::abs: {
2033 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2034 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2035 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2036 break;
2037 }
2038 case Intrinsic::bitreverse:
2039 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2040 Known = Known.unionWith(Known2.reverseBits());
2041 break;
2042 case Intrinsic::bswap:
2043 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2044 Known = Known.unionWith(Known2.byteSwap());
2045 break;
2046 case Intrinsic::ctlz: {
2047 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2048 // If we have a known 1, its position is our upper bound.
2049 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2050 // If this call is poison for 0 input, the result will be less than 2^n.
2051 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2052 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2053 unsigned LowBits = llvm::bit_width(PossibleLZ);
2054 Known.Zero.setBitsFrom(LowBits);
2055 break;
2056 }
2057 case Intrinsic::cttz: {
2058 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2059 // If we have a known 1, its position is our upper bound.
2060 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2061 // If this call is poison for 0 input, the result will be less than 2^n.
2062 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2063 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2064 unsigned LowBits = llvm::bit_width(PossibleTZ);
2065 Known.Zero.setBitsFrom(LowBits);
2066 break;
2067 }
2068 case Intrinsic::ctpop: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 // We can bound the space the count needs. Also, bits known to be zero
2071 // can't contribute to the population.
2072 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2073 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2074 Known.Zero.setBitsFrom(LowBits);
2075 // TODO: we could bound KnownOne using the lower bound on the number
2076 // of bits which might be set provided by popcnt KnownOne2.
2077 break;
2078 }
2079 case Intrinsic::fshr:
2080 case Intrinsic::fshl: {
2081 const APInt *SA;
2082 if (!match(I->getOperand(2), m_APInt(SA)))
2083 break;
2084
2085 KnownBits Known3(BitWidth);
2086 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2087 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2088 Known = II->getIntrinsicID() == Intrinsic::fshl
2089 ? KnownBits::fshl(Known2, Known3, *SA)
2090 : KnownBits::fshr(Known2, Known3, *SA);
2091 break;
2092 }
2093 case Intrinsic::clmul:
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2095 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2096 Known = KnownBits::clmul(Known, Known2);
2097 break;
2098 case Intrinsic::pext:
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2100 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2101 Known = KnownBits::pext(Known, Known2);
2102 break;
2103 case Intrinsic::pdep:
2104 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2105 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2106 Known = KnownBits::pdep(Known, Known2);
2107 break;
2108 case Intrinsic::uadd_sat:
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2111 Known = KnownBits::uadd_sat(Known, Known2);
2112 break;
2113 case Intrinsic::usub_sat:
2114 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2115 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2116 Known = KnownBits::usub_sat(Known, Known2);
2117 break;
2118 case Intrinsic::sadd_sat:
2119 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2120 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2121 Known = KnownBits::sadd_sat(Known, Known2);
2122 break;
2123 case Intrinsic::ssub_sat:
2124 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2125 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2126 Known = KnownBits::ssub_sat(Known, Known2);
2127 break;
2128 // Vec reverse preserves bits from input vec.
2129 case Intrinsic::vector_reverse:
2130 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2131 Depth + 1);
2132 break;
2133 // for min/max/and/or reduce, any bit common to each element in the
2134 // input vec is set in the output.
2135 case Intrinsic::vector_reduce_and:
2136 case Intrinsic::vector_reduce_or:
2137 case Intrinsic::vector_reduce_umax:
2138 case Intrinsic::vector_reduce_umin:
2139 case Intrinsic::vector_reduce_smax:
2140 case Intrinsic::vector_reduce_smin:
2141 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2142 break;
2143 case Intrinsic::vector_reduce_xor: {
2144 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2145 // The zeros common to all vecs are zero in the output.
2146 // If the number of elements is odd, then the common ones remain. If the
2147 // number of elements is even, then the common ones becomes zeros.
2148 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2149 // Even, so the ones become zeros.
2150 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2151 if (EvenCnt)
2152 Known.Zero |= Known.One;
2153 // Maybe even element count so need to clear ones.
2154 if (VecTy->isScalableTy() || EvenCnt)
2155 Known.One.clearAllBits();
2156 break;
2157 }
2158 case Intrinsic::vector_reduce_add: {
2159 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2160 if (!VecTy)
2161 break;
2162 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2163 Known = Known.reduceAdd(VecTy->getNumElements());
2164 break;
2165 }
2166 case Intrinsic::umin:
2167 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2168 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2169 Known = KnownBits::umin(Known, Known2);
2170 break;
2171 case Intrinsic::umax:
2172 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2173 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2174 Known = KnownBits::umax(Known, Known2);
2175 break;
2176 case Intrinsic::smin:
2177 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2178 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2179 Known = KnownBits::smin(Known, Known2);
2181 break;
2182 case Intrinsic::smax:
2183 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2184 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2185 Known = KnownBits::smax(Known, Known2);
2187 break;
2188 case Intrinsic::ptrmask: {
2189 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2190
2191 const Value *Mask = I->getOperand(1);
2192 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2193 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2194 // TODO: 1-extend would be more precise.
2195 Known &= Known2.anyextOrTrunc(BitWidth);
2196 break;
2197 }
2198 case Intrinsic::x86_sse2_pmulh_w:
2199 case Intrinsic::x86_avx2_pmulh_w:
2200 case Intrinsic::x86_avx512_pmulh_w_512:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::mulhs(Known, Known2);
2204 break;
2205 case Intrinsic::x86_sse2_pmulhu_w:
2206 case Intrinsic::x86_avx2_pmulhu_w:
2207 case Intrinsic::x86_avx512_pmulhu_w_512:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::mulhu(Known, Known2);
2211 break;
2212 case Intrinsic::x86_sse42_crc32_64_64:
2213 Known.Zero.setBitsFrom(32);
2214 break;
2215 case Intrinsic::x86_ssse3_phadd_d_128:
2216 case Intrinsic::x86_ssse3_phadd_w_128:
2217 case Intrinsic::x86_avx2_phadd_d:
2218 case Intrinsic::x86_avx2_phadd_w: {
2220 I, DemandedElts, Q, Depth,
2221 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2222 return KnownBits::add(KnownLHS, KnownRHS);
2223 });
2224 break;
2225 }
2226 case Intrinsic::x86_ssse3_phadd_sw_128:
2227 case Intrinsic::x86_avx2_phadd_sw: {
2229 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2230 break;
2231 }
2232 case Intrinsic::x86_ssse3_phsub_d_128:
2233 case Intrinsic::x86_ssse3_phsub_w_128:
2234 case Intrinsic::x86_avx2_phsub_d:
2235 case Intrinsic::x86_avx2_phsub_w: {
2237 I, DemandedElts, Q, Depth,
2238 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2239 return KnownBits::sub(KnownLHS, KnownRHS);
2240 });
2241 break;
2242 }
2243 case Intrinsic::x86_ssse3_phsub_sw_128:
2244 case Intrinsic::x86_avx2_phsub_sw: {
2246 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2247 break;
2248 }
2249 case Intrinsic::riscv_vsetvli:
2250 case Intrinsic::riscv_vsetvlimax: {
2251 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2252 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2254 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2255 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2256 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2257 uint64_t MaxVLEN =
2258 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2259 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2260
2261 // Result of vsetvli must be not larger than AVL.
2262 if (HasAVL)
2263 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2264 MaxVL = std::min(MaxVL, CI->getZExtValue());
2265
2266 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2267 if (BitWidth > KnownZeroFirstBit)
2268 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2269 break;
2270 }
2271 case Intrinsic::amdgcn_mbcnt_hi:
2272 case Intrinsic::amdgcn_mbcnt_lo: {
2273 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2274 // most 31 + src1.
2275 Known.Zero.setBitsFrom(
2276 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2277 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2278 Known = KnownBits::add(Known, Known2);
2279 break;
2280 }
2281 case Intrinsic::vscale: {
2282 if (!II->getParent() || !II->getFunction())
2283 break;
2284
2285 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2286 break;
2287 }
2288 case Intrinsic::stepvector: {
2289 auto *VecTy = cast<VectorType>(II->getType());
2290 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2291 if (!isUIntN(BitWidth, MinNumElts))
2292 break;
2293
2294 bool Overflow = false;
2295 APInt MaxNumElts(BitWidth, MinNumElts);
2296 if (VecTy->isScalableTy()) {
2297 if (!II->getParent() || !II->getFunction())
2298 break;
2299 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2301 .umul_ov(MaxNumElts, Overflow);
2302 }
2303
2304 // Give up if the lane count could wrap. Stepvector truncates lane
2305 // indices that do not fit in the element type.
2306 if (Overflow)
2307 break;
2308
2309 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2310 break;
2311 }
2312 }
2313 }
2314 break;
2315 }
2316 case Instruction::ShuffleVector: {
2317 if (auto *Splat = getSplatValue(I)) {
2319 break;
2320 }
2321
2322 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2323 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2324 if (!Shuf) {
2325 Known.resetAll();
2326 return;
2327 }
2328 // For undef elements, we don't know anything about the common state of
2329 // the shuffle result.
2330 APInt DemandedLHS, DemandedRHS;
2331 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2332 Known.resetAll();
2333 return;
2334 }
2335 Known.setAllConflict();
2336 if (!!DemandedLHS) {
2337 const Value *LHS = Shuf->getOperand(0);
2338 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2339 // If we don't know any bits, early out.
2340 if (Known.isUnknown())
2341 break;
2342 }
2343 if (!!DemandedRHS) {
2344 const Value *RHS = Shuf->getOperand(1);
2345 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2346 Known = Known.intersectWith(Known2);
2347 }
2348 break;
2349 }
2350 case Instruction::InsertElement: {
2351 if (isa<ScalableVectorType>(I->getType())) {
2352 Known.resetAll();
2353 return;
2354 }
2355 const Value *Vec = I->getOperand(0);
2356 const Value *Elt = I->getOperand(1);
2357 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2358 unsigned NumElts = DemandedElts.getBitWidth();
2359 APInt DemandedVecElts = DemandedElts;
2360 bool NeedsElt = true;
2361 // If we know the index we are inserting too, clear it from Vec check.
2362 if (CIdx && CIdx->getValue().ult(NumElts)) {
2363 DemandedVecElts.clearBit(CIdx->getZExtValue());
2364 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2365 }
2366
2367 Known.setAllConflict();
2368 if (NeedsElt) {
2369 computeKnownBits(Elt, Known, Q, Depth + 1);
2370 // If we don't know any bits, early out.
2371 if (Known.isUnknown())
2372 break;
2373 }
2374
2375 if (!DemandedVecElts.isZero()) {
2376 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2377 Known = Known.intersectWith(Known2);
2378 }
2379 break;
2380 }
2381 case Instruction::ExtractElement: {
2382 // Look through extract element. If the index is non-constant or
2383 // out-of-range demand all elements, otherwise just the extracted element.
2384 const Value *Vec = I->getOperand(0);
2385 const Value *Idx = I->getOperand(1);
2386 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2387 if (isa<ScalableVectorType>(Vec->getType())) {
2388 // FIXME: there's probably *something* we can do with scalable vectors
2389 Known.resetAll();
2390 break;
2391 }
2392 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2393 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2394 if (CIdx && CIdx->getValue().ult(NumElts))
2395 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2396 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2397 break;
2398 }
2399 case Instruction::ExtractValue:
2400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2402 if (EVI->getNumIndices() != 1) break;
2403 if (EVI->getIndices()[0] == 0) {
2404 switch (II->getIntrinsicID()) {
2405 default: break;
2406 case Intrinsic::uadd_with_overflow:
2407 case Intrinsic::sadd_with_overflow:
2409 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2410 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2411 break;
2412 case Intrinsic::usub_with_overflow:
2413 case Intrinsic::ssub_with_overflow:
2415 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2416 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2417 break;
2418 case Intrinsic::umul_with_overflow:
2419 case Intrinsic::smul_with_overflow:
2420 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2421 false, DemandedElts, Known, Known2, Q, Depth);
2422 break;
2423 }
2424 }
2425 }
2426 break;
2427 case Instruction::Freeze:
2428 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2429 Depth + 1))
2430 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2431 break;
2432 }
2433}
2434
2435/// Determine which bits of V are known to be either zero or one and return
2436/// them.
2437KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2438 const SimplifyQuery &Q, unsigned Depth) {
2439 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2440 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2441 return Known;
2442}
2443
2444/// Determine which bits of V are known to be either zero or one and return
2445/// them.
2447 unsigned Depth) {
2448 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2450 return Known;
2451}
2452
2453/// Determine which bits of V are known to be either zero or one and return
2454/// them in the Known bit set.
2455///
2456/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2457/// we cannot optimize based on the assumption that it is zero without changing
2458/// it to be an explicit zero. If we don't change it to zero, other code could
2459/// optimized based on the contradictory assumption that it is non-zero.
2460/// Because instcombine aggressively folds operations with undef args anyway,
2461/// this won't lose us code quality.
2462///
2463/// This function is defined on values with integer type, values with pointer
2464/// type, and vectors of integers. In the case
2465/// where V is a vector, known zero, and known one values are the
2466/// same width as the vector element, and the bit is set only if it is true
2467/// for all of the demanded elements in the vector specified by DemandedElts.
2468void computeKnownBits(const Value *V, const APInt &DemandedElts,
2469 KnownBits &Known, const SimplifyQuery &Q,
2470 unsigned Depth) {
2471 if (!DemandedElts) {
2472 // No demanded elts, better to assume we don't know anything.
2473 Known.resetAll();
2474 return;
2475 }
2476
2477 assert(V && "No Value?");
2478 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2479
2480#ifndef NDEBUG
2481 Type *Ty = V->getType();
2482 unsigned BitWidth = Known.getBitWidth();
2483
2484 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2485 "Not integer or pointer type!");
2486
2487 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2488 assert(
2489 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2490 "DemandedElt width should equal the fixed vector number of elements");
2491 } else {
2492 assert(DemandedElts == APInt(1, 1) &&
2493 "DemandedElt width should be 1 for scalars or scalable vectors");
2494 }
2495
2496 Type *ScalarTy = Ty->getScalarType();
2497 if (ScalarTy->isPointerTy()) {
2498 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2499 "V and Known should have same BitWidth");
2500 } else {
2501 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2502 "V and Known should have same BitWidth");
2503 }
2504#endif
2505
2506 const APInt *C;
2507 if (match(V, m_APInt(C))) {
2508 // We know all of the bits for a scalar constant or a splat vector constant!
2510 return;
2511 }
2512 // Null and aggregate-zero are all-zeros.
2514 Known.setAllZero();
2515 return;
2516 }
2517 // Handle a constant vector by taking the intersection of the known bits of
2518 // each element.
2520 assert(!isa<ScalableVectorType>(V->getType()));
2521 // We know that CDV must be a vector of integers. Take the intersection of
2522 // each element.
2523 Known.setAllConflict();
2524 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2525 if (!DemandedElts[i])
2526 continue;
2527 APInt Elt = CDV->getElementAsAPInt(i);
2528 Known.Zero &= ~Elt;
2529 Known.One &= Elt;
2530 }
2531 if (Known.hasConflict())
2532 Known.resetAll();
2533 return;
2534 }
2535
2536 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2537 assert(!isa<ScalableVectorType>(V->getType()));
2538 // We know that CV must be a vector of integers. Take the intersection of
2539 // each element.
2540 Known.setAllConflict();
2541 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2542 if (!DemandedElts[i])
2543 continue;
2544 Constant *Element = CV->getAggregateElement(i);
2545 if (isa<PoisonValue>(Element))
2546 continue;
2547 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2548 if (!ElementCI) {
2549 Known.resetAll();
2550 return;
2551 }
2552 const APInt &Elt = ElementCI->getValue();
2553 Known.Zero &= ~Elt;
2554 Known.One &= Elt;
2555 }
2556 if (Known.hasConflict())
2557 Known.resetAll();
2558 return;
2559 }
2560
2561 // Start out not knowing anything.
2562 Known.resetAll();
2563
2564 // We can't imply anything about undefs.
2565 if (isa<UndefValue>(V))
2566 return;
2567
2568 // There's no point in looking through other users of ConstantData for
2569 // assumptions. Confirm that we've handled them all.
2570 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2571
2572 if (const auto *A = dyn_cast<Argument>(V))
2573 if (std::optional<ConstantRange> Range = A->getRange())
2574 Known = Range->toKnownBits();
2575
2576 // All recursive calls that increase depth must come after this.
2578 return;
2579
2580 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2581 // the bits of its aliasee.
2582 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2583 if (!GA->isInterposable())
2584 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2585 return;
2586 }
2587
2588 if (const Operator *I = dyn_cast<Operator>(V))
2589 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2590 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2591 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2592 Known = CR->toKnownBits();
2593 }
2594
2595 // Aligned pointers have trailing zeros - refine Known.Zero set
2596 if (isa<PointerType>(V->getType())) {
2597 Align Alignment = V->getPointerAlignment(Q.DL);
2598 Known.Zero.setLowBits(Log2(Alignment));
2599 }
2600
2601 // computeKnownBitsFromContext strictly refines Known.
2602 // Therefore, we run them after computeKnownBitsFromOperator.
2603
2604 // Check whether we can determine known bits from context such as assumes.
2606}
2607
2608/// Try to detect a recurrence that the value of the induction variable is
2609/// always a power of two (or zero).
2610static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2611 SimplifyQuery &Q, unsigned Depth) {
2612 BinaryOperator *BO = nullptr;
2613 Value *Start = nullptr, *Step = nullptr;
2614 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2615 return false;
2616
2617 // Initial value must be a power of two.
2618 for (const Use &U : PN->operands()) {
2619 if (U.get() == Start) {
2620 // Initial value comes from a different BB, need to adjust context
2621 // instruction for analysis.
2622 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2623 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2624 return false;
2625 }
2626 }
2627
2628 // Except for Mul, the induction variable must be on the left side of the
2629 // increment expression, otherwise its value can be arbitrary.
2630 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2631 return false;
2632
2633 Q.CxtI = BO->getParent()->getTerminator();
2634 switch (BO->getOpcode()) {
2635 case Instruction::Mul:
2636 // Power of two is closed under multiplication.
2637 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2638 Q.IIQ.hasNoSignedWrap(BO)) &&
2639 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2640 case Instruction::SDiv:
2641 // Start value must not be signmask for signed division, so simply being a
2642 // power of two is not sufficient, and it has to be a constant.
2643 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2644 return false;
2645 [[fallthrough]];
2646 case Instruction::UDiv:
2647 // Divisor must be a power of two.
2648 // If OrZero is false, cannot guarantee induction variable is non-zero after
2649 // division, same for Shr, unless it is exact division.
2650 return (OrZero || Q.IIQ.isExact(BO)) &&
2651 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2652 case Instruction::Shl:
2653 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2654 case Instruction::AShr:
2655 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2656 return false;
2657 [[fallthrough]];
2658 case Instruction::LShr:
2659 return OrZero || Q.IIQ.isExact(BO);
2660 default:
2661 return false;
2662 }
2663}
2664
2665/// Return true if we can infer that \p V is known to be a power of 2 from
2666/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2667static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2668 const Value *Cond,
2669 bool CondIsTrue) {
2670 CmpPredicate Pred;
2671 const APInt *RHSC;
2672 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2673 return false;
2674 if (!CondIsTrue)
2675 Pred = ICmpInst::getInversePredicate(Pred);
2676 // ctpop(V) u< 2
2677 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2678 return true;
2679 // ctpop(V) == 1
2680 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2681}
2682
2683/// Return true if the given value is known to have exactly one
2684/// bit set when defined. For vectors return true if every element is known to
2685/// be a power of two when defined. Supports values with integer or pointer
2686/// types and vectors of integers.
2687bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2688 const SimplifyQuery &Q, unsigned Depth) {
2689 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2690
2691 if (isa<Constant>(V))
2692 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2693
2694 // i1 is by definition a power of 2 or zero.
2695 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2696 return true;
2697
2698 // Try to infer from assumptions.
2699 if (Q.AC && Q.CxtI) {
2700 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2701 if (!AssumeVH)
2702 continue;
2703 CallInst *I = cast<CallInst>(AssumeVH);
2704 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2705 /*CondIsTrue=*/true) &&
2707 return true;
2708 }
2709 }
2710
2711 // Handle dominating conditions.
2712 if (Q.DC && Q.CxtI && Q.DT) {
2713 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2714 Value *Cond = BI->getCondition();
2715
2716 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2718 /*CondIsTrue=*/true) &&
2719 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2720 return true;
2721
2722 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2724 /*CondIsTrue=*/false) &&
2725 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2726 return true;
2727 }
2728 }
2729
2730 auto *I = dyn_cast<Instruction>(V);
2731 if (!I)
2732 return false;
2733
2734 if (Q.CxtI && match(V, m_VScale())) {
2735 const Function *F = Q.CxtI->getFunction();
2736 // The vscale_range indicates vscale is a power-of-two.
2737 return F->hasFnAttribute(Attribute::VScaleRange);
2738 }
2739
2740 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2741 // it is shifted off the end then the result is undefined.
2742 if (match(I, m_Shl(m_One(), m_Value())))
2743 return true;
2744
2745 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2746 // the bottom. If it is shifted off the bottom then the result is undefined.
2747 if (match(I, m_LShr(m_SignMask(), m_Value())))
2748 return true;
2749
2750 // The remaining tests are all recursive, so bail out if we hit the limit.
2752 return false;
2753
2754 switch (I->getOpcode()) {
2755 case Instruction::ZExt:
2756 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2757 case Instruction::Trunc:
2758 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2759 case Instruction::Shl:
2760 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2761 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2762 return false;
2763 case Instruction::LShr:
2764 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2765 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2766 return false;
2767 case Instruction::UDiv:
2769 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2770 return false;
2771 case Instruction::Mul:
2772 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2773 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2774 (OrZero || isKnownNonZero(I, Q, Depth));
2775 case Instruction::And:
2776 // A power of two and'd with anything is a power of two or zero.
2777 if (OrZero &&
2778 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2779 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2780 return true;
2781 // X & (-X) is always a power of two or zero.
2782 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2783 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2784 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2785 return false;
2786 case Instruction::Add: {
2787 // Adding a power-of-two or zero to the same power-of-two or zero yields
2788 // either the original power-of-two, a larger power-of-two or zero.
2790 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2791 Q.IIQ.hasNoSignedWrap(VOBO)) {
2792 if (match(I->getOperand(0),
2793 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2794 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2795 return true;
2796 if (match(I->getOperand(1),
2797 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2798 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2799 return true;
2800
2801 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2802 KnownBits LHSBits(BitWidth);
2803 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2804
2805 KnownBits RHSBits(BitWidth);
2806 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2807 // If i8 V is a power of two or zero:
2808 // ZeroBits: 1 1 1 0 1 1 1 1
2809 // ~ZeroBits: 0 0 0 1 0 0 0 0
2810 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2811 // If OrZero isn't set, we cannot give back a zero result.
2812 // Make sure either the LHS or RHS has a bit set.
2813 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2814 return true;
2815 }
2816
2817 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2818 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2819 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2820 return true;
2821 return false;
2822 }
2823 case Instruction::Select:
2824 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2825 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2826 case Instruction::PHI: {
2827 // A PHI node is power of two if all incoming values are power of two, or if
2828 // it is an induction variable where in each step its value is a power of
2829 // two.
2830 auto *PN = cast<PHINode>(I);
2832
2833 // Check if it is an induction variable and always power of two.
2834 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2835 return true;
2836
2837 // Recursively check all incoming values. Limit recursion to 2 levels, so
2838 // that search complexity is limited to number of operands^2.
2839 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2840 return llvm::all_of(PN->operands(), [&](const Use &U) {
2841 // Value is power of 2 if it is coming from PHI node itself by induction.
2842 if (U.get() == PN)
2843 return true;
2844
2845 // Change the context instruction to the incoming block where it is
2846 // evaluated.
2847 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2848 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2849 });
2850 }
2851 case Instruction::Invoke:
2852 case Instruction::Call: {
2853 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2854 switch (II->getIntrinsicID()) {
2855 case Intrinsic::umax:
2856 case Intrinsic::smax:
2857 case Intrinsic::umin:
2858 case Intrinsic::smin:
2859 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2860 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2861 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2862 // thus dont change pow2/non-pow2 status.
2863 case Intrinsic::bitreverse:
2864 case Intrinsic::bswap:
2865 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2866 case Intrinsic::fshr:
2867 case Intrinsic::fshl:
2868 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2869 if (II->getArgOperand(0) == II->getArgOperand(1))
2870 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2871 break;
2872 case Intrinsic::riscv_vsetvlimax:
2873 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2874 // for any valid vtype, so it is a power of two regardless of OrZero.
2875 return true;
2876 default:
2877 break;
2878 }
2879 }
2880 return false;
2881 }
2882 default:
2883 return false;
2884 }
2885}
2886
2887/// Test whether a GEP's result is known to be non-null.
2888///
2889/// Uses properties inherent in a GEP to try to determine whether it is known
2890/// to be non-null.
2891///
2892/// Currently this routine does not support vector GEPs.
2893static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2894 unsigned Depth) {
2895 const Function *F = nullptr;
2896 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2897 F = I->getFunction();
2898
2899 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2900 // may be null iff the base pointer is null and the offset is zero.
2901 if (!GEP->hasNoUnsignedWrap() &&
2902 !(GEP->isInBounds() &&
2903 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2904 return false;
2905
2906 // FIXME: Support vector-GEPs.
2907 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2908
2909 // If the base pointer is non-null, we cannot walk to a null address with an
2910 // inbounds GEP in address space zero.
2911 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2912 return true;
2913
2914 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2915 // If so, then the GEP cannot produce a null pointer, as doing so would
2916 // inherently violate the inbounds contract within address space zero.
2918 GTI != GTE; ++GTI) {
2919 // Struct types are easy -- they must always be indexed by a constant.
2920 if (StructType *STy = GTI.getStructTypeOrNull()) {
2921 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2922 unsigned ElementIdx = OpC->getZExtValue();
2923 const StructLayout *SL = Q.DL.getStructLayout(STy);
2924 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2925 if (ElementOffset > 0)
2926 return true;
2927 continue;
2928 }
2929
2930 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2931 if (GTI.getSequentialElementStride(Q.DL).isZero())
2932 continue;
2933
2934 // Fast path the constant operand case both for efficiency and so we don't
2935 // increment Depth when just zipping down an all-constant GEP.
2936 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2937 if (!OpC->isZero())
2938 return true;
2939 continue;
2940 }
2941
2942 // We post-increment Depth here because while isKnownNonZero increments it
2943 // as well, when we pop back up that increment won't persist. We don't want
2944 // to recurse 10k times just because we have 10k GEP operands. We don't
2945 // bail completely out because we want to handle constant GEPs regardless
2946 // of depth.
2948 continue;
2949
2950 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2951 return true;
2952 }
2953
2954 return false;
2955}
2956
2958 const Instruction *CtxI,
2959 const DominatorTree *DT) {
2960 assert(!isa<Constant>(V) && "Called for constant?");
2961
2962 if (!CtxI || !DT)
2963 return false;
2964
2965 unsigned NumUsesExplored = 0;
2966 for (auto &U : V->uses()) {
2967 // Avoid massive lists
2968 if (NumUsesExplored >= DomConditionsMaxUses)
2969 break;
2970 NumUsesExplored++;
2971
2972 const Instruction *UI = cast<Instruction>(U.getUser());
2973 // If the value is used as an argument to a call or invoke, then argument
2974 // attributes may provide an answer about null-ness.
2975 if (V->getType()->isPointerTy()) {
2976 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2977 if (CB->isArgOperand(&U) &&
2978 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2979 /*AllowUndefOrPoison=*/false) &&
2980 DT->dominates(CB, CtxI))
2981 return true;
2982 }
2983 }
2984
2985 // If the value is used as a load/store, then the pointer must be non null.
2986 if (V == getLoadStorePointerOperand(UI)) {
2989 DT->dominates(UI, CtxI))
2990 return true;
2991 }
2992
2993 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2994 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2995 isValidAssumeForContext(UI, CtxI, DT))
2996 return true;
2997
2998 // Consider only compare instructions uniquely controlling a branch
2999 Value *RHS;
3000 CmpPredicate Pred;
3001 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3002 continue;
3003
3004 bool NonNullIfTrue;
3005 if (cmpExcludesZero(Pred, RHS))
3006 NonNullIfTrue = true;
3008 NonNullIfTrue = false;
3009 else
3010 continue;
3011
3014 for (const auto *CmpU : UI->users()) {
3015 assert(WorkList.empty() && "Should be!");
3016 if (Visited.insert(CmpU).second)
3017 WorkList.push_back(CmpU);
3018
3019 while (!WorkList.empty()) {
3020 auto *Curr = WorkList.pop_back_val();
3021
3022 // If a user is an AND, add all its users to the work list. We only
3023 // propagate "pred != null" condition through AND because it is only
3024 // correct to assume that all conditions of AND are met in true branch.
3025 // TODO: Support similar logic of OR and EQ predicate?
3026 if (NonNullIfTrue)
3027 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3028 for (const auto *CurrU : Curr->users())
3029 if (Visited.insert(CurrU).second)
3030 WorkList.push_back(CurrU);
3031 continue;
3032 }
3033
3034 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3035 BasicBlock *NonNullSuccessor =
3036 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3037 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3038 if (DT->dominates(Edge, CtxI->getParent()))
3039 return true;
3040 } else if (NonNullIfTrue && isGuard(Curr) &&
3041 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3042 return true;
3043 }
3044 }
3045 }
3046 }
3047
3048 return false;
3049}
3050
3051/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3052/// ensure that the value it's attached to is never Value? 'RangeType' is
3053/// is the type of the value described by the range.
3054static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3055 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3056 assert(NumRanges >= 1);
3057 for (unsigned i = 0; i < NumRanges; ++i) {
3059 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3061 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3062 ConstantRange Range(Lower->getValue(), Upper->getValue());
3063 if (Range.contains(Value))
3064 return false;
3065 }
3066 return true;
3067}
3068
3069/// Try to detect a recurrence that monotonically increases/decreases from a
3070/// non-zero starting value. These are common as induction variables.
3071static bool isNonZeroRecurrence(const PHINode *PN) {
3072 BinaryOperator *BO = nullptr;
3073 Value *Start = nullptr, *Step = nullptr;
3074 const APInt *StartC, *StepC;
3075 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3076 !match(Start, m_APInt(StartC)) || StartC->isZero())
3077 return false;
3078
3079 switch (BO->getOpcode()) {
3080 case Instruction::Add:
3081 // Starting from non-zero and stepping away from zero can never wrap back
3082 // to zero.
3083 return BO->hasNoUnsignedWrap() ||
3084 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3085 StartC->isNegative() == StepC->isNegative());
3086 case Instruction::Mul:
3087 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3088 match(Step, m_APInt(StepC)) && !StepC->isZero();
3089 case Instruction::Shl:
3090 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3091 case Instruction::AShr:
3092 case Instruction::LShr:
3093 return BO->isExact();
3094 default:
3095 return false;
3096 }
3097}
3098
3099static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3101 m_Specific(Op1), m_Zero()))) ||
3103 m_Specific(Op0), m_Zero())));
3104}
3105
3106static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3107 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3108 bool NUW, unsigned Depth) {
3109 // (X + (X != 0)) is non zero
3110 if (matchOpWithOpEqZero(X, Y))
3111 return true;
3112
3113 if (NUW)
3114 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3115 isKnownNonZero(X, DemandedElts, Q, Depth);
3116
3117 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3118 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3119
3120 // If X and Y are both non-negative (as signed values) then their sum is not
3121 // zero unless both X and Y are zero.
3122 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3123 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3124 isKnownNonZero(X, DemandedElts, Q, Depth))
3125 return true;
3126
3127 // If X and Y are both negative (as signed values) then their sum is not
3128 // zero unless both X and Y equal INT_MIN.
3129 if (XKnown.isNegative() && YKnown.isNegative()) {
3131 // The sign bit of X is set. If some other bit is set then X is not equal
3132 // to INT_MIN.
3133 if (XKnown.One.intersects(Mask))
3134 return true;
3135 // The sign bit of Y is set. If some other bit is set then Y is not equal
3136 // to INT_MIN.
3137 if (YKnown.One.intersects(Mask))
3138 return true;
3139 }
3140
3141 // The sum of a non-negative number and a power of two is not zero.
3142 if (XKnown.isNonNegative() &&
3143 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3144 return true;
3145 if (YKnown.isNonNegative() &&
3146 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3147 return true;
3148
3149 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3150}
3151
3152static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3153 unsigned BitWidth, Value *X, Value *Y,
3154 unsigned Depth) {
3155 // (X - (X != 0)) is non zero
3156 // ((X != 0) - X) is non zero
3157 if (matchOpWithOpEqZero(X, Y))
3158 return true;
3159
3160 // TODO: Move this case into isKnownNonEqual().
3161 if (auto *C = dyn_cast<Constant>(X))
3162 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3163 return true;
3164
3165 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3166}
3167
3168static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3169 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3170 bool NUW, unsigned Depth) {
3171 // If X and Y are non-zero then so is X * Y as long as the multiplication
3172 // does not overflow.
3173 if (NSW || NUW)
3174 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3175 isKnownNonZero(Y, DemandedElts, Q, Depth);
3176
3177 // If either X or Y is odd, then if the other is non-zero the result can't
3178 // be zero.
3179 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3180 if (XKnown.One[0])
3181 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3182
3183 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3184 if (YKnown.One[0])
3185 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3186
3187 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3188 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3189 // the lowest known One of X and Y. If they are non-zero, the result
3190 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3191 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3192 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3193 BitWidth;
3194}
3195
3196static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3197 const SimplifyQuery &Q, const KnownBits &KnownVal,
3198 unsigned Depth) {
3199 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3200 switch (I->getOpcode()) {
3201 case Instruction::Shl:
3202 return Lhs.shl(Rhs);
3203 case Instruction::LShr:
3204 return Lhs.lshr(Rhs);
3205 case Instruction::AShr:
3206 return Lhs.ashr(Rhs);
3207 default:
3208 llvm_unreachable("Unknown Shift Opcode");
3209 }
3210 };
3211
3212 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3213 switch (I->getOpcode()) {
3214 case Instruction::Shl:
3215 return Lhs.lshr(Rhs);
3216 case Instruction::LShr:
3217 case Instruction::AShr:
3218 return Lhs.shl(Rhs);
3219 default:
3220 llvm_unreachable("Unknown Shift Opcode");
3221 }
3222 };
3223
3224 if (KnownVal.isUnknown())
3225 return false;
3226
3227 KnownBits KnownCnt =
3228 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3229 APInt MaxShift = KnownCnt.getMaxValue();
3230 unsigned NumBits = KnownVal.getBitWidth();
3231 if (MaxShift.uge(NumBits))
3232 return false;
3233
3234 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3235 return true;
3236
3237 // If all of the bits shifted out are known to be zero, and Val is known
3238 // non-zero then at least one non-zero bit must remain.
3239 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3240 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3241 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3242 return true;
3243
3244 return false;
3245}
3246
3248 const APInt &DemandedElts,
3249 const SimplifyQuery &Q, unsigned Depth) {
3250 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3251 switch (I->getOpcode()) {
3252 case Instruction::Alloca:
3253 // Alloca never returns null, malloc might.
3254 return I->getType()->getPointerAddressSpace() == 0;
3255 case Instruction::GetElementPtr:
3256 if (I->getType()->isPointerTy())
3258 break;
3259 case Instruction::BitCast: {
3260 // We need to be a bit careful here. We can only peek through the bitcast
3261 // if the scalar size of elements in the operand are smaller than and a
3262 // multiple of the size they are casting too. Take three cases:
3263 //
3264 // 1) Unsafe:
3265 // bitcast <2 x i16> %NonZero to <4 x i8>
3266 //
3267 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3268 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3269 // guranteed (imagine just sign bit set in the 2 i16 elements).
3270 //
3271 // 2) Unsafe:
3272 // bitcast <4 x i3> %NonZero to <3 x i4>
3273 //
3274 // Even though the scalar size of the src (`i3`) is smaller than the
3275 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3276 // its possible for the `3 x i4` elements to be zero because there are
3277 // some elements in the destination that don't contain any full src
3278 // element.
3279 //
3280 // 3) Safe:
3281 // bitcast <4 x i8> %NonZero to <2 x i16>
3282 //
3283 // This is always safe as non-zero in the 4 i8 elements implies
3284 // non-zero in the combination of any two adjacent ones. Since i8 is a
3285 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3286 // This all implies the 2 i16 elements are non-zero.
3287 Type *FromTy = I->getOperand(0)->getType();
3288 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3289 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3290 return isKnownNonZero(I->getOperand(0), Q, Depth);
3291 } break;
3292 case Instruction::IntToPtr:
3293 // Note that we have to take special care to avoid looking through
3294 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3295 // as casts that can alter the value, e.g., AddrSpaceCasts.
3296 if (!isa<ScalableVectorType>(I->getType()) &&
3297 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3298 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3299 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3300 break;
3301 case Instruction::PtrToAddr:
3302 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3303 // so we can directly forward.
3304 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3305 case Instruction::PtrToInt:
3306 // For inttoptr, make sure the result size is >= the address size. If the
3307 // address is non-zero, any larger value is also non-zero.
3308 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3309 I->getType()->getScalarSizeInBits())
3310 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3311 break;
3312 case Instruction::Trunc:
3313 // nuw/nsw trunc preserves zero/non-zero status of input.
3314 if (auto *TI = dyn_cast<TruncInst>(I))
3315 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3316 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3317 break;
3318
3319 // Iff x - y != 0, then x ^ y != 0
3320 // Therefore we can do the same exact checks
3321 case Instruction::Xor:
3322 case Instruction::Sub:
3323 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3324 I->getOperand(1), Depth);
3325 case Instruction::Or:
3326 // (X | (X != 0)) is non zero
3327 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3328 return true;
3329 // X | Y != 0 if X != Y.
3330 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3331 Depth))
3332 return true;
3333 // X | Y != 0 if X != 0 or Y != 0.
3334 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3335 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3336 case Instruction::SExt:
3337 case Instruction::ZExt:
3338 // ext X != 0 if X != 0.
3339 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3340
3341 case Instruction::Shl: {
3342 // shl nsw/nuw can't remove any non-zero bits.
3344 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3345 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3346
3347 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3348 // if the lowest bit is shifted off the end.
3350 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3351 if (Known.One[0])
3352 return true;
3353
3354 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3355 }
3356 case Instruction::LShr:
3357 case Instruction::AShr: {
3358 // shr exact can only shift out zero bits.
3360 if (BO->isExact())
3361 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3362
3363 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3364 // defined if the sign bit is shifted off the end.
3366 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3367 if (Known.isNegative())
3368 return true;
3369
3370 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3371 // position >= C, because the sum >= max(A, B).
3372 Value *A, *B;
3373 const APInt *C;
3374 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3375 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3376 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3377 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3378 if (!KnownA.One.lshr(*C).isZero())
3379 return true;
3380 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3381 if (!KnownB.One.lshr(*C).isZero())
3382 return true;
3383 }
3384
3385 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3386 }
3387 case Instruction::UDiv:
3388 case Instruction::SDiv: {
3389 // X / Y
3390 // div exact can only produce a zero if the dividend is zero.
3391 if (cast<PossiblyExactOperator>(I)->isExact())
3392 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3393
3394 KnownBits XKnown =
3395 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3396 // If X is fully unknown we won't be able to figure anything out so don't
3397 // both computing knownbits for Y.
3398 if (XKnown.isUnknown())
3399 return false;
3400
3401 KnownBits YKnown =
3402 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3403 if (I->getOpcode() == Instruction::SDiv) {
3404 // For signed division need to compare abs value of the operands.
3405 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3406 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3407 }
3408 // If X u>= Y then div is non zero (0/0 is UB).
3409 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3410 // If X is total unknown or X u< Y we won't be able to prove non-zero
3411 // with compute known bits so just return early.
3412 return XUgeY && *XUgeY;
3413 }
3414 case Instruction::Add: {
3415 // X + Y.
3416
3417 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3418 // non-zero.
3420 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3421 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3422 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3423 }
3424 case Instruction::Mul: {
3426 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3427 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3428 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3429 }
3430 case Instruction::Select: {
3431 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3432
3433 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3434 // then see if the select condition implies the arm is non-zero. For example
3435 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3436 // dominated by `X != 0`.
3437 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3438 Value *Op;
3439 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3440 // Op is trivially non-zero.
3441 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3442 return true;
3443
3444 // The condition of the select dominates the true/false arm. Check if the
3445 // condition implies that a given arm is non-zero.
3446 Value *X;
3447 CmpPredicate Pred;
3448 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3449 return false;
3450
3451 if (!IsTrueArm)
3452 Pred = ICmpInst::getInversePredicate(Pred);
3453
3454 return cmpExcludesZero(Pred, X);
3455 };
3456
3457 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3458 SelectArmIsNonZero(/* IsTrueArm */ false))
3459 return true;
3460 break;
3461 }
3462 case Instruction::PHI: {
3463 auto *PN = cast<PHINode>(I);
3465 return true;
3466
3467 // Check if all incoming values are non-zero using recursion.
3469 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3470 return llvm::all_of(PN->operands(), [&](const Use &U) {
3471 if (U.get() == PN)
3472 return true;
3473 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3474 // Check if the branch on the phi excludes zero.
3475 CmpPredicate Pred;
3476 Value *X;
3477 BasicBlock *TrueSucc, *FalseSucc;
3478 if (match(RecQ.CxtI,
3479 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3480 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3481 // Check for cases of duplicate successors.
3482 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3483 // If we're using the false successor, invert the predicate.
3484 if (FalseSucc == PN->getParent())
3485 Pred = CmpInst::getInversePredicate(Pred);
3486 if (cmpExcludesZero(Pred, X))
3487 return true;
3488 }
3489 }
3490 // Finally recurse on the edge and check it directly.
3491 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3492 });
3493 }
3494 case Instruction::InsertElement: {
3495 if (isa<ScalableVectorType>(I->getType()))
3496 break;
3497
3498 const Value *Vec = I->getOperand(0);
3499 const Value *Elt = I->getOperand(1);
3500 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3501
3502 unsigned NumElts = DemandedElts.getBitWidth();
3503 APInt DemandedVecElts = DemandedElts;
3504 bool SkipElt = false;
3505 // If we know the index we are inserting too, clear it from Vec check.
3506 if (CIdx && CIdx->getValue().ult(NumElts)) {
3507 DemandedVecElts.clearBit(CIdx->getZExtValue());
3508 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3509 }
3510
3511 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3512 // are non-zero.
3513 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3514 (DemandedVecElts.isZero() ||
3515 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3516 }
3517 case Instruction::ExtractElement:
3518 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3519 const Value *Vec = EEI->getVectorOperand();
3520 const Value *Idx = EEI->getIndexOperand();
3521 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3522 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3523 unsigned NumElts = VecTy->getNumElements();
3524 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3525 if (CIdx && CIdx->getValue().ult(NumElts))
3526 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3527 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3528 }
3529 }
3530 break;
3531 case Instruction::ShuffleVector: {
3532 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3533 if (!Shuf)
3534 break;
3535 APInt DemandedLHS, DemandedRHS;
3536 // For undef elements, we don't know anything about the common state of
3537 // the shuffle result.
3538 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3539 break;
3540 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3541 return (DemandedRHS.isZero() ||
3542 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3543 (DemandedLHS.isZero() ||
3544 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3545 }
3546 case Instruction::Freeze:
3547 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3548 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3549 Depth);
3550 case Instruction::Load: {
3551 auto *LI = cast<LoadInst>(I);
3552 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3553 // is never null.
3554 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3555 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3556 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3557 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3558 return true;
3559 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3561 }
3562
3563 // No need to fall through to computeKnownBits as range metadata is already
3564 // handled in isKnownNonZero.
3565 return false;
3566 }
3567 case Instruction::ExtractValue: {
3568 const WithOverflowInst *WO;
3570 switch (WO->getBinaryOp()) {
3571 default:
3572 break;
3573 case Instruction::Add:
3574 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3575 WO->getArgOperand(1),
3576 /*NSW=*/false,
3577 /*NUW=*/false, Depth);
3578 case Instruction::Sub:
3579 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3580 WO->getArgOperand(1), Depth);
3581 case Instruction::Mul:
3582 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3583 WO->getArgOperand(1),
3584 /*NSW=*/false, /*NUW=*/false, Depth);
3585 break;
3586 }
3587 }
3588 break;
3589 }
3590 case Instruction::Call:
3591 case Instruction::Invoke: {
3592 const auto *Call = cast<CallBase>(I);
3593 if (I->getType()->isPointerTy()) {
3594 if (Call->isReturnNonNull())
3595 return true;
3596 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3597 Call, /*MustPreserveOffset=*/true))
3598 return isKnownNonZero(RP, Q, Depth);
3599 } else {
3600 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3602 if (std::optional<ConstantRange> Range = Call->getRange()) {
3603 const APInt ZeroValue(Range->getBitWidth(), 0);
3604 if (!Range->contains(ZeroValue))
3605 return true;
3606 }
3607 if (const Value *RV = Call->getReturnedArgOperand())
3608 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3609 return true;
3610 }
3611
3612 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3613 switch (II->getIntrinsicID()) {
3614 case Intrinsic::sshl_sat:
3615 case Intrinsic::ushl_sat:
3616 case Intrinsic::abs:
3617 case Intrinsic::bitreverse:
3618 case Intrinsic::bswap:
3619 case Intrinsic::ctpop:
3620 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3621 // NB: We don't do usub_sat here as in any case we can prove its
3622 // non-zero, we will fold it to `sub nuw` in InstCombine.
3623 case Intrinsic::ssub_sat:
3624 // For most types, if x != y then ssub.sat x, y != 0. But
3625 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3626 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3627 if (BitWidth == 1)
3628 return false;
3629 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3630 II->getArgOperand(1), Depth);
3631 case Intrinsic::sadd_sat:
3632 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3633 II->getArgOperand(1),
3634 /*NSW=*/true, /* NUW=*/false, Depth);
3635 // Vec reverse preserves zero/non-zero status from input vec.
3636 case Intrinsic::vector_reverse:
3637 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3638 Q, Depth);
3639 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3640 case Intrinsic::vector_reduce_or:
3641 case Intrinsic::vector_reduce_umax:
3642 case Intrinsic::vector_reduce_umin:
3643 case Intrinsic::vector_reduce_smax:
3644 case Intrinsic::vector_reduce_smin:
3645 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3646 case Intrinsic::umax:
3647 case Intrinsic::uadd_sat:
3648 // umax(X, (X != 0)) is non zero
3649 // X +usat (X != 0) is non zero
3650 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3651 return true;
3652
3653 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3654 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3655 case Intrinsic::smax: {
3656 // If either arg is strictly positive the result is non-zero. Otherwise
3657 // the result is non-zero if both ops are non-zero.
3658 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3659 const KnownBits &OpKnown) {
3660 if (!OpNonZero.has_value())
3661 OpNonZero = OpKnown.isNonZero() ||
3662 isKnownNonZero(Op, DemandedElts, Q, Depth);
3663 return *OpNonZero;
3664 };
3665 // Avoid re-computing isKnownNonZero.
3666 std::optional<bool> Op0NonZero, Op1NonZero;
3667 KnownBits Op1Known =
3668 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3669 if (Op1Known.isNonNegative() &&
3670 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3671 return true;
3672 KnownBits Op0Known =
3673 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3674 if (Op0Known.isNonNegative() &&
3675 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3676 return true;
3677 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3678 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3679 }
3680 case Intrinsic::smin: {
3681 // If either arg is negative the result is non-zero. Otherwise
3682 // the result is non-zero if both ops are non-zero.
3683 KnownBits Op1Known =
3684 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3685 if (Op1Known.isNegative())
3686 return true;
3687 KnownBits Op0Known =
3688 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3689 if (Op0Known.isNegative())
3690 return true;
3691
3692 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3693 return true;
3694 }
3695 [[fallthrough]];
3696 case Intrinsic::umin:
3697 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3698 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3699 case Intrinsic::cttz:
3700 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3701 .Zero[0];
3702 case Intrinsic::ctlz:
3703 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3704 .isNonNegative();
3705 case Intrinsic::fshr:
3706 case Intrinsic::fshl:
3707 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3708 if (II->getArgOperand(0) == II->getArgOperand(1))
3709 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3710 break;
3711 case Intrinsic::vscale:
3712 return true;
3713 case Intrinsic::experimental_get_vector_length:
3714 return isKnownNonZero(I->getOperand(0), Q, Depth);
3715 default:
3716 break;
3717 }
3718 break;
3719 }
3720
3721 return false;
3722 }
3723 }
3724
3726 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3727 return Known.One != 0;
3728}
3729
3730/// Return true if the given value is known to be non-zero when defined. For
3731/// vectors, return true if every demanded element is known to be non-zero when
3732/// defined. For pointers, if the context instruction and dominator tree are
3733/// specified, perform context-sensitive analysis and return true if the
3734/// pointer couldn't possibly be null at the specified instruction.
3735/// Supports values with integer or pointer type and vectors of integers.
3736bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3737 const SimplifyQuery &Q, unsigned Depth) {
3738 Type *Ty = V->getType();
3739
3740#ifndef NDEBUG
3741 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3742
3743 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3744 assert(
3745 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3746 "DemandedElt width should equal the fixed vector number of elements");
3747 } else {
3748 assert(DemandedElts == APInt(1, 1) &&
3749 "DemandedElt width should be 1 for scalars");
3750 }
3751#endif
3752
3753 if (auto *C = dyn_cast<Constant>(V)) {
3754 if (C->isNullValue())
3755 return false;
3756 if (isa<ConstantInt>(C))
3757 // Must be non-zero due to null test above.
3758 return true;
3759
3760 // For constant vectors, check that all elements are poison or known
3761 // non-zero to determine that the whole vector is known non-zero.
3762 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3763 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3764 if (!DemandedElts[i])
3765 continue;
3766 Constant *Elt = C->getAggregateElement(i);
3767 if (!Elt || Elt->isNullValue())
3768 return false;
3769 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3770 return false;
3771 }
3772 return true;
3773 }
3774
3775 // Constant ptrauth can be null, iff the base pointer can be.
3776 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3777 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3778
3779 // A global variable in address space 0 is non null unless extern weak
3780 // or an absolute symbol reference. Other address spaces may have null as a
3781 // valid address for a global, so we can't assume anything.
3782 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3783 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3784 GV->getType()->getAddressSpace() == 0)
3785 return true;
3786 }
3787
3788 // For constant expressions, fall through to the Operator code below.
3789 if (!isa<ConstantExpr>(V))
3790 return false;
3791 }
3792
3793 if (const auto *A = dyn_cast<Argument>(V))
3794 if (std::optional<ConstantRange> Range = A->getRange()) {
3795 const APInt ZeroValue(Range->getBitWidth(), 0);
3796 if (!Range->contains(ZeroValue))
3797 return true;
3798 }
3799
3800 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3801 return true;
3802
3803 // Some of the tests below are recursive, so bail out if we hit the limit.
3805 return false;
3806
3807 // Check for pointer simplifications.
3808
3809 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3810 // A byval, inalloca may not be null in a non-default addres space. A
3811 // nonnull argument is assumed never 0.
3812 if (const Argument *A = dyn_cast<Argument>(V)) {
3813 if (((A->hasPassPointeeByValueCopyAttr() &&
3814 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3815 A->hasNonNullAttr()))
3816 return true;
3817 }
3818 }
3819
3820 if (const auto *I = dyn_cast<Operator>(V))
3821 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3822 return true;
3823
3824 if (!isa<Constant>(V) &&
3826 return true;
3827
3828 if (const Value *Stripped = stripNullTest(V))
3829 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3830
3831 return false;
3832}
3833
3835 unsigned Depth) {
3836 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3837 APInt DemandedElts =
3838 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3839 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3840}
3841
3842/// If the pair of operators are the same invertible function, return the
3843/// the operands of the function corresponding to each input. Otherwise,
3844/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3845/// every input value to exactly one output value. This is equivalent to
3846/// saying that Op1 and Op2 are equal exactly when the specified pair of
3847/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3848static std::optional<std::pair<Value*, Value*>>
3850 const Operator *Op2) {
3851 if (Op1->getOpcode() != Op2->getOpcode())
3852 return std::nullopt;
3853
3854 auto getOperands = [&](unsigned OpNum) -> auto {
3855 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3856 };
3857
3858 switch (Op1->getOpcode()) {
3859 default:
3860 break;
3861 case Instruction::Or:
3862 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3863 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3864 break;
3865 [[fallthrough]];
3866 case Instruction::Xor:
3867 case Instruction::Add: {
3868 Value *Other;
3869 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3870 return std::make_pair(Op1->getOperand(1), Other);
3871 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3872 return std::make_pair(Op1->getOperand(0), Other);
3873 break;
3874 }
3875 case Instruction::Sub:
3876 if (Op1->getOperand(0) == Op2->getOperand(0))
3877 return getOperands(1);
3878 if (Op1->getOperand(1) == Op2->getOperand(1))
3879 return getOperands(0);
3880 break;
3881 case Instruction::Mul: {
3882 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3883 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3884 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3885 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3886 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3887 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3888 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3889 break;
3890
3891 // Assume operand order has been canonicalized
3892 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3893 isa<ConstantInt>(Op1->getOperand(1)) &&
3894 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3895 return getOperands(0);
3896 break;
3897 }
3898 case Instruction::Shl: {
3899 // Same as multiplies, with the difference that we don't need to check
3900 // for a non-zero multiply. Shifts always multiply by non-zero.
3901 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3902 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3903 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3904 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3905 break;
3906
3907 if (Op1->getOperand(1) == Op2->getOperand(1))
3908 return getOperands(0);
3909 break;
3910 }
3911 case Instruction::AShr:
3912 case Instruction::LShr: {
3913 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3914 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3915 if (!PEO1->isExact() || !PEO2->isExact())
3916 break;
3917
3918 if (Op1->getOperand(1) == Op2->getOperand(1))
3919 return getOperands(0);
3920 break;
3921 }
3922 case Instruction::SExt:
3923 case Instruction::ZExt:
3924 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3925 return getOperands(0);
3926 break;
3927 case Instruction::PHI: {
3928 const PHINode *PN1 = cast<PHINode>(Op1);
3929 const PHINode *PN2 = cast<PHINode>(Op2);
3930
3931 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3932 // are a single invertible function of the start values? Note that repeated
3933 // application of an invertible function is also invertible
3934 BinaryOperator *BO1 = nullptr;
3935 Value *Start1 = nullptr, *Step1 = nullptr;
3936 BinaryOperator *BO2 = nullptr;
3937 Value *Start2 = nullptr, *Step2 = nullptr;
3938 if (PN1->getParent() != PN2->getParent() ||
3939 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3940 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3941 break;
3942
3944 cast<Operator>(BO2));
3945 if (!Values)
3946 break;
3947
3948 // We have to be careful of mutually defined recurrences here. Ex:
3949 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3950 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3951 // The invertibility of these is complicated, and not worth reasoning
3952 // about (yet?).
3953 if (Values->first != PN1 || Values->second != PN2)
3954 break;
3955
3956 return std::make_pair(Start1, Start2);
3957 }
3958 }
3959 return std::nullopt;
3960}
3961
3962/// Return true if V1 == (binop V2, X), where X is known non-zero.
3963/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3964/// implies V2 != V1.
3965static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3966 const APInt &DemandedElts,
3967 const SimplifyQuery &Q, unsigned Depth) {
3969 if (!BO)
3970 return false;
3971 switch (BO->getOpcode()) {
3972 default:
3973 break;
3974 case Instruction::Or:
3975 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3976 break;
3977 [[fallthrough]];
3978 case Instruction::Xor:
3979 case Instruction::Add:
3980 Value *Op = nullptr;
3981 if (V2 == BO->getOperand(0))
3982 Op = BO->getOperand(1);
3983 else if (V2 == BO->getOperand(1))
3984 Op = BO->getOperand(0);
3985 else
3986 return false;
3987 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3988 }
3989 return false;
3990}
3991
3992/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3993/// the multiplication is nuw or nsw.
3994static bool isNonEqualMul(const Value *V1, const Value *V2,
3995 const APInt &DemandedElts, const SimplifyQuery &Q,
3996 unsigned Depth) {
3997 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3998 const APInt *C;
3999 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4000 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4001 !C->isZero() && !C->isOne() &&
4002 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4003 }
4004 return false;
4005}
4006
4007/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4008/// the shift is nuw or nsw.
4009static bool isNonEqualShl(const Value *V1, const Value *V2,
4010 const APInt &DemandedElts, const SimplifyQuery &Q,
4011 unsigned Depth) {
4012 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4013 const APInt *C;
4014 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4015 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4016 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4017 }
4018 return false;
4019}
4020
4021static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4022 const APInt &DemandedElts, const SimplifyQuery &Q,
4023 unsigned Depth) {
4024 // Check two PHIs are in same block.
4025 if (PN1->getParent() != PN2->getParent())
4026 return false;
4027
4029 bool UsedFullRecursion = false;
4030 for (const BasicBlock *IncomBB : PN1->blocks()) {
4031 if (!VisitedBBs.insert(IncomBB).second)
4032 continue; // Don't reprocess blocks that we have dealt with already.
4033 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4034 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4035 const APInt *C1, *C2;
4036 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4037 continue;
4038
4039 // Only one pair of phi operands is allowed for full recursion.
4040 if (UsedFullRecursion)
4041 return false;
4042
4044 RecQ.CxtI = IncomBB->getTerminator();
4045 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4046 return false;
4047 UsedFullRecursion = true;
4048 }
4049 return true;
4050}
4051
4052static bool isNonEqualSelect(const Value *V1, const Value *V2,
4053 const APInt &DemandedElts, const SimplifyQuery &Q,
4054 unsigned Depth) {
4055 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4056 if (!SI1)
4057 return false;
4058
4059 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4060 const Value *Cond1 = SI1->getCondition();
4061 const Value *Cond2 = SI2->getCondition();
4062 if (Cond1 == Cond2)
4063 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4064 DemandedElts, Q, Depth + 1) &&
4065 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4066 DemandedElts, Q, Depth + 1);
4067 }
4068 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4069 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4070}
4071
4072// Check to see if A is both a GEP and is the incoming value for a PHI in the
4073// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4074// one of them being the recursive GEP A and the other a ptr at same base and at
4075// the same/higher offset than B we are only incrementing the pointer further in
4076// loop if offset of recursive GEP is greater than 0.
4078 const SimplifyQuery &Q) {
4079 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4080 return false;
4081
4082 auto *GEPA = dyn_cast<GEPOperator>(A);
4083 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4084 return false;
4085
4086 // Handle 2 incoming PHI values with one being a recursive GEP.
4087 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4088 if (!PN || PN->getNumIncomingValues() != 2)
4089 return false;
4090
4091 // Search for the recursive GEP as an incoming operand, and record that as
4092 // Step.
4093 Value *Start = nullptr;
4094 Value *Step = const_cast<Value *>(A);
4095 if (PN->getIncomingValue(0) == Step)
4096 Start = PN->getIncomingValue(1);
4097 else if (PN->getIncomingValue(1) == Step)
4098 Start = PN->getIncomingValue(0);
4099 else
4100 return false;
4101
4102 // Other incoming node base should match the B base.
4103 // StartOffset >= OffsetB && StepOffset > 0?
4104 // StartOffset <= OffsetB && StepOffset < 0?
4105 // Is non-equal if above are true.
4106 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4107 // optimisation to inbounds GEPs only.
4108 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4109 APInt StartOffset(IndexWidth, 0);
4110 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4111 APInt StepOffset(IndexWidth, 0);
4112 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4113
4114 // Check if Base Pointer of Step matches the PHI.
4115 if (Step != PN)
4116 return false;
4117 APInt OffsetB(IndexWidth, 0);
4118 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4119 return Start == B &&
4120 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4121 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4122}
4123
4124static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4125 const SimplifyQuery &Q, unsigned Depth) {
4126 if (!Q.CxtI)
4127 return false;
4128
4129 // Try to infer NonEqual based on information from dominating conditions.
4130 if (Q.DC && Q.DT) {
4131 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4132 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4133 Value *Cond = BI->getCondition();
4134 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4135 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4137 /*LHSIsTrue=*/true, Depth)
4138 .value_or(false))
4139 return true;
4140
4141 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4142 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4144 /*LHSIsTrue=*/false, Depth)
4145 .value_or(false))
4146 return true;
4147 }
4148
4149 return false;
4150 };
4151
4152 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4153 IsKnownNonEqualFromDominatingCondition(V2))
4154 return true;
4155 }
4156
4157 if (!Q.AC)
4158 return false;
4159
4160 // Try to infer NonEqual based on information from assumptions.
4161 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4162 if (!AssumeVH)
4163 continue;
4164 CallInst *I = cast<CallInst>(AssumeVH);
4165
4166 assert(I->getFunction() == Q.CxtI->getFunction() &&
4167 "Got assumption for the wrong function!");
4168 assert(I->getIntrinsicID() == Intrinsic::assume &&
4169 "must be an assume intrinsic");
4170
4171 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4172 /*LHSIsTrue=*/true, Depth)
4173 .value_or(false) &&
4175 return true;
4176 }
4177
4178 return false;
4179}
4180
4181static bool isNonEqualURem(const Value *X, const Value *Rem,
4182 const SimplifyQuery &Q) {
4183 const Value *Y;
4184 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4185 return false;
4186
4187 // For a defined urem, X != X urem Y exactly when X u>= Y.
4188 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4190 return true;
4191
4192 std::optional<bool> Implied =
4194 return Implied && *Implied;
4195}
4196
4197/// Return true if it is known that V1 != V2.
4198static bool isKnownNonEqual(const Value *V1, const Value *V2,
4199 const APInt &DemandedElts, const SimplifyQuery &Q,
4200 unsigned Depth) {
4201 if (V1 == V2)
4202 return false;
4203 if (V1->getType() != V2->getType())
4204 // We can't look through casts yet.
4205 return false;
4206
4208 return false;
4209
4210 // See if we can recurse through (exactly one of) our operands. This
4211 // requires our operation be 1-to-1 and map every input value to exactly
4212 // one output value. Such an operation is invertible.
4213 auto *O1 = dyn_cast<Operator>(V1);
4214 auto *O2 = dyn_cast<Operator>(V2);
4215 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4216 if (auto Values = getInvertibleOperands(O1, O2))
4217 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4218 Depth + 1);
4219
4220 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4221 const PHINode *PN2 = cast<PHINode>(V2);
4222 // FIXME: This is missing a generalization to handle the case where one is
4223 // a PHI and another one isn't.
4224 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4225 return true;
4226 };
4227 }
4228
4229 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4230 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4231 return true;
4232
4233 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4234 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4235 return true;
4236
4237 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4238 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4239 return true;
4240
4241 if (V1->getType()->isIntOrIntVectorTy()) {
4242 // Are any known bits in V1 contradictory to known bits in V2? If V1
4243 // has a known zero where V2 has a known one, they must not be equal.
4244 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4245 if (!Known1.isUnknown()) {
4246 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4247 if (Known1.Zero.intersects(Known2.One) ||
4248 Known2.Zero.intersects(Known1.One))
4249 return true;
4250 }
4251 }
4252
4253 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4254 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4255 return true;
4256
4259 return true;
4260
4261 Value *A, *B;
4262 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4263 // Check PtrToInt type matches the pointer size.
4264 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4266 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4267
4268 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4269 return true;
4270
4271 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4272 return true;
4273
4274 return false;
4275}
4276
4277/// For vector constants, loop over the elements and find the constant with the
4278/// minimum number of sign bits. Return 0 if the value is not a vector constant
4279/// or if any element was not analyzed; otherwise, return the count for the
4280/// element with the minimum number of sign bits.
4282 const APInt &DemandedElts,
4283 unsigned TyBits) {
4284 const auto *CV = dyn_cast<Constant>(V);
4285 if (!CV || !isa<FixedVectorType>(CV->getType()))
4286 return 0;
4287
4288 unsigned MinSignBits = TyBits;
4289 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4290 for (unsigned i = 0; i != NumElts; ++i) {
4291 if (!DemandedElts[i])
4292 continue;
4293 // If we find a non-ConstantInt, bail out.
4294 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4295 if (!Elt)
4296 return 0;
4297
4298 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4299 }
4300
4301 return MinSignBits;
4302}
4303
4304static unsigned ComputeNumSignBitsImpl(const Value *V,
4305 const APInt &DemandedElts,
4306 const SimplifyQuery &Q, unsigned Depth);
4307
4308static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4309 const SimplifyQuery &Q, unsigned Depth) {
4310 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4311 assert(Result > 0 && "At least one sign bit needs to be present!");
4312 return Result;
4313}
4314
4315/// Return the number of times the sign bit of the register is replicated into
4316/// the other bits. We know that at least 1 bit is always equal to the sign bit
4317/// (itself), but other cases can give us information. For example, immediately
4318/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4319/// other, so we return 3. For vectors, return the number of sign bits for the
4320/// vector element with the minimum number of known sign bits of the demanded
4321/// elements in the vector specified by DemandedElts.
4322static unsigned ComputeNumSignBitsImpl(const Value *V,
4323 const APInt &DemandedElts,
4324 const SimplifyQuery &Q, unsigned Depth) {
4325 Type *Ty = V->getType();
4326#ifndef NDEBUG
4327 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4328
4329 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4330 assert(
4331 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4332 "DemandedElt width should equal the fixed vector number of elements");
4333 } else {
4334 assert(DemandedElts == APInt(1, 1) &&
4335 "DemandedElt width should be 1 for scalars");
4336 }
4337#endif
4338
4339 // We return the minimum number of sign bits that are guaranteed to be present
4340 // in V, so for undef we have to conservatively return 1. We don't have the
4341 // same behavior for poison though -- that's a FIXME today.
4342
4343 Type *ScalarTy = Ty->getScalarType();
4344 unsigned TyBits = ScalarTy->isPointerTy() ?
4345 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4346 Q.DL.getTypeSizeInBits(ScalarTy);
4347
4348 unsigned Tmp, Tmp2;
4349 unsigned FirstAnswer = 1;
4350
4351 // Note that ConstantInt is handled by the general computeKnownBits case
4352 // below.
4353
4355 return 1;
4356
4357 if (auto *U = dyn_cast<Operator>(V)) {
4358 switch (Operator::getOpcode(V)) {
4359 default: break;
4360 case Instruction::BitCast: {
4361 Value *Src = U->getOperand(0);
4362 Type *SrcTy = Src->getType();
4363
4364 // Skip if the source type is not an integer or integer vector type
4365 // This ensures we only process integer-like types
4366 if (!SrcTy->isIntOrIntVectorTy())
4367 break;
4368
4369 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4370
4371 // Bitcast 'large element' scalar/vector to 'small element' vector.
4372 if ((SrcBits % TyBits) != 0)
4373 break;
4374
4375 // Only proceed if the destination type is a fixed-size vector
4376 if (isa<FixedVectorType>(Ty)) {
4377 // Fast case - sign splat can be simply split across the small elements.
4378 // This works for both vector and scalar sources
4379 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4380 if (Tmp == SrcBits)
4381 return TyBits;
4382 }
4383 break;
4384 }
4385 case Instruction::SExt:
4386 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4387 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4388 Tmp;
4389
4390 case Instruction::SDiv: {
4391 const APInt *Denominator;
4392 // sdiv X, C -> adds log(C) sign bits.
4393 if (match(U->getOperand(1), m_APInt(Denominator))) {
4394
4395 // Ignore non-positive denominator.
4396 if (!Denominator->isStrictlyPositive())
4397 break;
4398
4399 // Calculate the incoming numerator bits.
4400 unsigned NumBits =
4401 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4402
4403 // Add floor(log(C)) bits to the numerator bits.
4404 return std::min(TyBits, NumBits + Denominator->logBase2());
4405 }
4406 break;
4407 }
4408
4409 case Instruction::SRem: {
4410 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4411
4412 const APInt *Denominator;
4413 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4414 // positive constant. This let us put a lower bound on the number of sign
4415 // bits.
4416 if (match(U->getOperand(1), m_APInt(Denominator))) {
4417
4418 // Ignore non-positive denominator.
4419 if (Denominator->isStrictlyPositive()) {
4420 // Calculate the leading sign bit constraints by examining the
4421 // denominator. Given that the denominator is positive, there are two
4422 // cases:
4423 //
4424 // 1. The numerator is positive. The result range is [0,C) and
4425 // [0,C) u< (1 << ceilLogBase2(C)).
4426 //
4427 // 2. The numerator is negative. Then the result range is (-C,0] and
4428 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4429 //
4430 // Thus a lower bound on the number of sign bits is `TyBits -
4431 // ceilLogBase2(C)`.
4432
4433 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4434 Tmp = std::max(Tmp, ResBits);
4435 }
4436 }
4437 return Tmp;
4438 }
4439
4440 case Instruction::AShr: {
4441 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4442 // ashr X, C -> adds C sign bits. Vectors too.
4443 const APInt *ShAmt;
4444 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4445 if (ShAmt->uge(TyBits))
4446 break; // Bad shift.
4447 unsigned ShAmtLimited = ShAmt->getZExtValue();
4448 Tmp += ShAmtLimited;
4449 if (Tmp > TyBits) Tmp = TyBits;
4450 }
4451 return Tmp;
4452 }
4453 case Instruction::Shl: {
4454 const APInt *ShAmt;
4455 Value *X = nullptr;
4456 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4457 // shl destroys sign bits.
4458 if (ShAmt->uge(TyBits))
4459 break; // Bad shift.
4460 // We can look through a zext (more or less treating it as a sext) if
4461 // all extended bits are shifted out.
4462 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4463 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4464 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4465 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4466 } else
4467 Tmp =
4468 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4469 if (ShAmt->uge(Tmp))
4470 break; // Shifted all sign bits out.
4471 Tmp2 = ShAmt->getZExtValue();
4472 return Tmp - Tmp2;
4473 }
4474 break;
4475 }
4476 case Instruction::And:
4477 case Instruction::Or:
4478 case Instruction::Xor: // NOT is handled here.
4479 // Logical binary ops preserve the number of sign bits at the worst.
4480 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4481 if (Tmp != 1) {
4482 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4483 FirstAnswer = std::min(Tmp, Tmp2);
4484 // We computed what we know about the sign bits as our first
4485 // answer. Now proceed to the generic code that uses
4486 // computeKnownBits, and pick whichever answer is better.
4487 }
4488 break;
4489
4490 case Instruction::Select: {
4491 // If we have a clamp pattern, we know that the number of sign bits will
4492 // be the minimum of the clamp min/max range.
4493 const Value *X;
4494 const APInt *CLow, *CHigh;
4495 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4496 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4497
4498 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4499 if (Tmp == 1)
4500 break;
4501 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4502 return std::min(Tmp, Tmp2);
4503 }
4504
4505 case Instruction::Add:
4506 // Add can have at most one carry bit. Thus we know that the output
4507 // is, at worst, one more bit than the inputs.
4508 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4509 if (Tmp == 1) break;
4510
4511 // Special case decrementing a value (ADD X, -1):
4512 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4513 if (CRHS->isAllOnesValue()) {
4514 KnownBits Known(TyBits);
4515 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4516
4517 // If the input is known to be 0 or 1, the output is 0/-1, which is
4518 // all sign bits set.
4519 if ((Known.Zero | 1).isAllOnes())
4520 return TyBits;
4521
4522 // If we are subtracting one from a positive number, there is no carry
4523 // out of the result.
4524 if (Known.isNonNegative())
4525 return Tmp;
4526 }
4527
4528 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4529 if (Tmp2 == 1)
4530 break;
4531 return std::min(Tmp, Tmp2) - 1;
4532
4533 case Instruction::Sub:
4534 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4535 if (Tmp2 == 1)
4536 break;
4537
4538 // Handle NEG.
4539 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4540 if (CLHS->isNullValue()) {
4541 KnownBits Known(TyBits);
4542 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4543 // If the input is known to be 0 or 1, the output is 0/-1, which is
4544 // all sign bits set.
4545 if ((Known.Zero | 1).isAllOnes())
4546 return TyBits;
4547
4548 // If the input is known to be positive (the sign bit is known clear),
4549 // the output of the NEG has the same number of sign bits as the
4550 // input.
4551 if (Known.isNonNegative())
4552 return Tmp2;
4553
4554 // Otherwise, we treat this like a SUB.
4555 }
4556
4557 // Sub can have at most one carry bit. Thus we know that the output
4558 // is, at worst, one more bit than the inputs.
4559 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4560 if (Tmp == 1)
4561 break;
4562 return std::min(Tmp, Tmp2) - 1;
4563
4564 case Instruction::Mul: {
4565 // The output of the Mul can be at most twice the valid bits in the
4566 // inputs.
4567 unsigned SignBitsOp0 =
4568 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4569 if (SignBitsOp0 == 1)
4570 break;
4571 unsigned SignBitsOp1 =
4572 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4573 if (SignBitsOp1 == 1)
4574 break;
4575 unsigned OutValidBits =
4576 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4577 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4578 }
4579
4580 case Instruction::PHI: {
4581 const PHINode *PN = cast<PHINode>(U);
4582 unsigned NumIncomingValues = PN->getNumIncomingValues();
4583 // Don't analyze large in-degree PHIs.
4584 if (NumIncomingValues > 4) break;
4585 // Unreachable blocks may have zero-operand PHI nodes.
4586 if (NumIncomingValues == 0) break;
4587
4588 // Take the minimum of all incoming values. This can't infinitely loop
4589 // because of our depth threshold.
4591 Tmp = TyBits;
4592 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4593 if (Tmp == 1) return Tmp;
4594 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4595 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4596 DemandedElts, RecQ, Depth + 1));
4597 }
4598 return Tmp;
4599 }
4600
4601 case Instruction::Trunc: {
4602 // If the input contained enough sign bits that some remain after the
4603 // truncation, then we can make use of that. Otherwise we don't know
4604 // anything.
4605 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4606 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4607 if (Tmp > (OperandTyBits - TyBits))
4608 return Tmp - (OperandTyBits - TyBits);
4609
4610 return 1;
4611 }
4612
4613 case Instruction::ExtractElement:
4614 // Look through extract element. At the moment we keep this simple and
4615 // skip tracking the specific element. But at least we might find
4616 // information valid for all elements of the vector (for example if vector
4617 // is sign extended, shifted, etc).
4618 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4619
4620 case Instruction::ShuffleVector: {
4621 // Collect the minimum number of sign bits that are shared by every vector
4622 // element referenced by the shuffle.
4623 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4624 if (!Shuf) {
4625 // FIXME: Add support for shufflevector constant expressions.
4626 return 1;
4627 }
4628 APInt DemandedLHS, DemandedRHS;
4629 // For undef elements, we don't know anything about the common state of
4630 // the shuffle result.
4631 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4632 return 1;
4633 Tmp = std::numeric_limits<unsigned>::max();
4634 if (!!DemandedLHS) {
4635 const Value *LHS = Shuf->getOperand(0);
4636 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4637 }
4638 // If we don't know anything, early out and try computeKnownBits
4639 // fall-back.
4640 if (Tmp == 1)
4641 break;
4642 if (!!DemandedRHS) {
4643 const Value *RHS = Shuf->getOperand(1);
4644 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4645 Tmp = std::min(Tmp, Tmp2);
4646 }
4647 // If we don't know anything, early out and try computeKnownBits
4648 // fall-back.
4649 if (Tmp == 1)
4650 break;
4651 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4652 return Tmp;
4653 }
4654 case Instruction::Call: {
4655 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4656 switch (II->getIntrinsicID()) {
4657 default:
4658 break;
4659 case Intrinsic::abs:
4660 Tmp =
4661 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4662 if (Tmp == 1)
4663 break;
4664
4665 // Absolute value reduces number of sign bits by at most 1.
4666 return Tmp - 1;
4667 case Intrinsic::smin:
4668 case Intrinsic::smax: {
4669 const APInt *CLow, *CHigh;
4670 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4671 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4672 }
4673 }
4674 }
4675 }
4676 }
4677 }
4678
4679 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4680 // use this information.
4681
4682 // If we can examine all elements of a vector constant successfully, we're
4683 // done (we can't do any better than that). If not, keep trying.
4684 if (unsigned VecSignBits =
4685 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4686 return VecSignBits;
4687
4688 KnownBits Known(TyBits);
4689 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4690
4691 // If we know that the sign bit is either zero or one, determine the number of
4692 // identical bits in the top of the input value.
4693 return std::max(FirstAnswer, Known.countMinSignBits());
4694}
4695
4697 const TargetLibraryInfo *TLI) {
4698 const Function *F = CB.getCalledFunction();
4699 if (!F)
4701
4702 if (F->isIntrinsic())
4703 return F->getIntrinsicID();
4704
4705 // We are going to infer semantics of a library function based on mapping it
4706 // to an LLVM intrinsic. Check that the library function is available from
4707 // this callbase and in this environment.
4708 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4710
4711 LibFunc Func = TLI->getLibFunc(CB);
4712 if (Func == NotLibFunc)
4714
4715 switch (Func) {
4716 default:
4717 break;
4718 case LibFunc_sin:
4719 case LibFunc_sinf:
4720 case LibFunc_sinl:
4721 return Intrinsic::sin;
4722 case LibFunc_cos:
4723 case LibFunc_cosf:
4724 case LibFunc_cosl:
4725 return Intrinsic::cos;
4726 case LibFunc_tan:
4727 case LibFunc_tanf:
4728 case LibFunc_tanl:
4729 return Intrinsic::tan;
4730 case LibFunc_asin:
4731 case LibFunc_asinf:
4732 case LibFunc_asinl:
4733 return Intrinsic::asin;
4734 case LibFunc_acos:
4735 case LibFunc_acosf:
4736 case LibFunc_acosl:
4737 return Intrinsic::acos;
4738 case LibFunc_atan:
4739 case LibFunc_atanf:
4740 case LibFunc_atanl:
4741 return Intrinsic::atan;
4742 case LibFunc_atan2:
4743 case LibFunc_atan2f:
4744 case LibFunc_atan2l:
4745 return Intrinsic::atan2;
4746 case LibFunc_sinh:
4747 case LibFunc_sinhf:
4748 case LibFunc_sinhl:
4749 return Intrinsic::sinh;
4750 case LibFunc_cosh:
4751 case LibFunc_coshf:
4752 case LibFunc_coshl:
4753 return Intrinsic::cosh;
4754 case LibFunc_tanh:
4755 case LibFunc_tanhf:
4756 case LibFunc_tanhl:
4757 return Intrinsic::tanh;
4758 case LibFunc_exp:
4759 case LibFunc_expf:
4760 case LibFunc_expl:
4761 return Intrinsic::exp;
4762 case LibFunc_exp2:
4763 case LibFunc_exp2f:
4764 case LibFunc_exp2l:
4765 return Intrinsic::exp2;
4766 case LibFunc_exp10:
4767 case LibFunc_exp10f:
4768 case LibFunc_exp10l:
4769 return Intrinsic::exp10;
4770 case LibFunc_log:
4771 case LibFunc_logf:
4772 case LibFunc_logl:
4773 return Intrinsic::log;
4774 case LibFunc_log10:
4775 case LibFunc_log10f:
4776 case LibFunc_log10l:
4777 return Intrinsic::log10;
4778 case LibFunc_log2:
4779 case LibFunc_log2f:
4780 case LibFunc_log2l:
4781 return Intrinsic::log2;
4782 case LibFunc_fabs:
4783 case LibFunc_fabsf:
4784 case LibFunc_fabsl:
4785 return Intrinsic::fabs;
4786 case LibFunc_fmin:
4787 case LibFunc_fminf:
4788 case LibFunc_fminl:
4789 return Intrinsic::minnum;
4790 case LibFunc_fmax:
4791 case LibFunc_fmaxf:
4792 case LibFunc_fmaxl:
4793 return Intrinsic::maxnum;
4794 case LibFunc_copysign:
4795 case LibFunc_copysignf:
4796 case LibFunc_copysignl:
4797 return Intrinsic::copysign;
4798 case LibFunc_floor:
4799 case LibFunc_floorf:
4800 case LibFunc_floorl:
4801 return Intrinsic::floor;
4802 case LibFunc_ceil:
4803 case LibFunc_ceilf:
4804 case LibFunc_ceill:
4805 return Intrinsic::ceil;
4806 case LibFunc_trunc:
4807 case LibFunc_truncf:
4808 case LibFunc_truncl:
4809 return Intrinsic::trunc;
4810 case LibFunc_rint:
4811 case LibFunc_rintf:
4812 case LibFunc_rintl:
4813 return Intrinsic::rint;
4814 case LibFunc_nearbyint:
4815 case LibFunc_nearbyintf:
4816 case LibFunc_nearbyintl:
4817 return Intrinsic::nearbyint;
4818 case LibFunc_round:
4819 case LibFunc_roundf:
4820 case LibFunc_roundl:
4821 return Intrinsic::round;
4822 case LibFunc_roundeven:
4823 case LibFunc_roundevenf:
4824 case LibFunc_roundevenl:
4825 return Intrinsic::roundeven;
4826 case LibFunc_pow:
4827 case LibFunc_powf:
4828 case LibFunc_powl:
4829 return Intrinsic::pow;
4830 case LibFunc_sqrt:
4831 case LibFunc_sqrtf:
4832 case LibFunc_sqrtl:
4833 return Intrinsic::sqrt;
4834 }
4835
4837}
4838
4839/// Given an exploded icmp instruction, return true if the comparison only
4840/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4841/// the result of the comparison is true when the input value is signed.
4843 bool &TrueIfSigned) {
4844 switch (Pred) {
4845 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4846 TrueIfSigned = true;
4847 return RHS.isZero();
4848 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4849 TrueIfSigned = true;
4850 return RHS.isAllOnes();
4851 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4852 TrueIfSigned = false;
4853 return RHS.isAllOnes();
4854 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4855 TrueIfSigned = false;
4856 return RHS.isZero();
4857 case ICmpInst::ICMP_UGT:
4858 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4859 TrueIfSigned = true;
4860 return RHS.isMaxSignedValue();
4861 case ICmpInst::ICMP_UGE:
4862 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4863 TrueIfSigned = true;
4864 return RHS.isMinSignedValue();
4865 case ICmpInst::ICMP_ULT:
4866 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4867 TrueIfSigned = false;
4868 return RHS.isMinSignedValue();
4869 case ICmpInst::ICMP_ULE:
4870 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4871 TrueIfSigned = false;
4872 return RHS.isMaxSignedValue();
4873 default:
4874 return false;
4875 }
4876}
4877
4879 bool CondIsTrue,
4880 const Instruction *CxtI,
4881 KnownFPClass &KnownFromContext,
4882 unsigned Depth = 0) {
4883 Value *A, *B;
4885 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4886 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4887 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4888 Depth + 1);
4889 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4890 Depth + 1);
4891 return;
4892 }
4894 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4895 Depth + 1);
4896 return;
4897 }
4898 CmpPredicate Pred;
4899 Value *LHS;
4900 uint64_t ClassVal = 0;
4901 const APFloat *CRHS;
4902 const APInt *RHS;
4903 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4904 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4905 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4906 LHS != V);
4907 if (CmpVal == V)
4908 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4910 m_Specific(V), m_ConstantInt(ClassVal)))) {
4911 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4912 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4913 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4914 m_APInt(RHS)))) {
4915 bool TrueIfSigned;
4916 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4917 return;
4918 if (TrueIfSigned == CondIsTrue)
4919 KnownFromContext.signBitMustBeOne();
4920 else
4921 KnownFromContext.signBitMustBeZero();
4922 }
4923}
4924
4925/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4926/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4927/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4928/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4929/// exponent range is [-149, -2], but the 0 edge case is above this range).
4930static std::tuple<int, int, int>
4932 if (!Q.CxtI || !Q.DC || !Q.DT)
4934
4935 // Intersect the bounds implied by every dominating condition, keeping the
4936 // tightest maximum. A value may participate in multiple compares
4937 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4938 int MaxExp = APFloat::IEK_Inf;
4939 int MaxExpNonZero = APFloat::IEK_Inf;
4940
4941 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4942 CmpPredicate Pred;
4943 const APFloat *LimitC;
4944 if (!match(BI->getCondition(),
4945 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4946 continue;
4947
4948 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4949 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4950 continue;
4951
4952 // If fabs(x) <= K, implies the exponent min exp range.
4953 // if fabs(x) >= K, swap the successor
4954 bool IsLessEqual =
4955 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4956 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4957 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4958
4959 bool KnownStrictlyLess =
4960 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4961 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4962
4963 BasicBlockEdge Edge1(BI->getParent(),
4964 BI->getSuccessor(IsLessEqual ? 0 : 1));
4965 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4966 // frexp returns an exponent one greater than ilogb.
4967 int Exp = ilogb(*LimitC) + 1;
4968
4969 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4970 // exponent drops by one when K is exact power of two.
4971 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4972 --Exp;
4973
4974 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4975 // may exclude.
4976
4977 // TODO: Figure out lower bound to detect no-underflow.
4978 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4979 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4980 }
4981 }
4982
4983 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4984}
4985
4987 const SimplifyQuery &Q) {
4988 KnownFPClass KnownFromContext;
4989
4990 if (Q.CC && Q.CC->AffectedValues.contains(V))
4992 KnownFromContext);
4993
4994 if (!Q.CxtI)
4995 return KnownFromContext;
4996
4997 if (Q.DC && Q.DT) {
4998 // Handle dominating conditions.
4999 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5000 Value *Cond = BI->getCondition();
5001
5002 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5003 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5004 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5005 KnownFromContext);
5006
5007 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5008 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5009 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5010 KnownFromContext);
5011 }
5012 }
5013
5014 if (!Q.AC)
5015 return KnownFromContext;
5016
5017 // Try to restrict the floating-point classes based on information from
5018 // assumptions.
5019 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5020 if (!AssumeVH)
5021 continue;
5022 CallInst *I = cast<CallInst>(AssumeVH);
5023
5024 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5025 "Got assumption for the wrong function!");
5026 assert(I->getIntrinsicID() == Intrinsic::assume &&
5027 "must be an assume intrinsic");
5028
5029 if (!isValidAssumeForContext(I, Q))
5030 continue;
5031
5032 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5033 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5034 }
5035
5036 return KnownFromContext;
5037}
5038
5040 Value *Arm, bool Invert,
5041 const SimplifyQuery &SQ,
5042 unsigned Depth) {
5043
5044 KnownFPClass KnownSrc;
5046 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5047 Depth + 1);
5048 KnownSrc = KnownSrc.unionWith(Known);
5049 if (KnownSrc.isUnknown())
5050 return;
5051
5052 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5053 Known = KnownSrc;
5054}
5055
5056void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5057 FPClassTest InterestedClasses, KnownFPClass &Known,
5058 const SimplifyQuery &Q, unsigned Depth);
5059
5061 FPClassTest InterestedClasses,
5062 const SimplifyQuery &Q, unsigned Depth) {
5063 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5064 APInt DemandedElts =
5065 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5066 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5067}
5068
5070 const APInt &DemandedElts,
5071 FPClassTest InterestedClasses,
5073 const SimplifyQuery &Q,
5074 unsigned Depth) {
5075 if ((InterestedClasses &
5077 return;
5078
5079 KnownFPClass KnownSrc;
5080 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5081 KnownSrc, Q, Depth + 1);
5082 Known = KnownFPClass::fptrunc(KnownSrc);
5083}
5084
5086 switch (IID) {
5087 case Intrinsic::minimum:
5089 case Intrinsic::maximum:
5091 case Intrinsic::minimumnum:
5093 case Intrinsic::maximumnum:
5095 case Intrinsic::minnum:
5097 case Intrinsic::maxnum:
5099 default:
5100 llvm_unreachable("not a floating-point min-max intrinsic");
5101 }
5102}
5103
5104/// \return true if this is a floating point value that is known to have a
5105/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5106static bool isAbsoluteValueULEOne(const Value *V) {
5107 // TODO: Handle frexp
5108 // TODO: Other rounding intrinsics?
5109 // TODO: Try computeKnownExponentRangeFromContext
5110
5111 // fabs(x - floor(x)) <= 1
5112 const Value *SubFloorX;
5113 if (match(V, m_FSub(m_Value(SubFloorX),
5115 return true;
5116
5119}
5120
5121void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5122 FPClassTest InterestedClasses, KnownFPClass &Known,
5123 const SimplifyQuery &Q, unsigned Depth) {
5124 assert(Known.isUnknown() && "should not be called with known information");
5125
5126 if (!DemandedElts) {
5127 // No demanded elts, better to assume we don't know anything.
5128 Known.resetAll();
5129 return;
5130 }
5131
5132 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5133
5134 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5135 Known = KnownFPClass(CFP->getValueAPF());
5136 return;
5137 }
5138
5140 Known.KnownFPClasses = fcPosZero;
5141 Known.SignBit = false;
5142 return;
5143 }
5144
5145 if (isa<PoisonValue>(V)) {
5146 Known.KnownFPClasses = fcNone;
5147 Known.SignBit = false;
5148 return;
5149 }
5150
5151 // Try to handle fixed width vector constants
5152 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5153 const Constant *CV = dyn_cast<Constant>(V);
5154 if (VFVTy && CV) {
5155 Known.KnownFPClasses = fcNone;
5156 bool SignBitAllZero = true;
5157 bool SignBitAllOne = true;
5158
5159 // For vectors, verify that each element is not NaN.
5160 unsigned NumElts = VFVTy->getNumElements();
5161 for (unsigned i = 0; i != NumElts; ++i) {
5162 if (!DemandedElts[i])
5163 continue;
5164
5165 Constant *Elt = CV->getAggregateElement(i);
5166 if (!Elt) {
5167 Known = KnownFPClass();
5168 return;
5169 }
5170 if (isa<PoisonValue>(Elt))
5171 continue;
5172 auto *CElt = dyn_cast<ConstantFP>(Elt);
5173 if (!CElt) {
5174 Known = KnownFPClass();
5175 return;
5176 }
5177
5178 const APFloat &C = CElt->getValueAPF();
5179 Known.KnownFPClasses |= C.classify();
5180 if (C.isNegative())
5181 SignBitAllZero = false;
5182 else
5183 SignBitAllOne = false;
5184 }
5185 if (SignBitAllOne != SignBitAllZero)
5186 Known.SignBit = SignBitAllOne;
5187 return;
5188 }
5189
5190 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5191 Known.KnownFPClasses = fcNone;
5192 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5193 Known |= CDS->getElementAsAPFloat(I).classify();
5194 return;
5195 }
5196
5197 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5198 // TODO: Handle complex aggregates
5199 Known.KnownFPClasses = fcNone;
5200 for (const Use &Op : CA->operands()) {
5201 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5202 if (!CFP) {
5203 Known = KnownFPClass();
5204 return;
5205 }
5206
5207 Known |= CFP->getValueAPF().classify();
5208 }
5209
5210 return;
5211 }
5212
5213 FPClassTest KnownNotFromFlags = fcNone;
5214 if (const auto *CB = dyn_cast<CallBase>(V))
5215 KnownNotFromFlags |= CB->getRetNoFPClass();
5216 else if (const auto *Arg = dyn_cast<Argument>(V))
5217 KnownNotFromFlags |= Arg->getNoFPClass();
5218
5219 const Operator *Op = dyn_cast<Operator>(V);
5221 if (FPOp->hasNoNaNs())
5222 KnownNotFromFlags |= fcNan;
5223 if (FPOp->hasNoInfs())
5224 KnownNotFromFlags |= fcInf;
5225 }
5226
5227 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5228 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5229
5230 // We no longer need to find out about these bits from inputs if we can
5231 // assume this from flags/attributes.
5232 InterestedClasses &= ~KnownNotFromFlags;
5233
5234 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5235 Known.knownNot(KnownNotFromFlags);
5236 if (!Known.SignBit && AssumedClasses.SignBit) {
5237 if (*AssumedClasses.SignBit)
5238 Known.signBitMustBeOne();
5239 else
5240 Known.signBitMustBeZero();
5241 }
5242 });
5243
5244 if (!Op)
5245 return;
5246
5247 // All recursive calls that increase depth must come after this.
5249 return;
5250
5251 const unsigned Opc = Op->getOpcode();
5252 switch (Opc) {
5253 case Instruction::FNeg: {
5254 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5255 Known, Q, Depth + 1);
5256 Known.fneg();
5257 break;
5258 }
5259 case Instruction::Select: {
5260 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5261 KnownFPClass Res;
5262 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5263 Depth + 1);
5264 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5265 Depth);
5266 return Res;
5267 };
5268 // Only known if known in both the LHS and RHS.
5269 Known =
5270 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5271 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5272 break;
5273 }
5274 case Instruction::Load: {
5275 const MDNode *NoFPClass =
5276 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5277 if (!NoFPClass)
5278 break;
5279
5280 ConstantInt *MaskVal =
5282 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5283 break;
5284 }
5285 case Instruction::Call: {
5286 const CallInst *II = cast<CallInst>(Op);
5287 const Intrinsic::ID IID = II->getIntrinsicID();
5288 switch (IID) {
5289 case Intrinsic::fabs: {
5290 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5291 // If we only care about the sign bit we don't need to inspect the
5292 // operand.
5293 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5294 InterestedClasses, Known, Q, Depth + 1);
5295 }
5296
5297 Known.fabs();
5298 break;
5299 }
5300 case Intrinsic::copysign: {
5301 KnownFPClass KnownSign;
5302
5303 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5304 Known, Q, Depth + 1);
5305 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5306 KnownSign, Q, Depth + 1);
5307 Known.copysign(KnownSign);
5308 break;
5309 }
5310 case Intrinsic::fma:
5311 case Intrinsic::fmuladd: {
5312 if ((InterestedClasses & fcNegative) == fcNone)
5313 break;
5314
5315 // FIXME: This should check isGuaranteedNotToBeUndef
5316 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5317 KnownFPClass KnownSrc, KnownAddend;
5318 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5319 InterestedClasses, KnownAddend, Q, Depth + 1);
5320 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5321 InterestedClasses, KnownSrc, Q, Depth + 1);
5322
5323 const Function *F = II->getFunction();
5324 const fltSemantics &FltSem =
5325 II->getType()->getScalarType()->getFltSemantics();
5327 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5328
5329 if (KnownNotFromFlags & fcNan) {
5330 KnownSrc.knownNot(fcNan);
5331 KnownAddend.knownNot(fcNan);
5332 }
5333
5334 if (KnownNotFromFlags & fcInf) {
5335 KnownSrc.knownNot(fcInf);
5336 KnownAddend.knownNot(fcInf);
5337 }
5338
5339 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5340 break;
5341 }
5342
5343 KnownFPClass KnownSrc[3];
5344 for (int I = 0; I != 3; ++I) {
5345 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5346 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5347 if (KnownSrc[I].isUnknown())
5348 return;
5349
5350 if (KnownNotFromFlags & fcNan)
5351 KnownSrc[I].knownNot(fcNan);
5352 if (KnownNotFromFlags & fcInf)
5353 KnownSrc[I].knownNot(fcInf);
5354 }
5355
5356 const Function *F = II->getFunction();
5357 const fltSemantics &FltSem =
5358 II->getType()->getScalarType()->getFltSemantics();
5360 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5361 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5362 break;
5363 }
5364 case Intrinsic::sqrt:
5365 case Intrinsic::experimental_constrained_sqrt: {
5366 KnownFPClass KnownSrc;
5367 FPClassTest InterestedSrcs = InterestedClasses;
5368 if (InterestedClasses & fcNan)
5369 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5370
5371 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5372 KnownSrc, Q, Depth + 1);
5373
5375
5376 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5377 if (!HasNSZ) {
5378 const Function *F = II->getFunction();
5379 const fltSemantics &FltSem =
5380 II->getType()->getScalarType()->getFltSemantics();
5381 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5382 }
5383
5384 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5385 if (HasNSZ)
5386 Known.knownNot(fcNegZero);
5387
5388 break;
5389 }
5390 case Intrinsic::sin: {
5391 KnownFPClass KnownSrc;
5392 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5393 KnownSrc, Q, Depth + 1);
5394 Known = KnownFPClass::sin(KnownSrc);
5395 break;
5396 }
5397 case Intrinsic::cos: {
5398 KnownFPClass KnownSrc;
5399 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5400 KnownSrc, Q, Depth + 1);
5401 Known = KnownFPClass::cos(KnownSrc);
5402 break;
5403 }
5404 case Intrinsic::tan: {
5405 KnownFPClass KnownSrc;
5406 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5407 KnownSrc, Q, Depth + 1);
5408 Known = KnownFPClass::tan(KnownSrc);
5409 break;
5410 }
5411 case Intrinsic::sinh: {
5412 KnownFPClass KnownSrc;
5413 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5414 KnownSrc, Q, Depth + 1);
5415 Known = KnownFPClass::sinh(KnownSrc);
5416 break;
5417 }
5418 case Intrinsic::cosh: {
5419 KnownFPClass KnownSrc;
5420 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5421 KnownSrc, Q, Depth + 1);
5422 Known = KnownFPClass::cosh(KnownSrc);
5423 break;
5424 }
5425 case Intrinsic::tanh: {
5426 KnownFPClass KnownSrc;
5427 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5428 KnownSrc, Q, Depth + 1);
5429 Known = KnownFPClass::tanh(KnownSrc);
5430 break;
5431 }
5432 case Intrinsic::asin: {
5433 KnownFPClass KnownSrc;
5434 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5435 KnownSrc, Q, Depth + 1);
5436 Known = KnownFPClass::asin(KnownSrc);
5437 break;
5438 }
5439 case Intrinsic::acos: {
5440 KnownFPClass KnownSrc;
5441 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5442 KnownSrc, Q, Depth + 1);
5443 Known = KnownFPClass::acos(KnownSrc);
5444 break;
5445 }
5446 case Intrinsic::atan: {
5447 KnownFPClass KnownSrc;
5448 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5449 KnownSrc, Q, Depth + 1);
5450 Known = KnownFPClass::atan(KnownSrc);
5451 break;
5452 }
5453 case Intrinsic::atan2: {
5454 FPClassTest InterestedY = InterestedClasses;
5455 FPClassTest InterestedX = InterestedClasses;
5456
5457 // We can rule out zero and subnormal if x cannot have a positive value.
5458 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5459 InterestedX |= fcPositive | fcNegSubnormal;
5460
5461 KnownFPClass KnownY, KnownX;
5462 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5463 KnownY, Q, Depth + 1);
5464 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5465 KnownX, Q, Depth + 1);
5466
5467 const Function *F = II->getFunction();
5469 F ? F->getDenormalMode(
5470 II->getType()->getScalarType()->getFltSemantics())
5472 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5473 break;
5474 }
5475 case Intrinsic::maxnum:
5476 case Intrinsic::minnum:
5477 case Intrinsic::minimum:
5478 case Intrinsic::maximum:
5479 case Intrinsic::minimumnum:
5480 case Intrinsic::maximumnum: {
5481 KnownFPClass KnownLHS, KnownRHS;
5482 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5483 KnownLHS, Q, Depth + 1);
5484 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5485 KnownRHS, Q, Depth + 1);
5486
5487 const Function *F = II->getFunction();
5488
5490 F ? F->getDenormalMode(
5491 II->getType()->getScalarType()->getFltSemantics())
5493
5494 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5495 Mode);
5496 break;
5497 }
5498 case Intrinsic::canonicalize: {
5499 KnownFPClass KnownSrc;
5500 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5501 KnownSrc, Q, Depth + 1);
5502
5503 const Function *F = II->getFunction();
5504 DenormalMode DenormMode =
5505 F ? F->getDenormalMode(
5506 II->getType()->getScalarType()->getFltSemantics())
5508 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5509 break;
5510 }
5511 case Intrinsic::vector_reduce_fmax:
5512 case Intrinsic::vector_reduce_fmin:
5513 case Intrinsic::vector_reduce_fmaximum:
5514 case Intrinsic::vector_reduce_fminimum:
5515 case Intrinsic::vector_reduce_fmaximumnum:
5516 case Intrinsic::vector_reduce_fminimumnum: {
5517 // reduce min/max will choose an element from one of the vector elements,
5518 // so we can infer and class information that is common to all elements.
5519 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5520 InterestedClasses, Q, Depth + 1);
5521 // Can only propagate sign if output is never NaN.
5522 if (!Known.isKnownNeverNaN())
5523 Known.SignBit.reset();
5524 break;
5525 }
5526 // reverse preserves all characteristics of the input vec's element.
5527 case Intrinsic::vector_reverse:
5529 II->getArgOperand(0), DemandedElts.reverseBits(),
5530 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5531 break;
5532 case Intrinsic::trunc:
5533 case Intrinsic::floor:
5534 case Intrinsic::ceil:
5535 case Intrinsic::rint:
5536 case Intrinsic::nearbyint:
5537 case Intrinsic::round:
5538 case Intrinsic::roundeven: {
5539 KnownFPClass KnownSrc;
5540 FPClassTest InterestedSrcs = InterestedClasses;
5541 if (InterestedSrcs & fcPosFinite)
5542 InterestedSrcs |= fcPosFinite;
5543 if (InterestedSrcs & fcNegFinite)
5544 InterestedSrcs |= fcNegFinite;
5545 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5546 KnownSrc, Q, Depth + 1);
5547
5549 KnownSrc, IID == Intrinsic::trunc,
5550 V->getType()->getScalarType()->isMultiUnitFPType());
5551 break;
5552 }
5553 case Intrinsic::exp:
5554 case Intrinsic::exp2:
5555 case Intrinsic::exp10:
5556 case Intrinsic::amdgcn_exp2: {
5557 KnownFPClass KnownSrc;
5558 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5559 KnownSrc, Q, Depth + 1);
5560
5561 Known = KnownFPClass::exp(KnownSrc);
5562
5563 Type *EltTy = II->getType()->getScalarType();
5564 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5565 Known.knownNot(fcSubnormal);
5566
5567 break;
5568 }
5569 case Intrinsic::fptrunc_round: {
5570 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5571 Q, Depth);
5572 break;
5573 }
5574 case Intrinsic::log:
5575 case Intrinsic::log10:
5576 case Intrinsic::log2:
5577 case Intrinsic::experimental_constrained_log:
5578 case Intrinsic::experimental_constrained_log10:
5579 case Intrinsic::experimental_constrained_log2:
5580 case Intrinsic::amdgcn_log: {
5581 Type *EltTy = II->getType()->getScalarType();
5582
5583 // log(+inf) -> +inf
5584 // log([+-]0.0) -> -inf
5585 // log(-inf) -> nan
5586 // log(-x) -> nan
5587 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5588 FPClassTest InterestedSrcs = InterestedClasses;
5589 if ((InterestedClasses & fcNegInf) != fcNone)
5590 InterestedSrcs |= fcZero | fcSubnormal;
5591 if ((InterestedClasses & fcNan) != fcNone)
5592 InterestedSrcs |= fcNan | fcNegative;
5593
5594 KnownFPClass KnownSrc;
5595 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5596 KnownSrc, Q, Depth + 1);
5597
5598 const Function *F = II->getFunction();
5599 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5601 Known = KnownFPClass::log(KnownSrc, Mode);
5602 }
5603
5604 break;
5605 }
5606 case Intrinsic::pow: {
5607 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5608 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5609 if (!WantNaN && !WantNegative)
5610 break;
5611
5612 FPClassTest InterestedLHS = fcNone;
5613 FPClassTest InterestedRHS = fcNone;
5614 if (WantNaN) {
5615 // pow may return NaN if one of the arguments is NaN. NaN may also be
5616 // produced from a negative, non-zero finite base and a non-integer
5617 // exponent.
5618 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5619 InterestedRHS |= fcNan;
5620 }
5621 if (WantNegative) {
5622 // A negative value is returned when a negative base is raised to an odd
5623 // integer power. Only normal values can be odd integers.
5624 InterestedLHS |= fcNegative;
5625 InterestedRHS |= fcNormal;
5626 }
5627
5628 KnownFPClass KnownLHS;
5629 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5630 KnownLHS, Q, Depth + 1);
5631
5632 // If the LHS is unknown, then querying the RHS is only useful for rare
5633 // edge cases.
5634 if (KnownLHS.isUnknown())
5635 break;
5636
5637 KnownFPClass KnownRHS;
5638 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5639 KnownRHS, Q, Depth + 1);
5640 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5641 break;
5642 }
5643 case Intrinsic::powi: {
5644 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5645 break;
5646
5647 // The exponent is always a scalar, even when raising a vector to a power.
5648 const Value *Exp = II->getArgOperand(1);
5649 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5650 KnownBits ExponentKnownBits(BitWidth);
5651 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5652
5653 FPClassTest InterestedSrcs = fcNone;
5654 if (InterestedClasses & fcNan)
5655 InterestedSrcs |= fcNan;
5656 if (!ExponentKnownBits.isZero()) {
5657 if (InterestedClasses & fcInf)
5658 InterestedSrcs |= fcFinite | fcInf;
5659 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5660 InterestedSrcs |= fcNegative;
5661 }
5662
5663 KnownFPClass KnownSrc;
5664 if (InterestedSrcs != fcNone)
5665 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5666 KnownSrc, Q, Depth + 1);
5667
5668 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5669 break;
5670 }
5671 case Intrinsic::ldexp: {
5672 KnownFPClass KnownSrc;
5673 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5674 KnownSrc, Q, Depth + 1);
5675 // Can refine inf/zero handling based on the exponent operand.
5676 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5677
5678 const Value *ExpArg = II->getArgOperand(1);
5679 ConstantRange ExpKnownRange =
5680 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5681 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5682 : ConstantRange::getFull(
5683 ExpArg->getType()->getScalarSizeInBits());
5684
5685 const fltSemantics &Flt =
5686 II->getType()->getScalarType()->getFltSemantics();
5687
5688 const Function *F = II->getFunction();
5690 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5691
5692 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5693 ExpKnownRange.getSignedMax(), Flt, Mode);
5694 break;
5695 }
5696 case Intrinsic::arithmetic_fence: {
5697 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5698 Known, Q, Depth + 1);
5699 break;
5700 }
5701 case Intrinsic::experimental_constrained_sitofp:
5702 case Intrinsic::experimental_constrained_uitofp:
5703 // Cannot produce nan
5704 Known.knownNot(fcNan);
5705
5706 // sitofp and uitofp turn into +0.0 for zero.
5707 Known.knownNot(fcNegZero);
5708
5709 // Integers cannot be subnormal
5710 Known.knownNot(fcSubnormal);
5711
5712 if (IID == Intrinsic::experimental_constrained_uitofp)
5713 Known.signBitMustBeZero();
5714
5715 // TODO: Copy inf handling from instructions
5716 break;
5717
5718 case Intrinsic::amdgcn_fract: {
5719 Known.knownNot(fcInf);
5720
5721 if (InterestedClasses & fcNan) {
5722 KnownFPClass KnownSrc;
5723 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5724 InterestedClasses, KnownSrc, Q, Depth + 1);
5725
5726 if (KnownSrc.isKnownNeverInfOrNaN())
5727 Known.knownNot(fcNan);
5728 else if (KnownSrc.isKnownNever(fcSNan))
5729 Known.knownNot(fcSNan);
5730 }
5731
5732 break;
5733 }
5734 case Intrinsic::amdgcn_rcp: {
5735 KnownFPClass KnownSrc;
5736 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5737 KnownSrc, Q, Depth + 1);
5738
5739 Known.propagateNonNaN(KnownSrc);
5740
5741 Type *EltTy = II->getType()->getScalarType();
5742
5743 // f32 denormal always flushed.
5744 if (EltTy->isFloatTy()) {
5745 Known.knownNot(fcSubnormal);
5746 KnownSrc.knownNot(fcSubnormal);
5747 }
5748
5749 if (KnownSrc.isKnownNever(fcNegative))
5750 Known.knownNot(fcNegative);
5751 if (KnownSrc.isKnownNever(fcPositive))
5752 Known.knownNot(fcPositive);
5753
5754 if (const Function *F = II->getFunction()) {
5755 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5756 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5757 Known.knownNot(fcPosInf);
5758 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5759 Known.knownNot(fcNegInf);
5760 }
5761
5762 break;
5763 }
5764 case Intrinsic::amdgcn_rsq: {
5765 KnownFPClass KnownSrc;
5766 // The only negative value that can be returned is -inf for -0 inputs.
5768
5769 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5770 KnownSrc, Q, Depth + 1);
5771
5772 // Negative -> nan
5773 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5774 Known.knownNot(fcNan);
5775 else if (KnownSrc.isKnownNever(fcSNan))
5776 Known.knownNot(fcSNan);
5777
5778 // +inf -> +0
5779 if (KnownSrc.isKnownNeverPosInfinity())
5780 Known.knownNot(fcPosZero);
5781
5782 Type *EltTy = II->getType()->getScalarType();
5783
5784 // f32 denormal always flushed.
5785 if (EltTy->isFloatTy())
5786 Known.knownNot(fcPosSubnormal);
5787
5788 if (const Function *F = II->getFunction()) {
5789 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5790
5791 // -0 -> -inf
5792 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5793 Known.knownNot(fcNegInf);
5794
5795 // +0 -> +inf
5796 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5797 Known.knownNot(fcPosInf);
5798 }
5799
5800 break;
5801 }
5802 case Intrinsic::amdgcn_trig_preop: {
5803 // Always returns a value [0, 1)
5804 Known.knownNot(fcNan | fcInf | fcNegative);
5805 break;
5806 }
5807 case Intrinsic::convert_from_arbitrary_fp: {
5808 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5809 StringRef FormatStr = cast<MDString>(MD)->getString();
5810
5811 const fltSemantics *SrcSemantics =
5813 if (!SrcSemantics)
5814 break;
5815
5816 const fltSemantics DstSemantics =
5817 II->getType()->getScalarType()->getFltSemantics();
5818
5819 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5820 Known.knownNot(fcNan);
5821
5822 // fcInf can only be cleared if the source format has no Inf encoding
5823 // and the dst max exp can accommodate src max exp.
5824 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5825 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5826 APFloat::semanticsMaxExponent(DstSemantics))
5827 Known.knownNot(fcInf);
5828
5829 // Check and clear all neg flags for formats that do not have signed
5830 // representation.
5831 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5832 Known.knownNot(fcNegative);
5833
5834 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5835 // zero.
5836 if (!APFloat::semanticsHasZero(*SrcSemantics))
5837 Known.knownNot(fcZero);
5838 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5839 Known.knownNot(fcNegZero);
5840
5841 // If src lands normally in dest, the result can never be subnormal.
5842 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5843 Known.knownNot(fcSubnormal);
5844 break;
5845 }
5846 default:
5847 break;
5848 }
5849
5850 break;
5851 }
5852 case Instruction::FAdd:
5853 case Instruction::FSub: {
5854 KnownFPClass KnownLHS, KnownRHS;
5855 bool WantNegative =
5856 Op->getOpcode() == Instruction::FAdd &&
5857 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5858 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5859 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5860
5861 if (!WantNaN && !WantNegative && !WantNegZero)
5862 break;
5863
5864 FPClassTest InterestedSrcs = InterestedClasses;
5865 if (WantNegative)
5866 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5867 if (InterestedClasses & fcNan)
5868 InterestedSrcs |= fcInf;
5869 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5870 KnownRHS, Q, Depth + 1);
5871
5872 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5873 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5874 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5875 Depth + 1);
5876 if (Self)
5877 KnownLHS = KnownRHS;
5878
5879 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5880 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5881 WantNegZero || Opc == Instruction::FSub) {
5882
5883 // FIXME: Context function should always be passed in separately
5884 const Function *F = cast<Instruction>(Op)->getFunction();
5885 const fltSemantics &FltSem =
5886 Op->getType()->getScalarType()->getFltSemantics();
5888 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5889
5890 if (Self && Opc == Instruction::FAdd) {
5891 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5892 } else {
5893 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5894 // there's no point.
5895
5896 if (!Self) {
5897 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5898 KnownLHS, Q, Depth + 1);
5899 }
5900
5901 Known = Opc == Instruction::FAdd
5902 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5903 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5904 }
5905 }
5906
5907 break;
5908 }
5909 case Instruction::FMul: {
5910 const Function *F = cast<Instruction>(Op)->getFunction();
5912 F ? F->getDenormalMode(
5913 Op->getType()->getScalarType()->getFltSemantics())
5915
5916 Value *LHS = Op->getOperand(0);
5917 Value *RHS = Op->getOperand(1);
5918 // X * X is always non-negative or a NaN.
5919 // FIXME: Should check isGuaranteedNotToBeUndef
5920 if (LHS == RHS) {
5921 KnownFPClass KnownSrc;
5922 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5923 Depth + 1);
5924 Known = KnownFPClass::square(KnownSrc, Mode);
5925 break;
5926 }
5927
5928 KnownFPClass KnownLHS, KnownRHS;
5929
5930 const APFloat *CRHS;
5931 if (match(RHS, m_APFloat(CRHS))) {
5932 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5933 Depth + 1);
5934 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5935 } else {
5936 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5937 Depth + 1);
5938 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5939 // additional not-nan if the addend is known-not negative infinity if the
5940 // multiply is known-not infinity.
5941
5942 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5943 Depth + 1);
5944 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5945 }
5946
5947 /// Propgate no-infs if the other source is known smaller than one, such
5948 /// that this cannot introduce overflow.
5949 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5950 Known.knownNot(fcInf);
5951 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5952 Known.knownNot(fcInf);
5953
5954 break;
5955 }
5956 case Instruction::FDiv: {
5957 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5958
5959 const Function *F = cast<Instruction>(Op)->getFunction();
5960 const fltSemantics &FltSem =
5961 Op->getType()->getScalarType()->getFltSemantics();
5963 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5964
5965 if (Op->getOperand(0) == Op->getOperand(1) &&
5966 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5967 // X / X is always exactly 1.0 or a NaN.
5968 Known.KnownFPClasses = fcNan | fcPosNormal;
5969
5970 if (!WantNan)
5971 break;
5972
5973 KnownFPClass KnownSrc;
5974 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5975 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5976 Depth + 1);
5977
5978 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
5979 break;
5980 }
5981
5982 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5983 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
5984 if (!WantNan && !WantNegative && !WantPositive)
5985 break;
5986
5987 KnownFPClass KnownLHS, KnownRHS;
5988 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
5989 Q, Depth + 1);
5990
5991 bool KnowSomethingUseful =
5992 KnownRHS.isKnownNeverNaN() ||
5995
5996 if (KnowSomethingUseful)
5997 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5998 Q, Depth + 1);
5999
6000 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6001 break;
6002 }
6003 case Instruction::FRem: {
6004 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6005
6006 Known.knownNot(fcInf);
6007
6008 const Function *F = cast<Instruction>(Op)->getFunction();
6010 F ? F->getDenormalMode(
6011 Op->getType()->getScalarType()->getFltSemantics())
6013
6014 if (Op->getOperand(0) == Op->getOperand(1) &&
6015 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6016 // X % X is always exactly [+-]0.0 or a NaN.
6017 Known.KnownFPClasses = fcNan | fcZero;
6018
6019 if (!WantNan)
6020 break;
6021
6022 KnownFPClass KnownSrc;
6023 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6024 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6025 Depth + 1);
6026
6027 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6028 break;
6029 }
6030
6031 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6032 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6033 if (!WantNan && !WantNegative && !WantPositive)
6034 break;
6035
6036 KnownFPClass KnownLHS, KnownRHS;
6037 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6038 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6039 Depth + 1);
6040
6041 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6042 KnownRHS.isKnownNever(fcNegative) ||
6043 KnownRHS.isKnownNever(fcPositive);
6044
6045 if (KnowSomethingUseful || WantPositive)
6046 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6047 Q, Depth + 1);
6048
6049 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6050
6051 break;
6052 }
6053 case Instruction::FPExt: {
6054 KnownFPClass KnownSrc;
6055 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6056 KnownSrc, Q, Depth + 1);
6057
6058 const fltSemantics &DstTy =
6059 Op->getType()->getScalarType()->getFltSemantics();
6060 const fltSemantics &SrcTy =
6061 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6062
6063 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6064 break;
6065 }
6066 case Instruction::FPTrunc: {
6067 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6068 Depth);
6069 break;
6070 }
6071 case Instruction::SIToFP:
6072 case Instruction::UIToFP: {
6073 // Cannot produce nan
6074 Known.knownNot(fcNan);
6075
6076 // Integers cannot be subnormal
6077 Known.knownNot(fcSubnormal);
6078
6079 // sitofp and uitofp turn into +0.0 for zero.
6080 Known.knownNot(fcNegZero);
6081
6082 // UIToFP is always non-negative regardless of known bits.
6083 if (Op->getOpcode() == Instruction::UIToFP)
6084 Known.signBitMustBeZero();
6085
6086 // Only compute known bits if we can learn something useful from them.
6087 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6088 break;
6089
6090 KnownBits IntKnown =
6091 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6092
6093 // If the integer is non-zero, the result cannot be +0.0
6094 if (IntKnown.isNonZero())
6095 Known.knownNot(fcPosZero);
6096
6097 if (Op->getOpcode() == Instruction::SIToFP) {
6098 // If the signed integer is known non-negative, the result is
6099 // non-negative. If the signed integer is known negative, the result is
6100 // negative.
6101 if (IntKnown.isNonNegative()) {
6102 Known.signBitMustBeZero();
6103 } else if (IntKnown.isNegative()) {
6104 Known.signBitMustBeOne();
6105 }
6106 }
6107
6108 // Guard kept for ilogb()
6109 if (InterestedClasses & fcInf) {
6110 // Get width of largest magnitude integer known.
6111 // This still works for a signed minimum value because the largest FP
6112 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6113 int IntSize = IntKnown.getBitWidth();
6114 if (Op->getOpcode() == Instruction::UIToFP)
6115 IntSize -= IntKnown.countMinLeadingZeros();
6116 else if (Op->getOpcode() == Instruction::SIToFP)
6117 IntSize -= IntKnown.countMinSignBits();
6118
6119 // If the exponent of the largest finite FP value can hold the largest
6120 // integer, the result of the cast must be finite.
6121 Type *FPTy = Op->getType()->getScalarType();
6122 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6123 Known.knownNot(fcInf);
6124 }
6125
6126 break;
6127 }
6128 case Instruction::ExtractElement: {
6129 // Look through extract element. If the index is non-constant or
6130 // out-of-range demand all elements, otherwise just the extracted element.
6131 const Value *Vec = Op->getOperand(0);
6132
6133 APInt DemandedVecElts;
6134 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6135 unsigned NumElts = VecTy->getNumElements();
6136 DemandedVecElts = APInt::getAllOnes(NumElts);
6137 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6138 if (CIdx && CIdx->getValue().ult(NumElts))
6139 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6140 } else {
6141 DemandedVecElts = APInt(1, 1);
6142 }
6143
6144 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6145 Q, Depth + 1);
6146 }
6147 case Instruction::InsertElement: {
6148 if (isa<ScalableVectorType>(Op->getType()))
6149 return;
6150
6151 const Value *Vec = Op->getOperand(0);
6152 const Value *Elt = Op->getOperand(1);
6153 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6154 unsigned NumElts = DemandedElts.getBitWidth();
6155 APInt DemandedVecElts = DemandedElts;
6156 bool NeedsElt = true;
6157 // If we know the index we are inserting to, clear it from Vec check.
6158 if (CIdx && CIdx->getValue().ult(NumElts)) {
6159 DemandedVecElts.clearBit(CIdx->getZExtValue());
6160 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6161 }
6162
6163 // Do we demand the inserted element?
6164 if (NeedsElt) {
6165 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6166 // If we don't know any bits, early out.
6167 if (Known.isUnknown())
6168 break;
6169 } else {
6170 Known.KnownFPClasses = fcNone;
6171 }
6172
6173 // Do we need anymore elements from Vec?
6174 if (!DemandedVecElts.isZero()) {
6175 KnownFPClass Known2;
6176 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6177 Depth + 1);
6178 Known |= Known2;
6179 }
6180
6181 break;
6182 }
6183 case Instruction::ShuffleVector: {
6184 // Handle vector splat idiom
6185 if (Value *Splat = getSplatValue(V)) {
6186 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6187 break;
6188 }
6189
6190 // For undef elements, we don't know anything about the common state of
6191 // the shuffle result.
6192 APInt DemandedLHS, DemandedRHS;
6193 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6194 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6195 return;
6196
6197 if (!!DemandedLHS) {
6198 const Value *LHS = Shuf->getOperand(0);
6199 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6200 Depth + 1);
6201
6202 // If we don't know any bits, early out.
6203 if (Known.isUnknown())
6204 break;
6205 } else {
6206 Known.KnownFPClasses = fcNone;
6207 }
6208
6209 if (!!DemandedRHS) {
6210 KnownFPClass Known2;
6211 const Value *RHS = Shuf->getOperand(1);
6212 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6213 Depth + 1);
6214 Known |= Known2;
6215 }
6216
6217 break;
6218 }
6219 case Instruction::ExtractValue: {
6220 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6221 ArrayRef<unsigned> Indices = Extract->getIndices();
6222 const Value *Src = Extract->getAggregateOperand();
6223 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6224 Indices[0] == 0) {
6225 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6226 switch (II->getIntrinsicID()) {
6227 case Intrinsic::frexp: {
6228 Known.knownNot(fcSubnormal);
6229
6230 KnownFPClass KnownSrc;
6231 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6232 InterestedClasses, KnownSrc, Q, Depth + 1);
6233
6234 const Function *F = cast<Instruction>(Op)->getFunction();
6235 const fltSemantics &FltSem =
6236 Op->getType()->getScalarType()->getFltSemantics();
6237
6239 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6240 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6241 return;
6242 }
6243 default:
6244 break;
6245 }
6246 }
6247 }
6248
6249 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6250 Depth + 1);
6251 break;
6252 }
6253 case Instruction::PHI: {
6254 const PHINode *P = cast<PHINode>(Op);
6255 // Unreachable blocks may have zero-operand PHI nodes.
6256 if (P->getNumIncomingValues() == 0)
6257 break;
6258
6259 // Otherwise take the unions of the known bit sets of the operands,
6260 // taking conservative care to avoid excessive recursion.
6261 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6262
6263 if (Depth < PhiRecursionLimit) {
6264 // Skip if every incoming value references to ourself.
6265 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6266 break;
6267
6268 bool First = true;
6269
6270 for (const Use &U : P->operands()) {
6271 Value *IncValue;
6272 Instruction *CxtI;
6273 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6274 // Skip direct self references.
6275 if (IncValue == P)
6276 continue;
6277
6278 KnownFPClass KnownSrc;
6279 // Recurse, but cap the recursion to two levels, because we don't want
6280 // to waste time spinning around in loops. We need at least depth 2 to
6281 // detect known sign bits.
6282 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6284 PhiRecursionLimit);
6285
6286 if (First) {
6287 Known = KnownSrc;
6288 First = false;
6289 } else {
6290 Known |= KnownSrc;
6291 }
6292
6293 if (Known.KnownFPClasses == fcAllFlags)
6294 break;
6295 }
6296 }
6297
6298 // Look for the case of a for loop which has a positive
6299 // initial value and is incremented by a squared value.
6300 // This will propagate sign information out of such loops.
6301 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6302 break;
6303 for (unsigned I = 0; I < 2; I++) {
6304 Value *RecurValue = P->getIncomingValue(1 - I);
6306 if (!II)
6307 continue;
6308 Value *R, *L, *Init;
6309 PHINode *PN;
6311 PN == P) {
6312 switch (II->getIntrinsicID()) {
6313 case Intrinsic::fma:
6314 case Intrinsic::fmuladd: {
6315 KnownFPClass KnownStart;
6316 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6317 Q, Depth + 1);
6318 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6319 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6321 break;
6322 }
6323 }
6324 }
6325 }
6326 break;
6327 }
6328 case Instruction::BitCast: {
6329 const Value *Src;
6330 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6331 !Src->getType()->isIntOrIntVectorTy())
6332 break;
6333
6334 const Type *Ty = Op->getType();
6335
6336 Value *CastLHS, *CastRHS;
6337
6338 // Match bitcast(umax(bitcast(a), bitcast(b)))
6339 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6340 m_BitCast(m_Value(CastRHS)))) &&
6341 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6342 KnownFPClass KnownLHS, KnownRHS;
6343 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6344 Depth + 1);
6345 if (!KnownRHS.isUnknown()) {
6346 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6347 Q, Depth + 1);
6348 Known = KnownLHS | KnownRHS;
6349 }
6350
6351 return;
6352 }
6353
6354 const Type *EltTy = Ty->getScalarType();
6355 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6356 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6357
6359 break;
6360 }
6361 default:
6362 break;
6363 }
6364}
6365
6367 const APInt &DemandedElts,
6368 FPClassTest InterestedClasses,
6369 const SimplifyQuery &SQ,
6370 unsigned Depth) {
6371 KnownFPClass KnownClasses;
6372 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6373 Depth);
6374 return KnownClasses;
6375}
6376
6378 FPClassTest InterestedClasses,
6379 const SimplifyQuery &SQ,
6380 unsigned Depth) {
6382 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6383 return Known;
6384}
6385
6387 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6388 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6389 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6390 return computeKnownFPClass(V, InterestedClasses,
6391 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6392 Depth);
6393}
6394
6396llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6397 FastMathFlags FMF, FPClassTest InterestedClasses,
6398 const SimplifyQuery &SQ, unsigned Depth) {
6399 if (FMF.noNaNs())
6400 InterestedClasses &= ~fcNan;
6401 if (FMF.noInfs())
6402 InterestedClasses &= ~fcInf;
6403
6404 KnownFPClass Result =
6405 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6406
6407 if (FMF.noNaNs())
6408 Result.KnownFPClasses &= ~fcNan;
6409 if (FMF.noInfs())
6410 Result.KnownFPClasses &= ~fcInf;
6411 return Result;
6412}
6413
6415 FPClassTest InterestedClasses,
6416 const SimplifyQuery &SQ,
6417 unsigned Depth) {
6418 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6419 APInt DemandedElts =
6420 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6421 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6422 Depth);
6423}
6424
6426 unsigned Depth) {
6428 return Known.isKnownNeverNegZero();
6429}
6430
6432 unsigned Depth) {
6435 return Known.cannotBeOrderedLessThanZero();
6436}
6437
6439 unsigned Depth) {
6441 return Known.isKnownNeverInfinity();
6442}
6443
6444/// Return true if the floating-point value can never contain a NaN or infinity.
6446 unsigned Depth) {
6448 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6449}
6450
6451/// Return true if the floating-point scalar value is not a NaN or if the
6452/// floating-point vector value has no NaN elements. Return false if a value
6453/// could ever be NaN.
6455 unsigned Depth) {
6457 return Known.isKnownNeverNaN();
6458}
6459
6460/// Return false if we can prove that the specified FP value's sign bit is 0.
6461/// Return true if we can prove that the specified FP value's sign bit is 1.
6462/// Otherwise return std::nullopt.
6463std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6464 const SimplifyQuery &SQ,
6465 unsigned Depth) {
6467 return Known.SignBit;
6468}
6469
6471 auto *User = cast<Instruction>(U.getUser());
6472 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6473 if (FPOp->hasNoSignedZeros())
6474 return true;
6475 }
6476
6477 switch (User->getOpcode()) {
6478 case Instruction::FPToSI:
6479 case Instruction::FPToUI:
6480 return true;
6481 case Instruction::FCmp:
6482 // fcmp treats both positive and negative zero as equal.
6483 return true;
6484 case Instruction::Call:
6485 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6486 switch (II->getIntrinsicID()) {
6487 case Intrinsic::fabs:
6488 return true;
6489 case Intrinsic::copysign:
6490 return U.getOperandNo() == 0;
6491 case Intrinsic::is_fpclass: {
6492 auto Test =
6493 static_cast<FPClassTest>(
6494 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6497 }
6498 default:
6499 return false;
6500 }
6501 }
6502 return false;
6503 default:
6504 return false;
6505 }
6506}
6507
6509 auto *User = cast<Instruction>(U.getUser());
6510 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6511 if (FPOp->hasNoNaNs())
6512 return true;
6513 }
6514
6515 switch (User->getOpcode()) {
6516 case Instruction::FPToSI:
6517 case Instruction::FPToUI:
6518 return true;
6519 // Proper FP math operations ignore the sign bit of NaN.
6520 case Instruction::FAdd:
6521 case Instruction::FSub:
6522 case Instruction::FMul:
6523 case Instruction::FDiv:
6524 case Instruction::FRem:
6525 case Instruction::FPTrunc:
6526 case Instruction::FPExt:
6527 case Instruction::FCmp:
6528 return true;
6529 // Bitwise FP operations should preserve the sign bit of NaN.
6530 case Instruction::FNeg:
6531 case Instruction::Select:
6532 case Instruction::PHI:
6533 return false;
6534 case Instruction::Ret:
6535 return User->getFunction()->getAttributes().getRetNoFPClass() &
6537 case Instruction::Call:
6538 case Instruction::Invoke: {
6539 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6540 switch (II->getIntrinsicID()) {
6541 case Intrinsic::fabs:
6542 return true;
6543 case Intrinsic::copysign:
6544 return U.getOperandNo() == 0;
6545 // Other proper FP math intrinsics ignore the sign bit of NaN.
6546 case Intrinsic::maxnum:
6547 case Intrinsic::minnum:
6548 case Intrinsic::maximum:
6549 case Intrinsic::minimum:
6550 case Intrinsic::maximumnum:
6551 case Intrinsic::minimumnum:
6552 case Intrinsic::canonicalize:
6553 case Intrinsic::fma:
6554 case Intrinsic::fmuladd:
6555 case Intrinsic::sqrt:
6556 case Intrinsic::pow:
6557 case Intrinsic::powi:
6558 case Intrinsic::fptoui_sat:
6559 case Intrinsic::fptosi_sat:
6560 case Intrinsic::is_fpclass:
6561 return true;
6562 default:
6563 return false;
6564 }
6565 }
6566
6567 FPClassTest NoFPClass =
6568 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6569 return NoFPClass & FPClassTest::fcNan;
6570 }
6571 default:
6572 return false;
6573 }
6574}
6575
6577 FastMathFlags FMF) {
6578 if (isa<PoisonValue>(V))
6579 return true;
6580 if (isa<UndefValue>(V))
6581 return false;
6582
6583 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6584 return true;
6585
6587 if (!I)
6588 return false;
6589
6590 switch (I->getOpcode()) {
6591 case Instruction::SIToFP:
6592 case Instruction::UIToFP:
6593 // TODO: Could check nofpclass(inf) on incoming argument
6594 if (FMF.noInfs())
6595 return true;
6596
6597 // Need to check int size cannot produce infinity, which computeKnownFPClass
6598 // knows how to do already.
6599 return isKnownNeverInfinity(I, SQ);
6600 case Instruction::Call: {
6601 const CallInst *CI = cast<CallInst>(I);
6602 switch (CI->getIntrinsicID()) {
6603 case Intrinsic::trunc:
6604 case Intrinsic::floor:
6605 case Intrinsic::ceil:
6606 case Intrinsic::rint:
6607 case Intrinsic::nearbyint:
6608 case Intrinsic::round:
6609 case Intrinsic::roundeven:
6610 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6611 default:
6612 break;
6613 }
6614
6615 break;
6616 }
6617 default:
6618 break;
6619 }
6620
6621 return false;
6622}
6623
6625
6626 // All byte-wide stores are splatable, even of arbitrary variables.
6627 if (V->getType()->isIntegerTy(8))
6628 return V;
6629
6630 LLVMContext &Ctx = V->getContext();
6631
6632 // Undef don't care.
6633 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6634 if (isa<UndefValue>(V))
6635 return UndefInt8;
6636
6637 // Return poison for zero-sized type.
6638 if (DL.getTypeStoreSize(V->getType()).isZero())
6639 return PoisonValue::get(Type::getInt8Ty(Ctx));
6640
6642 if (!C) {
6643 // Conceptually, we could handle things like:
6644 // %a = zext i8 %X to i16
6645 // %b = shl i16 %a, 8
6646 // %c = or i16 %a, %b
6647 // but until there is an example that actually needs this, it doesn't seem
6648 // worth worrying about.
6649 return nullptr;
6650 }
6651
6652 // Handle 'null' ConstantArrayZero etc.
6653 if (C->isNullValue())
6655
6656 // Constant floating-point values can be handled as integer values if the
6657 // corresponding integer value is "byteable". An important case is 0.0.
6658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6659 Type *ScalarTy = CFP->getType()->getScalarType();
6660 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6661 return isBytewiseValue(
6662 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6663
6664 // Don't handle long double formats, which have strange constraints.
6665 return nullptr;
6666 }
6667
6668 // We can handle constant integers that are multiple of 8 bits.
6669 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6670 if (CI->getBitWidth() % 8 == 0) {
6671 if (!CI->getValue().isSplat(8))
6672 return nullptr;
6673 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6674 }
6675 }
6676
6677 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6678 if (CE->getOpcode() == Instruction::IntToPtr) {
6679 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6680 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6682 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6683 return isBytewiseValue(Op, DL);
6684 }
6685 }
6686 }
6687
6688 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6689 if (LHS == RHS)
6690 return LHS;
6691 if (!LHS || !RHS)
6692 return nullptr;
6693 if (LHS == UndefInt8)
6694 return RHS;
6695 if (RHS == UndefInt8)
6696 return LHS;
6697 return nullptr;
6698 };
6699
6701 Value *Val = UndefInt8;
6702 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6703 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6704 return nullptr;
6705 return Val;
6706 }
6707
6709 Value *Val = UndefInt8;
6710 for (Value *Op : C->operands())
6711 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6712 return nullptr;
6713 return Val;
6714 }
6715
6716 // Don't try to handle the handful of other constants.
6717 return nullptr;
6718}
6719
6720// This is the recursive version of BuildSubAggregate. It takes a few different
6721// arguments. Idxs is the index within the nested struct From that we are
6722// looking at now (which is of type IndexedType). IdxSkip is the number of
6723// indices from Idxs that should be left out when inserting into the resulting
6724// struct. To is the result struct built so far, new insertvalue instructions
6725// build on that.
6726static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6728 unsigned IdxSkip,
6729 BasicBlock::iterator InsertBefore) {
6730 StructType *STy = dyn_cast<StructType>(IndexedType);
6731 if (STy) {
6732 // Save the original To argument so we can modify it
6733 Value *OrigTo = To;
6734 // General case, the type indexed by Idxs is a struct
6735 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6736 // Process each struct element recursively
6737 Idxs.push_back(i);
6738 Value *PrevTo = To;
6739 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6740 InsertBefore);
6741 Idxs.pop_back();
6742 if (!To) {
6743 // Couldn't find any inserted value for this index? Cleanup
6744 while (PrevTo != OrigTo) {
6746 PrevTo = Del->getAggregateOperand();
6747 Del->eraseFromParent();
6748 }
6749 // Stop processing elements
6750 break;
6751 }
6752 }
6753 // If we successfully found a value for each of our subaggregates
6754 if (To)
6755 return To;
6756 }
6757 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6758 // the struct's elements had a value that was inserted directly. In the latter
6759 // case, perhaps we can't determine each of the subelements individually, but
6760 // we might be able to find the complete struct somewhere.
6761
6762 // Find the value that is at that particular spot
6763 Value *V = FindInsertedValue(From, Idxs);
6764
6765 if (!V)
6766 return nullptr;
6767
6768 // Insert the value in the new (sub) aggregate
6769 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6770 InsertBefore);
6771}
6772
6773// This helper takes a nested struct and extracts a part of it (which is again a
6774// struct) into a new value. For example, given the struct:
6775// { a, { b, { c, d }, e } }
6776// and the indices "1, 1" this returns
6777// { c, d }.
6778//
6779// It does this by inserting an insertvalue for each element in the resulting
6780// struct, as opposed to just inserting a single struct. This will only work if
6781// each of the elements of the substruct are known (ie, inserted into From by an
6782// insertvalue instruction somewhere).
6783//
6784// All inserted insertvalue instructions are inserted before InsertBefore
6786 BasicBlock::iterator InsertBefore) {
6787 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6788 idx_range);
6789 Value *To = PoisonValue::get(IndexedType);
6790 SmallVector<unsigned, 10> Idxs(idx_range);
6791 unsigned IdxSkip = Idxs.size();
6792
6793 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6794}
6795
6796/// Given an aggregate and a sequence of indices, see if the scalar value
6797/// indexed is already around as a register, for example if it was inserted
6798/// directly into the aggregate.
6799///
6800/// If InsertBefore is not null, this function will duplicate (modified)
6801/// insertvalues when a part of a nested struct is extracted.
6802Value *
6804 std::optional<BasicBlock::iterator> InsertBefore) {
6805 // Nothing to index? Just return V then (this is useful at the end of our
6806 // recursion).
6807 if (idx_range.empty())
6808 return V;
6809 // We have indices, so V should have an indexable type.
6810 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6811 "Not looking at a struct or array?");
6812 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6813 "Invalid indices for type?");
6814
6815 if (Constant *C = dyn_cast<Constant>(V)) {
6816 C = C->getAggregateElement(idx_range[0]);
6817 if (!C) return nullptr;
6818 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6819 }
6820
6822 // Loop the indices for the insertvalue instruction in parallel with the
6823 // requested indices
6824 const unsigned *req_idx = idx_range.begin();
6825 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6826 i != e; ++i, ++req_idx) {
6827 if (req_idx == idx_range.end()) {
6828 // We can't handle this without inserting insertvalues
6829 if (!InsertBefore)
6830 return nullptr;
6831
6832 // The requested index identifies a part of a nested aggregate. Handle
6833 // this specially. For example,
6834 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6835 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6836 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6837 // This can be changed into
6838 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6839 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6840 // which allows the unused 0,0 element from the nested struct to be
6841 // removed.
6842 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6843 *InsertBefore);
6844 }
6845
6846 // This insert value inserts something else than what we are looking for.
6847 // See if the (aggregate) value inserted into has the value we are
6848 // looking for, then.
6849 if (*req_idx != *i)
6850 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6851 InsertBefore);
6852 }
6853 // If we end up here, the indices of the insertvalue match with those
6854 // requested (though possibly only partially). Now we recursively look at
6855 // the inserted value, passing any remaining indices.
6856 return FindInsertedValue(I->getInsertedValueOperand(),
6857 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6858 }
6859
6861 // If we're extracting a value from an aggregate that was extracted from
6862 // something else, we can extract from that something else directly instead.
6863 // However, we will need to chain I's indices with the requested indices.
6864
6865 // Calculate the number of indices required
6866 unsigned size = I->getNumIndices() + idx_range.size();
6867 // Allocate some space to put the new indices in
6869 Idxs.reserve(size);
6870 // Add indices from the extract value instruction
6871 Idxs.append(I->idx_begin(), I->idx_end());
6872
6873 // Add requested indices
6874 Idxs.append(idx_range.begin(), idx_range.end());
6875
6876 assert(Idxs.size() == size
6877 && "Number of indices added not correct?");
6878
6879 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6880 }
6881 // Otherwise, we don't know (such as, extracting from a function return value
6882 // or load instruction)
6883 return nullptr;
6884}
6885
6886// If V refers to an initialized global constant, set Slice either to
6887// its initializer if the size of its elements equals ElementSize, or,
6888// for ElementSize == 8, to its representation as an array of unsiged
6889// char. Return true on success.
6890// Offset is in the unit "nr of ElementSize sized elements".
6893 unsigned ElementSize, uint64_t Offset) {
6894 assert(V && "V should not be null.");
6895 assert((ElementSize % 8) == 0 &&
6896 "ElementSize expected to be a multiple of the size of a byte.");
6897 unsigned ElementSizeInBytes = ElementSize / 8;
6898
6899 // Drill down into the pointer expression V, ignoring any intervening
6900 // casts, and determine the identity of the object it references along
6901 // with the cumulative byte offset into it.
6902 const GlobalVariable *GV =
6904 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6905 // Fail if V is not based on constant global object.
6906 return false;
6907
6908 const DataLayout &DL = GV->getDataLayout();
6909 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6910
6911 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6912 /*AllowNonInbounds*/ true))
6913 // Fail if a constant offset could not be determined.
6914 return false;
6915
6916 uint64_t StartIdx = Off.getLimitedValue();
6917 if (StartIdx == UINT64_MAX)
6918 // Fail if the constant offset is excessive.
6919 return false;
6920
6921 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6922 // elements. Simply bail out if that isn't possible.
6923 if ((StartIdx % ElementSizeInBytes) != 0)
6924 return false;
6925
6926 Offset += StartIdx / ElementSizeInBytes;
6927 ConstantDataArray *Array = nullptr;
6928 ArrayType *ArrayTy = nullptr;
6929
6930 if (GV->getInitializer()->isNullValue()) {
6931 Type *GVTy = GV->getValueType();
6932 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6933 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6934
6935 Slice.Array = nullptr;
6936 Slice.Offset = 0;
6937 // Return an empty Slice for undersized constants to let callers
6938 // transform even undefined library calls into simpler, well-defined
6939 // expressions. This is preferable to making the calls although it
6940 // prevents sanitizers from detecting such calls.
6941 Slice.Length = Length < Offset ? 0 : Length - Offset;
6942 return true;
6943 }
6944
6945 auto *Init = const_cast<Constant *>(GV->getInitializer());
6946 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6947 Type *InitElTy = ArrayInit->getElementType();
6948 if (InitElTy->isIntegerTy(ElementSize)) {
6949 // If Init is an initializer for an array of the expected type
6950 // and size, use it as is.
6951 Array = ArrayInit;
6952 ArrayTy = ArrayInit->getType();
6953 }
6954 }
6955
6956 if (!Array) {
6957 if (ElementSize != 8)
6958 // TODO: Handle conversions to larger integral types.
6959 return false;
6960
6961 // Otherwise extract the portion of the initializer starting
6962 // at Offset as an array of bytes, and reset Offset.
6964 if (!Init)
6965 return false;
6966
6967 Offset = 0;
6969 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6970 }
6971
6972 uint64_t NumElts = ArrayTy->getArrayNumElements();
6973 if (Offset > NumElts)
6974 return false;
6975
6976 Slice.Array = Array;
6977 Slice.Offset = Offset;
6978 Slice.Length = NumElts - Offset;
6979 return true;
6980}
6981
6982/// Extract bytes from the initializer of the constant array V, which need
6983/// not be a nul-terminated string. On success, store the bytes in Str and
6984/// return true. When TrimAtNul is set, Str will contain only the bytes up
6985/// to but not including the first nul. Return false on failure.
6987 bool TrimAtNul) {
6989 if (!getConstantDataArrayInfo(V, Slice, 8))
6990 return false;
6991
6992 if (Slice.Array == nullptr) {
6993 if (TrimAtNul) {
6994 // Return a nul-terminated string even for an empty Slice. This is
6995 // safe because all existing SimplifyLibcalls callers require string
6996 // arguments and the behavior of the functions they fold is undefined
6997 // otherwise. Folding the calls this way is preferable to making
6998 // the undefined library calls, even though it prevents sanitizers
6999 // from reporting such calls.
7000 Str = StringRef();
7001 return true;
7002 }
7003 if (Slice.Length == 1) {
7004 Str = StringRef("", 1);
7005 return true;
7006 }
7007 // We cannot instantiate a StringRef as we do not have an appropriate string
7008 // of 0s at hand.
7009 return false;
7010 }
7011
7012 // Start out with the entire array in the StringRef.
7013 Str = Slice.Array->getAsString();
7014 // Skip over 'offset' bytes.
7015 Str = Str.substr(Slice.Offset);
7016
7017 if (TrimAtNul) {
7018 // Trim off the \0 and anything after it. If the array is not nul
7019 // terminated, we just return the whole end of string. The client may know
7020 // some other way that the string is length-bound.
7021 Str = Str.substr(0, Str.find('\0'));
7022 }
7023 return true;
7024}
7025
7026// These next two are very similar to the above, but also look through PHI
7027// nodes.
7028// TODO: See if we can integrate these two together.
7029
7030/// If we can compute the length of the string pointed to by
7031/// the specified pointer, return 'len+1'. If we can't, return 0.
7034 unsigned CharSize) {
7035 // Look through noop bitcast instructions.
7036 V = V->stripPointerCasts();
7037
7038 // If this is a PHI node, there are two cases: either we have already seen it
7039 // or we haven't.
7040 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7041 if (!PHIs.insert(PN).second)
7042 return ~0ULL; // already in the set.
7043
7044 // If it was new, see if all the input strings are the same length.
7045 uint64_t LenSoFar = ~0ULL;
7046 for (Value *IncValue : PN->incoming_values()) {
7047 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7048 if (Len == 0) return 0; // Unknown length -> unknown.
7049
7050 if (Len == ~0ULL) continue;
7051
7052 if (Len != LenSoFar && LenSoFar != ~0ULL)
7053 return 0; // Disagree -> unknown.
7054 LenSoFar = Len;
7055 }
7056
7057 // Success, all agree.
7058 return LenSoFar;
7059 }
7060
7061 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7062 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7063 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7064 if (Len1 == 0) return 0;
7065 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7066 if (Len2 == 0) return 0;
7067 if (Len1 == ~0ULL) return Len2;
7068 if (Len2 == ~0ULL) return Len1;
7069 if (Len1 != Len2) return 0;
7070 return Len1;
7071 }
7072
7073 // Otherwise, see if we can read the string.
7075 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7076 return 0;
7077
7078 if (Slice.Array == nullptr)
7079 // Zeroinitializer (including an empty one).
7080 return 1;
7081
7082 // Search for the first nul character. Return a conservative result even
7083 // when there is no nul. This is safe since otherwise the string function
7084 // being folded such as strlen is undefined, and can be preferable to
7085 // making the undefined library call.
7086 unsigned NullIndex = 0;
7087 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7088 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7089 break;
7090 }
7091
7092 return NullIndex + 1;
7093}
7094
7095/// If we can compute the length of the string pointed to by
7096/// the specified pointer, return 'len+1'. If we can't, return 0.
7097uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7098 if (!V->getType()->isPointerTy())
7099 return 0;
7100
7102 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7103 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7104 // an empty string as a length.
7105 return Len == ~0ULL ? 1 : Len;
7106}
7107
7108const Value *
7110 bool MustPreserveOffset) {
7111 assert(Call &&
7112 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7113 if (const Value *RV = Call->getReturnedArgOperand())
7114 return RV;
7115 // This can be used only as a aliasing property.
7117 Call, MustPreserveOffset))
7118 return Call->getArgOperand(0);
7119 return nullptr;
7120}
7121
7123 const CallBase *Call, bool MustPreserveOffset) {
7124 switch (Call->getIntrinsicID()) {
7125 case Intrinsic::launder_invariant_group:
7126 case Intrinsic::strip_invariant_group:
7127 case Intrinsic::aarch64_irg:
7128 case Intrinsic::aarch64_tagp:
7129 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7130 // input pointer (and thus preserves the byte offset, which is the property
7131 // the MustPreserveOffset flag selects). However, it will not necessarily
7132 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7133 // descriptor", which has "all loads return 0, all stores are dropped"
7134 // semantics. Given the context of this intrinsic list, no one should be
7135 // relying on such a strict bit-exact null mapping (and, at time of
7136 // writing, they are not), but we document this fact out of an abundance
7137 // of caution.
7138 case Intrinsic::amdgcn_make_buffer_rsrc:
7139 return true;
7140 case Intrinsic::ptrmask:
7141 return !MustPreserveOffset;
7142 case Intrinsic::threadlocal_address:
7143 // The underlying variable changes with thread ID. The Thread ID may change
7144 // at coroutine suspend points.
7145 return !Call->getParent()->getParent()->isPresplitCoroutine();
7146 default:
7147 return false;
7148 }
7149}
7150
7151/// \p PN defines a loop-variant pointer to an object. Check if the
7152/// previous iteration of the loop was referring to the same object as \p PN.
7154 const LoopInfo *LI) {
7155 // Find the loop-defined value.
7156 Loop *L = LI->getLoopFor(PN->getParent());
7157 if (PN->getNumIncomingValues() != 2)
7158 return true;
7159
7160 // Find the value from previous iteration.
7161 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7162 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7163 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7164 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7165 return true;
7166
7167 // If a new pointer is loaded in the loop, the pointer references a different
7168 // object in every iteration. E.g.:
7169 // for (i)
7170 // int *p = a[i];
7171 // ...
7172 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7173 if (!L->isLoopInvariant(Load->getPointerOperand()))
7174 return false;
7175 return true;
7176}
7177
7178const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7179 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7180 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7181 const Value *PtrOp = GEP->getPointerOperand();
7182 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7183 return V;
7184 V = PtrOp;
7185 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7186 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7187 Value *NewV = cast<Operator>(V)->getOperand(0);
7188 if (!NewV->getType()->isPointerTy())
7189 return V;
7190 V = NewV;
7191 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7192 if (GA->isInterposable())
7193 return V;
7194 V = GA->getAliasee();
7195 } else {
7196 if (auto *PHI = dyn_cast<PHINode>(V)) {
7197 // Look through single-arg phi nodes created by LCSSA.
7198 if (PHI->getNumIncomingValues() == 1) {
7199 V = PHI->getIncomingValue(0);
7200 continue;
7201 }
7202 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7203 // CaptureTracking can know about special capturing properties of some
7204 // intrinsics like launder.invariant.group, that can't be expressed with
7205 // the attributes, but have properties like returning aliasing pointer.
7206 // Because some analysis may assume that nocaptured pointer is not
7207 // returned from some special intrinsic (because function would have to
7208 // be marked with returns attribute), it is crucial to use this function
7209 // because it should be in sync with CaptureTracking. Not using it may
7210 // cause weird miscompilations where 2 aliasing pointers are assumed to
7211 // noalias.
7213 Call, /*MustPreserveOffset=*/false)) {
7214 V = RP;
7215 continue;
7216 }
7217 }
7218
7219 return V;
7220 }
7221 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7222 }
7223 return V;
7224}
7225
7228 const LoopInfo *LI, unsigned MaxLookup) {
7231 Worklist.push_back(V);
7232 do {
7233 const Value *P = Worklist.pop_back_val();
7234 P = getUnderlyingObject(P, MaxLookup);
7235
7236 if (!Visited.insert(P).second)
7237 continue;
7238
7239 if (auto *SI = dyn_cast<SelectInst>(P)) {
7240 Worklist.push_back(SI->getTrueValue());
7241 Worklist.push_back(SI->getFalseValue());
7242 continue;
7243 }
7244
7245 if (auto *PN = dyn_cast<PHINode>(P)) {
7246 // If this PHI changes the underlying object in every iteration of the
7247 // loop, don't look through it. Consider:
7248 // int **A;
7249 // for (i) {
7250 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7251 // Curr = A[i];
7252 // *Prev, *Curr;
7253 //
7254 // Prev is tracking Curr one iteration behind so they refer to different
7255 // underlying objects.
7256 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7258 append_range(Worklist, PN->incoming_values());
7259 else
7260 Objects.push_back(P);
7261 continue;
7262 }
7263
7264 Objects.push_back(P);
7265 } while (!Worklist.empty());
7266}
7267
7269 const unsigned MaxVisited = 8;
7270
7273 Worklist.push_back(V);
7274 const Value *Object = nullptr;
7275 // Used as fallback if we can't find a common underlying object through
7276 // recursion.
7277 bool First = true;
7278 const Value *FirstObject = getUnderlyingObject(V);
7279 do {
7280 const Value *P = Worklist.pop_back_val();
7281 P = First ? FirstObject : getUnderlyingObject(P);
7282 First = false;
7283
7284 if (!Visited.insert(P).second)
7285 continue;
7286
7287 if (Visited.size() == MaxVisited)
7288 return FirstObject;
7289
7290 if (auto *SI = dyn_cast<SelectInst>(P)) {
7291 Worklist.push_back(SI->getTrueValue());
7292 Worklist.push_back(SI->getFalseValue());
7293 continue;
7294 }
7295
7296 if (auto *PN = dyn_cast<PHINode>(P)) {
7297 append_range(Worklist, PN->incoming_values());
7298 continue;
7299 }
7300
7301 if (!Object)
7302 Object = P;
7303 else if (Object != P)
7304 return FirstObject;
7305 } while (!Worklist.empty());
7306
7307 return Object ? Object : FirstObject;
7308}
7309
7310/// This is the function that does the work of looking through basic
7311/// ptrtoint+arithmetic+inttoptr sequences.
7312static const Value *getUnderlyingObjectFromInt(const Value *V) {
7313 do {
7314 if (const Operator *U = dyn_cast<Operator>(V)) {
7315 // If we find a ptrtoint, we can transfer control back to the
7316 // regular getUnderlyingObjectFromInt.
7317 if (U->getOpcode() == Instruction::PtrToInt)
7318 return U->getOperand(0);
7319 // If we find an add of a constant, a multiplied value, or a phi, it's
7320 // likely that the other operand will lead us to the base
7321 // object. We don't have to worry about the case where the
7322 // object address is somehow being computed by the multiply,
7323 // because our callers only care when the result is an
7324 // identifiable object.
7325 if (U->getOpcode() != Instruction::Add ||
7326 (!isa<ConstantInt>(U->getOperand(1)) &&
7327 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7328 !isa<PHINode>(U->getOperand(1))))
7329 return V;
7330 V = U->getOperand(0);
7331 } else {
7332 return V;
7333 }
7334 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7335 } while (true);
7336}
7337
7338/// This is a wrapper around getUnderlyingObjects and adds support for basic
7339/// ptrtoint+arithmetic+inttoptr sequences.
7340/// It returns false if unidentified object is found in getUnderlyingObjects.
7342 SmallVectorImpl<Value *> &Objects) {
7344 SmallVector<const Value *, 4> Working(1, V);
7345 do {
7346 V = Working.pop_back_val();
7347
7349 getUnderlyingObjects(V, Objs);
7350
7351 for (const Value *V : Objs) {
7352 if (!Visited.insert(V).second)
7353 continue;
7354 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7355 const Value *O =
7356 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7357 if (O->getType()->isPointerTy()) {
7358 Working.push_back(O);
7359 continue;
7360 }
7361 }
7362 // If getUnderlyingObjects fails to find an identifiable object,
7363 // getUnderlyingObjectsForCodeGen also fails for safety.
7364 if (!isIdentifiedObject(V)) {
7365 Objects.clear();
7366 return false;
7367 }
7368 Objects.push_back(const_cast<Value *>(V));
7369 }
7370 } while (!Working.empty());
7371 return true;
7372}
7373
7375 AllocaInst *Result = nullptr;
7377 SmallVector<Value *, 4> Worklist;
7378
7379 auto AddWork = [&](Value *V) {
7380 if (Visited.insert(V).second)
7381 Worklist.push_back(V);
7382 };
7383
7384 AddWork(V);
7385 do {
7386 V = Worklist.pop_back_val();
7387 assert(Visited.count(V));
7388
7389 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7390 if (Result && Result != AI)
7391 return nullptr;
7392 Result = AI;
7393 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7394 AddWork(CI->getOperand(0));
7395 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7396 for (Value *IncValue : PN->incoming_values())
7397 AddWork(IncValue);
7398 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7399 AddWork(SI->getTrueValue());
7400 AddWork(SI->getFalseValue());
7402 if (OffsetZero && !GEP->hasAllZeroIndices())
7403 return nullptr;
7404 AddWork(GEP->getPointerOperand());
7405 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7406 Value *Returned = CB->getReturnedArgOperand();
7407 if (Returned)
7408 AddWork(Returned);
7409 else
7410 return nullptr;
7411 } else {
7412 return nullptr;
7413 }
7414 } while (!Worklist.empty());
7415
7416 return Result;
7417}
7418
7420 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7421 for (const User *U : V->users()) {
7423 if (!II)
7424 return false;
7425
7426 if (AllowLifetime && II->isLifetimeStartOrEnd())
7427 continue;
7428
7429 if (AllowDroppable && II->isDroppable())
7430 continue;
7431
7432 return false;
7433 }
7434 return true;
7435}
7436
7439 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7440}
7443 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7444}
7445
7447 if (auto *II = dyn_cast<IntrinsicInst>(I))
7448 return isTriviallyVectorizable(II->getIntrinsicID());
7449 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7450 return (!Shuffle || Shuffle->isSelect()) &&
7452}
7453
7455 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7456 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7457 bool IgnoreUBImplyingAttrs) {
7458 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7459 AC, DT, TLI, UseVariableInfo,
7460 IgnoreUBImplyingAttrs);
7461}
7462
7464 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7465 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7466 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7467#ifndef NDEBUG
7468 if (Inst->getOpcode() != Opcode) {
7469 // Check that the operands are actually compatible with the Opcode override.
7470 auto hasEqualReturnAndLeadingOperandTypes =
7471 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7472 if (Inst->getNumOperands() < NumLeadingOperands)
7473 return false;
7474 const Type *ExpectedType = Inst->getType();
7475 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7476 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7477 return false;
7478 return true;
7479 };
7481 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7482 assert(!Instruction::isUnaryOp(Opcode) ||
7483 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7484 }
7485#endif
7486
7487 switch (Opcode) {
7488 default:
7489 return true;
7490 case Instruction::UDiv:
7491 case Instruction::URem: {
7492 // x / y is undefined if y == 0.
7493 const APInt *V;
7494 if (match(Inst->getOperand(1), m_APInt(V)))
7495 return *V != 0;
7496 return false;
7497 }
7498 case Instruction::SDiv:
7499 case Instruction::SRem: {
7500 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7501 const APInt *Numerator, *Denominator;
7502 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7503 return false;
7504 // We cannot hoist this division if the denominator is 0.
7505 if (*Denominator == 0)
7506 return false;
7507 // It's safe to hoist if the denominator is not 0 or -1.
7508 if (!Denominator->isAllOnes())
7509 return true;
7510 // At this point we know that the denominator is -1. It is safe to hoist as
7511 // long we know that the numerator is not INT_MIN.
7512 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7513 return !Numerator->isMinSignedValue();
7514 // The numerator *might* be MinSignedValue.
7515 return false;
7516 }
7517 case Instruction::Load: {
7518 if (!UseVariableInfo)
7519 return false;
7520
7521 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7522 if (!LI)
7523 return false;
7524 if (mustSuppressSpeculation(*LI))
7525 return false;
7526 const DataLayout &DL = LI->getDataLayout();
7528 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7529 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7530 }
7531 case Instruction::Call: {
7532 auto *CI = dyn_cast<const CallInst>(Inst);
7533 if (!CI)
7534 return false;
7535 const Function *Callee = CI->getCalledFunction();
7536
7537 // The called function could have undefined behavior or side-effects, even
7538 // if marked readnone nounwind.
7539 if (!Callee || !Callee->isSpeculatable())
7540 return false;
7541 // Since the operands may be changed after hoisting, undefined behavior may
7542 // be triggered by some UB-implying attributes.
7543 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7544 }
7545 case Instruction::VAArg:
7546 case Instruction::Alloca:
7547 case Instruction::Invoke:
7548 case Instruction::CallBr:
7549 case Instruction::PHI:
7550 case Instruction::Store:
7551 case Instruction::Ret:
7552 case Instruction::UncondBr:
7553 case Instruction::CondBr:
7554 case Instruction::IndirectBr:
7555 case Instruction::Switch:
7556 case Instruction::Unreachable:
7557 case Instruction::Fence:
7558 case Instruction::AtomicRMW:
7559 case Instruction::AtomicCmpXchg:
7560 case Instruction::LandingPad:
7561 case Instruction::Resume:
7562 case Instruction::CatchSwitch:
7563 case Instruction::CatchPad:
7564 case Instruction::CatchRet:
7565 case Instruction::CleanupPad:
7566 case Instruction::CleanupRet:
7567 return false; // Misc instructions which have effects
7568 }
7569}
7570
7572 if (I.mayReadOrWriteMemory())
7573 // Memory dependency possible
7574 return true;
7576 // Can't move above a maythrow call or infinite loop. Or if an
7577 // inalloca alloca, above a stacksave call.
7578 return true;
7580 // 1) Can't reorder two inf-loop calls, even if readonly
7581 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7582 // safe to speculative execute. (Inverse of above)
7583 return true;
7584 return false;
7585}
7586
7587/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7601
7602/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7605 bool ForSigned,
7606 const SimplifyQuery &SQ) {
7607 ConstantRange CR1 =
7608 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7609 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7612 return CR1.intersectWith(CR2, RangeType);
7613}
7614
7616 const Value *RHS,
7617 const SimplifyQuery &SQ,
7618 bool IsNSW) {
7619 ConstantRange LHSRange =
7620 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7621 ConstantRange RHSRange =
7622 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7623
7624 // mul nsw of two non-negative numbers is also nuw.
7625 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7627
7628 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7629}
7630
7632 const Value *RHS,
7633 const SimplifyQuery &SQ) {
7634 // Multiplying n * m significant bits yields a result of n + m significant
7635 // bits. If the total number of significant bits does not exceed the
7636 // result bit width (minus 1), there is no overflow.
7637 // This means if we have enough leading sign bits in the operands
7638 // we can guarantee that the result does not overflow.
7639 // Ref: "Hacker's Delight" by Henry Warren
7640 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7641
7642 // Note that underestimating the number of sign bits gives a more
7643 // conservative answer.
7644 unsigned SignBits =
7645 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7646
7647 // First handle the easy case: if we have enough sign bits there's
7648 // definitely no overflow.
7649 if (SignBits > BitWidth + 1)
7651
7652 // There are two ambiguous cases where there can be no overflow:
7653 // SignBits == BitWidth + 1 and
7654 // SignBits == BitWidth
7655 // The second case is difficult to check, therefore we only handle the
7656 // first case.
7657 if (SignBits == BitWidth + 1) {
7658 // It overflows only when both arguments are negative and the true
7659 // product is exactly the minimum negative number.
7660 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7661 // For simplicity we just check if at least one side is not negative.
7662 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7663 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7664 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7666 }
7668}
7669
7672 const WithCache<const Value *> &RHS,
7673 const SimplifyQuery &SQ) {
7674 ConstantRange LHSRange =
7675 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7676 ConstantRange RHSRange =
7677 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7678 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7679}
7680
7681static OverflowResult
7684 const AddOperator *Add, const SimplifyQuery &SQ) {
7685 if (Add && Add->hasNoSignedWrap()) {
7687 }
7688
7689 // If LHS and RHS each have at least two sign bits, the addition will look
7690 // like
7691 //
7692 // XX..... +
7693 // YY.....
7694 //
7695 // If the carry into the most significant position is 0, X and Y can't both
7696 // be 1 and therefore the carry out of the addition is also 0.
7697 //
7698 // If the carry into the most significant position is 1, X and Y can't both
7699 // be 0 and therefore the carry out of the addition is also 1.
7700 //
7701 // Since the carry into the most significant position is always equal to
7702 // the carry out of the addition, there is no signed overflow.
7703 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7705
7706 ConstantRange LHSRange =
7707 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7708 ConstantRange RHSRange =
7709 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7710 OverflowResult OR =
7711 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7713 return OR;
7714
7715 // The remaining code needs Add to be available. Early returns if not so.
7716 if (!Add)
7718
7719 // If the sign of Add is the same as at least one of the operands, this add
7720 // CANNOT overflow. If this can be determined from the known bits of the
7721 // operands the above signedAddMayOverflow() check will have already done so.
7722 // The only other way to improve on the known bits is from an assumption, so
7723 // call computeKnownBitsFromContext() directly.
7724 bool LHSOrRHSKnownNonNegative =
7725 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7726 bool LHSOrRHSKnownNegative =
7727 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7728 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7729 KnownBits AddKnown(LHSRange.getBitWidth());
7730 computeKnownBitsFromContext(Add, AddKnown, SQ);
7731 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7732 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7734 }
7735
7737}
7738
7740 const Value *RHS,
7741 const SimplifyQuery &SQ) {
7742 // X - (X % ?)
7743 // The remainder of a value can't have greater magnitude than itself,
7744 // so the subtraction can't overflow.
7745
7746 // X - (X -nuw ?)
7747 // In the minimal case, this would simplify to "?", so there's no subtract
7748 // at all. But if this analysis is used to peek through casts, for example,
7749 // then determining no-overflow may allow other transforms.
7750
7751 // TODO: There are other patterns like this.
7752 // See simplifyICmpWithBinOpOnLHS() for candidates.
7753 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7754 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7755 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7757
7758 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7759 SQ.DL)) {
7760 if (*C)
7763 }
7764
7765 ConstantRange LHSRange =
7766 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7767 ConstantRange RHSRange =
7768 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7769 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7770}
7771
7773 const Value *RHS,
7774 const SimplifyQuery &SQ) {
7775 // X - (X % ?)
7776 // The remainder of a value can't have greater magnitude than itself,
7777 // so the subtraction can't overflow.
7778
7779 // X - (X -nsw ?)
7780 // In the minimal case, this would simplify to "?", so there's no subtract
7781 // at all. But if this analysis is used to peek through casts, for example,
7782 // then determining no-overflow may allow other transforms.
7783 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7784 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7785 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7787
7788 // If LHS and RHS each have at least two sign bits, the subtraction
7789 // cannot overflow.
7790 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7792
7793 ConstantRange LHSRange =
7794 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7795 ConstantRange RHSRange =
7796 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7797 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7798}
7799
7801 const DominatorTree &DT) {
7802 SmallVector<const CondBrInst *, 2> GuardingBranches;
7804
7805 for (const User *U : WO->users()) {
7806 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7807 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7808
7809 if (EVI->getIndices()[0] == 0)
7810 Results.push_back(EVI);
7811 else {
7812 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7813
7814 for (const auto *U : EVI->users())
7815 if (const auto *B = dyn_cast<CondBrInst>(U))
7816 GuardingBranches.push_back(B);
7817 }
7818 } else {
7819 // We are using the aggregate directly in a way we don't want to analyze
7820 // here (storing it to a global, say).
7821 return false;
7822 }
7823 }
7824
7825 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7826 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7827
7828 // Check if all users of the add are provably no-wrap.
7829 for (const auto *Result : Results) {
7830 // If the extractvalue itself is not executed on overflow, the we don't
7831 // need to check each use separately, since domination is transitive.
7832 if (DT.dominates(NoWrapEdge, Result->getParent()))
7833 continue;
7834
7835 for (const auto &RU : Result->uses())
7836 if (!DT.dominates(NoWrapEdge, RU))
7837 return false;
7838 }
7839
7840 return true;
7841 };
7842
7843 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7844}
7845
7846/// Shifts return poison if shiftwidth is larger than the bitwidth.
7847static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7848 auto *C = dyn_cast<Constant>(ShiftAmount);
7849 if (!C)
7850 return false;
7851
7852 // Shifts return poison if shiftwidth is larger than the bitwidth.
7854 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7855 unsigned NumElts = FVTy->getNumElements();
7856 for (unsigned i = 0; i < NumElts; ++i)
7857 ShiftAmounts.push_back(C->getAggregateElement(i));
7858 } else if (isa<ScalableVectorType>(C->getType()))
7859 return false; // Can't tell, just return false to be safe
7860 else
7861 ShiftAmounts.push_back(C);
7862
7863 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7864 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7865 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7866 });
7867
7868 return Safe;
7869}
7870
7872 bool ConsiderFlagsAndMetadata) {
7873
7874 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7875 Op->hasPoisonGeneratingAnnotations())
7876 return true;
7877
7878 unsigned Opcode = Op->getOpcode();
7879
7880 // Check whether opcode is a poison/undef-generating operation
7881 switch (Opcode) {
7882 case Instruction::Shl:
7883 case Instruction::AShr:
7884 case Instruction::LShr:
7885 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7886 case Instruction::FPToSI:
7887 case Instruction::FPToUI:
7888 // fptosi/ui yields poison if the resulting value does not fit in the
7889 // destination type.
7890 return true;
7891 case Instruction::Call:
7892 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7893 switch (II->getIntrinsicID()) {
7894 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7895 case Intrinsic::ctlz:
7896 case Intrinsic::cttz:
7897 case Intrinsic::abs:
7898 // We're not considering flags so it is safe to just return false.
7899 return false;
7900 case Intrinsic::sshl_sat:
7901 case Intrinsic::ushl_sat:
7902 if (!includesPoison(Kind) ||
7903 shiftAmountKnownInRange(II->getArgOperand(1)))
7904 return false;
7905 break;
7906 }
7907 }
7908 [[fallthrough]];
7909 case Instruction::CallBr:
7910 case Instruction::Invoke: {
7911 const auto *CB = cast<CallBase>(Op);
7912 return !CB->hasRetAttr(Attribute::NoUndef) &&
7913 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7914 }
7915 case Instruction::InsertElement:
7916 case Instruction::ExtractElement: {
7917 // If index exceeds the length of the vector, it returns poison
7918 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7919 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7920 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7921 if (includesPoison(Kind))
7922 return !Idx ||
7923 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7924 return false;
7925 }
7926 case Instruction::ShuffleVector: {
7928 ? cast<ConstantExpr>(Op)->getShuffleMask()
7929 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7930 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7931 }
7932 case Instruction::FNeg:
7933 case Instruction::PHI:
7934 case Instruction::Select:
7935 case Instruction::ExtractValue:
7936 case Instruction::InsertValue:
7937 case Instruction::Freeze:
7938 case Instruction::ICmp:
7939 case Instruction::FCmp:
7940 case Instruction::GetElementPtr:
7941 return false;
7942 case Instruction::AddrSpaceCast:
7943 return true;
7944 default: {
7945 const auto *CE = dyn_cast<ConstantExpr>(Op);
7946 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7947 return false;
7948 else if (Instruction::isBinaryOp(Opcode))
7949 return false;
7950 // Be conservative and return true.
7951 return true;
7952 }
7953 }
7954}
7955
7957 bool ConsiderFlagsAndMetadata) {
7958 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7959 ConsiderFlagsAndMetadata);
7960}
7961
7962bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7963 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7964 ConsiderFlagsAndMetadata);
7965}
7966
7967static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7968 unsigned Depth) {
7969 if (ValAssumedPoison == V)
7970 return true;
7971
7972 const unsigned MaxDepth = 2;
7973 if (Depth >= MaxDepth)
7974 return false;
7975
7976 if (const auto *I = dyn_cast<Instruction>(V)) {
7977 if (any_of(I->operands(), [=](const Use &Op) {
7978 return propagatesPoison(Op) &&
7979 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7980 }))
7981 return true;
7982
7983 // V = extractvalue V0, idx
7984 // V2 = extractvalue V0, idx2
7985 // V0's elements are all poison or not. (e.g., add_with_overflow)
7986 const WithOverflowInst *II;
7988 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7989 llvm::is_contained(II->args(), ValAssumedPoison)))
7990 return true;
7991 }
7992 return false;
7993}
7994
7995static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7996 unsigned Depth) {
7997 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7998 return true;
7999
8000 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8001 return true;
8002
8003 const unsigned MaxDepth = 2;
8004 if (Depth >= MaxDepth)
8005 return false;
8006
8007 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8008 if (I && !canCreatePoison(cast<Operator>(I))) {
8009 return all_of(I->operands(), [=](const Value *Op) {
8010 return impliesPoison(Op, V, Depth + 1);
8011 });
8012 }
8013 return false;
8014}
8015
8016bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8017 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8018}
8019
8020static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8021
8023 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8024 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8026 return false;
8027
8028 if (isa<MetadataAsValue>(V))
8029 return false;
8030
8031 if (const auto *A = dyn_cast<Argument>(V)) {
8032 if (A->hasAttribute(Attribute::NoUndef) ||
8033 A->hasAttribute(Attribute::Dereferenceable) ||
8034 A->hasAttribute(Attribute::DereferenceableOrNull))
8035 return true;
8036 }
8037
8038 if (auto *C = dyn_cast<Constant>(V)) {
8039 if (isa<PoisonValue>(C))
8040 return !includesPoison(Kind);
8041
8042 if (isa<UndefValue>(C))
8043 return !includesUndef(Kind);
8044
8047 return true;
8048
8049 if (C->getType()->isVectorTy()) {
8050 if (isa<ConstantExpr>(C)) {
8051 // Scalable vectors can use a ConstantExpr to build a splat.
8052 if (Constant *SplatC = C->getSplatValue())
8053 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8054 return true;
8055 } else {
8056 if (includesUndef(Kind) && C->containsUndefElement())
8057 return false;
8058 if (includesPoison(Kind) && C->containsPoisonElement())
8059 return false;
8060 return !C->containsConstantExpression();
8061 }
8062 }
8063 }
8064
8065 // Strip cast operations from a pointer value.
8066 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8067 // inbounds with zero offset. To guarantee that the result isn't poison, the
8068 // stripped pointer is checked as it has to be pointing into an allocated
8069 // object or be null `null` to ensure `inbounds` getelement pointers with a
8070 // zero offset could not produce poison.
8071 // It can strip off addrspacecast that do not change bit representation as
8072 // well. We believe that such addrspacecast is equivalent to no-op.
8073 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8074 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8075 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8076 return true;
8077
8078 auto OpCheck = [&](const Value *V) {
8079 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8080 };
8081
8082 if (auto *Opr = dyn_cast<Operator>(V)) {
8083 // If the value is a freeze instruction, then it can never
8084 // be undef or poison.
8085 if (isa<FreezeInst>(V))
8086 return true;
8087
8088 if (const auto *CB = dyn_cast<CallBase>(V)) {
8089 if (CB->hasRetAttr(Attribute::NoUndef) ||
8090 CB->hasRetAttr(Attribute::Dereferenceable) ||
8091 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8092 return true;
8093 }
8094
8095 if (!::canCreateUndefOrPoison(Opr, Kind,
8096 /*ConsiderFlagsAndMetadata=*/true)) {
8097 if (const auto *PN = dyn_cast<PHINode>(V)) {
8098 unsigned Num = PN->getNumIncomingValues();
8099 bool IsWellDefined = true;
8100 for (unsigned i = 0; i < Num; ++i) {
8101 if (PN == PN->getIncomingValue(i))
8102 continue;
8103 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8104 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8105 DT, Depth + 1, Kind)) {
8106 IsWellDefined = false;
8107 break;
8108 }
8109 }
8110 if (IsWellDefined)
8111 return true;
8112 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8113 : nullptr) {
8114 // For splats we only need to check the value being splatted.
8115 if (OpCheck(Splat))
8116 return true;
8117 } else if (all_of(Opr->operands(), OpCheck))
8118 return true;
8119 }
8120 }
8121
8122 if (auto *I = dyn_cast<LoadInst>(V))
8123 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8124 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8125 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8126 return true;
8127
8129 return true;
8130
8131 // CxtI may be null or a cloned instruction.
8132 if (!CtxI || !CtxI->getParent() || !DT)
8133 return false;
8134
8135 auto *DNode = DT->getNode(CtxI->getParent());
8136 if (!DNode)
8137 // Unreachable block
8138 return false;
8139
8140 // If V is used as a branch condition before reaching CtxI, V cannot be
8141 // undef or poison.
8142 // br V, BB1, BB2
8143 // BB1:
8144 // CtxI ; V cannot be undef or poison here
8145 auto *Dominator = DNode->getIDom();
8146 // This check is purely for compile time reasons: we can skip the IDom walk
8147 // if what we are checking for includes undef and the value is not an integer.
8148 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8149 while (Dominator) {
8150 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8151
8152 Value *Cond = nullptr;
8153 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8154 Cond = BI->getCondition();
8155 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8156 Cond = SI->getCondition();
8157 }
8158
8159 if (Cond) {
8160 if (Cond == V)
8161 return true;
8162 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8163 // For poison, we can analyze further
8164 auto *Opr = cast<Operator>(Cond);
8165 if (any_of(Opr->operands(), [V](const Use &U) {
8166 return V == U && propagatesPoison(U);
8167 }))
8168 return true;
8169 }
8170 }
8171
8172 Dominator = Dominator->getIDom();
8173 }
8174
8175 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8176 return true;
8177
8178 return false;
8179}
8180
8182 const Instruction *CtxI,
8183 const DominatorTree *DT,
8184 unsigned Depth) {
8185 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8187}
8188
8190 const Instruction *CtxI,
8191 const DominatorTree *DT, unsigned Depth) {
8192 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8194}
8195
8197 const Instruction *CtxI,
8198 const DominatorTree *DT, unsigned Depth) {
8199 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8201}
8202
8203/// Return true if undefined behavior would provably be executed on the path to
8204/// OnPathTo if Root produced a posion result. Note that this doesn't say
8205/// anything about whether OnPathTo is actually executed or whether Root is
8206/// actually poison. This can be used to assess whether a new use of Root can
8207/// be added at a location which is control equivalent with OnPathTo (such as
8208/// immediately before it) without introducing UB which didn't previously
8209/// exist. Note that a false result conveys no information.
8211 Instruction *OnPathTo,
8212 DominatorTree *DT) {
8213 // Basic approach is to assume Root is poison, propagate poison forward
8214 // through all users we can easily track, and then check whether any of those
8215 // users are provable UB and must execute before out exiting block might
8216 // exit.
8217
8218 // The set of all recursive users we've visited (which are assumed to all be
8219 // poison because of said visit)
8222 Worklist.push_back(Root);
8223 while (!Worklist.empty()) {
8224 const Instruction *I = Worklist.pop_back_val();
8225
8226 // If we know this must trigger UB on a path leading our target.
8227 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8228 return true;
8229
8230 // If we can't analyze propagation through this instruction, just skip it
8231 // and transitive users. Safe as false is a conservative result.
8232 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8233 return KnownPoison.contains(U) && propagatesPoison(U);
8234 }))
8235 continue;
8236
8237 if (KnownPoison.insert(I).second)
8238 for (const User *User : I->users())
8239 Worklist.push_back(cast<Instruction>(User));
8240 }
8241
8242 // Might be non-UB, or might have a path we couldn't prove must execute on
8243 // way to exiting bb.
8244 return false;
8245}
8246
8248 const SimplifyQuery &SQ) {
8249 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8250 Add, SQ);
8251}
8252
8255 const WithCache<const Value *> &RHS,
8256 const SimplifyQuery &SQ) {
8257 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8258}
8259
8261 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8262 // of time because it's possible for another thread to interfere with it for an
8263 // arbitrary length of time, but programs aren't allowed to rely on that.
8264
8265 // If there is no successor, then execution can't transfer to it.
8266 if (isa<ReturnInst>(I))
8267 return false;
8269 return false;
8270
8271 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8272 // Instruction::willReturn.
8273 //
8274 // FIXME: Move this check into Instruction::willReturn.
8275 if (isa<CatchPadInst>(I)) {
8276 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8277 default:
8278 // A catchpad may invoke exception object constructors and such, which
8279 // in some languages can be arbitrary code, so be conservative by default.
8280 return false;
8282 // For CoreCLR, it just involves a type test.
8283 return true;
8284 }
8285 }
8286
8287 // An instruction that returns without throwing must transfer control flow
8288 // to a successor.
8289 return !I->mayThrow() && I->willReturn();
8290}
8291
8293 // TODO: This is slightly conservative for invoke instruction since exiting
8294 // via an exception *is* normal control for them.
8295 for (const Instruction &I : *BB)
8297 return false;
8298 return true;
8299}
8300
8307
8310 assert(ScanLimit && "scan limit must be non-zero");
8311 for (const Instruction &I : Range) {
8312 if (--ScanLimit == 0)
8313 return false;
8315 return false;
8316 }
8317 return true;
8318}
8319
8321 const Loop *L) {
8322 // The loop header is guaranteed to be executed for every iteration.
8323 //
8324 // FIXME: Relax this constraint to cover all basic blocks that are
8325 // guaranteed to be executed at every iteration.
8326 if (I->getParent() != L->getHeader()) return false;
8327
8328 for (const Instruction &LI : *L->getHeader()) {
8329 if (&LI == I) return true;
8330 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8331 }
8332 llvm_unreachable("Instruction not contained in its own parent basic block.");
8333}
8334
8336 switch (IID) {
8337 // TODO: Add more intrinsics.
8338 case Intrinsic::sadd_with_overflow:
8339 case Intrinsic::ssub_with_overflow:
8340 case Intrinsic::smul_with_overflow:
8341 case Intrinsic::uadd_with_overflow:
8342 case Intrinsic::usub_with_overflow:
8343 case Intrinsic::umul_with_overflow:
8344 // If an input is a vector containing a poison element, the
8345 // two output vectors (calculated results, overflow bits)'
8346 // corresponding lanes are poison.
8347 return true;
8348 case Intrinsic::ctpop:
8349 case Intrinsic::ctlz:
8350 case Intrinsic::cttz:
8351 case Intrinsic::abs:
8352 case Intrinsic::smax:
8353 case Intrinsic::smin:
8354 case Intrinsic::umax:
8355 case Intrinsic::umin:
8356 case Intrinsic::scmp:
8357 case Intrinsic::is_fpclass:
8358 case Intrinsic::ptrmask:
8359 case Intrinsic::ucmp:
8360 case Intrinsic::bitreverse:
8361 case Intrinsic::bswap:
8362 case Intrinsic::sadd_sat:
8363 case Intrinsic::ssub_sat:
8364 case Intrinsic::sshl_sat:
8365 case Intrinsic::uadd_sat:
8366 case Intrinsic::usub_sat:
8367 case Intrinsic::ushl_sat:
8368 case Intrinsic::smul_fix:
8369 case Intrinsic::smul_fix_sat:
8370 case Intrinsic::umul_fix:
8371 case Intrinsic::umul_fix_sat:
8372 case Intrinsic::pow:
8373 case Intrinsic::powi:
8374 case Intrinsic::sin:
8375 case Intrinsic::sinh:
8376 case Intrinsic::cos:
8377 case Intrinsic::cosh:
8378 case Intrinsic::sincos:
8379 case Intrinsic::sincospi:
8380 case Intrinsic::tan:
8381 case Intrinsic::tanh:
8382 case Intrinsic::asin:
8383 case Intrinsic::acos:
8384 case Intrinsic::atan:
8385 case Intrinsic::atan2:
8386 case Intrinsic::canonicalize:
8387 case Intrinsic::sqrt:
8388 case Intrinsic::exp:
8389 case Intrinsic::exp2:
8390 case Intrinsic::exp10:
8391 case Intrinsic::log:
8392 case Intrinsic::log2:
8393 case Intrinsic::log10:
8394 case Intrinsic::modf:
8395 case Intrinsic::floor:
8396 case Intrinsic::ceil:
8397 case Intrinsic::trunc:
8398 case Intrinsic::rint:
8399 case Intrinsic::nearbyint:
8400 case Intrinsic::round:
8401 case Intrinsic::roundeven:
8402 case Intrinsic::lrint:
8403 case Intrinsic::llrint:
8404 case Intrinsic::fshl:
8405 case Intrinsic::fshr:
8406 case Intrinsic::frexp:
8407 case Intrinsic::get_active_lane_mask:
8408 return true;
8409 default:
8410 return false;
8411 }
8412}
8413
8414bool llvm::propagatesPoison(const Use &PoisonOp) {
8415 const Operator *I = cast<Operator>(PoisonOp.getUser());
8416 switch (I->getOpcode()) {
8417 case Instruction::Freeze:
8418 case Instruction::PHI:
8419 case Instruction::Invoke:
8420 return false;
8421 case Instruction::Select:
8422 return PoisonOp.getOperandNo() == 0;
8423 case Instruction::Call:
8424 if (auto *II = dyn_cast<IntrinsicInst>(I))
8425 return intrinsicPropagatesPoison(II->getIntrinsicID());
8426 return false;
8427 case Instruction::ICmp:
8428 case Instruction::FCmp:
8429 case Instruction::GetElementPtr:
8430 return true;
8431 default:
8433 return true;
8434
8435 // Be conservative and return false.
8436 return false;
8437 }
8438}
8439
8440/// Enumerates all operands of \p I that are guaranteed to not be undef or
8441/// poison. If the callback \p Handle returns true, stop processing and return
8442/// true. Otherwise, return false.
8443template <typename CallableT>
8445 const CallableT &Handle) {
8446 switch (I->getOpcode()) {
8447 case Instruction::Store:
8448 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8449 return true;
8450 break;
8451
8452 case Instruction::Load:
8453 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8454 return true;
8455 break;
8456
8457 // Since dereferenceable attribute imply noundef, atomic operations
8458 // also implicitly have noundef pointers too
8459 case Instruction::AtomicCmpXchg:
8461 return true;
8462 break;
8463
8464 case Instruction::AtomicRMW:
8465 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8466 return true;
8467 break;
8468
8469 case Instruction::Call:
8470 case Instruction::Invoke: {
8471 const CallBase *CB = cast<CallBase>(I);
8472 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8473 return true;
8474 for (unsigned i = 0; i < CB->arg_size(); ++i)
8475 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8476 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8477 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8478 Handle(CB->getArgOperand(i)))
8479 return true;
8480 break;
8481 }
8482 case Instruction::Ret:
8483 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8484 Handle(I->getOperand(0)))
8485 return true;
8486 break;
8487 case Instruction::Switch:
8488 if (Handle(cast<SwitchInst>(I)->getCondition()))
8489 return true;
8490 break;
8491 case Instruction::CondBr:
8492 if (Handle(cast<CondBrInst>(I)->getCondition()))
8493 return true;
8494 break;
8495 default:
8496 break;
8497 }
8498
8499 return false;
8500}
8501
8502/// Enumerates all operands of \p I that are guaranteed to not be poison.
8503template <typename CallableT>
8505 const CallableT &Handle) {
8506 if (handleGuaranteedWellDefinedOps(I, Handle))
8507 return true;
8508 switch (I->getOpcode()) {
8509 // Divisors of these operations are allowed to be partially undef.
8510 case Instruction::UDiv:
8511 case Instruction::SDiv:
8512 case Instruction::URem:
8513 case Instruction::SRem:
8514 return Handle(I->getOperand(1));
8515 default:
8516 return false;
8517 }
8518}
8519
8521 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8523 I, [&](const Value *V) { return KnownPoison.count(V); });
8524}
8525
8527 bool PoisonOnly) {
8528 // We currently only look for uses of values within the same basic
8529 // block, as that makes it easier to guarantee that the uses will be
8530 // executed given that Inst is executed.
8531 //
8532 // FIXME: Expand this to consider uses beyond the same basic block. To do
8533 // this, look out for the distinction between post-dominance and strong
8534 // post-dominance.
8535 const BasicBlock *BB = nullptr;
8537 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8538 BB = Inst->getParent();
8539 Begin = Inst->getIterator();
8540 Begin++;
8541 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8542 if (Arg->getParent()->isDeclaration())
8543 return false;
8544 BB = &Arg->getParent()->getEntryBlock();
8545 Begin = BB->begin();
8546 } else {
8547 return false;
8548 }
8549
8550 // Limit number of instructions we look at, to avoid scanning through large
8551 // blocks. The current limit is chosen arbitrarily.
8552 unsigned ScanLimit = 32;
8553 BasicBlock::const_iterator End = BB->end();
8554
8555 if (!PoisonOnly) {
8556 // Since undef does not propagate eagerly, be conservative & just check
8557 // whether a value is directly passed to an instruction that must take
8558 // well-defined operands.
8559
8560 for (const auto &I : make_range(Begin, End)) {
8561 if (--ScanLimit == 0)
8562 break;
8563
8564 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8565 return WellDefinedOp == V;
8566 }))
8567 return true;
8568
8570 break;
8571 }
8572 return false;
8573 }
8574
8575 // Set of instructions that we have proved will yield poison if Inst
8576 // does.
8577 SmallPtrSet<const Value *, 16> YieldsPoison;
8579
8580 YieldsPoison.insert(V);
8581 Visited.insert(BB);
8582
8583 while (true) {
8584 for (const auto &I : make_range(Begin, End)) {
8585 if (--ScanLimit == 0)
8586 return false;
8587 if (mustTriggerUB(&I, YieldsPoison))
8588 return true;
8590 return false;
8591
8592 // If an operand is poison and propagates it, mark I as yielding poison.
8593 for (const Use &Op : I.operands()) {
8594 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8595 YieldsPoison.insert(&I);
8596 break;
8597 }
8598 }
8599
8600 // Special handling for select, which returns poison if its operand 0 is
8601 // poison (handled in the loop above) *or* if both its true/false operands
8602 // are poison (handled here).
8603 if (I.getOpcode() == Instruction::Select &&
8604 YieldsPoison.count(I.getOperand(1)) &&
8605 YieldsPoison.count(I.getOperand(2))) {
8606 YieldsPoison.insert(&I);
8607 }
8608 }
8609
8610 BB = BB->getSingleSuccessor();
8611 if (!BB || !Visited.insert(BB).second)
8612 break;
8613
8614 Begin = BB->getFirstNonPHIIt();
8615 End = BB->end();
8616 }
8617 return false;
8618}
8619
8621 return ::programUndefinedIfUndefOrPoison(Inst, false);
8622}
8623
8625 return ::programUndefinedIfUndefOrPoison(Inst, true);
8626}
8627
8628static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8629 if (FMF.noNaNs())
8630 return true;
8631
8632 if (auto *C = dyn_cast<ConstantFP>(V))
8633 return !C->isNaN();
8634
8635 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8636 if (!C->getElementType()->isFloatingPointTy())
8637 return false;
8638 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8639 if (C->getElementAsAPFloat(I).isNaN())
8640 return false;
8641 }
8642 return true;
8643 }
8644
8646 return true;
8647
8648 return false;
8649}
8650
8651static bool isKnownNonZero(const Value *V) {
8652 if (auto *C = dyn_cast<ConstantFP>(V))
8653 return !C->isZero();
8654
8655 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8656 if (!C->getElementType()->isFloatingPointTy())
8657 return false;
8658 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8659 if (C->getElementAsAPFloat(I).isZero())
8660 return false;
8661 }
8662 return true;
8663 }
8664
8665 return false;
8666}
8667
8668/// Match clamp pattern for float types without care about NaNs or signed zeros.
8669/// Given non-min/max outer cmp/select from the clamp pattern this
8670/// function recognizes if it can be substitued by a "canonical" min/max
8671/// pattern.
8673 Value *CmpLHS, Value *CmpRHS,
8674 Value *TrueVal, Value *FalseVal,
8675 Value *&LHS, Value *&RHS) {
8676 // Try to match
8677 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8678 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8679 // and return description of the outer Max/Min.
8680
8681 // First, check if select has inverse order:
8682 if (CmpRHS == FalseVal) {
8683 std::swap(TrueVal, FalseVal);
8684 Pred = CmpInst::getInversePredicate(Pred);
8685 }
8686
8687 // Assume success now. If there's no match, callers should not use these anyway.
8688 LHS = TrueVal;
8689 RHS = FalseVal;
8690
8691 const APFloat *FC1;
8692 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8693 return {SPF_UNKNOWN, SPNB_NA, false};
8694
8695 const APFloat *FC2;
8696 switch (Pred) {
8697 case CmpInst::FCMP_OLT:
8698 case CmpInst::FCMP_OLE:
8699 case CmpInst::FCMP_ULT:
8700 case CmpInst::FCMP_ULE:
8701 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8702 *FC1 < *FC2)
8703 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8704 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8705 *FC1 < *FC2)
8706 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8707 break;
8708 case CmpInst::FCMP_OGT:
8709 case CmpInst::FCMP_OGE:
8710 case CmpInst::FCMP_UGT:
8711 case CmpInst::FCMP_UGE:
8712 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8713 *FC1 > *FC2)
8714 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8715 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8716 *FC1 > *FC2)
8717 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8718 break;
8719 default:
8720 break;
8721 }
8722
8723 return {SPF_UNKNOWN, SPNB_NA, false};
8724}
8725
8726/// Recognize variations of:
8727/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8729 Value *CmpLHS, Value *CmpRHS,
8730 Value *TrueVal, Value *FalseVal) {
8731 // Swap the select operands and predicate to match the patterns below.
8732 if (CmpRHS != TrueVal) {
8733 Pred = ICmpInst::getSwappedPredicate(Pred);
8734 std::swap(TrueVal, FalseVal);
8735 }
8736 const APInt *C1;
8737 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8738 const APInt *C2;
8739 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8740 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8741 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8742 return {SPF_SMAX, SPNB_NA, false};
8743
8744 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8745 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8746 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8747 return {SPF_SMIN, SPNB_NA, false};
8748
8749 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8750 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8751 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8752 return {SPF_UMAX, SPNB_NA, false};
8753
8754 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8755 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8756 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8757 return {SPF_UMIN, SPNB_NA, false};
8758 }
8759 return {SPF_UNKNOWN, SPNB_NA, false};
8760}
8761
8762/// Recognize variations of:
8763/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8765 Value *CmpLHS, Value *CmpRHS,
8766 Value *TVal, Value *FVal,
8767 unsigned Depth) {
8768 // TODO: Allow FP min/max with nnan/nsz.
8769 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8770
8771 Value *A = nullptr, *B = nullptr;
8772 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8773 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8774 return {SPF_UNKNOWN, SPNB_NA, false};
8775
8776 Value *C = nullptr, *D = nullptr;
8777 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8778 if (L.Flavor != R.Flavor)
8779 return {SPF_UNKNOWN, SPNB_NA, false};
8780
8781 // We have something like: x Pred y ? min(a, b) : min(c, d).
8782 // Try to match the compare to the min/max operations of the select operands.
8783 // First, make sure we have the right compare predicate.
8784 switch (L.Flavor) {
8785 case SPF_SMIN:
8786 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8787 Pred = ICmpInst::getSwappedPredicate(Pred);
8788 std::swap(CmpLHS, CmpRHS);
8789 }
8790 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8791 break;
8792 return {SPF_UNKNOWN, SPNB_NA, false};
8793 case SPF_SMAX:
8794 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8795 Pred = ICmpInst::getSwappedPredicate(Pred);
8796 std::swap(CmpLHS, CmpRHS);
8797 }
8798 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8799 break;
8800 return {SPF_UNKNOWN, SPNB_NA, false};
8801 case SPF_UMIN:
8802 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8803 Pred = ICmpInst::getSwappedPredicate(Pred);
8804 std::swap(CmpLHS, CmpRHS);
8805 }
8806 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8807 break;
8808 return {SPF_UNKNOWN, SPNB_NA, false};
8809 case SPF_UMAX:
8810 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8811 Pred = ICmpInst::getSwappedPredicate(Pred);
8812 std::swap(CmpLHS, CmpRHS);
8813 }
8814 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8815 break;
8816 return {SPF_UNKNOWN, SPNB_NA, false};
8817 default:
8818 return {SPF_UNKNOWN, SPNB_NA, false};
8819 }
8820
8821 // If there is a common operand in the already matched min/max and the other
8822 // min/max operands match the compare operands (either directly or inverted),
8823 // then this is min/max of the same flavor.
8824
8825 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8826 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8827 if (D == B) {
8828 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8829 match(A, m_Not(m_Specific(CmpRHS)))))
8830 return {L.Flavor, SPNB_NA, false};
8831 }
8832 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8833 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8834 if (C == B) {
8835 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8836 match(A, m_Not(m_Specific(CmpRHS)))))
8837 return {L.Flavor, SPNB_NA, false};
8838 }
8839 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8840 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8841 if (D == A) {
8842 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8843 match(B, m_Not(m_Specific(CmpRHS)))))
8844 return {L.Flavor, SPNB_NA, false};
8845 }
8846 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8847 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8848 if (C == A) {
8849 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8850 match(B, m_Not(m_Specific(CmpRHS)))))
8851 return {L.Flavor, SPNB_NA, false};
8852 }
8853
8854 return {SPF_UNKNOWN, SPNB_NA, false};
8855}
8856
8857/// If the input value is the result of a 'not' op, constant integer, or vector
8858/// splat of a constant integer, return the bitwise-not source value.
8859/// TODO: This could be extended to handle non-splat vector integer constants.
8861 Value *NotV;
8862 if (match(V, m_Not(m_Value(NotV))))
8863 return NotV;
8864
8865 const APInt *C;
8866 if (match(V, m_APInt(C)))
8867 return ConstantInt::get(V->getType(), ~(*C));
8868
8869 return nullptr;
8870}
8871
8872/// Match non-obvious integer minimum and maximum sequences.
8874 Value *CmpLHS, Value *CmpRHS,
8875 Value *TrueVal, Value *FalseVal,
8876 Value *&LHS, Value *&RHS,
8877 unsigned Depth) {
8878 // Assume success. If there's no match, callers should not use these anyway.
8879 LHS = TrueVal;
8880 RHS = FalseVal;
8881
8882 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8884 return SPR;
8885
8886 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8888 return SPR;
8889
8890 // Look through 'not' ops to find disguised min/max.
8891 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8892 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8893 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8894 switch (Pred) {
8895 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8896 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8897 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8898 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8899 default: break;
8900 }
8901 }
8902
8903 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8904 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8905 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8906 switch (Pred) {
8907 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8908 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8909 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8910 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8911 default: break;
8912 }
8913 }
8914
8915 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8916 return {SPF_UNKNOWN, SPNB_NA, false};
8917
8918 const APInt *C1;
8919 if (!match(CmpRHS, m_APInt(C1)))
8920 return {SPF_UNKNOWN, SPNB_NA, false};
8921
8922 // An unsigned min/max can be written with a signed compare.
8923 const APInt *C2;
8924 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8925 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8926 // Is the sign bit set?
8927 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8928 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8929 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
8930 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8931
8932 // Is the sign bit clear?
8933 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
8934 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
8935 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
8936 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8937 }
8938
8939 return {SPF_UNKNOWN, SPNB_NA, false};
8940}
8941
8942bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
8943 bool AllowPoison) {
8944 assert(X && Y && "Invalid operand");
8945
8946 auto IsNegationOf = [&](const Value *X, const Value *Y) {
8947 if (!match(X, m_Neg(m_Specific(Y))))
8948 return false;
8949
8950 auto *BO = cast<BinaryOperator>(X);
8951 if (NeedNSW && !BO->hasNoSignedWrap())
8952 return false;
8953
8954 auto *Zero = cast<Constant>(BO->getOperand(0));
8955 if (!AllowPoison && !Zero->isNullValue())
8956 return false;
8957
8958 return true;
8959 };
8960
8961 // X = -Y or Y = -X
8962 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
8963 return true;
8964
8965 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
8966 Value *A, *B;
8967 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
8968 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
8969 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
8971}
8972
8973bool llvm::isKnownInversion(const Value *X, const Value *Y) {
8974 // Handle X = icmp pred A, B, Y = icmp pred A, C.
8975 Value *A, *B, *C;
8976 CmpPredicate Pred1, Pred2;
8977 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
8978 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
8979 return false;
8980
8981 // They must both have samesign flag or not.
8982 if (Pred1.hasSameSign() != Pred2.hasSameSign())
8983 return false;
8984
8985 if (B == C)
8986 return Pred1 == ICmpInst::getInversePredicate(Pred2);
8987
8988 // Try to infer the relationship from constant ranges.
8989 const APInt *RHSC1, *RHSC2;
8990 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
8991 return false;
8992
8993 // Sign bits of two RHSCs should match.
8994 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
8995 return false;
8996
8997 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
8998 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
8999
9000 return CR1.inverse() == CR2;
9001}
9002
9004 SelectPatternNaNBehavior NaNBehavior,
9005 bool Ordered) {
9006 switch (Pred) {
9007 default:
9008 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9009 case ICmpInst::ICMP_UGT:
9010 case ICmpInst::ICMP_UGE:
9011 return {SPF_UMAX, SPNB_NA, false};
9012 case ICmpInst::ICMP_SGT:
9013 case ICmpInst::ICMP_SGE:
9014 return {SPF_SMAX, SPNB_NA, false};
9015 case ICmpInst::ICMP_ULT:
9016 case ICmpInst::ICMP_ULE:
9017 return {SPF_UMIN, SPNB_NA, false};
9018 case ICmpInst::ICMP_SLT:
9019 case ICmpInst::ICMP_SLE:
9020 return {SPF_SMIN, SPNB_NA, false};
9021 case FCmpInst::FCMP_UGT:
9022 case FCmpInst::FCMP_UGE:
9023 case FCmpInst::FCMP_OGT:
9024 case FCmpInst::FCMP_OGE:
9025 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9026 case FCmpInst::FCMP_ULT:
9027 case FCmpInst::FCMP_ULE:
9028 case FCmpInst::FCMP_OLT:
9029 case FCmpInst::FCMP_OLE:
9030 return {SPF_FMINNUM, NaNBehavior, Ordered};
9031 }
9032}
9033
9034std::optional<std::pair<CmpPredicate, Constant *>>
9037 "Only for relational integer predicates.");
9038 if (isa<UndefValue>(C))
9039 return std::nullopt;
9040
9041 Type *Type = C->getType();
9042 bool IsSigned = ICmpInst::isSigned(Pred);
9043
9045 bool WillIncrement =
9046 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9047
9048 // Check if the constant operand can be safely incremented/decremented
9049 // without overflowing/underflowing.
9050 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9051 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9052 return false;
9053
9054 if (!Pred.hasSameSign())
9055 return true;
9056
9057 // Crossing the corresponding boundary in the other ordering changes the
9058 // sign bit, and therefore changes the poison domain.
9059 return WillIncrement ? !C->isMaxValue(!IsSigned)
9060 : !C->isMinValue(!IsSigned);
9061 };
9062
9063 Constant *SafeReplacementConstant = nullptr;
9064 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9065 // Bail out if the constant can't be safely incremented/decremented.
9066 if (!ConstantIsOk(CI))
9067 return std::nullopt;
9068 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9069 unsigned NumElts = FVTy->getNumElements();
9070 for (unsigned i = 0; i != NumElts; ++i) {
9071 Constant *Elt = C->getAggregateElement(i);
9072 if (!Elt)
9073 return std::nullopt;
9074
9075 if (isa<UndefValue>(Elt))
9076 continue;
9077
9078 // Bail out if we can't determine if this constant is min/max or if we
9079 // know that this constant is min/max.
9080 auto *CI = dyn_cast<ConstantInt>(Elt);
9081 if (!CI || !ConstantIsOk(CI))
9082 return std::nullopt;
9083
9084 if (!SafeReplacementConstant)
9085 SafeReplacementConstant = CI;
9086 }
9087 } else if (isa<VectorType>(C->getType())) {
9088 // Handle scalable splat
9089 Value *SplatC = C->getSplatValue();
9090 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9091 // Bail out if the constant can't be safely incremented/decremented.
9092 if (!CI || !ConstantIsOk(CI))
9093 return std::nullopt;
9094 } else {
9095 // ConstantExpr?
9096 return std::nullopt;
9097 }
9098
9099 // It may not be safe to change a compare predicate in the presence of
9100 // undefined elements, so replace those elements with the first safe constant
9101 // that we found.
9102 // TODO: in case of poison, it is safe; let's replace undefs only.
9103 if (C->containsUndefOrPoisonElement()) {
9104 assert(SafeReplacementConstant && "Replacement constant not set");
9105 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9106 }
9107
9109 Pred.hasSameSign());
9110
9111 // Increment or decrement the constant.
9112 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9113 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9114
9115 return std::make_pair(NewPred, NewC);
9116}
9117
9119 FastMathFlags FMF,
9120 Value *CmpLHS, Value *CmpRHS,
9121 Value *TrueVal, Value *FalseVal,
9122 Value *&LHS, Value *&RHS,
9123 unsigned Depth) {
9124 if (CmpInst::isFPPredicate(Pred)) {
9125 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9126 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9127 // purpose of identifying min/max. Disregard vector constants with undefined
9128 // elements because those can not be back-propagated for analysis.
9129 Value *OutputZeroVal = nullptr;
9130 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9131 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9132 OutputZeroVal = TrueVal;
9133 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9134 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9135 OutputZeroVal = FalseVal;
9136
9137 if (OutputZeroVal) {
9138 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9139 CmpLHS = OutputZeroVal;
9140 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9141 CmpRHS = OutputZeroVal;
9142 }
9143 }
9144
9145 LHS = CmpLHS;
9146 RHS = CmpRHS;
9147
9148 // Signed zero may return inconsistent results between implementations.
9149 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9150 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9151 // Therefore, we behave conservatively and only proceed if at least one of the
9152 // operands is known to not be zero or if we don't care about signed zero.
9153 if (CmpInst::isFPPredicate(Pred)) {
9154 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9155 !isKnownNonZero(CmpRHS))
9156 return {SPF_UNKNOWN, SPNB_NA, false};
9157 }
9158
9159 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9160 bool Ordered = false;
9161
9162 // When given one NaN and one non-NaN input:
9163 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9164 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9165 // ordered comparison fails), which could be NaN or non-NaN.
9166 // so here we discover exactly what NaN behavior is required/accepted.
9167 if (CmpInst::isFPPredicate(Pred)) {
9168 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9169 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9170
9171 if (LHSSafe && RHSSafe) {
9172 // Both operands are known non-NaN.
9173 NaNBehavior = SPNB_RETURNS_ANY;
9174 Ordered = CmpInst::isOrdered(Pred);
9175 } else if (CmpInst::isOrdered(Pred)) {
9176 // An ordered comparison will return false when given a NaN, so it
9177 // returns the RHS.
9178 Ordered = true;
9179 if (LHSSafe)
9180 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9181 NaNBehavior = SPNB_RETURNS_NAN;
9182 else if (RHSSafe)
9183 NaNBehavior = SPNB_RETURNS_OTHER;
9184 else
9185 // Completely unsafe.
9186 return {SPF_UNKNOWN, SPNB_NA, false};
9187 } else {
9188 Ordered = false;
9189 // An unordered comparison will return true when given a NaN, so it
9190 // returns the LHS.
9191 if (LHSSafe)
9192 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9193 NaNBehavior = SPNB_RETURNS_OTHER;
9194 else if (RHSSafe)
9195 NaNBehavior = SPNB_RETURNS_NAN;
9196 else
9197 // Completely unsafe.
9198 return {SPF_UNKNOWN, SPNB_NA, false};
9199 }
9200 }
9201
9202 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9203 std::swap(CmpLHS, CmpRHS);
9204 Pred = CmpInst::getSwappedPredicate(Pred);
9205 if (NaNBehavior == SPNB_RETURNS_NAN)
9206 NaNBehavior = SPNB_RETURNS_OTHER;
9207 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9208 NaNBehavior = SPNB_RETURNS_NAN;
9209 Ordered = !Ordered;
9210 }
9211
9212 // ([if]cmp X, Y) ? X : Y
9213 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9214 return getSelectPattern(Pred, NaNBehavior, Ordered);
9215
9216 if (isKnownNegation(TrueVal, FalseVal)) {
9217 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9218 // match against either LHS or sign-preserving operations on LHS, like
9219 // sext(LHS), or binary ops that do not wrap in signed sense.
9220 auto CmpLHSOrSExt =
9221 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9222 auto MaybeSExtOrMulCmpLHS =
9223 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9224 m_NSWShl(CmpLHSOrSExt, m_Value()));
9225 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9226 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9227 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9228 // Set the return values. If the compare uses the negated value (-X >s 0),
9229 // swap the return values because the negated value is always 'RHS'.
9230 LHS = TrueVal;
9231 RHS = FalseVal;
9232 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9233 std::swap(LHS, RHS);
9234
9235 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9236 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9237 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9238 return {SPF_ABS, SPNB_NA, false};
9239
9240 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9241 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9242 return {SPF_ABS, SPNB_NA, false};
9243
9244 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9245 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9246 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9247 return {SPF_NABS, SPNB_NA, false};
9248 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9249 // Set the return values. If the compare uses the negated value (-X >s 0),
9250 // swap the return values because the negated value is always 'RHS'.
9251 LHS = FalseVal;
9252 RHS = TrueVal;
9253 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9254 std::swap(LHS, RHS);
9255
9256 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9257 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9258 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9259 return {SPF_NABS, SPNB_NA, false};
9260
9261 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9262 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9263 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9264 return {SPF_ABS, SPNB_NA, false};
9265 }
9266 }
9267
9268 if (CmpInst::isIntPredicate(Pred))
9269 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9270
9271 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9272 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9273 // semantics than minNum. Be conservative in such case.
9274 if (NaNBehavior != SPNB_RETURNS_ANY ||
9275 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9276 !isKnownNonZero(CmpRHS)))
9277 return {SPF_UNKNOWN, SPNB_NA, false};
9278
9279 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9280}
9281
9283 Instruction::CastOps *CastOp) {
9284 const DataLayout &DL = CmpI->getDataLayout();
9285
9286 Constant *CastedTo = nullptr;
9287 switch (*CastOp) {
9288 case Instruction::ZExt:
9289 if (CmpI->isUnsigned())
9290 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9291 break;
9292 case Instruction::SExt:
9293 if (CmpI->isSigned())
9294 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9295 break;
9296 case Instruction::Trunc:
9297 Constant *CmpConst;
9298 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9299 CmpConst->getType() == SrcTy) {
9300 // Here we have the following case:
9301 //
9302 // %cond = cmp iN %x, CmpConst
9303 // %tr = trunc iN %x to iK
9304 // %narrowsel = select i1 %cond, iK %t, iK C
9305 //
9306 // We can always move trunc after select operation:
9307 //
9308 // %cond = cmp iN %x, CmpConst
9309 // %widesel = select i1 %cond, iN %x, iN CmpConst
9310 // %tr = trunc iN %widesel to iK
9311 //
9312 // Note that C could be extended in any way because we don't care about
9313 // upper bits after truncation. It can't be abs pattern, because it would
9314 // look like:
9315 //
9316 // select i1 %cond, x, -x.
9317 //
9318 // So only min/max pattern could be matched. Such match requires widened C
9319 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9320 // CmpConst == C is checked below.
9321 CastedTo = CmpConst;
9322 } else {
9323 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9324 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9325 }
9326 break;
9327 case Instruction::FPTrunc:
9328 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9329 break;
9330 case Instruction::FPExt:
9331 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9332 break;
9333 case Instruction::FPToUI:
9334 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9335 break;
9336 case Instruction::FPToSI:
9337 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9338 break;
9339 case Instruction::UIToFP:
9340 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9341 break;
9342 case Instruction::SIToFP:
9343 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9344 break;
9345 default:
9346 break;
9347 }
9348
9349 if (!CastedTo)
9350 return nullptr;
9351
9352 // Make sure the cast doesn't lose any information.
9353 Constant *CastedBack =
9354 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9355 if (CastedBack && CastedBack != C)
9356 return nullptr;
9357
9358 return CastedTo;
9359}
9360
9361/// Helps to match a select pattern in case of a type mismatch.
9362///
9363/// The function processes the case when type of true and false values of a
9364/// select instruction differs from type of the cmp instruction operands because
9365/// of a cast instruction. The function checks if it is legal to move the cast
9366/// operation after "select". If yes, it returns the new second value of
9367/// "select" (with the assumption that cast is moved):
9368/// 1. As operand of cast instruction when both values of "select" are same cast
9369/// instructions.
9370/// 2. As restored constant (by applying reverse cast operation) when the first
9371/// value of the "select" is a cast operation and the second value is a
9372/// constant. It is implemented in lookThroughCastConst().
9373/// 3. As one operand is cast instruction and the other is not. The operands in
9374/// sel(cmp) are in different type integer.
9375/// NOTE: We return only the new second value because the first value could be
9376/// accessed as operand of cast instruction.
9378 Instruction::CastOps *CastOp) {
9379 auto *Cast1 = dyn_cast<CastInst>(V1);
9380 if (!Cast1)
9381 return nullptr;
9382
9383 *CastOp = Cast1->getOpcode();
9384 Type *SrcTy = Cast1->getSrcTy();
9385 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9386 // If V1 and V2 are both the same cast from the same type, look through V1.
9387 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9388 return Cast2->getOperand(0);
9389 return nullptr;
9390 }
9391
9392 auto *C = dyn_cast<Constant>(V2);
9393 if (C)
9394 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9395
9396 Value *CastedTo = nullptr;
9397 if (*CastOp == Instruction::Trunc) {
9398 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9399 // Here we have the following case:
9400 // %y_ext = sext iK %y to iN
9401 // %cond = cmp iN %x, %y_ext
9402 // %tr = trunc iN %x to iK
9403 // %narrowsel = select i1 %cond, iK %tr, iK %y
9404 //
9405 // We can always move trunc after select operation:
9406 // %y_ext = sext iK %y to iN
9407 // %cond = cmp iN %x, %y_ext
9408 // %widesel = select i1 %cond, iN %x, iN %y_ext
9409 // %tr = trunc iN %widesel to iK
9410 assert(V2->getType() == Cast1->getType() &&
9411 "V2 and Cast1 should be the same type.");
9412 CastedTo = CmpI->getOperand(1);
9413 }
9414 }
9415
9416 return CastedTo;
9417}
9419 Instruction::CastOps *CastOp,
9420 unsigned Depth) {
9422 return {SPF_UNKNOWN, SPNB_NA, false};
9423
9425 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9426
9427 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9428 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9429
9430 Value *TrueVal = SI->getTrueValue();
9431 Value *FalseVal = SI->getFalseValue();
9432
9433 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9434 SI->getFastMathFlagsOrNone(),
9435 CastOp, Depth);
9436}
9437
9439 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9440 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9441 CmpInst::Predicate Pred = CmpI->getPredicate();
9442 Value *CmpLHS = CmpI->getOperand(0);
9443 Value *CmpRHS = CmpI->getOperand(1);
9444 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9445 FMF.setNoNaNs();
9446
9447 // Bail out early.
9448 if (CmpI->isEquality())
9449 return {SPF_UNKNOWN, SPNB_NA, false};
9450
9451 // Deal with type mismatches.
9452 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9453 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9454 // If this is a potential fmin/fmax with a cast to integer, then ignore
9455 // -0.0 because there is no corresponding integer value.
9456 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9457 FMF.setNoSignedZeros();
9458 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9459 cast<CastInst>(TrueVal)->getOperand(0), C,
9460 LHS, RHS, Depth);
9461 }
9462 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9463 // If this is a potential fmin/fmax with a cast to integer, then ignore
9464 // -0.0 because there is no corresponding integer value.
9465 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9466 FMF.setNoSignedZeros();
9467 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9468 C, cast<CastInst>(FalseVal)->getOperand(0),
9469 LHS, RHS, Depth);
9470 }
9471 }
9472 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9473 LHS, RHS, Depth);
9474}
9475
9477 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9478 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9479 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9480 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9481 if (SPF == SPF_FMINNUM)
9482 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9483 if (SPF == SPF_FMAXNUM)
9484 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9485 llvm_unreachable("unhandled!");
9486}
9487
9489 switch (SPF) {
9491 return Intrinsic::umin;
9493 return Intrinsic::umax;
9495 return Intrinsic::smin;
9497 return Intrinsic::smax;
9498 default:
9499 llvm_unreachable("Unexpected SPF");
9500 }
9501}
9502
9504 if (SPF == SPF_SMIN) return SPF_SMAX;
9505 if (SPF == SPF_UMIN) return SPF_UMAX;
9506 if (SPF == SPF_SMAX) return SPF_SMIN;
9507 if (SPF == SPF_UMAX) return SPF_UMIN;
9508 llvm_unreachable("unhandled!");
9509}
9510
9512 switch (MinMaxID) {
9513 case Intrinsic::smax: return Intrinsic::smin;
9514 case Intrinsic::smin: return Intrinsic::smax;
9515 case Intrinsic::umax: return Intrinsic::umin;
9516 case Intrinsic::umin: return Intrinsic::umax;
9517 // Please note that next four intrinsics may produce the same result for
9518 // original and inverted case even if X != Y due to NaN is handled specially.
9519 case Intrinsic::maximum: return Intrinsic::minimum;
9520 case Intrinsic::minimum: return Intrinsic::maximum;
9521 case Intrinsic::maxnum: return Intrinsic::minnum;
9522 case Intrinsic::minnum: return Intrinsic::maxnum;
9523 case Intrinsic::maximumnum:
9524 return Intrinsic::minimumnum;
9525 case Intrinsic::minimumnum:
9526 return Intrinsic::maximumnum;
9527 default: llvm_unreachable("Unexpected intrinsic");
9528 }
9529}
9530
9532 switch (SPF) {
9535 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9536 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9537 default: llvm_unreachable("Unexpected flavor");
9538 }
9539}
9540
9541std::pair<Intrinsic::ID, bool>
9543 // Check if VL contains select instructions that can be folded into a min/max
9544 // vector intrinsic and return the intrinsic if it is possible.
9545 // TODO: Support floating point min/max.
9546 bool AllCmpSingleUse = true;
9547 SelectPatternResult SelectPattern;
9548 SelectPattern.Flavor = SPF_UNKNOWN;
9549 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9550 Value *LHS, *RHS;
9551 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9552 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9553 return false;
9554 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9555 SelectPattern.Flavor != CurrentPattern.Flavor)
9556 return false;
9557 SelectPattern = CurrentPattern;
9558 AllCmpSingleUse &=
9560 return true;
9561 })) {
9562 switch (SelectPattern.Flavor) {
9563 case SPF_SMIN:
9564 return {Intrinsic::smin, AllCmpSingleUse};
9565 case SPF_UMIN:
9566 return {Intrinsic::umin, AllCmpSingleUse};
9567 case SPF_SMAX:
9568 return {Intrinsic::smax, AllCmpSingleUse};
9569 case SPF_UMAX:
9570 return {Intrinsic::umax, AllCmpSingleUse};
9571 case SPF_FMAXNUM:
9572 return {Intrinsic::maxnum, AllCmpSingleUse};
9573 case SPF_FMINNUM:
9574 return {Intrinsic::minnum, AllCmpSingleUse};
9575 default:
9576 llvm_unreachable("unexpected select pattern flavor");
9577 }
9578 }
9579 return {Intrinsic::not_intrinsic, false};
9580}
9581
9582template <typename InstTy>
9583static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9584 Value *&Init, Value *&OtherOp) {
9585 // Handle the case of a simple two-predecessor recurrence PHI.
9586 // There's a lot more that could theoretically be done here, but
9587 // this is sufficient to catch some interesting cases.
9588 // TODO: Expand list -- gep, uadd.sat etc.
9589 if (PN->getNumIncomingValues() != 2)
9590 return false;
9591
9592 for (unsigned I = 0; I != 2; ++I) {
9593 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9594 Operation && Operation->getNumOperands() >= 2) {
9595 Value *LHS = Operation->getOperand(0);
9596 Value *RHS = Operation->getOperand(1);
9597 if (LHS != PN && RHS != PN)
9598 continue;
9599
9600 Inst = Operation;
9601 Init = PN->getIncomingValue(!I);
9602 OtherOp = (LHS == PN) ? RHS : LHS;
9603 return true;
9604 }
9605 }
9606 return false;
9607}
9608
9609template <typename InstTy>
9610static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9611 Value *&Init, Value *&OtherOp0,
9612 Value *&OtherOp1) {
9613 if (PN->getNumIncomingValues() != 2)
9614 return false;
9615
9616 for (unsigned I = 0; I != 2; ++I) {
9617 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9618 Operation && Operation->getNumOperands() >= 3) {
9619 Value *Op0 = Operation->getOperand(0);
9620 Value *Op1 = Operation->getOperand(1);
9621 Value *Op2 = Operation->getOperand(2);
9622
9623 if (Op0 != PN && Op1 != PN && Op2 != PN)
9624 continue;
9625
9626 Inst = Operation;
9627 Init = PN->getIncomingValue(!I);
9628 if (Op0 == PN) {
9629 OtherOp0 = Op1;
9630 OtherOp1 = Op2;
9631 } else if (Op1 == PN) {
9632 OtherOp0 = Op0;
9633 OtherOp1 = Op2;
9634 } else {
9635 OtherOp0 = Op0;
9636 OtherOp1 = Op1;
9637 }
9638 return true;
9639 }
9640 }
9641 return false;
9642}
9644 Value *&Start, Value *&Step) {
9645 // We try to match a recurrence of the form:
9646 // %iv = [Start, %entry], [%iv.next, %backedge]
9647 // %iv.next = binop %iv, Step
9648 // Or:
9649 // %iv = [Start, %entry], [%iv.next, %backedge]
9650 // %iv.next = binop Step, %iv
9651 return matchTwoInputRecurrence(P, BO, Start, Step);
9652}
9653
9655 Value *&Start, Value *&Step) {
9656 BinaryOperator *BO = nullptr;
9657 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9658 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9659}
9660
9662 PHINode *&P, Value *&Init,
9663 Value *&OtherOp) {
9664 // Binary intrinsics only supported for now.
9665 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9666 I->getType() != I->getArgOperand(1)->getType())
9667 return false;
9668
9669 IntrinsicInst *II = nullptr;
9670 P = dyn_cast<PHINode>(I->getArgOperand(0));
9671 if (!P)
9672 P = dyn_cast<PHINode>(I->getArgOperand(1));
9673
9674 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9675}
9676
9678 PHINode *&P, Value *&Init,
9679 Value *&OtherOp0,
9680 Value *&OtherOp1) {
9681 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9682 I->getType() != I->getArgOperand(1)->getType() ||
9683 I->getType() != I->getArgOperand(2)->getType())
9684 return false;
9685 IntrinsicInst *II = nullptr;
9686 P = dyn_cast<PHINode>(I->getArgOperand(0));
9687 if (!P) {
9688 P = dyn_cast<PHINode>(I->getArgOperand(1));
9689 if (!P)
9690 P = dyn_cast<PHINode>(I->getArgOperand(2));
9691 }
9692 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9693 II == I;
9694}
9695
9696/// Return true if "icmp Pred LHS RHS" is always true.
9698 const Value *RHS) {
9699 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9700 return true;
9701
9702 switch (Pred) {
9703 default:
9704 return false;
9705
9706 case CmpInst::ICMP_SLE: {
9707 const APInt *C;
9708
9709 // LHS s<= LHS +_{nsw} C if C >= 0
9710 // LHS s<= LHS | C if C >= 0
9711 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9713 return !C->isNegative();
9714
9715 // LHS s<= smax(LHS, V) for any V
9717 return true;
9718
9719 // smin(RHS, V) s<= RHS for any V
9721 return true;
9722
9723 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9724 const Value *X;
9725 const APInt *CLHS, *CRHS;
9726 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9728 return CLHS->sle(*CRHS);
9729
9730 return false;
9731 }
9732
9733 case CmpInst::ICMP_ULE: {
9734 // LHS u<= LHS +_{nuw} V for any V
9735 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9737 return true;
9738
9739 // LHS u<= LHS | V for any V
9740 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9741 return true;
9742
9743 // LHS u<= umax(LHS, V) for any V
9745 return true;
9746
9747 // RHS >> V u<= RHS for any V
9748 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9749 return true;
9750
9751 // RHS u/ C_ugt_1 u<= RHS
9752 const APInt *C;
9753 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9754 return true;
9755
9756 // RHS & V u<= RHS for any V
9758 return true;
9759
9760 // umin(RHS, V) u<= RHS for any V
9762 return true;
9763
9764 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9765 const Value *X;
9766 const APInt *CLHS, *CRHS;
9767 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9769 return CLHS->ule(*CRHS);
9770
9771 return false;
9772 }
9773 }
9774}
9775
9776/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9777/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9778static std::optional<bool>
9780 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9781 switch (Pred) {
9782 default:
9783 return std::nullopt;
9784
9785 case CmpInst::ICMP_SLT:
9786 case CmpInst::ICMP_SLE:
9787 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9789 return true;
9790 return std::nullopt;
9791
9792 case CmpInst::ICMP_SGT:
9793 case CmpInst::ICMP_SGE:
9794 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9796 return true;
9797 return std::nullopt;
9798
9799 case CmpInst::ICMP_ULT:
9800 case CmpInst::ICMP_ULE:
9801 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9803 return true;
9804 return std::nullopt;
9805
9806 case CmpInst::ICMP_UGT:
9807 case CmpInst::ICMP_UGE:
9808 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9810 return true;
9811 return std::nullopt;
9812 }
9813}
9814
9815/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9816/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9817/// Otherwise, return std::nullopt if we can't infer anything.
9818static std::optional<bool>
9820 CmpPredicate RPred, const ConstantRange &RCR) {
9821 auto CRImpliesPred = [&](ConstantRange CR,
9822 CmpInst::Predicate Pred) -> std::optional<bool> {
9823 // If all true values for lhs and true for rhs, lhs implies rhs
9824 if (CR.icmp(Pred, RCR))
9825 return true;
9826
9827 // If there is no overlap, lhs implies not rhs
9828 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9829 return false;
9830
9831 return std::nullopt;
9832 };
9833 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9834 RPred))
9835 return Res;
9836 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9838 : LPred.dropSameSign();
9840 : RPred.dropSameSign();
9841 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9842 RPred);
9843 }
9844 return std::nullopt;
9845}
9846
9847/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9848/// is true. Return false if LHS implies RHS is false. Otherwise, return
9849/// std::nullopt if we can't infer anything.
9850static std::optional<bool>
9851isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9852 CmpPredicate RPred, const Value *R0, const Value *R1,
9853 const DataLayout &DL, bool LHSIsTrue) {
9854 // The rest of the logic assumes the LHS condition is true. If that's not the
9855 // case, invert the predicate to make it so.
9856 if (!LHSIsTrue)
9857 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9858
9859 // We can have non-canonical operands, so try to normalize any common operand
9860 // to L0/R0.
9861 if (L0 == R1) {
9862 std::swap(R0, R1);
9863 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9864 }
9865 if (R0 == L1) {
9866 std::swap(L0, L1);
9867 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9868 }
9869 if (L1 == R1) {
9870 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9871 if (L0 != R0 || match(L0, m_ImmConstant())) {
9872 std::swap(L0, L1);
9873 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9874 std::swap(R0, R1);
9875 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9876 }
9877 }
9878
9879 // See if we can infer anything if operand-0 matches and we have at least one
9880 // constant.
9881 const APInt *Unused;
9882 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9883 // Potential TODO: We could also further use the constant range of L0/R0 to
9884 // further constraint the constant ranges. At the moment this leads to
9885 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9886 // C1` (see discussion: D58633).
9887 SimplifyQuery SQ(DL);
9892
9893 // Even if L1/R1 are not both constant, we can still sometimes deduce
9894 // relationship from a single constant. For example X u> Y implies X != 0.
9895 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9896 return R;
9897 // If both L1/R1 were exact constant ranges and we didn't get anything
9898 // here, we won't be able to deduce this.
9899 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9900 return std::nullopt;
9901 }
9902
9903 // Can we infer anything when the two compares have matching operands?
9904 if (L0 == R0 && L1 == R1)
9905 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9906
9907 // It only really makes sense in the context of signed comparison for "X - Y
9908 // must be positive if X >= Y and no overflow".
9909 // Take SGT as an example: L0:x > L1:y and C >= 0
9910 // ==> R0:(x -nsw y) < R1:(-C) is false
9911 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9912 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9913 SignedLPred == ICmpInst::ICMP_SGE) &&
9914 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9915 if (match(R1, m_NonPositive()) &&
9916 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9917 return false;
9918 }
9919
9920 // Take SLT as an example: L0:x < L1:y and C <= 0
9921 // ==> R0:(x -nsw y) < R1:(-C) is true
9922 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9923 SignedLPred == ICmpInst::ICMP_SLE) &&
9924 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9925 if (match(R1, m_NonNegative()) &&
9926 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9927 return true;
9928 }
9929
9930 // a - b == NonZero -> a != b
9931 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
9932 const APInt *L1C;
9933 Value *A, *B;
9934 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
9935 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
9936 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
9937 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
9942 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
9943 }
9944
9945 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
9946 if (L0 == R0 &&
9947 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
9948 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
9949 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
9950 return CmpPredicate::getMatching(LPred, RPred).has_value();
9951
9952 if (auto P = CmpPredicate::getMatching(LPred, RPred))
9953 return isImpliedCondOperands(*P, L0, L1, R0, R1);
9954
9955 return std::nullopt;
9956}
9957
9958/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9959/// is true. Return false if LHS implies RHS is false. Otherwise, return
9960/// std::nullopt if we can't infer anything.
9961static std::optional<bool>
9963 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
9964 const DataLayout &DL, bool LHSIsTrue) {
9965 // The rest of the logic assumes the LHS condition is true. If that's not the
9966 // case, invert the predicate to make it so.
9967 if (!LHSIsTrue)
9968 LPred = FCmpInst::getInversePredicate(LPred);
9969
9970 // We can have non-canonical operands, so try to normalize any common operand
9971 // to L0/R0.
9972 if (L0 == R1) {
9973 std::swap(R0, R1);
9974 RPred = FCmpInst::getSwappedPredicate(RPred);
9975 }
9976 if (R0 == L1) {
9977 std::swap(L0, L1);
9978 LPred = FCmpInst::getSwappedPredicate(LPred);
9979 }
9980 if (L1 == R1) {
9981 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9982 if (L0 != R0 || match(L0, m_ImmConstant())) {
9983 std::swap(L0, L1);
9984 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9985 std::swap(R0, R1);
9986 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9987 }
9988 }
9989
9990 // Can we infer anything when the two compares have matching operands?
9991 if (L0 == R0 && L1 == R1) {
9992 if ((LPred & RPred) == LPred)
9993 return true;
9994 if ((LPred & ~RPred) == LPred)
9995 return false;
9996 }
9997
9998 // See if we can infer anything if operand-0 matches and we have at least one
9999 // constant.
10000 const APFloat *L1C, *R1C;
10001 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10002 if (std::optional<ConstantFPRange> DomCR =
10004 if (std::optional<ConstantFPRange> ImpliedCR =
10006 if (ImpliedCR->contains(*DomCR))
10007 return true;
10008 }
10009 if (std::optional<ConstantFPRange> ImpliedCR =
10011 FCmpInst::getInversePredicate(RPred), *R1C)) {
10012 if (ImpliedCR->contains(*DomCR))
10013 return false;
10014 }
10015 }
10016 }
10017
10018 return std::nullopt;
10019}
10020
10021/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10022/// false. Otherwise, return std::nullopt if we can't infer anything. We
10023/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10024/// instruction.
10025static std::optional<bool>
10027 const Value *RHSOp0, const Value *RHSOp1,
10028 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10029 // The LHS must be an 'or', 'and', or a 'select' instruction.
10030 assert((LHS->getOpcode() == Instruction::And ||
10031 LHS->getOpcode() == Instruction::Or ||
10032 LHS->getOpcode() == Instruction::Select) &&
10033 "Expected LHS to be 'and', 'or', or 'select'.");
10034
10035 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10036
10037 // If the result of an 'or' is false, then we know both legs of the 'or' are
10038 // false. Similarly, if the result of an 'and' is true, then we know both
10039 // legs of the 'and' are true.
10040 const Value *ALHS, *ARHS;
10041 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10042 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10043 // FIXME: Make this non-recursion.
10044 if (std::optional<bool> Implication = isImpliedCondition(
10045 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10046 return Implication;
10047 if (std::optional<bool> Implication = isImpliedCondition(
10048 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10049 return Implication;
10050 return std::nullopt;
10051 }
10052 return std::nullopt;
10053}
10054
10055std::optional<bool>
10057 const Value *RHSOp0, const Value *RHSOp1,
10058 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10059 // Bail out when we hit the limit.
10061 return std::nullopt;
10062
10063 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10064 // example.
10065 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10066 return std::nullopt;
10067
10068 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10069 "Expected integer type only!");
10070
10071 // Match not
10072 if (match(LHS, m_Not(m_Value(LHS))))
10073 LHSIsTrue = !LHSIsTrue;
10074
10075 // Both LHS and RHS are icmps.
10076 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10077 CmpPredicate LHSPred;
10078 Value *LHSOp0, *LHSOp1;
10079 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10080 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10081 RHSOp1, DL, LHSIsTrue);
10082 } else {
10083 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10084 "Expected floating point type only!");
10085 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10086 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10087 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10088 DL, LHSIsTrue);
10089 }
10090
10091 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10092 /// the RHS to be an icmp.
10093 /// FIXME: Add support for and/or/select on the RHS.
10094 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10095 if ((LHSI->getOpcode() == Instruction::And ||
10096 LHSI->getOpcode() == Instruction::Or ||
10097 LHSI->getOpcode() == Instruction::Select))
10098 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10099 Depth);
10100 }
10101 return std::nullopt;
10102}
10103
10104std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10105 const DataLayout &DL,
10106 bool LHSIsTrue, unsigned Depth) {
10107 // LHS ==> RHS by definition
10108 if (LHS == RHS)
10109 return LHSIsTrue;
10110
10111 // Match not
10112 bool InvertRHS = false;
10113 if (match(RHS, m_Not(m_Value(RHS)))) {
10114 if (LHS == RHS)
10115 return !LHSIsTrue;
10116 InvertRHS = true;
10117 }
10118
10119 CmpPredicate RHSPred;
10120 Value *RHSOp0, *RHSOp1;
10121 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10122 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10123 LHSIsTrue, Depth))
10124 return InvertRHS ? !*Implied : *Implied;
10125 return std::nullopt;
10126 }
10127 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10128 if (auto Implied = isImpliedCondition(
10129 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10130 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10131 return InvertRHS ? !*Implied : *Implied;
10132 return std::nullopt;
10133 }
10134
10136 return std::nullopt;
10137
10138 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10139 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10140 const Value *RHS1, *RHS2;
10141 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10142 if (std::optional<bool> Imp =
10143 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10144 if (*Imp == true)
10145 return !InvertRHS;
10146 if (std::optional<bool> Imp =
10147 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10148 if (*Imp == true)
10149 return !InvertRHS;
10150 }
10151 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10152 if (std::optional<bool> Imp =
10153 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10154 if (*Imp == false)
10155 return InvertRHS;
10156 if (std::optional<bool> Imp =
10157 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10158 if (*Imp == false)
10159 return InvertRHS;
10160 }
10161
10162 return std::nullopt;
10163}
10164
10165// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10166// condition dominating ContextI or nullptr, if no condition is found.
10167static std::pair<Value *, bool>
10169 if (!ContextI || !ContextI->getParent())
10170 return {nullptr, false};
10171
10172 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10173 // dominator tree (eg, from a SimplifyQuery) instead?
10174 const BasicBlock *ContextBB = ContextI->getParent();
10175 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10176 if (!PredBB)
10177 return {nullptr, false};
10178
10179 // We need a conditional branch in the predecessor.
10180 Value *PredCond;
10181 BasicBlock *TrueBB, *FalseBB;
10182 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10183 return {nullptr, false};
10184
10185 // The branch should get simplified. Don't bother simplifying this condition.
10186 if (TrueBB == FalseBB)
10187 return {nullptr, false};
10188
10189 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10190 "Predecessor block does not point to successor?");
10191
10192 // Is this condition implied by the predecessor condition?
10193 return {PredCond, TrueBB == ContextBB};
10194}
10195
10196std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10197 const Instruction *ContextI,
10198 const DataLayout &DL) {
10199 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10200 auto PredCond = getDomPredecessorCondition(ContextI);
10201 if (PredCond.first)
10202 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10203 return std::nullopt;
10204}
10205
10207 const Value *LHS,
10208 const Value *RHS,
10209 const Instruction *ContextI,
10210 const DataLayout &DL) {
10211 auto PredCond = getDomPredecessorCondition(ContextI);
10212 if (PredCond.first)
10213 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10214 PredCond.second);
10215 return std::nullopt;
10216}
10217
10219 APInt &Upper, const InstrInfoQuery &IIQ,
10220 bool PreferSignedRange) {
10221 unsigned Width = Lower.getBitWidth();
10222 const APInt *C;
10223 switch (BO.getOpcode()) {
10224 case Instruction::Sub:
10225 if (match(BO.getOperand(0), m_APInt(C))) {
10226 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10227 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10228
10229 // If the caller expects a signed compare, then try to use a signed range.
10230 // Otherwise if both no-wraps are set, use the unsigned range because it
10231 // is never larger than the signed range. Example:
10232 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10233 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10234 if (PreferSignedRange && HasNSW && HasNUW)
10235 HasNUW = false;
10236
10237 if (HasNUW) {
10238 // 'sub nuw c, x' produces [0, C].
10239 Upper = *C + 1;
10240 } else if (HasNSW) {
10241 if (C->isNegative()) {
10242 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10244 Upper = *C - APInt::getSignedMaxValue(Width);
10245 } else {
10246 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10247 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10248 Lower = *C - APInt::getSignedMaxValue(Width);
10250 }
10251 }
10252 }
10253 break;
10254 case Instruction::Add:
10255 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10256 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10257 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10258
10259 // If the caller expects a signed compare, then try to use a signed
10260 // range. Otherwise if both no-wraps are set, use the unsigned range
10261 // because it is never larger than the signed range. Example: "add nuw
10262 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10263 if (PreferSignedRange && HasNSW && HasNUW)
10264 HasNUW = false;
10265
10266 if (HasNUW) {
10267 // 'add nuw x, C' produces [C, UINT_MAX].
10268 Lower = *C;
10269 } else if (HasNSW) {
10270 if (C->isNegative()) {
10271 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10273 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10274 } else {
10275 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10276 Lower = APInt::getSignedMinValue(Width) + *C;
10277 Upper = APInt::getSignedMaxValue(Width) + 1;
10278 }
10279 }
10280 }
10281 break;
10282
10283 case Instruction::And:
10284 if (match(BO.getOperand(1), m_APInt(C)))
10285 // 'and x, C' produces [0, C].
10286 Upper = *C + 1;
10287 // X & -X is a power of two or zero. So we can cap the value at max power of
10288 // two.
10289 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10290 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10291 Upper = APInt::getSignedMinValue(Width) + 1;
10292 break;
10293
10294 case Instruction::Or:
10295 if (match(BO.getOperand(1), m_APInt(C)))
10296 // 'or x, C' produces [C, UINT_MAX].
10297 Lower = *C;
10298 break;
10299
10300 case Instruction::AShr:
10301 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10302 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10304 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10305 } else if (match(BO.getOperand(0), m_APInt(C))) {
10306 unsigned ShiftAmount = Width - 1;
10307 if (!C->isZero() && IIQ.isExact(&BO))
10308 ShiftAmount = C->countr_zero();
10309 if (C->isNegative()) {
10310 // 'ashr C, x' produces [C, C >> (Width-1)]
10311 Lower = *C;
10312 Upper = C->ashr(ShiftAmount) + 1;
10313 } else {
10314 // 'ashr C, x' produces [C >> (Width-1), C]
10315 Lower = C->ashr(ShiftAmount);
10316 Upper = *C + 1;
10317 }
10318 }
10319 break;
10320
10321 case Instruction::LShr:
10322 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10323 // 'lshr x, C' produces [0, UINT_MAX >> C].
10324 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10325 } else if (match(BO.getOperand(0), m_APInt(C))) {
10326 // 'lshr C, x' produces [C >> (Width-1), C].
10327 unsigned ShiftAmount = Width - 1;
10328 if (!C->isZero() && IIQ.isExact(&BO))
10329 ShiftAmount = C->countr_zero();
10330 Lower = C->lshr(ShiftAmount);
10331 Upper = *C + 1;
10332 }
10333 break;
10334
10335 case Instruction::Shl:
10336 if (match(BO.getOperand(0), m_APInt(C))) {
10337 if (IIQ.hasNoUnsignedWrap(&BO)) {
10338 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10339 Lower = *C;
10340 Upper = Lower.shl(Lower.countl_zero()) + 1;
10341 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10342 if (C->isNegative()) {
10343 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10344 unsigned ShiftAmount = C->countl_one() - 1;
10345 Lower = C->shl(ShiftAmount);
10346 Upper = *C + 1;
10347 } else {
10348 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10349 unsigned ShiftAmount = C->countl_zero() - 1;
10350 Lower = *C;
10351 Upper = C->shl(ShiftAmount) + 1;
10352 }
10353 } else {
10354 // If lowbit is set, value can never be zero.
10355 if ((*C)[0])
10356 Lower = APInt::getOneBitSet(Width, 0);
10357 // If we are shifting a constant the largest it can be is if the longest
10358 // sequence of consecutive ones is shifted to the highbits (breaking
10359 // ties for which sequence is higher). At the moment we take a liberal
10360 // upper bound on this by just popcounting the constant.
10361 // TODO: There may be a bitwise trick for it longest/highest
10362 // consecutative sequence of ones (naive method is O(Width) loop).
10363 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10364 }
10365 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10366 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10367 }
10368 break;
10369
10370 case Instruction::SDiv:
10371 if (match(BO.getOperand(1), m_APInt(C))) {
10372 APInt IntMin = APInt::getSignedMinValue(Width);
10373 APInt IntMax = APInt::getSignedMaxValue(Width);
10374 if (C->isAllOnes()) {
10375 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10376 // where C != -1 and C != 0 and C != 1
10377 Lower = IntMin + 1;
10378 Upper = IntMax + 1;
10379 } else if (C->countl_zero() < Width - 1) {
10380 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10381 // where C != -1 and C != 0 and C != 1
10382 Lower = IntMin.sdiv(*C);
10383 Upper = IntMax.sdiv(*C);
10384 if (Lower.sgt(Upper))
10386 Upper = Upper + 1;
10387 assert(Upper != Lower && "Upper part of range has wrapped!");
10388 }
10389 } else if (match(BO.getOperand(0), m_APInt(C))) {
10390 if (C->isMinSignedValue()) {
10391 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10392 Lower = *C;
10393 Upper = Lower.lshr(1) + 1;
10394 } else {
10395 // 'sdiv C, x' produces [-|C|, |C|].
10396 Upper = C->abs() + 1;
10397 Lower = (-Upper) + 1;
10398 }
10399 }
10400 break;
10401
10402 case Instruction::UDiv:
10403 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10404 // 'udiv x, C' produces [0, UINT_MAX / C].
10405 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10406 } else if (match(BO.getOperand(0), m_APInt(C))) {
10407 // 'udiv C, x' produces [0, C].
10408 Upper = *C + 1;
10409 }
10410 break;
10411
10412 case Instruction::SRem:
10413 if (match(BO.getOperand(1), m_APInt(C))) {
10414 // 'srem x, C' produces (-|C|, |C|).
10415 Upper = C->abs();
10416 Lower = (-Upper) + 1;
10417 } else if (match(BO.getOperand(0), m_APInt(C))) {
10418 if (C->isNegative()) {
10419 // 'srem -|C|, x' produces [-|C|, 0].
10420 Upper = 1;
10421 Lower = *C;
10422 } else {
10423 // 'srem |C|, x' produces [0, |C|].
10424 Upper = *C + 1;
10425 }
10426 }
10427 break;
10428
10429 case Instruction::URem:
10430 if (match(BO.getOperand(1), m_APInt(C)))
10431 // 'urem x, C' produces [0, C).
10432 Upper = *C;
10433 else if (match(BO.getOperand(0), m_APInt(C)))
10434 // 'urem C, x' produces [0, C].
10435 Upper = *C + 1;
10436 break;
10437
10438 default:
10439 break;
10440 }
10441}
10442
10444 bool UseInstrInfo) {
10445 unsigned Width = II.getType()->getScalarSizeInBits();
10446 const APInt *C;
10447 switch (II.getIntrinsicID()) {
10448 case Intrinsic::ctlz:
10449 case Intrinsic::cttz: {
10450 APInt Upper(Width, Width);
10451 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10452 Upper += 1;
10453 // Maximum of set/clear bits is the bit width.
10455 }
10456 case Intrinsic::ctpop:
10457 // Maximum of set/clear bits is the bit width.
10459 APInt(Width, Width) + 1);
10460 case Intrinsic::uadd_sat:
10461 // uadd.sat(x, C) produces [C, UINT_MAX].
10462 if (match(II.getOperand(0), m_APInt(C)) ||
10463 match(II.getOperand(1), m_APInt(C)))
10465 break;
10466 case Intrinsic::sadd_sat:
10467 if (match(II.getOperand(0), m_APInt(C)) ||
10468 match(II.getOperand(1), m_APInt(C))) {
10469 if (C->isNegative())
10470 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10472 APInt::getSignedMaxValue(Width) + *C +
10473 1);
10474
10475 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10477 APInt::getSignedMaxValue(Width) + 1);
10478 }
10479 break;
10480 case Intrinsic::usub_sat:
10481 // usub.sat(C, x) produces [0, C].
10482 if (match(II.getOperand(0), m_APInt(C)))
10483 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10484
10485 // usub.sat(x, C) produces [0, UINT_MAX - C].
10486 if (match(II.getOperand(1), m_APInt(C)))
10488 APInt::getMaxValue(Width) - *C + 1);
10489 break;
10490 case Intrinsic::ssub_sat:
10491 if (match(II.getOperand(0), m_APInt(C))) {
10492 if (C->isNegative())
10493 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10495 *C - APInt::getSignedMinValue(Width) +
10496 1);
10497
10498 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10500 APInt::getSignedMaxValue(Width) + 1);
10501 } else if (match(II.getOperand(1), m_APInt(C))) {
10502 if (C->isNegative())
10503 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10505 APInt::getSignedMaxValue(Width) + 1);
10506
10507 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10509 APInt::getSignedMaxValue(Width) - *C +
10510 1);
10511 }
10512 break;
10513 case Intrinsic::umin:
10514 case Intrinsic::umax:
10515 case Intrinsic::smin:
10516 case Intrinsic::smax:
10517 if (!match(II.getOperand(0), m_APInt(C)) &&
10518 !match(II.getOperand(1), m_APInt(C)))
10519 break;
10520
10521 switch (II.getIntrinsicID()) {
10522 case Intrinsic::umin:
10523 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10524 case Intrinsic::umax:
10526 case Intrinsic::smin:
10528 *C + 1);
10529 case Intrinsic::smax:
10531 APInt::getSignedMaxValue(Width) + 1);
10532 default:
10533 llvm_unreachable("Must be min/max intrinsic");
10534 }
10535 break;
10536 case Intrinsic::abs:
10537 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10538 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10539 if (match(II.getOperand(1), m_One()))
10541 APInt::getSignedMaxValue(Width) + 1);
10542
10544 APInt::getSignedMinValue(Width) + 1);
10545 case Intrinsic::vscale:
10546 if (!II.getParent() || !II.getFunction())
10547 break;
10548 return getVScaleRange(II.getFunction(), Width);
10549 default:
10550 break;
10551 }
10552
10553 return ConstantRange::getFull(Width);
10554}
10555
10557 const InstrInfoQuery &IIQ) {
10558 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10559 const Value *LHS = nullptr, *RHS = nullptr;
10561 if (R.Flavor == SPF_UNKNOWN)
10562 return ConstantRange::getFull(BitWidth);
10563
10564 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10565 // If the negation part of the abs (in RHS) has the NSW flag,
10566 // then the result of abs(X) is [0..SIGNED_MAX],
10567 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10568 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10572
10575 }
10576
10577 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10578 // The result of -abs(X) is <= 0.
10580 APInt(BitWidth, 1));
10581 }
10582
10583 const APInt *C;
10584 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10585 return ConstantRange::getFull(BitWidth);
10586
10587 switch (R.Flavor) {
10588 case SPF_UMIN:
10590 case SPF_UMAX:
10592 case SPF_SMIN:
10594 *C + 1);
10595 case SPF_SMAX:
10598 default:
10599 return ConstantRange::getFull(BitWidth);
10600 }
10601}
10602
10604 // The maximum representable value of a half is 65504. For floats the maximum
10605 // value is 3.4e38 which requires roughly 129 bits.
10606 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10607 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10608 return;
10609 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10610 Lower = APInt(BitWidth, -65504, true);
10611 Upper = APInt(BitWidth, 65505);
10612 }
10613
10614 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10615 // For a fptoui the lower limit is left as 0.
10616 Upper = APInt(BitWidth, 65505);
10617 }
10618}
10619
10621 const SimplifyQuery &SQ,
10622 unsigned Depth) {
10623 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10624
10626 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10627
10628 if (auto *C = dyn_cast<Constant>(V))
10629 return C->toConstantRange();
10630
10631 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10632 ConstantRange CR = ConstantRange::getFull(BitWidth);
10633 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10634 APInt Lower = APInt(BitWidth, 0);
10635 APInt Upper = APInt(BitWidth, 0);
10636 // TODO: Return ConstantRange.
10637 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10639 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10641 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10642 ConstantRange CRTrue =
10643 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10644 ConstantRange CRFalse =
10645 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10646 CR = CRTrue.unionWith(CRFalse);
10648 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10649 ConstantRange SrcCR =
10650 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10651 CR = SrcCR.truncate(BitWidth);
10652 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10653 APInt Lower = APInt(BitWidth, 0);
10654 APInt Upper = APInt(BitWidth, 0);
10655 // TODO: Return ConstantRange.
10658 } else if (const auto *A = dyn_cast<Argument>(V))
10659 if (std::optional<ConstantRange> Range = A->getRange())
10660 CR = *Range;
10661
10662 if (auto *I = dyn_cast<Instruction>(V)) {
10663 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10665
10666 Value *FrexpSrc;
10667 if (const auto *CB = dyn_cast<CallBase>(V)) {
10668 if (std::optional<ConstantRange> Range = CB->getRange())
10669 CR = CR.intersectWith(*Range);
10671 m_Value(FrexpSrc))))) {
10672 const fltSemantics &FltSem =
10673 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10674 // It should be possible to implement this for any type, but this logic
10675 // only computes the range assuming standard subnormal handling.
10676 if (APFloat::isIEEELikeFP(FltSem)) {
10678 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10679
10680 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10681 // constrain its range when the source can be neither.
10682 if (KnownSrc.isKnownNeverInfOrNaN()) {
10683 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10684
10685 // Offset to find the true minimum exponent value for a denormal.
10686 if (!KnownSrc.isKnownNeverSubnormal())
10687 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10688
10689 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10690
10691 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10693
10694 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10695 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10696
10697 MinExp = std::max(AdjustedMin, MinExp);
10698 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10699 MaxExp);
10700
10702 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10703 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10704 /*isSigned=*/true));
10705 }
10706 }
10707 }
10708 }
10709
10710 if (SQ.CxtI && SQ.AC) {
10711 // Try to restrict the range based on information from assumptions.
10712 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10713 if (!AssumeVH)
10714 continue;
10715 CallInst *I = cast<CallInst>(AssumeVH);
10716 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10717 "Got assumption for the wrong function!");
10718 assert(I->getIntrinsicID() == Intrinsic::assume &&
10719 "must be an assume intrinsic");
10720
10721 if (!isValidAssumeForContext(I, SQ))
10722 continue;
10723 Value *Arg = I->getArgOperand(0);
10724 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10725 // Currently we just use information from comparisons.
10726 if (!Cmp || Cmp->getOperand(0) != V)
10727 continue;
10728 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10729 ConstantRange RHS =
10730 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10731 SQ.getWithInstruction(I), Depth + 1);
10732 CR = CR.intersectWith(
10733 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10734 }
10735 }
10736
10737 return CR;
10738}
10739
10740static void
10742 function_ref<void(Value *)> InsertAffected) {
10743 assert(V != nullptr);
10744 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10745 InsertAffected(V);
10746 } else if (auto *I = dyn_cast<Instruction>(V)) {
10747 InsertAffected(V);
10748
10749 // Peek through unary operators to find the source of the condition.
10750 Value *Op;
10752 m_Trunc(m_Value(Op))))) {
10754 InsertAffected(Op);
10755 }
10756 }
10757}
10758
10760 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10761 auto AddAffected = [&InsertAffected](Value *V) {
10762 addValueAffectedByCondition(V, InsertAffected);
10763 };
10764
10765 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10766 if (IsAssume) {
10767 AddAffected(LHS);
10768 AddAffected(RHS);
10769 } else if (match(RHS, m_Constant()))
10770 AddAffected(LHS);
10771 };
10772
10773 SmallVector<Value *, 8> Worklist;
10775 Worklist.push_back(Cond);
10776 while (!Worklist.empty()) {
10777 Value *V = Worklist.pop_back_val();
10778 if (!Visited.insert(V).second)
10779 continue;
10780
10781 CmpPredicate Pred;
10782 Value *A, *B, *X;
10783
10784 if (IsAssume) {
10785 AddAffected(V);
10786 if (match(V, m_Not(m_Value(X))))
10787 AddAffected(X);
10788 }
10789
10790 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10791 // assume(A && B) is split to -> assume(A); assume(B);
10792 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10793 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10794 // enough information to be worth handling (intersection of information as
10795 // opposed to union).
10796 if (!IsAssume) {
10797 Worklist.push_back(A);
10798 Worklist.push_back(B);
10799 }
10800 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10801 bool HasRHSC = match(B, m_ConstantInt());
10802 if (ICmpInst::isEquality(Pred)) {
10803 AddAffected(A);
10804 if (IsAssume)
10805 AddAffected(B);
10806 if (HasRHSC) {
10807 Value *Y;
10808 // (X << C) or (X >>_s C) or (X >>_u C).
10809 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10810 AddAffected(X);
10811 // (X & C) or (X | C).
10812 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10813 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10814 AddAffected(X);
10815 AddAffected(Y);
10816 }
10817 // X - Y
10818 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10819 AddAffected(X);
10820 AddAffected(Y);
10821 }
10822 }
10823 } else {
10824 AddCmpOperands(A, B);
10825 if (HasRHSC) {
10826 // Handle (A + C1) u< C2, which is the canonical form of
10827 // A > C3 && A < C4.
10829 AddAffected(X);
10830
10831 if (ICmpInst::isUnsigned(Pred)) {
10832 Value *Y;
10833 // X & Y u> C -> X >u C && Y >u C
10834 // X | Y u< C -> X u< C && Y u< C
10835 // X nuw+ Y u< C -> X u< C && Y u< C
10836 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10837 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10838 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10839 AddAffected(X);
10840 AddAffected(Y);
10841 }
10842 // X nuw- Y u> C -> X u> C
10843 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10844 AddAffected(X);
10845 }
10846 }
10847
10848 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10849 // by computeKnownFPClass().
10851 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10852 InsertAffected(X);
10853 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10854 InsertAffected(X);
10855 }
10856 }
10857
10858 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10859 Value *SquareOp = nullptr;
10860 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10861 AddAffected(SquareOp);
10862 };
10863 AddNuwSquareOperand(A);
10864 AddNuwSquareOperand(B);
10865
10866 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10867 AddAffected(X);
10868 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10869 AddCmpOperands(A, B);
10870
10871 // fcmp fneg(x), y
10872 // fcmp fabs(x), y
10873 // fcmp fneg(fabs(x)), y
10874 if (match(A, m_FNeg(m_Value(A))))
10875 AddAffected(A);
10876 if (match(A, m_FAbs(m_Value(A))))
10877 AddAffected(A);
10878
10880 m_Value()))) {
10881 // Handle patterns that computeKnownFPClass() support.
10882 AddAffected(A);
10883 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10884 // Assume is checked here as X is already added above for assumes in
10885 // addValueAffectedByCondition
10886 AddAffected(X);
10887 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10888 // Assume is checked here to avoid issues with ephemeral values
10889 Worklist.push_back(X);
10890 }
10891 }
10892}
10893
10895 // (X >> C) or/add (X & mask(C) != 0)
10896 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10897 if (BO->getOpcode() == Instruction::Add ||
10898 BO->getOpcode() == Instruction::Or) {
10899 const Value *X;
10900 const APInt *C1, *C2;
10901 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10905 m_Zero())))) &&
10906 C2->popcount() == C1->getZExtValue())
10907 return X;
10908 }
10909 }
10910 return nullptr;
10911}
10912
10914 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
10915}
10916
10919 unsigned MaxCount, bool AllowUndefOrPoison) {
10922 auto Push = [&](const Value *V) -> bool {
10923 Constant *C;
10924 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
10925 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
10926 return false;
10927 // Check existence first to avoid unnecessary allocations.
10928 if (Constants.contains(C))
10929 return true;
10930 if (Constants.size() == MaxCount)
10931 return false;
10932 Constants.insert(C);
10933 return true;
10934 }
10935
10936 if (auto *Inst = dyn_cast<Instruction>(V)) {
10937 if (Visited.insert(Inst).second)
10938 Worklist.push_back(Inst);
10939 return true;
10940 }
10941 return false;
10942 };
10943 if (!Push(V))
10944 return false;
10945 while (!Worklist.empty()) {
10946 const Instruction *CurInst = Worklist.pop_back_val();
10947 switch (CurInst->getOpcode()) {
10948 case Instruction::Select:
10949 if (!Push(CurInst->getOperand(1)))
10950 return false;
10951 if (!Push(CurInst->getOperand(2)))
10952 return false;
10953 break;
10954 case Instruction::PHI:
10955 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
10956 // Fast path for recurrence PHI.
10957 if (IncomingValue == CurInst)
10958 continue;
10959 if (!Push(IncomingValue))
10960 return false;
10961 }
10962 break;
10963 default:
10964 return false;
10965 }
10966 }
10967 return true;
10968}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:351
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:326
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:347
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:322
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:318
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:355
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:368
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:359
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:6131
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2007
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
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:1254
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1671
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1409
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
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:105
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:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange 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 bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:793
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...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
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:232
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:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
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:255
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:727
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3041
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
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:668
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI 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:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
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)
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
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 bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
std::optional< bool > SignBit
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 asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041