26#define DEBUG_TYPE "amdgpu-simplifylib"
32 cl::desc(
"Enable pre-link mode optimizations"),
37 cl::desc(
"Comma separated list of functions to replace with native, or all"),
41#define MATH_PI numbers::pi
42#define MATH_E numbers::e
43#define MATH_SQRT2 numbers::sqrt2
44#define MATH_SQRT1_2 numbers::inv_sqrt2
57 bool AllNative =
false;
78 bool parseFunctionName(
const StringRef &FMangledName, FuncInfo &FInfo);
80 bool TDOFold(
CallInst *CI,
const FuncInfo &FInfo);
91 const FuncInfo &FInfo);
97 bool sincosUseNative(
CallInst *aCI,
const FuncInfo &FInfo);
100 bool evaluateScalarMathFunc(
const FuncInfo &FInfo,
APFloat &Res0,
102 bool evaluateCall(
CallInst *aCI,
const FuncInfo &FInfo);
106 std::tuple<Value *, Value *, Value *> insertSinCos(
Value *Arg,
116 const FuncInfo &FInfo);
123 bool shouldReplaceLibcallWithIntrinsic(
const CallInst *CI,
124 bool AllowMinSizeF32 =
false,
125 bool AllowF64 =
false,
126 bool AllowStrictFP =
false);
132 bool AllowMinSizeF32 =
false,
133 bool AllowF64 =
false,
134 bool AllowStrictFP =
false);
142 I->replaceAllUsesWith(With);
143 I->eraseFromParent();
163template <
typename IRB>
165 const Twine &Name =
"") {
166 CallInst *R =
B.CreateCall(Callee, Arg, Name);
168 R->setCallingConv(
F->getCallingConv());
172template <
typename IRB>
175 CallInst *R =
B.CreateCall(Callee, {Arg1, Arg2}, Name);
177 R->setCallingConv(
F->getCallingConv());
187 {FT->getParamType(0), PowNExpTy},
false);
425 : AMDGPULibFunc::getFunction(
M, fInfo);
429 Module *M,
const FuncInfo &fInfo, FuncInfo &newInfo,
431 assert(NewFunc != FastVariant);
435 newInfo = AMDGPULibFunc(FastVariant, fInfo);
436 if (FunctionCallee NewCallee = getFunction(M, newInfo))
440 newInfo = AMDGPULibFunc(NewFunc, fInfo);
441 return getFunction(M, newInfo);
444bool AMDGPULibCalls::parseFunctionName(
const StringRef &FMangledName,
465bool AMDGPULibCalls::useNativeFunc(
const StringRef F)
const {
470 AllNative = useNativeFunc(
"all") ||
475bool AMDGPULibCalls::sincosUseNative(
CallInst *aCI,
const FuncInfo &FInfo) {
476 bool native_sin = useNativeFunc(
"sin");
477 bool native_cos = useNativeFunc(
"cos");
479 if (native_sin && native_cos) {
494 if (sinExpr && cosExpr) {
502 <<
" with native version of sin/cos");
517 if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.
isMangled() ||
520 !(AllNative || useNativeFunc(FInfo.
getName()))) {
525 return sincosUseNative(aCI, FInfo);
534 <<
" with native version");
546 const FuncInfo &FInfo) {
548 if (!Callee->isDeclaration())
551 assert(Callee->hasName() &&
"Invalid read_pipe/write_pipe function");
552 auto *M = Callee->getParent();
553 std::string Name = std::string(Callee->getName());
555 if (NumArg != 4 && NumArg != 6)
561 if (!PacketSize || !PacketAlign)
566 if (Alignment !=
Size)
569 unsigned PtrArgLoc = CI->
arg_size() - 3;
574 for (
unsigned I = 0;
I != PtrArgLoc; ++
I)
578 Name = Name +
"_" + std::to_string(
Size);
587 for (
unsigned I = 0;
I != PtrArgLoc; ++
I)
589 Args.push_back(PtrArg);
591 auto *NCI =
B.CreateCall(
F, Args);
604 if (!Callee || Callee->isIntrinsic() || CI->
isNoBuiltin())
608 if (!parseFunctionName(Callee->getName(), FInfo))
618 if (TDOFold(CI, FInfo))
623 B.setIsFPConstrained(
true);
634 B.setFastMathFlags(FMF);
639 switch (FInfo.
getId()) {
643 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::exp,
648 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::exp2,
653 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::log,
658 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::log2,
663 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::log10,
666 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::minnum,
669 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::maxnum,
672 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::fma,
true,
675 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::fmuladd,
678 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::fabs,
true,
681 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::copysign,
684 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::floor,
true,
687 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::ceil,
true,
690 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::trunc,
true,
693 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::rint,
true,
696 return tryReplaceLibcallWithSimpleIntrinsic(
B, CI, Intrinsic::round,
true,
699 if (!shouldReplaceLibcallWithIntrinsic(CI,
true,
true))
705 Value *SplatArg1 =
B.CreateVectorSplat(VecTy->getElementCount(), Arg1);
711 {CI->getType(), CI->getArgOperand(1)->getType()}));
717 return tryOptimizePow(FPOp,
B, FInfo);
720 if (fold_pow(FPOp,
B, FInfo))
727 Module *M = Callee->getParent();
735 if (!shouldReplaceLibcallWithIntrinsic(CI))
741 if (fold_pow(FPOp,
B, FInfo))
748 Module *M = Callee->getParent();
756 if (!shouldReplaceLibcallWithIntrinsic(CI))
762 if (fold_rootn(FPOp,
B, FInfo))
768 Module *M = Callee->getParent();
770 if (
FunctionCallee RootnFastFunc = getFunction(M, RootnFastInfo)) {
780 return tryReplaceLibcallWithSimpleIntrinsic(
781 B, CI, Intrinsic::sqrt,
true,
true,
false);
784 return fold_sincos(FPOp,
B, FInfo);
790 switch (FInfo.
getId()) {
795 return fold_read_write_pipe(CI,
B, FInfo);
807 assert(Ty->isSingleValueType() &&
808 "Type must either be a scalar or a vector.");
809 assert((!Ty->isVectorTy() || Ty->isScalableTy() ||
811 "Unexpected number of constant values.");
813 "Expected exactly one constant value");
823 ConstValues.
push_back(ConstantFP::get(ElemTy, APF));
829bool AMDGPULibCalls::TDOFold(
CallInst *CI,
const FuncInfo &FInfo) {
835 int const sz = (int)tr.
size();
845 for (
int eltNo = 0; eltNo < vecSize; ++eltNo) {
852 auto MatchingRow =
llvm::find_if(tr, [eltval](
const TableEntry &entry) {
855 if (MatchingRow == tr.
end())
860 LLVM_DEBUG(
errs() <<
"AMDIC: " << *CI <<
" ---> " << *NewValues <<
"\n");
867 for (
int i = 0; i < sz; ++i) {
868 if (CF->isExactlyValue(tr[i].input)) {
869 Value *nval = ConstantFP::get(CF->getType(), tr[i].result);
870 LLVM_DEBUG(
errs() <<
"AMDIC: " << *CI <<
" ---> " << *nval <<
"\n");
883#if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
892 const FuncInfo &FInfo) {
899 "fold_pow: encounter a wrong function call");
901 Module *
M =
B.GetInsertBlock()->getModule();
907 const APInt *CINT =
nullptr;
912 int ci_opr1 = (CINT ? (int)CINT->
getSExtValue() : 0x1111111);
919 bool SkipConstantFolds =
937 if (FunctionCallee FPExpr =
941 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> " << FInfo.getName()
942 <<
'(' << *opr0 <<
")\n");
944 issqrt ?
"__pow2sqrt" :
"__pow2rsqrt");
951 if (!SkipConstantFolds) {
952 if ((CF && CF->
isZero()) || (CINT && ci_opr1 == 0)) {
955 Constant *cnval = ConstantFP::get(eltType, 1.0);
962 if ((CF && CF->
isOne()) || (CINT && ci_opr1 == 1)) {
964 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> " << *opr0 <<
"\n");
970 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> " << *opr0 <<
" * "
972 Value *nval =
B.CreateFMul(opr0, opr0,
"__pow2");
976 if ((CF && CF->
isMinusOne()) || (CINT && ci_opr1 == -1)) {
978 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> 1 / " << *opr0 <<
"\n");
979 Constant *cnval = ConstantFP::get(eltType, 1.0);
983 Value *nval =
B.CreateFDiv(cnval, opr0,
"__powrecip");
999 int ival = (int)dval;
1000 if ((
double)ival == dval) {
1003 ci_opr1 = 0x11111111;
1008 unsigned abs_opr1 = (ci_opr1 < 0) ? -ci_opr1 : ci_opr1;
1009 if (abs_opr1 <= 12) {
1012 if (abs_opr1 == 0) {
1013 cnval = ConstantFP::get(eltType, 1.0);
1019 Value *valx2 =
nullptr;
1021 while (abs_opr1 > 0) {
1022 valx2 = valx2 ?
B.CreateFMul(valx2, valx2,
"__powx2") : opr0;
1024 nval = nval ?
B.CreateFMul(nval, valx2,
"__powprod") : valx2;
1031 cnval = ConstantFP::get(eltType, 1.0);
1035 nval =
B.CreateFDiv(cnval, nval,
"__1powprod");
1038 << ((ci_opr1 < 0) ?
"1/prod(" :
"prod(") << *opr0
1049 FunctionCallee ExpExpr;
1050 if (ShouldUseIntrinsic)
1059 bool needlog =
false;
1060 bool needabs =
false;
1061 bool needcopysign =
false;
1072 V =
log2(std::abs(V));
1073 cnval = ConstantFP::get(eltType, V);
1091 "Wrong vector size detected");
1096 if (V < 0.0) needcopysign =
true;
1097 V =
log2(std::abs(V));
1102 for (
double D : DVal)
1124 nval =
B.CreateFAbs(opr0,
nullptr,
"__fabs");
1126 nval = cnval ? cnval : opr0;
1129 FunctionCallee LogExpr;
1130 if (ShouldUseIntrinsic) {
1145 opr1 =
B.CreateSIToFP(opr1, nval->
getType(),
"pownI2F");
1147 nval =
B.CreateFMul(opr1, nval,
"__ylogx");
1149 CallInst *Exp2Call =
CreateCallEx(
B, ExpExpr, nval,
"__exp2");
1165 opr_n =
B.CreateZExtOrTrunc(opr_n, nTy,
"__ytou");
1167 opr_n =
B.CreateFPToSI(opr1, nTy,
"__ytou");
1170 Value *sign =
B.CreateShl(opr_n,
size-1,
"__yeven");
1171 sign =
B.CreateAnd(
B.CreateBitCast(opr0, nTy), sign,
"__pow_sign");
1173 nval =
B.CreateCopySign(nval,
B.CreateBitCast(sign, nval->
getType()),
1174 nullptr,
"__pow_sign");
1178 <<
"exp2(" << *opr1 <<
" * log2(" << *opr0 <<
"))\n");
1185 const FuncInfo &FInfo) {
1189 const APInt *CINT =
nullptr;
1193 Function *Parent =
B.GetInsertBlock()->getParent();
1196 if (ci_opr1 == 1 && !Parent->
hasFnAttribute(Attribute::StrictFP)) {
1200 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> " << *opr0 <<
'\n');
1205 Module *
M =
B.GetInsertBlock()->getModule();
1213 if (ci_opr1 == 2 && FMFOkForSqrt &&
1214 shouldReplaceLibcallWithIntrinsic(CI,
1218 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> sqrt(" << *opr0 <<
")\n");
1220 Value *NewCall =
B.CreateUnaryIntrinsic(Intrinsic::sqrt, opr0, CI);
1225 MDBuilder MDHelper(
M->getContext());
1226 MDNode *FPMD = MDHelper.createFPMath(std::max(FPOp->
getFPAccuracy(), 2.0f));
1228 NewCallI->setMetadata(LLVMContext::MD_fpmath, FPMD);
1235 if (FunctionCallee FPExpr =
1237 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> cbrt(" << *opr0
1243 }
else if (ci_opr1 == -1) {
1244 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> 1.0 / " << *opr0 <<
"\n");
1245 Value *nval =
B.CreateFDiv(ConstantFP::get(opr0->
getType(), 1.0),
1252 if (ci_opr1 == -2 && FMFOkForSqrt &&
1253 shouldReplaceLibcallWithIntrinsic(CI,
1260 MDBuilder MDHelper(
M->getContext());
1261 MDNode *FPMD = MDHelper.createFPMath(std::max(FPOp->
getFPAccuracy(), 2.0f));
1267 Value *Sqrt =
B.CreateUnaryIntrinsic(Intrinsic::sqrt, opr0, CI);
1269 B.CreateFDiv(ConstantFP::get(opr0->
getType(), 1.0), Sqrt));
1271 SqrtI->setFastMathFlags(FMF);
1275 LLVM_DEBUG(
errs() <<
"AMDIC: " << *FPOp <<
" ---> rsqrt(" << *opr0
1286 Value *TruncY =
B.CreateUnaryIntrinsic(Intrinsic::trunc,
Y);
1287 return B.CreateFCmpOEQ(TruncY,
Y);
1292 auto *HalfY =
B.CreateFMul(
Y, ConstantFP::get(
Y->getType(), 0.5));
1300 Value *NotEvenY =
B.CreateNot(IsEvenY);
1301 return B.CreateAnd(IsIntY, NotEvenY);
1306 auto *fabsVal =
B.CreateFAbs(val);
1312 Value *AbsX =
B.CreateFAbs(
X);
1313 Value *LogAbsX =
B.CreateUnaryIntrinsic(Intrinsic::log2, AbsX);
1314 Value *YTimesLogX =
B.CreateFMul(
Y, LogAbsX);
1315 return B.CreateUnaryIntrinsic(Intrinsic::exp2, YTimesLogX);
1325 Constant *One = ConstantFP::get(
X->getType(), 1.0);
1335 Value *SelSign =
B.CreateSelect(IsOddY,
X, One);
1336 Value *Ret =
B.CreateCopySign(ExpYLnX, SelSign);
1340 Value *condNegX =
B.CreateFCmpOLT(
X, Zero);
1341 Value *condNotIntY =
B.CreateNot(IsIntY);
1342 Value *condNaN =
B.CreateAnd(condNegX, condNotIntY);
1343 Ret =
B.CreateSelect(condNaN, QNaN, Ret);
1352 Value *YIsNegInf =
B.CreateFCmpUNE(
Y, AY);
1355 Value *AxEqOne =
B.CreateFCmpOEQ(AX, One);
1356 Value *AxLtOne =
B.CreateFCmpOLT(AX, One);
1357 Value *XorCond =
B.CreateXor(AxLtOne, YIsNegInf);
1359 B.CreateSelect(AxEqOne, AX,
B.CreateSelect(XorCond, Zero, AY));
1360 Ret =
B.CreateSelect(YIsInf, SelInf, Ret);
1364 Value *XEqZero =
B.CreateFCmpOEQ(
X, Zero);
1365 Value *AxInfOrZero =
B.CreateOr(XIsInf, XEqZero);
1366 Value *YLtZero =
B.CreateFCmpOLT(
Y, Zero);
1367 Value *XorZeroInf =
B.CreateXor(XEqZero, YLtZero);
1368 Value *SelVal =
B.CreateSelect(XorZeroInf, Zero, PInf);
1369 Value *SelSign2 =
B.CreateSelect(IsOddY,
X, Zero);
1370 Value *Copysign =
B.CreateCopySign(SelVal, SelSign2);
1371 Ret =
B.CreateSelect(AxInfOrZero, Copysign, Ret);
1374 Value *isUnordered =
B.CreateFCmpUNO(
X,
Y);
1375 return B.CreateSelect(isUnordered, QNaN, Ret);
1378 Value *YIsNeg =
B.CreateFCmpOLT(
Y, Zero);
1379 Value *IZ =
B.CreateSelect(YIsNeg, PInf, Zero);
1380 Value *ZI =
B.CreateSelect(YIsNeg, Zero, PInf);
1382 Value *YEqZero =
B.CreateFCmpOEQ(
Y, Zero);
1383 Value *SelZeroCase =
B.CreateSelect(YEqZero, QNaN, IZ);
1384 Value *XEqZero =
B.CreateFCmpOEQ(
X, Zero);
1385 Value *Ret =
B.CreateSelect(XEqZero, SelZeroCase, ExpYLnX);
1387 Value *XEqInf =
B.CreateFCmpOEQ(
X, PInf);
1388 Value *YNeZero =
B.CreateFCmpUNE(
Y, Zero);
1389 Value *CondInfCase =
B.CreateAnd(XEqInf, YNeZero);
1390 Ret =
B.CreateSelect(CondInfCase, ZI, Ret);
1393 Value *XNeOne =
B.CreateFCmpUNE(
X, One);
1394 Value *CondInfY =
B.CreateAnd(IsInfY, XNeOne);
1395 Value *XLtOne =
B.CreateFCmpOLT(
X, One);
1396 Value *SelInfYCase =
B.CreateSelect(XLtOne, IZ, ZI);
1397 Ret =
B.CreateSelect(CondInfY, SelInfYCase, Ret);
1399 Value *IsUnordered =
B.CreateFCmpUNO(
X,
Y);
1400 return B.CreateSelect(IsUnordered, QNaN, Ret);
1403 Constant *ZeroI = ConstantInt::get(
Y->getType(), 0);
1406 Value *OneI = ConstantInt::get(
Y->getType(), 1);
1407 Value *YAnd1 =
B.CreateAnd(
Y, OneI);
1408 Value *IsOddY =
B.CreateICmpNE(YAnd1, ZeroI);
1411 Value *SelSign =
B.CreateSelect(IsOddY,
X, One);
1412 Value *Ret =
B.CreateCopySign(ExpYLnX, SelSign);
1415 Value *FabsX =
B.CreateFAbs(
X);
1416 Value *XIsInf =
B.CreateFCmpOEQ(FabsX, PInf);
1417 Value *XEqZero =
B.CreateFCmpOEQ(
X, Zero);
1418 Value *InfOrZero =
B.CreateOr(XIsInf, XEqZero);
1421 Value *YLtZero =
B.CreateICmpSLT(
Y, ZeroI);
1422 Value *XorZeroInf =
B.CreateXor(XEqZero, YLtZero);
1423 Value *SelVal =
B.CreateSelect(XorZeroInf, Zero, PInf);
1426 Value *SelSign2 =
B.CreateSelect(IsOddY,
X, Zero);
1427 Value *Copysign =
B.CreateCopySign(SelVal, SelSign2);
1429 return B.CreateSelect(InfOrZero, Copysign, Ret);
1432 Constant *ZeroI = ConstantInt::get(
Y->getType(), 0);
1435 Value *YAnd1 =
B.CreateAnd(
Y, ConstantInt::get(
Y->getType(), 1));
1436 Value *IsOddY =
B.CreateICmpNE(YAnd1, ZeroI);
1439 Value *SelSign =
B.CreateSelect(IsOddY,
X, One);
1440 Value *Ret =
B.CreateCopySign(ExpYLnX, SelSign);
1443 Value *FabsX =
B.CreateFAbs(
X);
1444 Value *IsInfX =
B.CreateFCmpOEQ(FabsX, PInf);
1445 Value *XEqZero =
B.CreateFCmpOEQ(
X, Zero);
1446 Value *CondInfOrZero =
B.CreateOr(IsInfX, XEqZero);
1449 Value *YLtZero =
B.CreateICmpSLT(
Y, ZeroI);
1450 Value *XorZeroInf =
B.CreateXor(XEqZero, YLtZero);
1451 Value *SelVal =
B.CreateSelect(XorZeroInf, Zero, PInf);
1454 Value *SelSign2 =
B.CreateSelect(IsOddY,
X, Zero);
1455 Value *Copysign =
B.CreateCopySign(SelVal, SelSign2);
1457 Ret =
B.CreateSelect(CondInfOrZero, Copysign, Ret);
1460 Value *XIsNeg =
B.CreateFCmpOLT(
X, Zero);
1461 Value *NotOddY =
B.CreateNot(IsOddY);
1462 Value *CondNegAndNotOdd =
B.CreateAnd(XIsNeg, NotOddY);
1463 Value *YEqZero =
B.CreateICmpEQ(
Y, ZeroI);
1464 Value *CondBad =
B.CreateOr(CondNegAndNotOdd, YEqZero);
1465 return B.CreateSelect(CondBad, QNaN, Ret);
1490 Constant *One = ConstantFP::get(
X->getType(), 1.0);
1493 Value *XEqOne =
B.CreateFCmpOEQ(
X, One);
1494 Y =
B.CreateSelect(XEqOne, One,
Y);
1498 X =
B.CreateSelect(YEqZero, One,
X);
1516 Value *YEqZero =
B.CreateICmpEQ(
Y, ConstantInt::get(
Y->getType(), 0));
1519 X =
B.CreateSelect(YEqZero, ConstantFP::get(
X->getType(), 1.0),
X);
1521 Value *CastY =
B.CreateSIToFP(
Y,
X->getType());
1528 Value *CastY =
B.CreateSIToFP(
Y,
X->getType());
1531 Value *RcpY =
B.CreateFDiv(ConstantFP::get(
X->getType(), 1.0), CastY);
1543 const FuncInfo &FInfo) {
1553 FunctionCallee PowrFunc = getFloatFastVariant(
1561 SQ.getWithInstruction(
Call))) {
1563 return fold_pow(FPOp,
B, PowrInfo) ||
true;
1576 FunctionCallee PownFunc = getFloatFastVariant(
1584 B.CreateFPToSI(FPOp->
getOperand(1), PownType->getParamType(1));
1587 1, AttributeFuncs::typeIncompatible(CastedArg->
getType(),
1591 return fold_pow(FPOp,
B, PownInfo) ||
true;
1595 if (fold_pow(FPOp,
B, FInfo))
1604 if (FunctionCallee PowFastFunc = getFunction(M, PowFastInfo)) {
1606 return fold_pow(FPOp,
B, PowFastInfo) ||
true;
1615 const FuncInfo &FInfo) {
1618 FuncInfo nf = FInfo;
1620 return getFunction(M, nf);
1626bool AMDGPULibCalls::shouldReplaceLibcallWithIntrinsic(
const CallInst *CI,
1627 bool AllowMinSizeF32,
1629 bool AllowStrictFP) {
1644 if (!AllowStrictFP && ParentF->
hasFnAttribute(Attribute::StrictFP))
1647 if (IsF32 && !AllowMinSizeF32 && ParentF->
hasMinSize())
1652void AMDGPULibCalls::replaceLibCallWithSimpleIntrinsic(
IRBuilder<> &
B,
1660 if (Arg0VecTy && !Arg1VecTy) {
1661 Value *SplatRHS =
B.CreateVectorSplat(Arg0VecTy->getElementCount(), Arg1);
1663 }
else if (!Arg0VecTy && Arg1VecTy) {
1664 Value *SplatLHS =
B.CreateVectorSplat(Arg1VecTy->getElementCount(), Arg0);
1670 CI->
getModule(), IntrID, {CI->getType()}));
1674bool AMDGPULibCalls::tryReplaceLibcallWithSimpleIntrinsic(
1676 bool AllowF64,
bool AllowStrictFP) {
1677 if (!shouldReplaceLibcallWithIntrinsic(CI, AllowMinSizeF32, AllowF64,
1680 replaceLibCallWithSimpleIntrinsic(
B, CI, IntrID);
1684std::tuple<Value *, Value *, Value *>
1689 B.SetInsertPointPastAllocas(
F);
1691 AllocaInst *
Alloc =
B.CreateAlloca(Arg->
getType(),
nullptr,
"__sincos_");
1698 B.SetInsertPoint(*ArgInst->getInsertionPointAfterDef());
1701 B.SetCurrentDebugLocation(
DL);
1709 Value *CastAlloc =
B.CreateAddrSpaceCast(
Alloc, CosPtrTy);
1717 return {SinCos, LoadCos, SinCos};
1722 const FuncInfo &fInfo) {
1741 Function *
F =
B.GetInsertBlock()->getParent();
1747 SinCosLibFuncPrivate.getLeads()[0].PtrKind =
1751 SinCosLibFuncGeneric.getLeads()[0].PtrKind =
1754 FunctionCallee FSinCosPrivate = getFunction(M, SinCosLibFuncPrivate);
1755 FunctionCallee FSinCosGeneric = getFunction(M, SinCosLibFuncGeneric);
1756 FunctionCallee FSinCos = FSinCosPrivate ? FSinCosPrivate : FSinCosGeneric;
1765 const std::string PairName = PartnerInfo.mangle();
1769 const std::string SinCosPrivateName = SinCosLibFuncPrivate.mangle();
1770 const std::string SinCosGenericName = SinCosLibFuncGeneric.mangle();
1774 MDNode *FPMath = CI->
getMetadata(LLVMContext::MD_fpmath);
1778 for (User* U : CArgVal->
users()) {
1787 bool Handled =
true;
1789 if (UCallee->
getName() == SinName)
1791 else if (UCallee->
getName() == CosName)
1793 else if (UCallee->
getName() == SinCosPrivateName ||
1794 UCallee->
getName() == SinCosGenericName)
1802 FMF &= OtherOp->getFastMathFlags();
1813 ArgInst && !ArgInst->getInsertionPointAfterDef())
1816 B.setFastMathFlags(FMF);
1817 B.setDefaultFPMathTag(FPMath);
1819 B.SetCurrentDebugLocation(DbgLoc);
1821 auto [Sin, Cos, SinCos] = insertSinCos(CArgVal, FMF,
B, FSinCos);
1824 for (CallInst *
C : Calls)
1825 C->replaceAllUsesWith(Res);
1830 replaceTrigInsts(SinCalls, Sin);
1831 replaceTrigInsts(CosCalls, Cos);
1832 replaceTrigInsts(SinCosCalls, SinCos);
1839bool AMDGPULibCalls::evaluateScalarMathFunc(
const FuncInfo &FInfo,
1853 switch (FInfo.getId()) {
1863 Res0 =
APFloat{log(opr0 + sqrt(opr0 * opr0 - 1.0))};
1876 Res0 =
APFloat{log(opr0 + sqrt(opr0 * opr0 + 1.0))};
1889 Res0 =
APFloat{(log(opr0 + 1.0) - log(opr0 - 1.0)) / 2.0};
1898 APFloat{(opr0 < 0.0) ? -
pow(-opr0, 1.0 / 3.0) :
pow(opr0, 1.0 / 3.0)};
1914 Res0 =
APFloat{std::exp(opr0)};
1930 Res0 =
APFloat{log(opr0) / log(2.0)};
1934 Res0 =
APFloat{log(opr0) / log(10.0)};
1938 Res0 =
APFloat{1.0 / sqrt(opr0)};
1980 double val = (double)iopr1->getSExtValue();
1989 double val = (double)iopr1->getSExtValue();
2006bool AMDGPULibCalls::evaluateCall(
CallInst *aCI,
const FuncInfo &FInfo) {
2007 int numArgs = (int)aCI->
arg_size();
2030 if (FuncVecSize == 1) {
2031 if (!evaluateScalarMathFunc(FInfo, Val0.
emplace_back(0.0),
2041 for (
int i = 0; i < FuncVecSize; ++i) {
2044 if (!evaluateScalarMathFunc(FInfo, Val0.
emplace_back(0.0),
2066 Simplifier.initNativeFuncs();
2071 F.printAsOperand(
dbgs(),
false,
F.getParent());
dbgs() <<
'\n';);
2073 for (
auto &BB :
F) {
2080 if (Simplifier.fold(CI))
2094 Simplifier.initNativeFuncs();
2097 for (
auto &BB :
F) {
2102 if (CI && Simplifier.useNative(CI))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const TableEntry tbl_log[]
static const TableEntry tbl_tgamma[]
static AMDGPULibFunc::EType getArgType(const AMDGPULibFunc &FInfo)
static const TableEntry tbl_expm1[]
static const TableEntry tbl_asinpi[]
static const TableEntry tbl_cos[]
static const TableEntry tbl_exp10[]
static CallInst * CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg, const Twine &Name="")
static CallInst * CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1, Value *Arg2, const Twine &Name="")
static const TableEntry tbl_rsqrt[]
static const TableEntry tbl_atanh[]
static const TableEntry tbl_cosh[]
static const TableEntry tbl_asin[]
static const TableEntry tbl_sinh[]
static const TableEntry tbl_acos[]
static const TableEntry tbl_tan[]
static const TableEntry tbl_cospi[]
static const TableEntry tbl_tanpi[]
static cl::opt< bool > EnablePreLink("amdgpu-prelink", cl::desc("Enable pre-link mode optimizations"), cl::init(false), cl::Hidden)
static bool HasNative(AMDGPULibFunc::EFuncId id)
static Value * emitIsInf(IRBuilder<> &B, Value *val)
ArrayRef< TableEntry > TableRef
static int getVecSize(const AMDGPULibFunc &FInfo)
static Value * emitFastExpYLnx(IRBuilder<> &B, Value *X, Value *Y)
static Value * emitIsInteger(IRBuilder<> &B, Value *Y)
static Value * emitIsEvenInteger(IRBuilder<> &B, Value *Y)
static const TableEntry tbl_sin[]
static const TableEntry tbl_atan[]
static const TableEntry tbl_log2[]
static Constant * getConstantFloat(const ArrayRef< APFloat > Values, const Type *Ty)
static const TableEntry tbl_acospi[]
static Value * emitPowFixup(IRBuilder<> &B, Value *X, Value *Y, Value *ExpYLnX, PowKind Kind)
Emit special case management epilog code for fast pow, powr, pown, and rootn expansions.
static const TableEntry tbl_sqrt[]
static const TableEntry tbl_asinh[]
static TableRef getOptTable(AMDGPULibFunc::EFuncId id)
static const TableEntry tbl_acosh[]
static const TableEntry tbl_exp[]
static const TableEntry tbl_cbrt[]
static const TableEntry tbl_sinpi[]
static const TableEntry tbl_atanpi[]
static FunctionType * getPownType(FunctionType *FT)
static const TableEntry tbl_erf[]
static const TableEntry tbl_log10[]
static const TableEntry tbl_erfc[]
static cl::list< std::string > UseNative("amdgpu-use-native", cl::desc("Comma separated list of functions to replace with native, or all"), cl::CommaSeparated, cl::ValueOptional, cl::Hidden)
static const TableEntry tbl_tanh[]
static Value * emitIsOddInteger(IRBuilder<> &B, Value *Y)
static const TableEntry tbl_exp2[]
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
FunctionAnalysisManager FAM
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static void replaceCall(FPMathOperator *I, Value *With)
bool isUnsafeFiniteOnlyMath(const FPMathOperator *FPOp) const
bool canIncreasePrecisionOfConstantFold(const FPMathOperator *FPOp) const
static void replaceCall(Instruction *I, Value *With)
AMDGPULibCalls(Function &F, FunctionAnalysisManager &FAM)
bool useNative(CallInst *CI)
static unsigned getEPtrKindFromAddrSpace(unsigned AS)
Wrapper class for AMDGPULIbFuncImpl.
static bool parse(StringRef MangledName, AMDGPULibFunc &Ptr)
std::string getName() const
Get unmangled name for mangled library function and name for unmangled library function.
static FunctionCallee getOrInsertFunction(llvm::Module *M, const AMDGPULibFunc &fInfo)
void setPrefix(ENamePrefix PFX)
bool isCompatibleSignature(const Module &M, const FunctionType *FuncTy) const
Param * getLeads()
Get leading parameters for mangled lib functions.
ENamePrefix getPrefix() const
static constexpr roundingMode rmNearestTiesToEven
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
LLVM_ABI float convertToFloat() const
Converts this APFloat to host float value.
LLVM_READONLY bool isOne() const
LLVM_READONLY bool isMinusOne() const
int64_t getSExtValue() const
Get sign extended value.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
A function analysis which provides an AssumptionCache.
static LLVM_ABI Attribute getWithNoFPClass(LLVMContext &Context, FPClassTest Mask)
InstListType::iterator iterator
Instruction iterators...
void setCallingConv(CallingConv::ID CC)
void removeParamAttrs(unsigned ArgNo, const AttributeMask &AttrsToRemove)
Removes the attributes from the given argument.
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
AttributeSet getParamAttributes(unsigned ArgNo) const
Return the param attributes for this call.
bool isNoInline() const
Return true if the call should not be inlined.
void addRetAttr(Attribute::AttrKind Kind)
Adds the attribute to the return value.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
static LLVM_ABI Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
const APFloat & getValueAPF() const
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
LLVM_ABI bool isExactlyValue(const APFloat &V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Align getAlignValue() const
Return the constant as an llvm::Align, interpreting 0 as Align(1).
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
static LLVM_ABI DILocation * getMergedLocations(ArrayRef< DILocation * > Locs)
Try to combine the vector of locations passed as input in a single one.
Analysis pass which computes a DominatorTree.
Utility class for floating point operations which can have information about relaxed accuracy require...
bool isFast() const
Test if this operation allows all non-strict floating-point transforms.
bool hasNoNaNs() const
Test if this operation's arguments and results are assumed not-NaN.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
bool hasNoSignedZeros() const
Test if this operation can ignore the sign of zero.
bool hasNoInfs() const
Test if this operation's arguments and results are assumed not-infinite.
bool hasApproxFunc() const
Test if this operation allows approximations of math library functions or intrinsics.
LLVM_ABI float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
Convenience struct for specifying and reasoning about fast-math flags.
void setAllowContract(bool B=true)
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionType * getFunctionType()
Type * getParamType(unsigned i) const
Parameter type accessors.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
A Module instance is used to store all the information related to an LLVM module.
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.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Analysis pass providing the TargetLibraryInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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 isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVM_ABI Type * getWithNewType(Type *EltTy) const
Given vector type, change the element type, whilst keeping the old number of elements.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element 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.
void dropAllReferences()
Drop all references to operands.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
iterator_range< user_iterator > users()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
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.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ PRIVATE_ADDRESS
Address space for private memory.
LLVM_ABI APInt pow(const APInt &X, int64_t N)
Compute X^N for N>=0.
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
bool match(Val *V, const Pattern &P)
ap_match< APFloat > m_APFloatAllowPoison(const APFloat *&Res)
Match APFloat while allowing poison in splat vector constants.
initializer< Ty > init(const Ty &Val)
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
static double log2(double V)
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.
RelativeUniformCounterPtr Values
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
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.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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....
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This struct is a compact representation of a valid (non-zero power of two) alignment.