1//===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
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
7//===----------------------------------------------------------------------===//
9// This file implements folding of constants for LLVM. This implements the
10// (internal) ConstantFold.h interface, which is used by the
11// ConstantExpr::get* methods to automatically fold constants when possible.
13// The current constant folding implementation is implemented in two pieces: the
14// pieces that don't need DataLayout, and the pieces that do. This is to avoid
15// a dependence in IR on Target.
17//===----------------------------------------------------------------------===//
35//===----------------------------------------------------------------------===//
36// ConstantFold*Instruction Implementations
37//===----------------------------------------------------------------------===//
39/// This function determines which opcode to use to fold two constant cast
40/// expressions together. It uses CastInst::isEliminableCastPair to determine
41/// the opcode. Consequently its just a wrapper around that function.
42/// Determine if it is valid to fold a cast of a cast
45 unsigned opc,
///< opcode of the second cast constant expression
47 Type *DstTy
///< destination type of the first cast
49 assert(
Op &&
Op->isCast() &&
"Can't fold cast of cast without a cast!");
53 // The types and opcodes for the two Cast constant expressions
54 Type *SrcTy =
Op->getOperand(0)->getType();
55 Type *MidTy =
Op->getType();
63 Type *SrcTy = V->getType();
65 return V;
// no-op cast
67 if (V->isAllOnesValue())
70 // Handle ConstantInt -> ConstantFP
72 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
73 // This allows for other simplifications (although some of them
74 // can only be handled by Analysis/ConstantFolding.cpp).
78 // Make sure dest type is compatible with the folded fp constant.
79 // See note below regarding the PPC_FP128 restriction.
84 return ConstantFP::get(
89 // Handle ConstantFP -> ConstantInt
91 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
92 // This allows for other simplifications (although some of them
93 // can only be handled by Analysis/ConstantFolding.cpp).
97 // PPC_FP128 is really the sum of two consecutive doubles, where the first
98 // double is always stored first in memory, regardless of the target
99 // endianness. The memory layout of i128, however, depends on the target
100 // endianness, and so we can't fold this without target endianness
101 // information. This should instead be handled by
102 // Analysis/ConstantFolding.cpp
103 if (SrcTy->isPPC_FP128Ty())
106 // Make sure dest type is compatible with the folded integer constant.
111 return ConstantInt::get(DestTy,
FP->getValueAPF().bitcastToAPInt());
130 // zext(undef) = 0, because the top bits will be zero.
131 // sext(undef) = 0, because the top bits will all be the same.
132 // [us]itofp(undef) = 0, because the result value is bounded.
133 if (opc == Instruction::ZExt || opc == Instruction::SExt ||
134 opc == Instruction::UIToFP || opc == Instruction::SIToFP)
140 opc != Instruction::AddrSpaceCast)
143 // If the cast operand is a constant expression, there's a few things we can
144 // do to try to simplify it.
147 // Try hard to fold cast of cast because they are often eliminable.
153 // If the cast operand is a constant vector, perform the cast by
154 // operating on each element. In the cast of bitcasts, the element
155 // count may be mismatched; don't attempt to handle that here.
156 if (DestTy->
isVectorTy() && V->getType()->isVectorTy() &&
161 // Fast path for splatted constants.
185 // We actually have to do a cast now. Perform the cast according to the
190 case Instruction::FPTrunc:
191 case Instruction::FPExt:
194 APFloat Val = FPC->getValueAPF();
197 return ConstantFP::get(DestTy, Val);
199 return nullptr;
// Can't fold.
200 case Instruction::FPToUI:
201 case Instruction::FPToSI:
203 const APFloat &V = FPC->getValueAPF();
208 // Undefined behavior invoked - the destination type can't represent
209 // the input constant.
212 return ConstantInt::get(DestTy, IntVal);
214 return nullptr;
// Can't fold.
215 case Instruction::UIToFP:
216 case Instruction::SIToFP:
218 const APInt &api = CI->getValue();
223 return ConstantFP::get(DestTy, apf);
226 case Instruction::ZExt:
229 return ConstantInt::get(DestTy, CI->getValue().zext(
BitWidth));
232 case Instruction::SExt:
235 return ConstantInt::get(DestTy, CI->getValue().sext(
BitWidth));
238 case Instruction::Trunc: {
241 return ConstantInt::get(DestTy, CI->getValue().trunc(
BitWidth));
246 case Instruction::BitCast:
248 case Instruction::AddrSpaceCast:
249 case Instruction::IntToPtr:
250 case Instruction::PtrToAddr:
251 case Instruction::PtrToInt:
258 // Check for i1 and vector true/false conditions.
259 if (
Cond->isNullValue())
return V2;
260 if (
Cond->isAllOnesValue())
return V1;
262 // If the condition is a vector constant, fold the result elementwise.
264 auto *V1VTy = CondV->getType();
267 for (
unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
270 ConstantInt::get(Ty, i));
272 ConstantInt::get(Ty, i));
276 }
else if (V1Element == V2Element) {
282 V =
Cond->isNullValue() ? V2Element : V1Element;
287 // If we were able to build the vector, return it.
288 if (Result.size() == V1VTy->getNumElements())
300 if (V1 == V2)
return V1;
307 // If the true or false value is undef, we can fold to the other value as
308 // long as the other value isn't poison.
313 // TODO: We can analyze ConstExpr by opcode to determine if there is any
314 // possibility of poison.
322 if (
C->getType()->isVectorTy())
323 return !
C->containsPoisonElement() && !
C->containsConstantExpression();
325 // TODO: Recursively analyze aggregates or other constants.
338 // extractelt poison, C -> poison
339 // extractelt C, undef -> poison
343 // extractelt undef, C -> undef
352 // ee({w,x,y,z}, wrong_value) -> poison
353 if (CIdx->uge(ValFVTy->getNumElements()))
357 // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
361 Ops.reserve(CE->getNumOperands());
362 for (
unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
364 if (
Op->getType()->isVectorTy()) {
368 Ops.push_back(ScalarOp);
372 return CE->getWithOperands(
Ops, ValVTy->getElementType(),
false,
373 GEP->getSourceElementType());
374 }
else if (CE->getOpcode() == Instruction::InsertElement) {
377 APSInt(CIdx->getValue()))) {
378 return CE->getOperand(1);
389 // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
390 if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
404 // Inserting null into all zeros is still all zeros.
405 // TODO: This is true for undef and poison splats too.
410 if (!CIdx)
return nullptr;
412 // Do not iterate on scalable vector. The num of elements is unknown at
419 unsigned NumElts = ValTy->getNumElements();
420 if (CIdx->
uge(NumElts))
424 Result.reserve(NumElts);
427 for (
unsigned i = 0; i != NumElts; ++i) {
429 Result.push_back(Elt);
443 unsigned MaskNumElts = Mask.size();
446 Type *EltTy = V1VTy->getElementType();
448 // Poison shuffle mask -> poison value.
453 // If the mask is all zeros this is a splat, no need to go through all
455 if (
all_of(Mask, [](
int Elt) {
return Elt == 0; })) {
460 // For scalable vectors, make sure this doesn't fold back into a
466 // Do not iterate on scalable vector. The num of elements is unknown at
471 unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
473 // Loop over the shuffle mask, evaluating each element.
475 for (
unsigned i = 0; i != MaskNumElts; ++i) {
482 if (
unsigned(Elt) >= SrcNumElts*2)
484 else if (
unsigned(Elt) >= SrcNumElts) {
488 ConstantInt::get(Ty, Elt - SrcNumElts));
493 Result.push_back(InElt);
501 // Base case: no indices, so return the entire value.
514 // Base case: no indices, so replace the entire value.
520 NumElts = ST->getNumElements();
525 for (
unsigned i = 0; i != NumElts; ++i) {
527 if (!
C)
return nullptr;
543 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
544 // vectors are always evaluated per element.
546 bool HasScalarUndefOrScalableVectorUndef =
549 if (HasScalarUndefOrScalableVectorUndef) {
551 case Instruction::FNeg:
552 return C;
// -undef -> undef
553 case Instruction::UnaryOpsEnd:
558 // Constant should not be UndefValue, unless these are vector constants.
559 assert(!HasScalarUndefOrScalableVectorUndef &&
"Unexpected UndefValue");
560 // We only have FP UnaryOps right now.
564 const APFloat &CV = CFP->getValueAPF();
568 case Instruction::FNeg:
569 return ConstantFP::get(
C->getType(),
neg(CV));
572 // Fast path for splatted constants.
578 // Fold each element and create a vector constant from those constants.
581 for (
unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
582 Constant *ExtractIdx = ConstantInt::get(Ty, i);
587 Result.push_back(Res);
594 // We don't know how to fold this.
602 // Simplify BinOps with their identity values first. They are no-ops and we
603 // can always return the other value, including undef or poison values.
605 Opcode, C1->
getType(),
/*AllowRHSIdentity*/ false)) {
611 Opcode, C1->
getType(),
/*AllowRHSIdentity*/ true)) {
616 // Binary operations propagate poison.
620 // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
621 // vectors are always evaluated per element.
623 bool HasScalarUndefOrScalableVectorUndef =
624 (!C1->
getType()->isVectorTy() || IsScalableVector) &&
626 if (HasScalarUndefOrScalableVectorUndef) {
628 case Instruction::Xor:
630 // Handle undef ^ undef -> 0 special case. This is a common
634 case Instruction::Add:
635 case Instruction::Sub:
637 case Instruction::And:
641 case Instruction::Mul: {
642 // undef * undef -> undef
646 // X * undef -> undef if X is odd
651 // X * undef -> 0 otherwise
654 case Instruction::SDiv:
655 case Instruction::UDiv:
656 // X / undef -> poison
660 // undef / X -> 0 otherwise
662 case Instruction::URem:
663 case Instruction::SRem:
664 // X % undef -> poison
668 // undef % X -> 0 otherwise
670 case Instruction::Or:
// X | undef -> -1
674 case Instruction::LShr:
675 // X >>l undef -> poison
680 case Instruction::AShr:
681 // X >>a undef -> poison
684 // TODO: undef >>a X -> poison if the shift is exact
687 case Instruction::Shl:
688 // X << undef -> undef
693 case Instruction::FSub:
694 // -0.0 - undef --> undef (consistent with "fneg undef")
698 case Instruction::FAdd:
699 case Instruction::FMul:
700 case Instruction::FDiv:
701 case Instruction::FRem:
702 // [any flop] undef, undef -> undef
705 // [any flop] C, undef -> NaN
706 // [any flop] undef, C -> NaN
707 // We could potentially specialize NaN/Inf constants vs. 'normal'
708 // constants (possibly differently depending on opcode and operand). This
709 // would allow returning undef sometimes. But it is always safe to fold to
710 // NaN because we can choose the undef operand as NaN, and any FP opcode
711 // with a NaN operand will propagate NaN.
713 case Instruction::BinaryOpsEnd:
718 // Neither constant should be UndefValue, unless these are vector constants.
719 assert((!HasScalarUndefOrScalableVectorUndef) &&
"Unexpected UndefValue");
721 // Handle simplifications when the RHS is a constant int.
724 /*AllowLHSConstant*/ false))
728 case Instruction::UDiv:
729 case Instruction::SDiv:
733 case Instruction::URem:
734 case Instruction::SRem:
740 case Instruction::And:
741 assert(!CI2->isZero() &&
"And zero handled above");
743 // If and'ing the address of a global with a constant, fold it.
744 if ((CE1->getOpcode() == Instruction::PtrToInt ||
745 CE1->getOpcode() == Instruction::PtrToAddr) &&
749 Align GVAlign;
// defaults to 1
755 // If the function alignment is not specified then assume that it
757 // This is dangerous; on x86, the alignment of the pointer
758 // corresponds to the alignment of the function, but might be less
759 // than 4 if it isn't explicitly specified.
760 // However, a fix for this behaviour was reverted because it
761 // increased code size (see https://reviews.llvm.org/D55115)
762 // FIXME: This code should be deleted once existing targets have
763 // appropriate defaults
771 unsigned DstWidth = CI2->getBitWidth();
772 unsigned SrcWidth = std::min(DstWidth,
Log2(GVAlign));
775 // If checking bits we know are clear, return zero.
776 if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
784 // If C1 is a ConstantInt and C2 is not, swap the operands.
793 const APInt &C1V = CI1->getValue();
794 const APInt &C2V = CI2->getValue();
798 case Instruction::Add:
799 return ConstantInt::get(C1->
getType(), C1V + C2V);
800 case Instruction::Sub:
801 return ConstantInt::get(C1->
getType(), C1V - C2V);
802 case Instruction::Mul:
803 return ConstantInt::get(C1->
getType(), C1V * C2V);
804 case Instruction::UDiv:
805 assert(!CI2->isZero() &&
"Div by zero handled above");
806 return ConstantInt::get(CI1->getType(), C1V.
udiv(C2V));
807 case Instruction::SDiv:
808 assert(!CI2->isZero() &&
"Div by zero handled above");
811 return ConstantInt::get(CI1->getType(), C1V.
sdiv(C2V));
812 case Instruction::URem:
813 assert(!CI2->isZero() &&
"Div by zero handled above");
814 return ConstantInt::get(C1->
getType(), C1V.
urem(C2V));
815 case Instruction::SRem:
816 assert(!CI2->isZero() &&
"Div by zero handled above");
819 return ConstantInt::get(C1->
getType(), C1V.
srem(C2V));
820 case Instruction::And:
821 return ConstantInt::get(C1->
getType(), C1V & C2V);
822 case Instruction::Or:
823 return ConstantInt::get(C1->
getType(), C1V | C2V);
824 case Instruction::Xor:
825 return ConstantInt::get(C1->
getType(), C1V ^ C2V);
826 case Instruction::Shl:
828 return ConstantInt::get(C1->
getType(), C1V.
shl(C2V));
830 case Instruction::LShr:
832 return ConstantInt::get(C1->
getType(), C1V.
lshr(C2V));
834 case Instruction::AShr:
836 return ConstantInt::get(C1->
getType(), C1V.
ashr(C2V));
842 /*AllowLHSConstant*/ true))
846 const APFloat &C1V = CFP1->getValueAPF();
847 const APFloat &C2V = CFP2->getValueAPF();
848 APFloat C3V = C1V;
// copy for modification
852 case Instruction::FAdd:
854 return ConstantFP::get(C1->
getType(), C3V);
855 case Instruction::FSub:
857 return ConstantFP::get(C1->
getType(), C3V);
858 case Instruction::FMul:
860 return ConstantFP::get(C1->
getType(), C3V);
861 case Instruction::FDiv:
863 return ConstantFP::get(C1->
getType(), C3V);
864 case Instruction::FRem:
866 return ConstantFP::get(C1->
getType(), C3V);
872 // Fast path for splatted constants.
888 // Fold each element and create a vector constant from those constants.
891 for (
unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
892 Constant *ExtractIdx = ConstantInt::get(Ty, i);
900 Result.push_back(Res);
908 // There are many possible foldings we could do here. We should probably
909 // at least fold add of a pointer with an integer into the appropriate
910 // getelementptr. This will improve alias analysis a bit.
912 // Given ((a + b) + c), if (b + c) folds to something interesting, return
920 // If C2 is a constant expr and C1 isn't, flop them around and fold the
921 // other way if possible.
926 // i1 can be simplified in many cases.
929 case Instruction::Add:
930 case Instruction::Sub:
932 case Instruction::Shl:
933 case Instruction::LShr:
934 case Instruction::AShr:
935 // We can assume that C2 == 0. If it were one the result would be
936 // undefined because the shift value is as large as the bitwidth.
938 case Instruction::SDiv:
939 case Instruction::UDiv:
940 // We can assume that C2 == 1. If it were zero the result would be
941 // undefined through division by zero.
943 case Instruction::URem:
944 case Instruction::SRem:
945 // We can assume that C2 == 1. If it were zero the result would be
946 // undefined through division by zero.
953 // We don't know how to fold this.
959 auto isGlobalUnsafeForEquality = [](
const GlobalValue *GV) {
960 if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
963 Type *Ty = GVar->getValueType();
964 // A global with opaque type might end up being zero sized.
967 // A global with an empty type might lie at the address of any other
974 // Don't try to decide equality of aliases.
976 if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
981/// This function determines if there is anything we can decide about the two
982/// constants provided. This doesn't need to handle simple things like integer
983/// comparisons, but should instead handle ConstantExprs and GlobalValues.
984/// If we can determine that the two constants have a particular relation to
985/// each other, we should return the corresponding ICmp predicate, otherwise
986/// return ICmpInst::BAD_ICMP_PREDICATE.
989 "Cannot compare different types of values!");
992 // The following folds only apply to pointers.
996 // To simplify this code we canonicalize the relation so that the first
997 // operand is always the most "complex" of the two. We consider simple
998 // constants (like ConstantPointerNull) to be the simplest, followed by
999 // BlockAddress, GlobalValues, and ConstantExpr's (the most complex).
1000 auto GetComplexity = [](
Constant *V) {
1009 if (GetComplexity(V1) < GetComplexity(V2)) {
1017 // Now we know that the RHS is a BlockAddress or simple constant.
1019 // Block address in another function can't equal this one, but block
1020 // addresses in the current function might be the same if blocks are
1022 if (BA2->getFunction() != BA->getFunction())
1028 // Now we know that the RHS is a GlobalValue, BlockAddress or simple
1035 // GlobalVals can never be null unless they have external weak linkage.
1036 // We don't try to evaluate aliases here.
1037 // NOTE: We should not be doing this constant folding if null pointer
1038 // is considered valid for the function. But currently there is no way to
1039 // query it from the Constant type.
1042 GV->getType()->getAddressSpace()))
1046 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
1047 // constantexpr, a global, block address, or a simple constant.
1050 switch (CE1->getOpcode()) {
1051 case Instruction::GetElementPtr: {
1053 // Ok, since this is a getelementptr, we know that the constant has a
1054 // pointer type. Check the various cases.
1056 // If we are comparing a GEP to a null pointer, check to see if the base
1057 // of the GEP equals the null pointer.
1059 // If its not weak linkage, the GVal must have a non-zero address
1060 // so the result is greater-than
1061 if (!GV->hasExternalWeakLinkage() && CE1GEP->
isInBounds())
1073 // By far the most common case to handle is when the base pointers are
1074 // obviously to the same global.
1077 // Don't know relative ordering, but check for inequality.
1078 if (CE1Op0 != CE2Op0) {
1101 VT->getElementCount());
1105 // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1112 // Handle some degenerate cases first
1118 // For EQ and NE, we can always pick a value for the undef to make the
1119 // predicate pass or fail, so we can return undef.
1120 // Also, if both operands are undef, we can return undef for int comparison.
1124 // Otherwise, for integer compare, pick the same value as the non-undef
1125 // operand, and fold it to true or false.
1126 if (isIntegerPredicate)
1129 // Choosing NaN for the undef will always make unordered comparison succeed
1130 // and ordered comparison fails.
1135 // The caller is expected to commute the operands if the constant expression
1145 // If the comparison is a comparison between two i1's, simplify it.
1147 switch (Predicate) {
1169 // Fast path for splatted constants.
1176 // Do not iterate on scalable vector. The number of elements is unknown at
1181 // If we can constant fold the comparison of each element, constant fold
1182 // the whole vector comparison.
1185 // Compare the elements, producing an i1 result or constant expr.
1186 for (
unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
1204 // We know that C1 == C2 || isUnordered(C1, C2).
1211 // Evaluate the relation between the two constants, per the predicate.
1212 int Result = -1;
// -1 = unknown, 0 = known false, 1 = known true.
1216 break;
// Couldn't determine anything about these constants.
1218 // If we know the constants are equal, we can decide the result of this
1219 // computation precisely.
1223 switch (Predicate) {
1233 switch (Predicate) {
1243 switch (Predicate) {
1253 switch (Predicate) {
1294 // If we evaluated the result, return it now.
1296 return ConstantInt::get(ResultTy, Result);
1300 // If C2 is a constant expr and C1 isn't, flip them around and fold the
1301 // other way if possible.
1302 // Also, if C1 is null and C2 isn't, flip them around.
1311 std::optional<ConstantRange>
InRange,
1313 if (Idxs.
empty())
return C;
1324 auto IsNoOp = [&]() {
1325 // Avoid losing inrange information.
1335 return GEPTy->
isVectorTy() && !
C->getType()->isVectorTy()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static unsigned foldConstantCastPair(unsigned opc, ConstantExpr *Op, Type *DstTy)
This function determines which opcode to use to fold two constant cast expressions together.
static Constant * foldMaybeUndesirableCast(unsigned opc, Constant *V, Type *DestTy)
static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1, const GlobalValue *GV2)
static Constant * FoldBitCast(Constant *V, Type *DestTy)
static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2)
This function determines if there is anything we can decide about the two constants provided.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
static constexpr roundingMode rmTowardZero
static constexpr roundingMode rmNearestTiesToEven
opStatus divide(const APFloat &RHS, roundingMode RM)
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
opStatus subtract(const APFloat &RHS, roundingMode RM)
opStatus add(const APFloat &RHS, roundingMode RM)
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
opStatus multiply(const APFloat &RHS, roundingMode RM)
opStatus mod(const APFloat &RHS)
Class for arbitrary precision integers.
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
bool isMinSignedValue() const
Determine if this is the smallest signed value.
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
unsigned getBitWidth() const
Return the number of bits in the APInt.
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
APInt shl(unsigned shiftAmt) const
Left-shift function.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
An arbitrary precision integer that knows its signedness.
static bool isSameValue(const APSInt &I1, const APSInt &I2)
Determine if two APSInts have the same value, zero- or sign-extending as needed.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
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.
The address of a basic block.
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
static bool isIntPredicate(Predicate P)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
ConstantFP - Floating Point Values [float, double].
static LLVM_ABI Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
bool uge(uint64_t Num) const
This function will return true iff this constant represents a value with active bits bigger than 64 b...
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
Constant Vector Declarations.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
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...
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
A parsed version of the target data layout string in and methods for querying it.
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
bool hasAllZeroIndices() const
Return true if all of the indices of this GEP are zeros.
static Type * getGEPReturnType(Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
Module * getParent()
Get the module that this global value is contained inside of...
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LLVM_ABI bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A Module instance is used to store all the information related to an LLVM module.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isX86_AMXTy() const
Return true if this is X86 AMX.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
LLVM_ABI const fltSemantics & getFltSemantics() const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Base class of all SIMD vector types.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
cstfp_pred_ty< is_neg_zero_fp > m_NegZeroFP()
Match a floating-point negative zero.
auto m_Undef()
Match an arbitrary undef constant.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
LLVM_ABI Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
LLVM_ABI Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, std::optional< ConstantRange > InRange, ArrayRef< Value * > Idxs)
LLVM_ABI Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
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 Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
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...
constexpr int PoisonMaskElem
LLVM_ABI Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
APFloat neg(APFloat X)
Returns the negated value of the argument.
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
unsigned Log2(Align A)
Returns the log2 of the alignment.
LLVM_ABI Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
This struct is a compact representation of a valid (non-zero power of two) alignment.