1 //===- AMDGPULibCalls.cpp -------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
10 /// This file does AMD library function optimizations.
12 //===----------------------------------------------------------------------===//
15 #include "AMDGPULibFunc.h"
16 #include "GCNSubtarget.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/Loads.h"
19 #include "llvm/IR/IntrinsicsAMDGPU.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Target/TargetMachine.h"
24 #define DEBUG_TYPE "amdgpu-simplifylib"
28 static cl::opt<bool> EnablePreLink("amdgpu-prelink",
29 cl::desc("Enable pre-link mode optimizations"),
33 static cl::list<std::string> UseNative("amdgpu-use-native",
34 cl::desc("Comma separated list of functions to replace with native, or all"),
35 cl::CommaSeparated, cl::ValueOptional,
38 #define MATH_PI numbers::pi
39 #define MATH_E numbers::e
40 #define MATH_SQRT2 numbers::sqrt2
41 #define MATH_SQRT1_2 numbers::inv_sqrt2
45 class AMDGPULibCalls {
48 typedef llvm::AMDGPULibFunc FuncInfo;
50 const TargetMachine *TM;
53 bool AllNative = false;
55 bool useNativeFunc(const StringRef F) const;
57 // Return a pointer (pointer expr) to the function if function definition with
58 // "FuncName" exists. It may create a new function prototype in pre-link mode.
59 FunctionCallee getFunction(Module *M, const FuncInfo &fInfo);
61 bool parseFunctionName(const StringRef &FMangledName, FuncInfo &FInfo);
63 bool TDOFold(CallInst *CI, const FuncInfo &FInfo);
65 /* Specialized optimizations */
67 // recip (half or native)
68 bool fold_recip(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
70 // divide (half or native)
71 bool fold_divide(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
74 bool fold_pow(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
77 bool fold_rootn(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
80 bool fold_fma_mad(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
82 // -fuse-native for sincos
83 bool sincosUseNative(CallInst *aCI, const FuncInfo &FInfo);
85 // evaluate calls if calls' arguments are constants.
86 bool evaluateScalarMathFunc(const FuncInfo &FInfo, double& Res0,
87 double& Res1, Constant *copr0, Constant *copr1, Constant *copr2);
88 bool evaluateCall(CallInst *aCI, const FuncInfo &FInfo);
91 bool fold_sqrt(CallInst *CI, IRBuilder<> &B, const FuncInfo &FInfo);
94 bool fold_sincos(CallInst * CI, IRBuilder<> &B, AliasAnalysis * AA);
96 // __read_pipe/__write_pipe
97 bool fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
98 const FuncInfo &FInfo);
100 // llvm.amdgcn.wavefrontsize
101 bool fold_wavefrontsize(CallInst *CI, IRBuilder<> &B);
103 // Get insertion point at entry.
104 BasicBlock::iterator getEntryIns(CallInst * UI);
105 // Insert an Alloc instruction.
106 AllocaInst* insertAlloca(CallInst * UI, IRBuilder<> &B, const char *prefix);
107 // Get a scalar native builtin single argument FP function
108 FunctionCallee getNativeFunction(Module *M, const FuncInfo &FInfo);
113 bool isUnsafeMath(const CallInst *CI) const;
115 void replaceCall(Value *With) {
116 CI->replaceAllUsesWith(With);
117 CI->eraseFromParent();
121 AMDGPULibCalls(const TargetMachine *TM_ = nullptr) : TM(TM_) {}
123 bool fold(CallInst *CI, AliasAnalysis *AA = nullptr);
125 void initNativeFuncs();
127 // Replace a normal math function call with that native version
128 bool useNative(CallInst *CI);
131 } // end llvm namespace
135 class AMDGPUSimplifyLibCalls : public FunctionPass {
137 AMDGPULibCalls Simplifier;
140 static char ID; // Pass identification
142 AMDGPUSimplifyLibCalls(const TargetMachine *TM = nullptr)
143 : FunctionPass(ID), Simplifier(TM) {
144 initializeAMDGPUSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
147 void getAnalysisUsage(AnalysisUsage &AU) const override {
148 AU.addRequired<AAResultsWrapperPass>();
151 bool runOnFunction(Function &M) override;
154 class AMDGPUUseNativeCalls : public FunctionPass {
156 AMDGPULibCalls Simplifier;
159 static char ID; // Pass identification
161 AMDGPUUseNativeCalls() : FunctionPass(ID) {
162 initializeAMDGPUUseNativeCallsPass(*PassRegistry::getPassRegistry());
163 Simplifier.initNativeFuncs();
166 bool runOnFunction(Function &F) override;
169 } // end anonymous namespace.
171 char AMDGPUSimplifyLibCalls::ID = 0;
172 char AMDGPUUseNativeCalls::ID = 0;
174 INITIALIZE_PASS_BEGIN(AMDGPUSimplifyLibCalls, "amdgpu-simplifylib",
175 "Simplify well-known AMD library calls", false, false)
176 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
177 INITIALIZE_PASS_END(AMDGPUSimplifyLibCalls, "amdgpu-simplifylib",
178 "Simplify well-known AMD library calls", false, false)
180 INITIALIZE_PASS(AMDGPUUseNativeCalls, "amdgpu-usenative",
181 "Replace builtin math calls with that native versions.",
184 template <typename IRB>
185 static CallInst *CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg,
186 const Twine &Name = "") {
187 CallInst *R = B.CreateCall(Callee, Arg, Name);
188 if (Function *F = dyn_cast<Function>(Callee.getCallee()))
189 R->setCallingConv(F->getCallingConv());
193 template <typename IRB>
194 static CallInst *CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1,
195 Value *Arg2, const Twine &Name = "") {
196 CallInst *R = B.CreateCall(Callee, {Arg1, Arg2}, Name);
197 if (Function *F = dyn_cast<Function>(Callee.getCallee()))
198 R->setCallingConv(F->getCallingConv());
202 // Data structures for table-driven optimizations.
203 // FuncTbl works for both f32 and f64 functions with 1 input argument
210 /* a list of {result, input} */
211 static const TableEntry tbl_acos[] = {
212 {MATH_PI / 2.0, 0.0},
213 {MATH_PI / 2.0, -0.0},
217 static const TableEntry tbl_acosh[] = {
220 static const TableEntry tbl_acospi[] = {
226 static const TableEntry tbl_asin[] = {
229 {MATH_PI / 2.0, 1.0},
230 {-MATH_PI / 2.0, -1.0}
232 static const TableEntry tbl_asinh[] = {
236 static const TableEntry tbl_asinpi[] = {
242 static const TableEntry tbl_atan[] = {
245 {MATH_PI / 4.0, 1.0},
246 {-MATH_PI / 4.0, -1.0}
248 static const TableEntry tbl_atanh[] = {
252 static const TableEntry tbl_atanpi[] = {
258 static const TableEntry tbl_cbrt[] = {
264 static const TableEntry tbl_cos[] = {
268 static const TableEntry tbl_cosh[] = {
272 static const TableEntry tbl_cospi[] = {
276 static const TableEntry tbl_erfc[] = {
280 static const TableEntry tbl_erf[] = {
284 static const TableEntry tbl_exp[] = {
289 static const TableEntry tbl_exp2[] = {
294 static const TableEntry tbl_exp10[] = {
299 static const TableEntry tbl_expm1[] = {
303 static const TableEntry tbl_log[] = {
307 static const TableEntry tbl_log2[] = {
311 static const TableEntry tbl_log10[] = {
315 static const TableEntry tbl_rsqrt[] = {
319 static const TableEntry tbl_sin[] = {
323 static const TableEntry tbl_sinh[] = {
327 static const TableEntry tbl_sinpi[] = {
331 static const TableEntry tbl_sqrt[] = {
336 static const TableEntry tbl_tan[] = {
340 static const TableEntry tbl_tanh[] = {
344 static const TableEntry tbl_tanpi[] = {
348 static const TableEntry tbl_tgamma[] = {
355 static bool HasNative(AMDGPULibFunc::EFuncId id) {
357 case AMDGPULibFunc::EI_DIVIDE:
358 case AMDGPULibFunc::EI_COS:
359 case AMDGPULibFunc::EI_EXP:
360 case AMDGPULibFunc::EI_EXP2:
361 case AMDGPULibFunc::EI_EXP10:
362 case AMDGPULibFunc::EI_LOG:
363 case AMDGPULibFunc::EI_LOG2:
364 case AMDGPULibFunc::EI_LOG10:
365 case AMDGPULibFunc::EI_POWR:
366 case AMDGPULibFunc::EI_RECIP:
367 case AMDGPULibFunc::EI_RSQRT:
368 case AMDGPULibFunc::EI_SIN:
369 case AMDGPULibFunc::EI_SINCOS:
370 case AMDGPULibFunc::EI_SQRT:
371 case AMDGPULibFunc::EI_TAN:
380 const TableEntry *table; // variable size: from 0 to (size - 1)
382 TableRef() : size(0), table(nullptr) {}
385 TableRef(const TableEntry (&tbl)[N]) : size(N), table(&tbl[0]) {}
388 static TableRef getOptTable(AMDGPULibFunc::EFuncId id) {
390 case AMDGPULibFunc::EI_ACOS: return TableRef(tbl_acos);
391 case AMDGPULibFunc::EI_ACOSH: return TableRef(tbl_acosh);
392 case AMDGPULibFunc::EI_ACOSPI: return TableRef(tbl_acospi);
393 case AMDGPULibFunc::EI_ASIN: return TableRef(tbl_asin);
394 case AMDGPULibFunc::EI_ASINH: return TableRef(tbl_asinh);
395 case AMDGPULibFunc::EI_ASINPI: return TableRef(tbl_asinpi);
396 case AMDGPULibFunc::EI_ATAN: return TableRef(tbl_atan);
397 case AMDGPULibFunc::EI_ATANH: return TableRef(tbl_atanh);
398 case AMDGPULibFunc::EI_ATANPI: return TableRef(tbl_atanpi);
399 case AMDGPULibFunc::EI_CBRT: return TableRef(tbl_cbrt);
400 case AMDGPULibFunc::EI_NCOS:
401 case AMDGPULibFunc::EI_COS: return TableRef(tbl_cos);
402 case AMDGPULibFunc::EI_COSH: return TableRef(tbl_cosh);
403 case AMDGPULibFunc::EI_COSPI: return TableRef(tbl_cospi);
404 case AMDGPULibFunc::EI_ERFC: return TableRef(tbl_erfc);
405 case AMDGPULibFunc::EI_ERF: return TableRef(tbl_erf);
406 case AMDGPULibFunc::EI_EXP: return TableRef(tbl_exp);
407 case AMDGPULibFunc::EI_NEXP2:
408 case AMDGPULibFunc::EI_EXP2: return TableRef(tbl_exp2);
409 case AMDGPULibFunc::EI_EXP10: return TableRef(tbl_exp10);
410 case AMDGPULibFunc::EI_EXPM1: return TableRef(tbl_expm1);
411 case AMDGPULibFunc::EI_LOG: return TableRef(tbl_log);
412 case AMDGPULibFunc::EI_NLOG2:
413 case AMDGPULibFunc::EI_LOG2: return TableRef(tbl_log2);
414 case AMDGPULibFunc::EI_LOG10: return TableRef(tbl_log10);
415 case AMDGPULibFunc::EI_NRSQRT:
416 case AMDGPULibFunc::EI_RSQRT: return TableRef(tbl_rsqrt);
417 case AMDGPULibFunc::EI_NSIN:
418 case AMDGPULibFunc::EI_SIN: return TableRef(tbl_sin);
419 case AMDGPULibFunc::EI_SINH: return TableRef(tbl_sinh);
420 case AMDGPULibFunc::EI_SINPI: return TableRef(tbl_sinpi);
421 case AMDGPULibFunc::EI_NSQRT:
422 case AMDGPULibFunc::EI_SQRT: return TableRef(tbl_sqrt);
423 case AMDGPULibFunc::EI_TAN: return TableRef(tbl_tan);
424 case AMDGPULibFunc::EI_TANH: return TableRef(tbl_tanh);
425 case AMDGPULibFunc::EI_TANPI: return TableRef(tbl_tanpi);
426 case AMDGPULibFunc::EI_TGAMMA: return TableRef(tbl_tgamma);
432 static inline int getVecSize(const AMDGPULibFunc& FInfo) {
433 return FInfo.getLeads()[0].VectorSize;
436 static inline AMDGPULibFunc::EType getArgType(const AMDGPULibFunc& FInfo) {
437 return (AMDGPULibFunc::EType)FInfo.getLeads()[0].ArgType;
440 FunctionCallee AMDGPULibCalls::getFunction(Module *M, const FuncInfo &fInfo) {
441 // If we are doing PreLinkOpt, the function is external. So it is safe to
442 // use getOrInsertFunction() at this stage.
444 return EnablePreLink ? AMDGPULibFunc::getOrInsertFunction(M, fInfo)
445 : AMDGPULibFunc::getFunction(M, fInfo);
448 bool AMDGPULibCalls::parseFunctionName(const StringRef &FMangledName,
450 return AMDGPULibFunc::parse(FMangledName, FInfo);
453 bool AMDGPULibCalls::isUnsafeMath(const CallInst *CI) const {
454 if (auto Op = dyn_cast<FPMathOperator>(CI))
457 const Function *F = CI->getParent()->getParent();
458 Attribute Attr = F->getFnAttribute("unsafe-fp-math");
459 return Attr.getValueAsBool();
462 bool AMDGPULibCalls::useNativeFunc(const StringRef F) const {
463 return AllNative || llvm::is_contained(UseNative, F);
466 void AMDGPULibCalls::initNativeFuncs() {
467 AllNative = useNativeFunc("all") ||
468 (UseNative.getNumOccurrences() && UseNative.size() == 1 &&
469 UseNative.begin()->empty());
472 bool AMDGPULibCalls::sincosUseNative(CallInst *aCI, const FuncInfo &FInfo) {
473 bool native_sin = useNativeFunc("sin");
474 bool native_cos = useNativeFunc("cos");
476 if (native_sin && native_cos) {
477 Module *M = aCI->getModule();
478 Value *opr0 = aCI->getArgOperand(0);
481 nf.getLeads()[0].ArgType = FInfo.getLeads()[0].ArgType;
482 nf.getLeads()[0].VectorSize = FInfo.getLeads()[0].VectorSize;
484 nf.setPrefix(AMDGPULibFunc::NATIVE);
485 nf.setId(AMDGPULibFunc::EI_SIN);
486 FunctionCallee sinExpr = getFunction(M, nf);
488 nf.setPrefix(AMDGPULibFunc::NATIVE);
489 nf.setId(AMDGPULibFunc::EI_COS);
490 FunctionCallee cosExpr = getFunction(M, nf);
491 if (sinExpr && cosExpr) {
492 Value *sinval = CallInst::Create(sinExpr, opr0, "splitsin", aCI);
493 Value *cosval = CallInst::Create(cosExpr, opr0, "splitcos", aCI);
494 new StoreInst(cosval, aCI->getArgOperand(1), aCI);
496 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
497 << " with native version of sin/cos");
506 bool AMDGPULibCalls::useNative(CallInst *aCI) {
508 Function *Callee = aCI->getCalledFunction();
511 if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.isMangled() ||
512 FInfo.getPrefix() != AMDGPULibFunc::NOPFX ||
513 getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()) ||
514 !(AllNative || useNativeFunc(FInfo.getName()))) {
518 if (FInfo.getId() == AMDGPULibFunc::EI_SINCOS)
519 return sincosUseNative(aCI, FInfo);
521 FInfo.setPrefix(AMDGPULibFunc::NATIVE);
522 FunctionCallee F = getFunction(aCI->getModule(), FInfo);
526 aCI->setCalledFunction(F);
527 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
528 << " with native version");
532 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
533 // builtin, with appended type size and alignment arguments, where 2 or 4
534 // indicates the original number of arguments. The library has optimized version
535 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
536 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
537 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
538 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
539 bool AMDGPULibCalls::fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
540 const FuncInfo &FInfo) {
541 auto *Callee = CI->getCalledFunction();
542 if (!Callee->isDeclaration())
545 assert(Callee->hasName() && "Invalid read_pipe/write_pipe function");
546 auto *M = Callee->getParent();
547 auto &Ctx = M->getContext();
548 std::string Name = std::string(Callee->getName());
549 auto NumArg = CI->arg_size();
550 if (NumArg != 4 && NumArg != 6)
552 auto *PacketSize = CI->getArgOperand(NumArg - 2);
553 auto *PacketAlign = CI->getArgOperand(NumArg - 1);
554 if (!isa<ConstantInt>(PacketSize) || !isa<ConstantInt>(PacketAlign))
556 unsigned Size = cast<ConstantInt>(PacketSize)->getZExtValue();
557 Align Alignment = cast<ConstantInt>(PacketAlign)->getAlignValue();
558 if (Alignment != Size)
563 PtrElemTy = Type::getIntNTy(Ctx, Size * 8);
565 PtrElemTy = FixedVectorType::get(Type::getInt64Ty(Ctx), Size / 8);
566 unsigned PtrArgLoc = CI->arg_size() - 3;
567 auto PtrArg = CI->getArgOperand(PtrArgLoc);
568 unsigned PtrArgAS = PtrArg->getType()->getPointerAddressSpace();
569 auto *PtrTy = llvm::PointerType::get(PtrElemTy, PtrArgAS);
571 SmallVector<llvm::Type *, 6> ArgTys;
572 for (unsigned I = 0; I != PtrArgLoc; ++I)
573 ArgTys.push_back(CI->getArgOperand(I)->getType());
574 ArgTys.push_back(PtrTy);
576 Name = Name + "_" + std::to_string(Size);
577 auto *FTy = FunctionType::get(Callee->getReturnType(),
578 ArrayRef<Type *>(ArgTys), false);
579 AMDGPULibFunc NewLibFunc(Name, FTy);
580 FunctionCallee F = AMDGPULibFunc::getOrInsertFunction(M, NewLibFunc);
584 auto *BCast = B.CreatePointerCast(PtrArg, PtrTy);
585 SmallVector<Value *, 6> Args;
586 for (unsigned I = 0; I != PtrArgLoc; ++I)
587 Args.push_back(CI->getArgOperand(I));
588 Args.push_back(BCast);
590 auto *NCI = B.CreateCall(F, Args);
591 NCI->setAttributes(CI->getAttributes());
592 CI->replaceAllUsesWith(NCI);
593 CI->dropAllReferences();
594 CI->eraseFromParent();
599 // This function returns false if no change; return true otherwise.
600 bool AMDGPULibCalls::fold(CallInst *CI, AliasAnalysis *AA) {
602 Function *Callee = CI->getCalledFunction();
604 // Ignore indirect calls.
605 if (Callee == nullptr)
608 BasicBlock *BB = CI->getParent();
609 LLVMContext &Context = CI->getParent()->getContext();
610 IRBuilder<> B(Context);
612 // Set the builder to the instruction after the call.
613 B.SetInsertPoint(BB, CI->getIterator());
615 // Copy fast flags from the original call.
616 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(CI))
617 B.setFastMathFlags(FPOp->getFastMathFlags());
619 switch (Callee->getIntrinsicID()) {
622 case Intrinsic::amdgcn_wavefrontsize:
623 return !EnablePreLink && fold_wavefrontsize(CI, B);
627 if (!parseFunctionName(Callee->getName(), FInfo))
630 // Further check the number of arguments to see if they match.
631 if (CI->arg_size() != FInfo.getNumArgs())
634 if (TDOFold(CI, FInfo))
637 // Under unsafe-math, evaluate calls if possible.
638 // According to Brian Sumner, we can do this for all f32 function calls
639 // using host's double function calls.
640 if (isUnsafeMath(CI) && evaluateCall(CI, FInfo))
643 // Specialized optimizations for each function call
644 switch (FInfo.getId()) {
645 case AMDGPULibFunc::EI_RECIP:
646 // skip vector function
647 assert ((FInfo.getPrefix() == AMDGPULibFunc::NATIVE ||
648 FInfo.getPrefix() == AMDGPULibFunc::HALF) &&
649 "recip must be an either native or half function");
650 return (getVecSize(FInfo) != 1) ? false : fold_recip(CI, B, FInfo);
652 case AMDGPULibFunc::EI_DIVIDE:
653 // skip vector function
654 assert ((FInfo.getPrefix() == AMDGPULibFunc::NATIVE ||
655 FInfo.getPrefix() == AMDGPULibFunc::HALF) &&
656 "divide must be an either native or half function");
657 return (getVecSize(FInfo) != 1) ? false : fold_divide(CI, B, FInfo);
659 case AMDGPULibFunc::EI_POW:
660 case AMDGPULibFunc::EI_POWR:
661 case AMDGPULibFunc::EI_POWN:
662 return fold_pow(CI, B, FInfo);
664 case AMDGPULibFunc::EI_ROOTN:
665 // skip vector function
666 return (getVecSize(FInfo) != 1) ? false : fold_rootn(CI, B, FInfo);
668 case AMDGPULibFunc::EI_FMA:
669 case AMDGPULibFunc::EI_MAD:
670 case AMDGPULibFunc::EI_NFMA:
671 // skip vector function
672 return (getVecSize(FInfo) != 1) ? false : fold_fma_mad(CI, B, FInfo);
674 case AMDGPULibFunc::EI_SQRT:
675 return isUnsafeMath(CI) && fold_sqrt(CI, B, FInfo);
676 case AMDGPULibFunc::EI_COS:
677 case AMDGPULibFunc::EI_SIN:
678 if ((getArgType(FInfo) == AMDGPULibFunc::F32 ||
679 getArgType(FInfo) == AMDGPULibFunc::F64)
680 && (FInfo.getPrefix() == AMDGPULibFunc::NOPFX))
681 return fold_sincos(CI, B, AA);
684 case AMDGPULibFunc::EI_READ_PIPE_2:
685 case AMDGPULibFunc::EI_READ_PIPE_4:
686 case AMDGPULibFunc::EI_WRITE_PIPE_2:
687 case AMDGPULibFunc::EI_WRITE_PIPE_4:
688 return fold_read_write_pipe(CI, B, FInfo);
697 bool AMDGPULibCalls::TDOFold(CallInst *CI, const FuncInfo &FInfo) {
698 // Table-Driven optimization
699 const TableRef tr = getOptTable(FInfo.getId());
703 int const sz = (int)tr.size;
704 const TableEntry * const ftbl = tr.table;
705 Value *opr0 = CI->getArgOperand(0);
707 if (getVecSize(FInfo) > 1) {
708 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(opr0)) {
709 SmallVector<double, 0> DVal;
710 for (int eltNo = 0; eltNo < getVecSize(FInfo); ++eltNo) {
711 ConstantFP *eltval = dyn_cast<ConstantFP>(
712 CV->getElementAsConstant((unsigned)eltNo));
713 assert(eltval && "Non-FP arguments in math function!");
715 for (int i=0; i < sz; ++i) {
716 if (eltval->isExactlyValue(ftbl[i].input)) {
717 DVal.push_back(ftbl[i].result);
723 // This vector constants not handled yet.
727 LLVMContext &context = CI->getParent()->getParent()->getContext();
729 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
730 SmallVector<float, 0> FVal;
731 for (unsigned i = 0; i < DVal.size(); ++i) {
732 FVal.push_back((float)DVal[i]);
734 ArrayRef<float> tmp(FVal);
735 nval = ConstantDataVector::get(context, tmp);
737 ArrayRef<double> tmp(DVal);
738 nval = ConstantDataVector::get(context, tmp);
740 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
746 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) {
747 for (int i = 0; i < sz; ++i) {
748 if (CF->isExactlyValue(ftbl[i].input)) {
749 Value *nval = ConstantFP::get(CF->getType(), ftbl[i].result);
750 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
761 // [native_]half_recip(c) ==> 1.0/c
762 bool AMDGPULibCalls::fold_recip(CallInst *CI, IRBuilder<> &B,
763 const FuncInfo &FInfo) {
764 Value *opr0 = CI->getArgOperand(0);
765 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) {
766 // Just create a normal div. Later, InstCombine will be able
767 // to compute the divide into a constant (avoid check float infinity
768 // or subnormal at this point).
769 Value *nval = B.CreateFDiv(ConstantFP::get(CF->getType(), 1.0),
772 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
779 // [native_]half_divide(x, c) ==> x/c
780 bool AMDGPULibCalls::fold_divide(CallInst *CI, IRBuilder<> &B,
781 const FuncInfo &FInfo) {
782 Value *opr0 = CI->getArgOperand(0);
783 Value *opr1 = CI->getArgOperand(1);
784 ConstantFP *CF0 = dyn_cast<ConstantFP>(opr0);
785 ConstantFP *CF1 = dyn_cast<ConstantFP>(opr1);
787 if ((CF0 && CF1) || // both are constants
788 (CF1 && (getArgType(FInfo) == AMDGPULibFunc::F32)))
789 // CF1 is constant && f32 divide
791 Value *nval1 = B.CreateFDiv(ConstantFP::get(opr1->getType(), 1.0),
792 opr1, "__div2recip");
793 Value *nval = B.CreateFMul(opr0, nval1, "__div2mul");
801 static double log2(double V) {
802 #if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
805 return log(V) / numbers::ln2;
810 bool AMDGPULibCalls::fold_pow(CallInst *CI, IRBuilder<> &B,
811 const FuncInfo &FInfo) {
812 assert((FInfo.getId() == AMDGPULibFunc::EI_POW ||
813 FInfo.getId() == AMDGPULibFunc::EI_POWR ||
814 FInfo.getId() == AMDGPULibFunc::EI_POWN) &&
815 "fold_pow: encounter a wrong function call");
820 ConstantAggregateZero *CZero;
823 opr0 = CI->getArgOperand(0);
824 opr1 = CI->getArgOperand(1);
825 CZero = dyn_cast<ConstantAggregateZero>(opr1);
826 if (getVecSize(FInfo) == 1) {
827 eltType = opr0->getType();
828 CF = dyn_cast<ConstantFP>(opr1);
829 CINT = dyn_cast<ConstantInt>(opr1);
831 VectorType *VTy = dyn_cast<VectorType>(opr0->getType());
832 assert(VTy && "Oprand of vector function should be of vectortype");
833 eltType = VTy->getElementType();
834 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr1);
836 // Now, only Handle vector const whose elements have the same value.
837 CF = CDV ? dyn_cast_or_null<ConstantFP>(CDV->getSplatValue()) : nullptr;
838 CINT = CDV ? dyn_cast_or_null<ConstantInt>(CDV->getSplatValue()) : nullptr;
841 // No unsafe math , no constant argument, do nothing
842 if (!isUnsafeMath(CI) && !CF && !CINT && !CZero)
845 // 0x1111111 means that we don't do anything for this call.
846 int ci_opr1 = (CINT ? (int)CINT->getSExtValue() : 0x1111111);
848 if ((CF && CF->isZero()) || (CINT && ci_opr1 == 0) || CZero) {
849 // pow/powr/pown(x, 0) == 1
850 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> 1\n");
851 Constant *cnval = ConstantFP::get(eltType, 1.0);
852 if (getVecSize(FInfo) > 1) {
853 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
858 if ((CF && CF->isExactlyValue(1.0)) || (CINT && ci_opr1 == 1)) {
859 // pow/powr/pown(x, 1.0) = x
860 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr0 << "\n");
864 if ((CF && CF->isExactlyValue(2.0)) || (CINT && ci_opr1 == 2)) {
865 // pow/powr/pown(x, 2.0) = x*x
866 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr0 << " * " << *opr0
868 Value *nval = B.CreateFMul(opr0, opr0, "__pow2");
872 if ((CF && CF->isExactlyValue(-1.0)) || (CINT && ci_opr1 == -1)) {
873 // pow/powr/pown(x, -1.0) = 1.0/x
874 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> 1 / " << *opr0 << "\n");
875 Constant *cnval = ConstantFP::get(eltType, 1.0);
876 if (getVecSize(FInfo) > 1) {
877 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
879 Value *nval = B.CreateFDiv(cnval, opr0, "__powrecip");
884 Module *M = CI->getModule();
885 if (CF && (CF->isExactlyValue(0.5) || CF->isExactlyValue(-0.5))) {
886 // pow[r](x, [-]0.5) = sqrt(x)
887 bool issqrt = CF->isExactlyValue(0.5);
888 if (FunctionCallee FPExpr =
889 getFunction(M, AMDGPULibFunc(issqrt ? AMDGPULibFunc::EI_SQRT
890 : AMDGPULibFunc::EI_RSQRT,
892 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> "
893 << FInfo.getName().c_str() << "(" << *opr0 << ")\n");
894 Value *nval = CreateCallEx(B,FPExpr, opr0, issqrt ? "__pow2sqrt"
901 if (!isUnsafeMath(CI))
904 // Unsafe Math optimization
906 // Remember that ci_opr1 is set if opr1 is integral
908 double dval = (getArgType(FInfo) == AMDGPULibFunc::F32)
909 ? (double)CF->getValueAPF().convertToFloat()
910 : CF->getValueAPF().convertToDouble();
911 int ival = (int)dval;
912 if ((double)ival == dval) {
915 ci_opr1 = 0x11111111;
918 // pow/powr/pown(x, c) = [1/](x*x*..x); where
919 // trunc(c) == c && the number of x == c && |c| <= 12
920 unsigned abs_opr1 = (ci_opr1 < 0) ? -ci_opr1 : ci_opr1;
921 if (abs_opr1 <= 12) {
925 cnval = ConstantFP::get(eltType, 1.0);
926 if (getVecSize(FInfo) > 1) {
927 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
931 Value *valx2 = nullptr;
933 while (abs_opr1 > 0) {
934 valx2 = valx2 ? B.CreateFMul(valx2, valx2, "__powx2") : opr0;
936 nval = nval ? B.CreateFMul(nval, valx2, "__powprod") : valx2;
943 cnval = ConstantFP::get(eltType, 1.0);
944 if (getVecSize(FInfo) > 1) {
945 cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
947 nval = B.CreateFDiv(cnval, nval, "__1powprod");
949 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> "
950 << ((ci_opr1 < 0) ? "1/prod(" : "prod(") << *opr0
956 // powr ---> exp2(y * log2(x))
957 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
958 FunctionCallee ExpExpr =
959 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2, FInfo));
963 bool needlog = false;
964 bool needabs = false;
965 bool needcopysign = false;
966 Constant *cnval = nullptr;
967 if (getVecSize(FInfo) == 1) {
968 CF = dyn_cast<ConstantFP>(opr0);
971 double V = (getArgType(FInfo) == AMDGPULibFunc::F32)
972 ? (double)CF->getValueAPF().convertToFloat()
973 : CF->getValueAPF().convertToDouble();
975 V = log2(std::abs(V));
976 cnval = ConstantFP::get(eltType, V);
977 needcopysign = (FInfo.getId() != AMDGPULibFunc::EI_POWR) &&
981 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR &&
982 (!CF || CF->isNegative());
985 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr0);
989 needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
991 assert ((int)CDV->getNumElements() == getVecSize(FInfo) &&
992 "Wrong vector size detected");
994 SmallVector<double, 0> DVal;
995 for (int i=0; i < getVecSize(FInfo); ++i) {
996 double V = (getArgType(FInfo) == AMDGPULibFunc::F32)
997 ? (double)CDV->getElementAsFloat(i)
998 : CDV->getElementAsDouble(i);
999 if (V < 0.0) needcopysign = true;
1000 V = log2(std::abs(V));
1003 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1004 SmallVector<float, 0> FVal;
1005 for (unsigned i=0; i < DVal.size(); ++i) {
1006 FVal.push_back((float)DVal[i]);
1008 ArrayRef<float> tmp(FVal);
1009 cnval = ConstantDataVector::get(M->getContext(), tmp);
1011 ArrayRef<double> tmp(DVal);
1012 cnval = ConstantDataVector::get(M->getContext(), tmp);
1017 if (needcopysign && (FInfo.getId() == AMDGPULibFunc::EI_POW)) {
1018 // We cannot handle corner cases for a general pow() function, give up
1019 // unless y is a constant integral value. Then proceed as if it were pown.
1020 if (getVecSize(FInfo) == 1) {
1021 if (const ConstantFP *CF = dyn_cast<ConstantFP>(opr1)) {
1022 double y = (getArgType(FInfo) == AMDGPULibFunc::F32)
1023 ? (double)CF->getValueAPF().convertToFloat()
1024 : CF->getValueAPF().convertToDouble();
1025 if (y != (double)(int64_t)y)
1030 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr1)) {
1031 for (int i=0; i < getVecSize(FInfo); ++i) {
1032 double y = (getArgType(FInfo) == AMDGPULibFunc::F32)
1033 ? (double)CDV->getElementAsFloat(i)
1034 : CDV->getElementAsDouble(i);
1035 if (y != (double)(int64_t)y)
1045 FunctionCallee AbsExpr =
1046 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_FABS, FInfo));
1049 nval = CreateCallEx(B, AbsExpr, opr0, "__fabs");
1051 nval = cnval ? cnval : opr0;
1054 FunctionCallee LogExpr =
1055 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2, FInfo));
1058 nval = CreateCallEx(B,LogExpr, nval, "__log2");
1061 if (FInfo.getId() == AMDGPULibFunc::EI_POWN) {
1062 // convert int(32) to fp(f32 or f64)
1063 opr1 = B.CreateSIToFP(opr1, nval->getType(), "pownI2F");
1065 nval = B.CreateFMul(opr1, nval, "__ylogx");
1066 nval = CreateCallEx(B,ExpExpr, nval, "__exp2");
1070 Type* rTy = opr0->getType();
1071 Type* nTyS = eltType->isDoubleTy() ? B.getInt64Ty() : B.getInt32Ty();
1073 if (const auto *vTy = dyn_cast<FixedVectorType>(rTy))
1074 nTy = FixedVectorType::get(nTyS, vTy);
1075 unsigned size = nTy->getScalarSizeInBits();
1076 opr_n = CI->getArgOperand(1);
1077 if (opr_n->getType()->isIntegerTy())
1078 opr_n = B.CreateZExtOrBitCast(opr_n, nTy, "__ytou");
1080 opr_n = B.CreateFPToSI(opr1, nTy, "__ytou");
1082 Value *sign = B.CreateShl(opr_n, size-1, "__yeven");
1083 sign = B.CreateAnd(B.CreateBitCast(opr0, nTy), sign, "__pow_sign");
1084 nval = B.CreateOr(B.CreateBitCast(nval, nTy), sign);
1085 nval = B.CreateBitCast(nval, opr0->getType());
1088 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> "
1089 << "exp2(" << *opr1 << " * log2(" << *opr0 << "))\n");
1095 bool AMDGPULibCalls::fold_rootn(CallInst *CI, IRBuilder<> &B,
1096 const FuncInfo &FInfo) {
1097 Value *opr0 = CI->getArgOperand(0);
1098 Value *opr1 = CI->getArgOperand(1);
1100 ConstantInt *CINT = dyn_cast<ConstantInt>(opr1);
1104 int ci_opr1 = (int)CINT->getSExtValue();
1105 if (ci_opr1 == 1) { // rootn(x, 1) = x
1106 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr0 << "\n");
1110 if (ci_opr1 == 2) { // rootn(x, 2) = sqrt(x)
1111 Module *M = CI->getModule();
1112 if (FunctionCallee FPExpr =
1113 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1114 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> sqrt(" << *opr0 << ")\n");
1115 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2sqrt");
1119 } else if (ci_opr1 == 3) { // rootn(x, 3) = cbrt(x)
1120 Module *M = CI->getModule();
1121 if (FunctionCallee FPExpr =
1122 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT, FInfo))) {
1123 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> cbrt(" << *opr0 << ")\n");
1124 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2cbrt");
1128 } else if (ci_opr1 == -1) { // rootn(x, -1) = 1.0/x
1129 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> 1.0 / " << *opr0 << "\n");
1130 Value *nval = B.CreateFDiv(ConstantFP::get(opr0->getType(), 1.0),
1135 } else if (ci_opr1 == -2) { // rootn(x, -2) = rsqrt(x)
1136 Module *M = CI->getModule();
1137 if (FunctionCallee FPExpr =
1138 getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT, FInfo))) {
1139 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> rsqrt(" << *opr0
1141 Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2rsqrt");
1149 bool AMDGPULibCalls::fold_fma_mad(CallInst *CI, IRBuilder<> &B,
1150 const FuncInfo &FInfo) {
1151 Value *opr0 = CI->getArgOperand(0);
1152 Value *opr1 = CI->getArgOperand(1);
1153 Value *opr2 = CI->getArgOperand(2);
1155 ConstantFP *CF0 = dyn_cast<ConstantFP>(opr0);
1156 ConstantFP *CF1 = dyn_cast<ConstantFP>(opr1);
1157 if ((CF0 && CF0->isZero()) || (CF1 && CF1->isZero())) {
1158 // fma/mad(a, b, c) = c if a=0 || b=0
1159 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr2 << "\n");
1163 if (CF0 && CF0->isExactlyValue(1.0f)) {
1164 // fma/mad(a, b, c) = b+c if a=1
1165 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr1 << " + " << *opr2
1167 Value *nval = B.CreateFAdd(opr1, opr2, "fmaadd");
1171 if (CF1 && CF1->isExactlyValue(1.0f)) {
1172 // fma/mad(a, b, c) = a+c if b=1
1173 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr0 << " + " << *opr2
1175 Value *nval = B.CreateFAdd(opr0, opr2, "fmaadd");
1179 if (ConstantFP *CF = dyn_cast<ConstantFP>(opr2)) {
1181 // fma/mad(a, b, c) = a*b if c=0
1182 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *opr0 << " * "
1184 Value *nval = B.CreateFMul(opr0, opr1, "fmamul");
1193 // Get a scalar native builtin single argument FP function
1194 FunctionCallee AMDGPULibCalls::getNativeFunction(Module *M,
1195 const FuncInfo &FInfo) {
1196 if (getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()))
1198 FuncInfo nf = FInfo;
1199 nf.setPrefix(AMDGPULibFunc::NATIVE);
1200 return getFunction(M, nf);
1203 // fold sqrt -> native_sqrt (x)
1204 bool AMDGPULibCalls::fold_sqrt(CallInst *CI, IRBuilder<> &B,
1205 const FuncInfo &FInfo) {
1206 if (getArgType(FInfo) == AMDGPULibFunc::F32 && (getVecSize(FInfo) == 1) &&
1207 (FInfo.getPrefix() != AMDGPULibFunc::NATIVE)) {
1208 if (FunctionCallee FPExpr = getNativeFunction(
1209 CI->getModule(), AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1210 Value *opr0 = CI->getArgOperand(0);
1211 LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> "
1212 << "sqrt(" << *opr0 << ")\n");
1213 Value *nval = CreateCallEx(B,FPExpr, opr0, "__sqrt");
1221 // fold sin, cos -> sincos.
1222 bool AMDGPULibCalls::fold_sincos(CallInst *CI, IRBuilder<> &B,
1223 AliasAnalysis *AA) {
1224 AMDGPULibFunc fInfo;
1225 if (!AMDGPULibFunc::parse(CI->getCalledFunction()->getName(), fInfo))
1228 assert(fInfo.getId() == AMDGPULibFunc::EI_SIN ||
1229 fInfo.getId() == AMDGPULibFunc::EI_COS);
1230 bool const isSin = fInfo.getId() == AMDGPULibFunc::EI_SIN;
1232 Value *CArgVal = CI->getArgOperand(0);
1233 BasicBlock * const CBB = CI->getParent();
1235 int const MaxScan = 30;
1236 bool Changed = false;
1238 { // fold in load value.
1239 LoadInst *LI = dyn_cast<LoadInst>(CArgVal);
1240 if (LI && LI->getParent() == CBB) {
1241 BasicBlock::iterator BBI = LI->getIterator();
1242 Value *AvailableVal = FindAvailableLoadedValue(LI, CBB, BBI, MaxScan, AA);
1245 CArgVal->replaceAllUsesWith(AvailableVal);
1246 if (CArgVal->getNumUses() == 0)
1247 LI->eraseFromParent();
1248 CArgVal = CI->getArgOperand(0);
1253 Module *M = CI->getModule();
1254 fInfo.setId(isSin ? AMDGPULibFunc::EI_COS : AMDGPULibFunc::EI_SIN);
1255 std::string const PairName = fInfo.mangle();
1257 CallInst *UI = nullptr;
1258 for (User* U : CArgVal->users()) {
1259 CallInst *XI = dyn_cast_or_null<CallInst>(U);
1260 if (!XI || XI == CI || XI->getParent() != CBB)
1263 Function *UCallee = XI->getCalledFunction();
1264 if (!UCallee || !UCallee->getName().equals(PairName))
1267 BasicBlock::iterator BBI = CI->getIterator();
1268 if (BBI == CI->getParent()->begin())
1271 for (int I = MaxScan; I > 0 && BBI != CBB->begin(); --BBI, --I) {
1272 if (cast<Instruction>(BBI) == XI) {
1283 // Merge the sin and cos.
1285 // for OpenCL 2.0 we have only generic implementation of sincos
1287 AMDGPULibFunc nf(AMDGPULibFunc::EI_SINCOS, fInfo);
1288 nf.getLeads()[0].PtrKind = AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS);
1289 FunctionCallee Fsincos = getFunction(M, nf);
1293 BasicBlock::iterator ItOld = B.GetInsertPoint();
1294 AllocaInst *Alloc = insertAlloca(UI, B, "__sincos_");
1295 B.SetInsertPoint(UI);
1298 Type *PTy = Fsincos.getFunctionType()->getParamType(1);
1299 // The allocaInst allocates the memory in private address space. This need
1300 // to be bitcasted to point to the address space of cos pointer type.
1301 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1302 if (PTy->getPointerAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
1303 P = B.CreateAddrSpaceCast(Alloc, PTy);
1304 CallInst *Call = CreateCallEx2(B, Fsincos, UI->getArgOperand(0), P);
1306 LLVM_DEBUG(errs() << "AMDIC: fold_sincos (" << *CI << ", " << *UI << ") with "
1309 if (!isSin) { // CI->cos, UI->sin
1310 B.SetInsertPoint(&*ItOld);
1311 UI->replaceAllUsesWith(&*Call);
1312 Instruction *Reload = B.CreateLoad(Alloc->getAllocatedType(), Alloc);
1313 CI->replaceAllUsesWith(Reload);
1314 UI->eraseFromParent();
1315 CI->eraseFromParent();
1316 } else { // CI->sin, UI->cos
1317 Instruction *Reload = B.CreateLoad(Alloc->getAllocatedType(), Alloc);
1318 UI->replaceAllUsesWith(Reload);
1319 CI->replaceAllUsesWith(Call);
1320 UI->eraseFromParent();
1321 CI->eraseFromParent();
1326 bool AMDGPULibCalls::fold_wavefrontsize(CallInst *CI, IRBuilder<> &B) {
1330 StringRef CPU = TM->getTargetCPU();
1331 StringRef Features = TM->getTargetFeatureString();
1332 if ((CPU.empty() || CPU.equals_insensitive("generic")) &&
1333 (Features.empty() || !Features.contains_insensitive("wavefrontsize")))
1336 Function *F = CI->getParent()->getParent();
1337 const GCNSubtarget &ST = TM->getSubtarget<GCNSubtarget>(*F);
1338 unsigned N = ST.getWavefrontSize();
1340 LLVM_DEBUG(errs() << "AMDIC: fold_wavefrontsize (" << *CI << ") with "
1343 CI->replaceAllUsesWith(ConstantInt::get(B.getInt32Ty(), N));
1344 CI->eraseFromParent();
1348 // Get insertion point at entry.
1349 BasicBlock::iterator AMDGPULibCalls::getEntryIns(CallInst * UI) {
1350 Function * Func = UI->getParent()->getParent();
1351 BasicBlock * BB = &Func->getEntryBlock();
1352 assert(BB && "Entry block not found!");
1353 BasicBlock::iterator ItNew = BB->begin();
1357 // Insert a AllocsInst at the beginning of function entry block.
1358 AllocaInst* AMDGPULibCalls::insertAlloca(CallInst *UI, IRBuilder<> &B,
1359 const char *prefix) {
1360 BasicBlock::iterator ItNew = getEntryIns(UI);
1361 Function *UCallee = UI->getCalledFunction();
1362 Type *RetType = UCallee->getReturnType();
1363 B.SetInsertPoint(&*ItNew);
1365 B.CreateAlloca(RetType, nullptr, std::string(prefix) + UI->getName());
1366 Alloc->setAlignment(
1367 Align(UCallee->getParent()->getDataLayout().getTypeAllocSize(RetType)));
1371 bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo,
1372 double& Res0, double& Res1,
1373 Constant *copr0, Constant *copr1,
1375 // By default, opr0/opr1/opr3 holds values of float/double type.
1376 // If they are not float/double, each function has to its
1377 // operand separately.
1378 double opr0=0.0, opr1=0.0, opr2=0.0;
1379 ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0);
1380 ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1);
1381 ConstantFP *fpopr2 = dyn_cast_or_null<ConstantFP>(copr2);
1383 opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1384 ? fpopr0->getValueAPF().convertToDouble()
1385 : (double)fpopr0->getValueAPF().convertToFloat();
1389 opr1 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1390 ? fpopr1->getValueAPF().convertToDouble()
1391 : (double)fpopr1->getValueAPF().convertToFloat();
1395 opr2 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1396 ? fpopr2->getValueAPF().convertToDouble()
1397 : (double)fpopr2->getValueAPF().convertToFloat();
1400 switch (FInfo.getId()) {
1401 default : return false;
1403 case AMDGPULibFunc::EI_ACOS:
1407 case AMDGPULibFunc::EI_ACOSH:
1408 // acosh(x) == log(x + sqrt(x*x - 1))
1409 Res0 = log(opr0 + sqrt(opr0*opr0 - 1.0));
1412 case AMDGPULibFunc::EI_ACOSPI:
1413 Res0 = acos(opr0) / MATH_PI;
1416 case AMDGPULibFunc::EI_ASIN:
1420 case AMDGPULibFunc::EI_ASINH:
1421 // asinh(x) == log(x + sqrt(x*x + 1))
1422 Res0 = log(opr0 + sqrt(opr0*opr0 + 1.0));
1425 case AMDGPULibFunc::EI_ASINPI:
1426 Res0 = asin(opr0) / MATH_PI;
1429 case AMDGPULibFunc::EI_ATAN:
1433 case AMDGPULibFunc::EI_ATANH:
1434 // atanh(x) == (log(x+1) - log(x-1))/2;
1435 Res0 = (log(opr0 + 1.0) - log(opr0 - 1.0))/2.0;
1438 case AMDGPULibFunc::EI_ATANPI:
1439 Res0 = atan(opr0) / MATH_PI;
1442 case AMDGPULibFunc::EI_CBRT:
1443 Res0 = (opr0 < 0.0) ? -pow(-opr0, 1.0/3.0) : pow(opr0, 1.0/3.0);
1446 case AMDGPULibFunc::EI_COS:
1450 case AMDGPULibFunc::EI_COSH:
1454 case AMDGPULibFunc::EI_COSPI:
1455 Res0 = cos(MATH_PI * opr0);
1458 case AMDGPULibFunc::EI_EXP:
1462 case AMDGPULibFunc::EI_EXP2:
1463 Res0 = pow(2.0, opr0);
1466 case AMDGPULibFunc::EI_EXP10:
1467 Res0 = pow(10.0, opr0);
1470 case AMDGPULibFunc::EI_EXPM1:
1471 Res0 = exp(opr0) - 1.0;
1474 case AMDGPULibFunc::EI_LOG:
1478 case AMDGPULibFunc::EI_LOG2:
1479 Res0 = log(opr0) / log(2.0);
1482 case AMDGPULibFunc::EI_LOG10:
1483 Res0 = log(opr0) / log(10.0);
1486 case AMDGPULibFunc::EI_RSQRT:
1487 Res0 = 1.0 / sqrt(opr0);
1490 case AMDGPULibFunc::EI_SIN:
1494 case AMDGPULibFunc::EI_SINH:
1498 case AMDGPULibFunc::EI_SINPI:
1499 Res0 = sin(MATH_PI * opr0);
1502 case AMDGPULibFunc::EI_SQRT:
1506 case AMDGPULibFunc::EI_TAN:
1510 case AMDGPULibFunc::EI_TANH:
1514 case AMDGPULibFunc::EI_TANPI:
1515 Res0 = tan(MATH_PI * opr0);
1518 case AMDGPULibFunc::EI_RECIP:
1522 // two-arg functions
1523 case AMDGPULibFunc::EI_DIVIDE:
1527 case AMDGPULibFunc::EI_POW:
1528 case AMDGPULibFunc::EI_POWR:
1529 Res0 = pow(opr0, opr1);
1532 case AMDGPULibFunc::EI_POWN: {
1533 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1534 double val = (double)iopr1->getSExtValue();
1535 Res0 = pow(opr0, val);
1541 case AMDGPULibFunc::EI_ROOTN: {
1542 if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1543 double val = (double)iopr1->getSExtValue();
1544 Res0 = pow(opr0, 1.0 / val);
1551 case AMDGPULibFunc::EI_SINCOS:
1556 // three-arg functions
1557 case AMDGPULibFunc::EI_FMA:
1558 case AMDGPULibFunc::EI_MAD:
1559 Res0 = opr0 * opr1 + opr2;
1566 bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) {
1567 int numArgs = (int)aCI->arg_size();
1571 Constant *copr0 = nullptr;
1572 Constant *copr1 = nullptr;
1573 Constant *copr2 = nullptr;
1575 if ((copr0 = dyn_cast<Constant>(aCI->getArgOperand(0))) == nullptr)
1580 if ((copr1 = dyn_cast<Constant>(aCI->getArgOperand(1))) == nullptr) {
1581 if (FInfo.getId() != AMDGPULibFunc::EI_SINCOS)
1587 if ((copr2 = dyn_cast<Constant>(aCI->getArgOperand(2))) == nullptr)
1591 // At this point, all arguments to aCI are constants.
1593 // max vector size is 16, and sincos will generate two results.
1594 double DVal0[16], DVal1[16];
1595 bool hasTwoResults = (FInfo.getId() == AMDGPULibFunc::EI_SINCOS);
1596 if (getVecSize(FInfo) == 1) {
1597 if (!evaluateScalarMathFunc(FInfo, DVal0[0],
1598 DVal1[0], copr0, copr1, copr2)) {
1602 ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0);
1603 ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1);
1604 ConstantDataVector *CDV2 = dyn_cast_or_null<ConstantDataVector>(copr2);
1605 for (int i=0; i < getVecSize(FInfo); ++i) {
1606 Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr;
1607 Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr;
1608 Constant *celt2 = CDV2 ? CDV2->getElementAsConstant(i) : nullptr;
1609 if (!evaluateScalarMathFunc(FInfo, DVal0[i],
1610 DVal1[i], celt0, celt1, celt2)) {
1616 LLVMContext &context = CI->getParent()->getParent()->getContext();
1617 Constant *nval0, *nval1;
1618 if (getVecSize(FInfo) == 1) {
1619 nval0 = ConstantFP::get(CI->getType(), DVal0[0]);
1621 nval1 = ConstantFP::get(CI->getType(), DVal1[0]);
1623 if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1624 SmallVector <float, 0> FVal0, FVal1;
1625 for (int i=0; i < getVecSize(FInfo); ++i)
1626 FVal0.push_back((float)DVal0[i]);
1627 ArrayRef<float> tmp0(FVal0);
1628 nval0 = ConstantDataVector::get(context, tmp0);
1629 if (hasTwoResults) {
1630 for (int i=0; i < getVecSize(FInfo); ++i)
1631 FVal1.push_back((float)DVal1[i]);
1632 ArrayRef<float> tmp1(FVal1);
1633 nval1 = ConstantDataVector::get(context, tmp1);
1636 ArrayRef<double> tmp0(DVal0);
1637 nval0 = ConstantDataVector::get(context, tmp0);
1638 if (hasTwoResults) {
1639 ArrayRef<double> tmp1(DVal1);
1640 nval1 = ConstantDataVector::get(context, tmp1);
1645 if (hasTwoResults) {
1647 assert(FInfo.getId() == AMDGPULibFunc::EI_SINCOS &&
1648 "math function with ptr arg not supported yet");
1649 new StoreInst(nval1, aCI->getArgOperand(1), aCI);
1656 // Public interface to the Simplify LibCalls pass.
1657 FunctionPass *llvm::createAMDGPUSimplifyLibCallsPass(const TargetMachine *TM) {
1658 return new AMDGPUSimplifyLibCalls(TM);
1661 FunctionPass *llvm::createAMDGPUUseNativeCallsPass() {
1662 return new AMDGPUUseNativeCalls();
1665 bool AMDGPUSimplifyLibCalls::runOnFunction(Function &F) {
1666 if (skipFunction(F))
1669 bool Changed = false;
1670 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1672 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1673 F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';);
1675 for (auto &BB : F) {
1676 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
1677 // Ignore non-calls.
1678 CallInst *CI = dyn_cast<CallInst>(I);
1680 // Ignore intrinsics that do not become real instructions.
1681 if (!CI || isa<DbgInfoIntrinsic>(CI) || CI->isLifetimeStartOrEnd())
1684 // Ignore indirect calls.
1685 Function *Callee = CI->getCalledFunction();
1686 if (Callee == nullptr)
1689 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << "\n";
1691 if(Simplifier.fold(CI, AA))
1698 PreservedAnalyses AMDGPUSimplifyLibCallsPass::run(Function &F,
1699 FunctionAnalysisManager &AM) {
1700 AMDGPULibCalls Simplifier(&TM);
1701 Simplifier.initNativeFuncs();
1703 bool Changed = false;
1704 auto AA = &AM.getResult<AAManager>(F);
1706 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1707 F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';);
1709 for (auto &BB : F) {
1710 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1711 // Ignore non-calls.
1712 CallInst *CI = dyn_cast<CallInst>(I);
1714 // Ignore intrinsics that do not become real instructions.
1715 if (!CI || isa<DbgInfoIntrinsic>(CI) || CI->isLifetimeStartOrEnd())
1718 // Ignore indirect calls.
1719 Function *Callee = CI->getCalledFunction();
1720 if (Callee == nullptr)
1723 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << "\n";
1725 if (Simplifier.fold(CI, AA))
1729 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1732 bool AMDGPUUseNativeCalls::runOnFunction(Function &F) {
1733 if (skipFunction(F) || UseNative.empty())
1736 bool Changed = false;
1737 for (auto &BB : F) {
1738 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ) {
1739 // Ignore non-calls.
1740 CallInst *CI = dyn_cast<CallInst>(I);
1744 // Ignore indirect calls.
1745 Function *Callee = CI->getCalledFunction();
1746 if (Callee == nullptr)
1749 if (Simplifier.useNative(CI))
1756 PreservedAnalyses AMDGPUUseNativeCallsPass::run(Function &F,
1757 FunctionAnalysisManager &AM) {
1758 if (UseNative.empty())
1759 return PreservedAnalyses::all();
1761 AMDGPULibCalls Simplifier;
1762 Simplifier.initNativeFuncs();
1764 bool Changed = false;
1765 for (auto &BB : F) {
1766 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1767 // Ignore non-calls.
1768 CallInst *CI = dyn_cast<CallInst>(I);
1773 // Ignore indirect calls.
1774 Function *Callee = CI->getCalledFunction();
1775 if (Callee == nullptr)
1778 if (Simplifier.useNative(CI))
1782 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();