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