29#include "llvm/IR/IntrinsicsAMDGPU.h"
40#define DEBUG_TYPE "amdgpu-codegenprepare"
47class AMDGPUCodeGenPrepareImpl
48 :
public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
50 const AMDGPUOptions &CLOpts;
59 const bool HasFP32DenormalFlush;
60 const bool ExpandDiv64InIR;
61 bool FlowChanged =
false;
63 mutable Function *LdexpF32 =
nullptr;
78 ExpandDiv64InIR(ExpandDiv64InIR) {}
86 F.getParent(), Intrinsic::amdgcn_sqrt, {Type::getFloatTy(Ctx)});
96 F.getParent(), Intrinsic::ldexp,
97 {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
101 bool canBreakPHINode(
const PHINode &
I);
104 bool isLegalFloatingTy(
const Type *
T)
const;
114 return HasFP32DenormalFlush ||
142 unsigned MaxDivBits,
bool Signed)
const;
148 bool IsSigned)
const;
152 bool IsDiv,
bool IsSigned)
const;
170 bool canWidenScalarExtLoad(
LoadInst &
I)
const;
185 float ReqdAccuracy)
const;
190 float ReqdAccuracy)
const;
192 std::pair<Value *, Value *> getFrexpResults(
IRBuilder<> &Builder,
196 bool IsNegative)
const;
203 bool IsNegative)
const;
207 void replaceWithMaskedWorkitemIdX(
Instruction &
I,
unsigned WaveSize)
const;
208 bool tryReplaceWithWorkitemId(
Instruction &
I,
unsigned Wave)
const;
236 explicit AMDGPUCodeGenPrepare(
bool ExpandDiv64InIR =
false)
245 if (!ExpandDiv64InIR)
249 StringRef getPassName()
const override {
return "AMDGPU IR optimizations"; }
252 bool ExpandDiv64InIR;
257bool AMDGPUCodeGenPrepareImpl::run() {
258 BreakPhiNodesCache.clear();
259 bool MadeChange =
false;
271 while (!DeadVals.empty()) {
279bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(
const Type *Ty)
const {
281 (Ty->
isHalfTy() && ST.has16BitInsts());
284bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &
I)
const {
285 Type *Ty =
I.getType();
286 int TySize =
DL.getTypeSizeInBits(Ty);
289 return I.isSimple() && TySize < 32 && Alignment >= 4 && UA.
isUniformAtDef(&
I);
293AMDGPUCodeGenPrepareImpl::numBitsUnsigned(
Value *
Op,
294 const Instruction *CtxI)
const {
299AMDGPUCodeGenPrepareImpl::numBitsSigned(
Value *
Op,
300 const Instruction *CtxI)
const {
312 for (
int I = 0,
E = VT->getNumElements();
I !=
E; ++
I)
313 Values.push_back(Builder.CreateExtractElement(
V,
I));
319 if (!Ty->isVectorTy()) {
326 NewVal = Builder.CreateInsertElement(NewVal,
Values[
I],
I);
331bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &
I)
const {
332 if (
I.getOpcode() != Instruction::Mul)
335 Type *Ty =
I.getType();
337 if (
Size <= 16 && ST.has16BitInsts())
347 Builder.SetCurrentDebugLocation(
I.getDebugLoc());
349 unsigned LHSBits = 0, RHSBits = 0;
350 bool IsSigned =
false;
352 if (ST.
hasMulU24() && (LHSBits = numBitsUnsigned(
LHS, &
I)) <= 24 &&
353 (RHSBits = numBitsUnsigned(
RHS, &
I)) <= 24) {
356 }
else if (ST.
hasMulI24() && (LHSBits = numBitsSigned(
LHS, &
I)) <= 24 &&
357 (RHSBits = numBitsSigned(
RHS, &
I)) <= 24) {
363 SmallVector<Value *, 4> LHSVals;
364 SmallVector<Value *, 4> RHSVals;
365 SmallVector<Value *, 4> ResultVals;
369 IntegerType *I32Ty = Builder.getInt32Ty();
370 IntegerType *IntrinTy =
Size > 32 ? Builder.getInt64Ty() : I32Ty;
371 Type *DstTy = LHSVals[0]->getType();
373 for (
int I = 0,
E = LHSVals.
size();
I !=
E; ++
I) {
374 Value *
LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[
I], I32Ty)
375 : Builder.CreateZExtOrTrunc(LHSVals[
I], I32Ty);
376 Value *
RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[
I], I32Ty)
377 : Builder.CreateZExtOrTrunc(RHSVals[
I], I32Ty);
379 IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
381 Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
382 : Builder.CreateZExtOrTrunc(Result, DstTy);
388 I.replaceAllUsesWith(NewVal);
389 DeadVals.push_back(&
I);
409bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO)
const {
430 if (!CBO || !CT || !CF)
457 Builder.setFastMathFlags(
FPOp->getFastMathFlags());
463 DeadVals.push_back(&BO);
465 DeadVals.push_back(CastOp);
466 DeadVals.push_back(Sel);
470std::pair<Value *, Value *>
471AMDGPUCodeGenPrepareImpl::getFrexpResults(
IRBuilder<> &Builder,
473 Type *Ty = Src->getType();
486 : Builder.CreateExtractValue(Frexp, {1});
487 return {FrexpMant, FrexpExp};
493 bool IsNegative)
const {
508 auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
511 return Builder.
CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
517 FastMathFlags FMF)
const {
521 if (HasFP32DenormalFlush && ST.
hasFractBug() && !ST.hasFastFMAF32() &&
527 auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder,
RHS);
532 auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder,
LHS);
544 FastMathFlags FMF)
const {
545 Type *Ty = Src->getType();
549 Builder.
CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
552 Value *InputScaleFactor =
559 Value *OutputScaleFactor =
561 return Builder.
CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
572 Type *Ty = Src->getType();
576 Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
577 Constant *One = ConstantFP::get(Ty, 1.0);
578 Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
580 ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
582 Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
584 Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
585 Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
586 Value *OutputScaleFactor = Builder.CreateSelect(
587 NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
589 return Builder.CreateFMul(Rsq, OutputScaleFactor);
595 FastMathFlags SqrtFMF,
596 FastMathFlags DivFMF,
597 const Instruction *CtxI,
598 bool IsNegative)
const {
620 bool MaybePosInf = !SqrtFMF.
noInfs() && !DivFMF.
noInfs();
621 bool MaybeZero = !DivFMF.
noInfs();
623 DenormalMode DenormMode;
630 if (Interested !=
fcNone) {
635 DenormMode =
F.getDenormalMode(
X->getType()->getFltSemantics());
641 if (MaybeZero || MaybePosInf) {
643 if (MaybePosInf && MaybeZero) {
644 if (DenormMode.
Input != DenormalMode::DenormalModeKind::Dynamic) {
659 }
else if (MaybeZero) {
672 Value *
E = Builder.
CreateFMA(NegXY0, Y0, ConstantFP::get(
X->getType(), 1.0));
677 ConstantFP::get(
X->getType(), 0.5));
679 return Builder.
CreateFMA(Y0E, EFMA, IsNegative ? NegY0 : Y0);
682bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(FastMathFlags DivFMF,
683 FastMathFlags SqrtFMF)
const {
689Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
691 const FastMathFlags SqrtFMF,
const Instruction *CtxI)
const {
702 bool IsNegative =
false;
708 IRBuilder<>::FastMathFlagGuard Guard(Builder);
709 FastMathFlags NewFMF = DivFMF | SqrtFMF;
717 canIgnoreDenormalInput(Den, CtxI)) {
728 return emitRsqF64(Builder, Den, SqrtFMF, DivFMF, CtxI, IsNegative);
742 Value *Den, FastMathFlags FMF,
743 const Instruction *CtxI)
const {
750 bool IsNegative =
false;
754 if (HasFP32DenormalFlush || FMF.
approxFunc()) {
775 return emitRcpIEEE1ULP(Builder, Src, IsNegative);
784 if (HasFP32DenormalFlush || FMF.
approxFunc()) {
789 Value *Recip = emitRcpIEEE1ULP(Builder, Den,
false);
803Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
806 if (ReqdAccuracy < 2.5f)
812 bool NumIsOne =
false;
814 if (CNum->isOne() || CNum->isMinusOne())
822 if (!HasFP32DenormalFlush && !NumIsOne)
825 return Builder.
CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {Num, Den});
828Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
830 FastMathFlags SqrtFMF,
Value *RsqOp,
const Instruction *FDivInst,
831 float ReqdDivAccuracy)
const {
834 optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
842 Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
850 Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
854 return emitFrexpDiv(Builder, Num, Den, DivFMF);
872bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
873 if (!CLOpts.codegenprepare_fdiv_expansion)
885 const FastMathFlags DivFMF =
FPOp->getFastMathFlags();
886 const float ReqdAccuracy =
FPOp->getFPAccuracy();
888 FastMathFlags SqrtFMF;
893 Value *RsqOp =
nullptr;
895 if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
896 DenII->hasOneUse()) {
898 SqrtFMF = SqrtOp->getFastMathFlags();
899 if (canOptimizeWithRsq(DivFMF, SqrtFMF))
900 RsqOp = SqrtOp->getOperand(0);
904 if (!IsFloat && !RsqOp)
916 const bool AllowInaccurateRcp = DivFMF.
approxFunc();
917 if (!RsqOp && AllowInaccurateRcp)
921 if (IsFloat && ReqdAccuracy < 1.0f)
928 SmallVector<Value *, 4> NumVals;
929 SmallVector<Value *, 4> DenVals;
930 SmallVector<Value *, 4> RsqDenVals;
937 SmallVector<Value *, 4> ResultVals(NumVals.
size());
938 for (
int I = 0,
E = NumVals.
size();
I !=
E; ++
I) {
939 Value *NumElt = NumVals[
I];
940 Value *DenElt = DenVals[
I];
941 Value *RsqDenElt = RsqOp ? RsqDenVals[
I] :
nullptr;
944 visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
953 NewEltInst->copyMetadata(FDiv);
956 ResultVals[
I] = NewElt;
964 DeadVals.push_back(&FDiv);
975 Value *LHS_EXT64 = Builder.CreateZExt(
LHS, I64Ty);
976 Value *RHS_EXT64 = Builder.CreateZExt(
RHS, I64Ty);
977 Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
978 Value *
Lo = Builder.CreateTrunc(MUL64, I32Ty);
979 Value *
Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
980 Hi = Builder.CreateTrunc(
Hi, I32Ty);
981 return std::pair(
Lo,
Hi);
992unsigned AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &
I,
Value *Num,
995 bool IsSigned)
const {
1002 unsigned DivBits = SSBits - RHSSignBits + 1;
1003 if (DivBits > MaxDivBits)
1008 unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1009 DivBits = SSBits - SignBits + 1;
1016 unsigned RHSBits =
Known.countMaxActiveBits();
1017 if (RHSBits > MaxDivBits)
1021 unsigned LHSBits =
Known.countMaxActiveBits();
1023 unsigned DivBits = std::max(LHSBits, RHSBits);
1031 bool IsSigned)
const {
1032 unsigned DivBits = getDivNumBits(
I, Num, Den, 23, IsSigned);
1034 if (DivBits > (IsSigned ? 23u : 22u))
1036 return expandDivRemToFloatImpl(Builder,
I, Num, Den, DivBits, IsDiv,
1040Value *AMDGPUCodeGenPrepareImpl::expandDivRemToFloatImpl(
1042 unsigned DivBits,
bool IsDiv,
bool IsSigned)
const {
1056 assert(0 < DivBits && DivBits <= (IsSigned ? 23u : 22u) &&
1057 "abs(Num) must be <= 0x400000 for expandDivRemToFloatImpl to work "
1065 ConstantInt *One = Builder.
getInt32(1);
1123bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &
I,
1129 if (
C->getType()->getScalarSizeInBits() <= 32)
1145 if (BinOpDen->getOpcode() == Instruction::Shl &&
1159 if (
Known.isNegative())
1161 if (
Known.isNonNegative())
1163 return Builder.CreateAShr(
V, Builder.getInt32(31));
1170 assert(
Opc == Instruction::URem ||
Opc == Instruction::UDiv ||
1171 Opc == Instruction::SRem ||
Opc == Instruction::SDiv);
1177 if (divHasSpecialOptimization(
I,
X,
Y))
1180 bool IsDiv =
Opc == Instruction::UDiv ||
Opc == Instruction::SDiv;
1181 bool IsSigned =
Opc == Instruction::SRem ||
Opc == Instruction::SDiv;
1183 Type *Ty =
X->getType();
1197 if (
Value *Res = expandDivRemToFloat(Builder,
I,
X,
Y, IsDiv, IsSigned)) {
1203 ConstantInt *One = Builder.
getInt32(1);
1291 BinaryOperator &
I,
Value *Num,
1293 if (!ExpandDiv64InIR && divHasSpecialOptimization(
I, Num, Den))
1298 bool IsDiv =
Opc == Instruction::SDiv ||
Opc == Instruction::UDiv;
1299 bool IsSigned =
Opc == Instruction::SDiv ||
Opc == Instruction::SRem;
1301 unsigned NumDivBits = getDivNumBits(
I, Num, Den, 32, IsSigned);
1302 if (NumDivBits > 32)
1305 Value *Narrowed =
nullptr;
1306 if (NumDivBits <= (IsSigned ? 23u : 22u)) {
1307 Narrowed = expandDivRemToFloatImpl(Builder,
I, Num, Den, NumDivBits, IsDiv,
1309 }
else if (NumDivBits <= (IsSigned ? 31u : 32u)) {
1314 Narrowed = expandDivRem32(Builder,
I, Num, Den);
1325void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &
I)
const {
1328 if (
Opc == Instruction::UDiv ||
Opc == Instruction::SDiv) {
1333 if (
Opc == Instruction::URem ||
Opc == Instruction::SRem) {
1353bool AMDGPUCodeGenPrepareImpl::tryNarrowMathIfNoOverflow(Instruction *
I) {
1354 unsigned Opc =
I->getOpcode();
1356 if (
Opc != Instruction::Add &&
Opc != Instruction::Mul)
1359 Type *OldType =
I->getType();
1363 MaxBitsNeeded = std::max<unsigned>(
bit_ceil(MaxBitsNeeded), 8);
1364 Type *NewType =
DL.getSmallestLegalIntType(
I->getContext(), MaxBitsNeeded);
1368 if (NewBit >= OrigBit)
1379 int NumOfNonConstOps = 2;
1382 NumOfNonConstOps = 1;
1392 if (NewCost >= OldCost)
1403 DeadVals.push_back(
I);
1407bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &
I) {
1408 if (foldBinOpIntoSelect(
I))
1411 if (CLOpts.codegenprepare_mul24 && replaceMulWithMul24(
I))
1413 if (tryNarrowMathIfNoOverflow(&
I))
1418 Type *Ty =
I.getType();
1419 Value *NewDiv =
nullptr;
1424 if ((
Opc == Instruction::URem ||
Opc == Instruction::UDiv ||
1425 Opc == Instruction::SRem ||
Opc == Instruction::SDiv) &&
1426 ScalarSize <= 64 && CLOpts.codegenprepare_idiv_expansion) {
1427 Value *Num =
I.getOperand(0);
1428 Value *Den =
I.getOperand(1);
1435 for (
unsigned N = 0,
E = VT->getNumElements();
N !=
E; ++
N) {
1440 if (ScalarSize <= 32) {
1441 NewElt = expandDivRem32(Builder,
I, NumEltN, DenEltN);
1447 NewElt = shrinkDivRem64(Builder,
I, NumEltN, DenEltN);
1461 NewEltI->copyIRFlags(&
I);
1466 if (ScalarSize <= 32)
1467 NewDiv = expandDivRem32(Builder,
I, Num, Den);
1469 NewDiv = shrinkDivRem64(Builder,
I, Num, Den);
1470 if (!NewDiv && ExpandDiv64InIR) {
1481 I.replaceAllUsesWith(NewDiv);
1482 DeadVals.push_back(&
I);
1487 if (ExpandDiv64InIR) {
1489 for (BinaryOperator *
Div : Div64ToExpand) {
1490 expandDivRem64(*
Div);
1499bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &
I) {
1500 if (!CLOpts.codegenprepare_widen_constant_loads)
1505 canWidenScalarExtLoad(
I)) {
1516 if (
auto *
Range =
I.getMetadata(LLVMContext::MD_range)) {
1519 if (!
Lower->isNullValue()) {
1526 WidenLoad->setMetadata(LLVMContext::MD_range,
1531 int TySize =
DL.getTypeSizeInBits(
I.getType());
1536 DeadVals.push_back(&
I);
1544bool AMDGPUCodeGenPrepareImpl::foldSelectToFMulLegacy(SelectInst &
I)
const {
1545 if (!
I.getType()->isFloatTy())
1553 Value *
Mul = Inverted ?
I.getTrueValue() :
I.getFalseValue();
1562 FCmpInst::Predicate ZeroCmpPred =
1563 Inverted ? FCmpInst::FCMP_UNE : FCmpInst::FCMP_OEQ;
1575 Value *SA = InstCombiner::stripSignOnlyFPOps(
A);
1576 Value *SB = InstCombiner::stripSignOnlyFPOps(
B);
1577 Value *SX = InstCombiner::stripSignOnlyFPOps(
X);
1578 Value *
SY = InstCombiner::stripSignOnlyFPOps(
Y);
1579 if (!((SA == SX && SB == SY) || (SA == SY && SB == SX)))
1596 I.replaceAllUsesWith(LegacyMul);
1597 DeadVals.push_back(&
I);
1601bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &
I) {
1606 if (foldSelectToFMulLegacy(
I))
1610 Value *Fract =
nullptr;
1619 Value *FractSrc = matchFractPatImpl(*
X, *
C);
1624 Fract = applyFractPat(Builder, FractSrc);
1634 CmpPredicate IsNanPred;
1643 if (IsNanPred == FCmpInst::FCMP_UNO && TrueVal == CmpVal &&
1644 CmpVal == matchFractPatNanAvoidant(*FalseVal)) {
1646 Fract = applyFractPat(Builder, CmpVal);
1647 }
else if (IsNanPred == FCmpInst::FCMP_ORD && FalseVal == CmpVal) {
1648 if (CmpVal == matchFractPatNanAvoidant(*TrueVal)) {
1650 Fract = applyFractPat(Builder, CmpVal);
1654 CmpPredicate PredInf;
1660 PredInf != FCmpInst::FCMP_UNE ||
1661 CmpVal != matchFractPatNanAvoidant(*IfNotInf))
1671 Value *NewFract = applyFractPat(Builder, CmpVal);
1675 DeadVals.push_back(ClampInfSelect->
getOperand(1));
1679 Fract = ClampInfSelect;
1686 I.replaceAllUsesWith(Fract);
1687 DeadVals.push_back(&
I);
1694 return IA && IB && IA->getParent() == IB->getParent();
1707 BitVector EltsCovered(FVT->getNumElements());
1714 if (!Idx || Idx->getZExtValue() >= FVT->getNumElements())
1717 const auto *VecSrc = IE->getOperand(0);
1726 EltsCovered.
set(Idx->getZExtValue());
1729 if (EltsCovered.
all())
1756 const auto [It, Inserted] = SeenPHIs.
insert(&
I);
1760 for (
const Value *Inc :
I.incoming_values()) {
1765 for (
const User *U :
I.users()) {
1771bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(
const PHINode &
I) {
1773 if (
const auto It = BreakPhiNodesCache.find(&
I);
1774 It != BreakPhiNodesCache.end())
1783 SmallPtrSet<const PHINode *, 8> WorkList;
1789 for (
const PHINode *WLP : WorkList) {
1790 assert(BreakPhiNodesCache.count(WLP) == 0);
1805 const auto Threshold = (
alignTo(WorkList.size() * 2, 3) / 3);
1806 unsigned NumBreakablePHIs = 0;
1807 bool CanBreak =
false;
1808 for (
const PHINode *Cur : WorkList) {
1816 if (++NumBreakablePHIs >= Threshold) {
1823 for (
const PHINode *Cur : WorkList)
1824 BreakPhiNodesCache[Cur] = CanBreak;
1873 Value *&Res = SlicedVals[{BB, Inc}];
1879 B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1885 Res =
B.CreateShuffleVector(Inc, Mask, NewValName);
1887 Res =
B.CreateExtractElement(Inc,
Idx, NewValName);
1896bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &
I) {
1907 if (!CLOpts.codegenprepare_break_large_phis ||
1909 cl::boolOrDefault::BOU_TRUE)
1914 DL.getTypeSizeInBits(FVT) <=
1915 CLOpts.codegenprepare_break_large_phis_threshold)
1918 if (!CLOpts.codegenprepare_force_break_large_phis && !canBreakPHINode(
I))
1921 std::vector<VectorSlice> Slices;
1928 const unsigned EltSize =
DL.getTypeSizeInBits(EltTy);
1930 if (EltSize == 8 || EltSize == 16) {
1931 const unsigned SubVecSize = (32 / EltSize);
1935 Slices.emplace_back(
SubVecTy, Idx, SubVecSize);
1939 for (;
Idx < NumElts; ++
Idx)
1940 Slices.emplace_back(EltTy, Idx, 1);
1943 assert(Slices.size() > 1);
1949 B.SetCurrentDebugLocation(
I.getDebugLoc());
1951 unsigned IncNameSuffix = 0;
1952 for (VectorSlice &S : Slices) {
1955 B.SetInsertPoint(
I.getParent()->getFirstNonPHIIt());
1956 S.NewPHI =
B.CreatePHI(S.Ty,
I.getNumIncomingValues());
1958 for (
const auto &[Idx, BB] :
enumerate(
I.blocks())) {
1959 S.NewPHI->addIncoming(S.getSlicedVal(BB,
I.getIncomingValue(Idx),
1960 "largephi.extractslice" +
1961 std::to_string(IncNameSuffix++)),
1968 unsigned NameSuffix = 0;
1969 for (VectorSlice &S : Slices) {
1970 const auto ValName =
"largephi.insertslice" + std::to_string(NameSuffix++);
1972 Vec =
B.CreateInsertVector(FVT, Vec, S.NewPHI, S.Idx, ValName);
1974 Vec =
B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
1977 I.replaceAllUsesWith(Vec);
1978 DeadVals.push_back(&
I);
2001 Load &&
Load->hasMetadata(LLVMContext::MD_nonnull))
2020 assert(SrcPtrKB.getBitWidth() ==
DL.getPointerSizeInBits(AS));
2021 assert((NullVal == 0 || NullVal == -1) &&
2022 "don't know how to check for this null value!");
2023 return NullVal ? !SrcPtrKB.getMaxValue().isAllOnes() : SrcPtrKB.isNonZero();
2026bool AMDGPUCodeGenPrepareImpl::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
2039 if (
I.getType()->isVectorTy())
2044 const unsigned SrcAS =
I.getSrcAddressSpace();
2045 const unsigned DstAS =
I.getDestAddressSpace();
2047 bool CanLower =
false;
2068bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &
I) {
2071 case Intrinsic::minnum:
2072 case Intrinsic::minimumnum:
2073 case Intrinsic::minimum:
2074 return visitFMinLike(
I);
2075 case Intrinsic::sqrt:
2076 return visitSqrt(
I);
2077 case Intrinsic::log:
2078 case Intrinsic::log10:
2080 case Intrinsic::log2:
2083 case Intrinsic::amdgcn_mbcnt_lo:
2084 return visitMbcntLo(
I);
2085 case Intrinsic::amdgcn_mbcnt_hi:
2086 return visitMbcntHi(
I);
2087 case Intrinsic::vector_reduce_add:
2088 return visitVectorReduceAdd(
I);
2089 case Intrinsic::uadd_sat:
2090 case Intrinsic::sadd_sat:
2091 return visitSaturatingAdd(
I);
2099Value *AMDGPUCodeGenPrepareImpl::matchFractPatImpl(
Value &FractSrc,
2100 const APFloat &
C)
const {
2109 OneNextDown.
next(
true);
2112 if (OneNextDown !=
C)
2132Value *AMDGPUCodeGenPrepareImpl::matchFractPatNanAvoidant(
Value &
V) {
2144 return matchFractPatImpl(*Arg0, *
C);
2149 SmallVector<Value *, 4> FractVals;
2152 SmallVector<Value *, 4> ResultVals(FractVals.
size());
2155 for (
unsigned I = 0,
E = FractVals.
size();
I !=
E; ++
I) {
2163bool AMDGPUCodeGenPrepareImpl::visitFMinLike(IntrinsicInst &
I) {
2171 FractArg = matchFractPatImpl(*
X, *
C);
2176 FractArg = matchFractPatNanAvoidant(
I);
2188 FastMathFlags FMF =
I.getFastMathFlags();
2192 Value *Fract = applyFractPat(Builder, FractArg);
2194 I.replaceAllUsesWith(Fract);
2195 DeadVals.push_back(&
I);
2200bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
2206 FastMathFlags SqrtFMF =
FPOp->getFastMathFlags();
2213 const float ReqdAccuracy =
FPOp->getFPAccuracy();
2216 if (ReqdAccuracy < 1.0f)
2220 bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
2224 if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
2228 SmallVector<Value *, 4> SrcVals;
2231 SmallVector<Value *, 4> ResultVals(SrcVals.
size());
2232 for (
int I = 0,
E = SrcVals.
size();
I !=
E; ++
I) {
2234 ResultVals[
I] = Builder.
CreateCall(getSqrtF32(), SrcVals[
I]);
2236 ResultVals[
I] = emitSqrtIEEE2ULP(Builder, SrcVals[
I], SqrtFMF);
2242 DeadVals.push_back(&Sqrt);
2247bool AMDGPUCodeGenPrepareImpl::visitLog(FPMathOperator &Log,
2253 FastMathFlags FMF =
Log.getFastMathFlags();
2260 if (
Log.getFPAccuracy() < 1.80f)
2271 double Log2BaseInverted =
2278 Log.replaceAllUsesWith(
Mul);
2279 DeadVals.push_back(&Log);
2283bool AMDGPUCodeGenPrepare::runOnFunction(
Function &
F) {
2284 if (skipFunction(
F))
2287 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
2291 const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2292 const TargetTransformInfo &
TTI =
2293 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
2294 const TargetLibraryInfo *
TLI =
2295 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F);
2296 AssumptionCache *AC =
2297 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F);
2298 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2299 const DominatorTree *DT = DTWP ? &DTWP->getDomTree() :
nullptr;
2301 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
2302 return AMDGPUCodeGenPrepareImpl(
F, TM,
TTI,
TLI, AC, DT, UA, ExpandDiv64InIR)
2314 AMDGPUCodeGenPrepareImpl Impl(
F, ATM,
TTI,
TLI, AC, DT, UA,
2315 ATM.
getCLOpts().codegenprepare_expand_div64);
2319 if (!Impl.FlowChanged)
2325 "AMDGPU IR optimizations",
false,
false)
2336 B.CreateIntrinsicWithoutFolding(Intrinsic::amdgcn_workitem_id_x, {});
2337 ST.makeLIDRangeMetadata(Tid);
2342void AMDGPUCodeGenPrepareImpl::replaceWithWorkitemIdX(Instruction &
I)
const {
2344 CallInst *Tid = createWorkitemIdX(
B);
2350void AMDGPUCodeGenPrepareImpl::replaceWithMaskedWorkitemIdX(
2351 Instruction &
I,
unsigned WaveSize)
const {
2353 CallInst *Tid = createWorkitemIdX(
B);
2355 Value *AndInst =
B.CreateAnd(Tid, Mask);
2363bool AMDGPUCodeGenPrepareImpl::tryReplaceWithWorkitemId(Instruction &
I,
2364 unsigned Wave)
const {
2371 if (*MaybeX == Wave) {
2372 replaceWithWorkitemIdX(
I);
2379 replaceWithMaskedWorkitemIdX(
I, Wave);
2387bool AMDGPUCodeGenPrepareImpl::visitMbcntLo(IntrinsicInst &
I)
const {
2403bool AMDGPUCodeGenPrepareImpl::visitMbcntHi(IntrinsicInst &
I)
const {
2421 using namespace PatternMatch;
2429 return tryReplaceWithWorkitemId(
I, Wave);
2455 Value *ExtSrc0, *ExtSrc1;
2475bool AMDGPUCodeGenPrepareImpl::visitVectorReduceAdd(IntrinsicInst &
I) {
2477 if (!ST.hasDot7Insts() || (!ST.hasDot1Insts() && !ST.hasDot8Insts()))
2480 Value *
A =
nullptr, *
B =
nullptr;
2483 bool IsSigned =
false;
2490 LLVMContext &Ctx =
I.getContext();
2491 Type *I32Ty = Type::getInt32Ty(Ctx);
2499 Value *Acc = ConstantInt::get(I32Ty, 0);
2503 IsSigned ? Intrinsic::amdgcn_sdot4 : Intrinsic::amdgcn_udot4;
2508 I.replaceAllUsesWith(Dot);
2509 DeadVals.push_back(&
I);
2517bool AMDGPUCodeGenPrepareImpl::visitSaturatingAdd(IntrinsicInst &
I) {
2519 if (!ST.hasDot7Insts() || (!ST.hasDot1Insts() && !ST.hasDot8Insts()))
2523 bool IsSigned = (IID == Intrinsic::sadd_sat);
2526 Value *Op0 =
I.getArgOperand(0);
2527 Value *Op1 =
I.getArgOperand(1);
2528 Value *MulOp =
nullptr;
2529 Value *Accum =
nullptr;
2530 IntrinsicInst *ReduceInst =
nullptr;
2535 }
else if (
match(Op1,
2543 Value *
A =
nullptr, *
B =
nullptr;
2548 LLVMContext &Ctx =
I.getContext();
2549 Type *I32Ty = Type::getInt32Ty(Ctx);
2560 IsSigned ? Intrinsic::amdgcn_sdot4 : Intrinsic::amdgcn_udot4;
2565 I.replaceAllUsesWith(Dot);
2566 DeadVals.push_back(&
I);
2569 DeadVals.push_back(ReduceInst);
2574char AMDGPUCodeGenPrepare::ID = 0;
2577 return new AMDGPUCodeGenPrepare(ExpandDiv64InIR);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
static Value * insertValues(IRBuilder<> &Builder, Type *Ty, SmallVectorImpl< Value * > &Values)
static void extractValues(IRBuilder<> &Builder, SmallVectorImpl< Value * > &Values, Value *V)
static Value * getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS)
static bool isInterestingPHIIncomingValue(const Value *V)
static SelectInst * findSelectThroughCast(Value *V, CastInst *&Cast)
static bool matchDot4Pattern(Value *MulOp, Value *&A, Value *&B, bool IsSigned)
Helper to match the dot4 pattern: mul(zext/sext <4 x i8>, zext/sext <4 x i8>) Returns true if pattern...
static bool isV4I8(Type *Ty)
Check if type is <4 x i8>.
static std::pair< Value *, Value * > getMul64(IRBuilder<> &Builder, Value *LHS, Value *RHS)
static Value * emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src, bool IsNegative)
Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
static Value * getSign32(Value *V, IRBuilder<> &Builder, const DataLayout DL)
static void collectPHINodes(const PHINode &I, SmallPtrSet< const PHINode *, 8 > &SeenPHIs)
static bool isPtrKnownNeverNull(const Value *V, const DataLayout &DL, const AMDGPUTargetMachine &TM, unsigned AS)
static bool areInSameBB(const Value *A, const Value *B)
The AMDGPU TargetMachine interface definition for hw codegen targets.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
This file provides the interface for the instcombine pass implementation.
SmallVector< MachineOperand, 4 > Cond
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Target-Independent Code Generator Pass Configuration Options pass.
VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
Value * getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName)
Slice Inc according to the information contained within this slice.
PreservedAnalyses run(Function &, FunctionAnalysisManager &)
std::optional< unsigned > getReqdWorkGroupSize(const Function &F, unsigned Dim) const
unsigned getWavefrontSize() const
bool hasWavefrontsEvenlySplittingXDim(const Function &F, bool RequiresUniformYZ=false) const
const AMDGPUOptions & getCLOpts() const
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
opStatus next(bool nextDown)
This class represents a conversion between pointers from one address space to another.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
BitVector & set()
Set all bits in the bitvector.
bool all() const
Returns true if all bits are set.
Represents analyses that only rely on functions' control flow.
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.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
bool isMinusOne() const
Returns true if this value is exactly -1.0.
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
bool isOne() const
Returns true if this value is exactly +1.0.
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Utility class for floating point operations which can have information about relaxed accuracy require...
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
bool noSignedZeros() const
static FastMathFlags intersectValue(FastMathFlags LHS, FastMathFlags RHS)
Intersect value flags.
bool allowReciprocal() const
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setNoInfs(bool B=true)
bool allowContract() const
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
FunctionPass class - This class is used to implement most global optimizations.
bool isWaveSizeKnown() const
Returns if the wavesize of this subtarget is known reliable.
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Value * CreateFDiv(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFPToUI(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Value * CreateUIToFP(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false, MDNode *FPMathTag=nullptr)
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Value * CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNSW=false)
LLVM_ABI Value * createIsFPClass(Value *FPNum, unsigned Test)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateFMA(Value *Factor1, Value *Factor2, Value *Summand, FMFSource FMFSource={}, const Twine &Name="")
Create call to the fma intrinsic.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Value * CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateSIToFP(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
Value * CreateFMulFMF(Value *L, Value *R, FMFSource FMFSource, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Value * CreateFPToSI(Value *V, Type *DestTy, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Base class for instruction visitors.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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 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.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVM_ABI unsigned getIntegerBitWidth() const
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI const fltSemantics & getFltSemantics() const
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Type * getElementType() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ LOCAL_ADDRESS
Address space for local memory.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ FLAT_ADDRESS
Address space for flat memory.
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr int64_t getNullPointerValue(unsigned AS)
Get the null pointer value for the given address space.
void copyMetadataForWidenedLoad(LoadInst &Dest, const LoadInst &Source)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
auto m_PosZeroFP()
Matches a floating-point positive zero.
AllOnesConstantMatch m_AllOnes()
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.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
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.
ap_match< APFloat > m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
FMaxMin_match< LHS, RHS, ufmin_pred_ty > m_UnordFMin(const LHS &L, const RHS &R)
Match an 'unordered' floating point minimum function.
auto m_FMinimum(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
cstfp_pred_ty< is_nonnan > m_NonNaN()
Match a non-NaN FP constant.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_FMinNum_or_FMinimumNum(const Opnd0 &Op0, const Opnd1 &Op1)
cstfp_pred_ty< is_signed_inf< false > > m_PosInf()
Match a positive infinity FP constant.
SpecificCmpClass_match< LHS, RHS, FCmpInst > m_SpecificFCmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_FAbs(const Opnd0 &Op0)
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.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
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.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
RelativeUniformCounterPtr Values
@ Known
Known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool expandRemainderUpTo64Bits(BinaryOperator *Rem)
Generate code to calculate the remainder of two integers, replacing Rem with the generated code.
@ Load
The value being inserted comes from a load (InsertElement only).
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
LLVM_ABI void ReplaceInstWithValue(BasicBlock::iterator &BI, Value *V)
Replace all uses of an instruction (specified by BI) with a value, then remove and delete the origina...
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
FPOp
The floating-point operations supported by the folding helpers.
auto reverse(ContainerTy &&C)
LLVM_ABI bool expandDivisionUpTo64Bits(BinaryOperator *Div)
Generate code to divide two integers, replacing Div with the generated code.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
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...
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
To bit_cast(const From &from) noexcept
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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...
unsigned Log2(Align A)
Returns the log2 of the alignment.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
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...
FunctionPass * createAMDGPUCodeGenPreparePass(bool ExpandDiv64InIR)
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
constexpr bool inputsAreZero() const
Return true if input denormals must be implicitly treated as 0.
static constexpr DenormalMode getPreserveSign()
SimplifyQuery getWithInstruction(const Instruction *I) const