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 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "amdgpu-simplifylib"
17 #include "AMDGPULibFunc.h"
18 #include "AMDGPUSubtarget.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/Loads.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
42 static cl::opt
<bool> EnablePreLink("amdgpu-prelink",
43 cl::desc("Enable pre-link mode optimizations"),
47 static cl::list
<std::string
> UseNative("amdgpu-use-native",
48 cl::desc("Comma separated list of functions to replace with native, or all"),
49 cl::CommaSeparated
, cl::ValueOptional
,
52 #define MATH_PI numbers::pi
53 #define MATH_E numbers::e
54 #define MATH_SQRT2 numbers::sqrt2
55 #define MATH_SQRT1_2 numbers::inv_sqrt2
59 class AMDGPULibCalls
{
62 typedef llvm::AMDGPULibFunc FuncInfo
;
64 const TargetMachine
*TM
;
67 bool AllNative
= false;
69 bool useNativeFunc(const StringRef F
) const;
71 // Return a pointer (pointer expr) to the function if function defintion with
72 // "FuncName" exists. It may create a new function prototype in pre-link mode.
73 FunctionCallee
getFunction(Module
*M
, const FuncInfo
&fInfo
);
75 // Replace a normal function with its native version.
76 bool replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
);
78 bool parseFunctionName(const StringRef
& FMangledName
,
79 FuncInfo
*FInfo
=nullptr /*out*/);
81 bool TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
);
83 /* Specialized optimizations */
85 // recip (half or native)
86 bool fold_recip(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
88 // divide (half or native)
89 bool fold_divide(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
92 bool fold_pow(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
95 bool fold_rootn(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
98 bool fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
100 // -fuse-native for sincos
101 bool sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
);
103 // evaluate calls if calls' arguments are constants.
104 bool evaluateScalarMathFunc(FuncInfo
&FInfo
, double& Res0
,
105 double& Res1
, Constant
*copr0
, Constant
*copr1
, Constant
*copr2
);
106 bool evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
);
109 bool fold_exp(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
112 bool fold_exp2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
115 bool fold_exp10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
118 bool fold_log(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
121 bool fold_log2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
124 bool fold_log10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
127 bool fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
130 bool fold_sincos(CallInst
* CI
, IRBuilder
<> &B
, AliasAnalysis
* AA
);
132 // __read_pipe/__write_pipe
133 bool fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
, FuncInfo
&FInfo
);
135 // llvm.amdgcn.wavefrontsize
136 bool fold_wavefrontsize(CallInst
*CI
, IRBuilder
<> &B
);
138 // Get insertion point at entry.
139 BasicBlock::iterator
getEntryIns(CallInst
* UI
);
140 // Insert an Alloc instruction.
141 AllocaInst
* insertAlloca(CallInst
* UI
, IRBuilder
<> &B
, const char *prefix
);
142 // Get a scalar native builtin signle argument FP function
143 FunctionCallee
getNativeFunction(Module
*M
, const FuncInfo
&FInfo
);
148 bool isUnsafeMath(const CallInst
*CI
) const;
150 void replaceCall(Value
*With
) {
151 CI
->replaceAllUsesWith(With
);
152 CI
->eraseFromParent();
156 AMDGPULibCalls(const TargetMachine
*TM_
= nullptr) : TM(TM_
) {}
158 bool fold(CallInst
*CI
, AliasAnalysis
*AA
= nullptr);
160 void initNativeFuncs();
162 // Replace a normal math function call with that native version
163 bool useNative(CallInst
*CI
);
166 } // end llvm namespace
170 class AMDGPUSimplifyLibCalls
: public FunctionPass
{
172 const TargetOptions Options
;
174 AMDGPULibCalls Simplifier
;
177 static char ID
; // Pass identification
179 AMDGPUSimplifyLibCalls(const TargetOptions
&Opt
= TargetOptions(),
180 const TargetMachine
*TM
= nullptr)
181 : FunctionPass(ID
), Options(Opt
), Simplifier(TM
) {
182 initializeAMDGPUSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
185 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
186 AU
.addRequired
<AAResultsWrapperPass
>();
189 bool runOnFunction(Function
&M
) override
;
192 class AMDGPUUseNativeCalls
: public FunctionPass
{
194 AMDGPULibCalls Simplifier
;
197 static char ID
; // Pass identification
199 AMDGPUUseNativeCalls() : FunctionPass(ID
) {
200 initializeAMDGPUUseNativeCallsPass(*PassRegistry::getPassRegistry());
201 Simplifier
.initNativeFuncs();
204 bool runOnFunction(Function
&F
) override
;
207 } // end anonymous namespace.
209 char AMDGPUSimplifyLibCalls::ID
= 0;
210 char AMDGPUUseNativeCalls::ID
= 0;
212 INITIALIZE_PASS_BEGIN(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
213 "Simplify well-known AMD library calls", false, false)
214 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
215 INITIALIZE_PASS_END(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
216 "Simplify well-known AMD library calls", false, false)
218 INITIALIZE_PASS(AMDGPUUseNativeCalls
, "amdgpu-usenative",
219 "Replace builtin math calls with that native versions.",
222 template <typename IRB
>
223 static CallInst
*CreateCallEx(IRB
&B
, FunctionCallee Callee
, Value
*Arg
,
224 const Twine
&Name
= "") {
225 CallInst
*R
= B
.CreateCall(Callee
, Arg
, Name
);
226 if (Function
*F
= dyn_cast
<Function
>(Callee
.getCallee()))
227 R
->setCallingConv(F
->getCallingConv());
231 template <typename IRB
>
232 static CallInst
*CreateCallEx2(IRB
&B
, FunctionCallee Callee
, Value
*Arg1
,
233 Value
*Arg2
, const Twine
&Name
= "") {
234 CallInst
*R
= B
.CreateCall(Callee
, {Arg1
, Arg2
}, Name
);
235 if (Function
*F
= dyn_cast
<Function
>(Callee
.getCallee()))
236 R
->setCallingConv(F
->getCallingConv());
240 // Data structures for table-driven optimizations.
241 // FuncTbl works for both f32 and f64 functions with 1 input argument
248 /* a list of {result, input} */
249 static const TableEntry tbl_acos
[] = {
250 {MATH_PI
/ 2.0, 0.0},
251 {MATH_PI
/ 2.0, -0.0},
255 static const TableEntry tbl_acosh
[] = {
258 static const TableEntry tbl_acospi
[] = {
264 static const TableEntry tbl_asin
[] = {
267 {MATH_PI
/ 2.0, 1.0},
268 {-MATH_PI
/ 2.0, -1.0}
270 static const TableEntry tbl_asinh
[] = {
274 static const TableEntry tbl_asinpi
[] = {
280 static const TableEntry tbl_atan
[] = {
283 {MATH_PI
/ 4.0, 1.0},
284 {-MATH_PI
/ 4.0, -1.0}
286 static const TableEntry tbl_atanh
[] = {
290 static const TableEntry tbl_atanpi
[] = {
296 static const TableEntry tbl_cbrt
[] = {
302 static const TableEntry tbl_cos
[] = {
306 static const TableEntry tbl_cosh
[] = {
310 static const TableEntry tbl_cospi
[] = {
314 static const TableEntry tbl_erfc
[] = {
318 static const TableEntry tbl_erf
[] = {
322 static const TableEntry tbl_exp
[] = {
327 static const TableEntry tbl_exp2
[] = {
332 static const TableEntry tbl_exp10
[] = {
337 static const TableEntry tbl_expm1
[] = {
341 static const TableEntry tbl_log
[] = {
345 static const TableEntry tbl_log2
[] = {
349 static const TableEntry tbl_log10
[] = {
353 static const TableEntry tbl_rsqrt
[] = {
357 static const TableEntry tbl_sin
[] = {
361 static const TableEntry tbl_sinh
[] = {
365 static const TableEntry tbl_sinpi
[] = {
369 static const TableEntry tbl_sqrt
[] = {
374 static const TableEntry tbl_tan
[] = {
378 static const TableEntry tbl_tanh
[] = {
382 static const TableEntry tbl_tanpi
[] = {
386 static const TableEntry tbl_tgamma
[] = {
393 static bool HasNative(AMDGPULibFunc::EFuncId id
) {
395 case AMDGPULibFunc::EI_DIVIDE
:
396 case AMDGPULibFunc::EI_COS
:
397 case AMDGPULibFunc::EI_EXP
:
398 case AMDGPULibFunc::EI_EXP2
:
399 case AMDGPULibFunc::EI_EXP10
:
400 case AMDGPULibFunc::EI_LOG
:
401 case AMDGPULibFunc::EI_LOG2
:
402 case AMDGPULibFunc::EI_LOG10
:
403 case AMDGPULibFunc::EI_POWR
:
404 case AMDGPULibFunc::EI_RECIP
:
405 case AMDGPULibFunc::EI_RSQRT
:
406 case AMDGPULibFunc::EI_SIN
:
407 case AMDGPULibFunc::EI_SINCOS
:
408 case AMDGPULibFunc::EI_SQRT
:
409 case AMDGPULibFunc::EI_TAN
:
418 const TableEntry
*table
; // variable size: from 0 to (size - 1)
420 TableRef() : size(0), table(nullptr) {}
423 TableRef(const TableEntry (&tbl
)[N
]) : size(N
), table(&tbl
[0]) {}
426 static TableRef
getOptTable(AMDGPULibFunc::EFuncId id
) {
428 case AMDGPULibFunc::EI_ACOS
: return TableRef(tbl_acos
);
429 case AMDGPULibFunc::EI_ACOSH
: return TableRef(tbl_acosh
);
430 case AMDGPULibFunc::EI_ACOSPI
: return TableRef(tbl_acospi
);
431 case AMDGPULibFunc::EI_ASIN
: return TableRef(tbl_asin
);
432 case AMDGPULibFunc::EI_ASINH
: return TableRef(tbl_asinh
);
433 case AMDGPULibFunc::EI_ASINPI
: return TableRef(tbl_asinpi
);
434 case AMDGPULibFunc::EI_ATAN
: return TableRef(tbl_atan
);
435 case AMDGPULibFunc::EI_ATANH
: return TableRef(tbl_atanh
);
436 case AMDGPULibFunc::EI_ATANPI
: return TableRef(tbl_atanpi
);
437 case AMDGPULibFunc::EI_CBRT
: return TableRef(tbl_cbrt
);
438 case AMDGPULibFunc::EI_NCOS
:
439 case AMDGPULibFunc::EI_COS
: return TableRef(tbl_cos
);
440 case AMDGPULibFunc::EI_COSH
: return TableRef(tbl_cosh
);
441 case AMDGPULibFunc::EI_COSPI
: return TableRef(tbl_cospi
);
442 case AMDGPULibFunc::EI_ERFC
: return TableRef(tbl_erfc
);
443 case AMDGPULibFunc::EI_ERF
: return TableRef(tbl_erf
);
444 case AMDGPULibFunc::EI_EXP
: return TableRef(tbl_exp
);
445 case AMDGPULibFunc::EI_NEXP2
:
446 case AMDGPULibFunc::EI_EXP2
: return TableRef(tbl_exp2
);
447 case AMDGPULibFunc::EI_EXP10
: return TableRef(tbl_exp10
);
448 case AMDGPULibFunc::EI_EXPM1
: return TableRef(tbl_expm1
);
449 case AMDGPULibFunc::EI_LOG
: return TableRef(tbl_log
);
450 case AMDGPULibFunc::EI_NLOG2
:
451 case AMDGPULibFunc::EI_LOG2
: return TableRef(tbl_log2
);
452 case AMDGPULibFunc::EI_LOG10
: return TableRef(tbl_log10
);
453 case AMDGPULibFunc::EI_NRSQRT
:
454 case AMDGPULibFunc::EI_RSQRT
: return TableRef(tbl_rsqrt
);
455 case AMDGPULibFunc::EI_NSIN
:
456 case AMDGPULibFunc::EI_SIN
: return TableRef(tbl_sin
);
457 case AMDGPULibFunc::EI_SINH
: return TableRef(tbl_sinh
);
458 case AMDGPULibFunc::EI_SINPI
: return TableRef(tbl_sinpi
);
459 case AMDGPULibFunc::EI_NSQRT
:
460 case AMDGPULibFunc::EI_SQRT
: return TableRef(tbl_sqrt
);
461 case AMDGPULibFunc::EI_TAN
: return TableRef(tbl_tan
);
462 case AMDGPULibFunc::EI_TANH
: return TableRef(tbl_tanh
);
463 case AMDGPULibFunc::EI_TANPI
: return TableRef(tbl_tanpi
);
464 case AMDGPULibFunc::EI_TGAMMA
: return TableRef(tbl_tgamma
);
470 static inline int getVecSize(const AMDGPULibFunc
& FInfo
) {
471 return FInfo
.getLeads()[0].VectorSize
;
474 static inline AMDGPULibFunc::EType
getArgType(const AMDGPULibFunc
& FInfo
) {
475 return (AMDGPULibFunc::EType
)FInfo
.getLeads()[0].ArgType
;
478 FunctionCallee
AMDGPULibCalls::getFunction(Module
*M
, const FuncInfo
&fInfo
) {
479 // If we are doing PreLinkOpt, the function is external. So it is safe to
480 // use getOrInsertFunction() at this stage.
482 return EnablePreLink
? AMDGPULibFunc::getOrInsertFunction(M
, fInfo
)
483 : AMDGPULibFunc::getFunction(M
, fInfo
);
486 bool AMDGPULibCalls::parseFunctionName(const StringRef
& FMangledName
,
488 return AMDGPULibFunc::parse(FMangledName
, *FInfo
);
491 bool AMDGPULibCalls::isUnsafeMath(const CallInst
*CI
) const {
492 if (auto Op
= dyn_cast
<FPMathOperator
>(CI
))
495 const Function
*F
= CI
->getParent()->getParent();
496 Attribute Attr
= F
->getFnAttribute("unsafe-fp-math");
497 return Attr
.getValueAsString() == "true";
500 bool AMDGPULibCalls::useNativeFunc(const StringRef F
) const {
502 std::find(UseNative
.begin(), UseNative
.end(), F
) != UseNative
.end();
505 void AMDGPULibCalls::initNativeFuncs() {
506 AllNative
= useNativeFunc("all") ||
507 (UseNative
.getNumOccurrences() && UseNative
.size() == 1 &&
508 UseNative
.begin()->empty());
511 bool AMDGPULibCalls::sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
) {
512 bool native_sin
= useNativeFunc("sin");
513 bool native_cos
= useNativeFunc("cos");
515 if (native_sin
&& native_cos
) {
516 Module
*M
= aCI
->getModule();
517 Value
*opr0
= aCI
->getArgOperand(0);
520 nf
.getLeads()[0].ArgType
= FInfo
.getLeads()[0].ArgType
;
521 nf
.getLeads()[0].VectorSize
= FInfo
.getLeads()[0].VectorSize
;
523 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
524 nf
.setId(AMDGPULibFunc::EI_SIN
);
525 FunctionCallee sinExpr
= getFunction(M
, nf
);
527 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
528 nf
.setId(AMDGPULibFunc::EI_COS
);
529 FunctionCallee cosExpr
= getFunction(M
, nf
);
530 if (sinExpr
&& cosExpr
) {
531 Value
*sinval
= CallInst::Create(sinExpr
, opr0
, "splitsin", aCI
);
532 Value
*cosval
= CallInst::Create(cosExpr
, opr0
, "splitcos", aCI
);
533 new StoreInst(cosval
, aCI
->getArgOperand(1), aCI
);
535 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
536 << " with native version of sin/cos");
545 bool AMDGPULibCalls::useNative(CallInst
*aCI
) {
547 Function
*Callee
= aCI
->getCalledFunction();
550 if (!parseFunctionName(Callee
->getName(), &FInfo
) || !FInfo
.isMangled() ||
551 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
552 getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()) ||
553 !(AllNative
|| useNativeFunc(FInfo
.getName()))) {
557 if (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
)
558 return sincosUseNative(aCI
, FInfo
);
560 FInfo
.setPrefix(AMDGPULibFunc::NATIVE
);
561 FunctionCallee F
= getFunction(aCI
->getModule(), FInfo
);
565 aCI
->setCalledFunction(F
);
566 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
567 << " with native version");
571 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
572 // builtin, with appended type size and alignment arguments, where 2 or 4
573 // indicates the original number of arguments. The library has optimized version
574 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
575 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
576 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
577 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
578 bool AMDGPULibCalls::fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
,
580 auto *Callee
= CI
->getCalledFunction();
581 if (!Callee
->isDeclaration())
584 assert(Callee
->hasName() && "Invalid read_pipe/write_pipe function");
585 auto *M
= Callee
->getParent();
586 auto &Ctx
= M
->getContext();
587 std::string Name
= Callee
->getName();
588 auto NumArg
= CI
->getNumArgOperands();
589 if (NumArg
!= 4 && NumArg
!= 6)
591 auto *PacketSize
= CI
->getArgOperand(NumArg
- 2);
592 auto *PacketAlign
= CI
->getArgOperand(NumArg
- 1);
593 if (!isa
<ConstantInt
>(PacketSize
) || !isa
<ConstantInt
>(PacketAlign
))
595 unsigned Size
= cast
<ConstantInt
>(PacketSize
)->getZExtValue();
596 unsigned Align
= cast
<ConstantInt
>(PacketAlign
)->getZExtValue();
597 if (Size
!= Align
|| !isPowerOf2_32(Size
))
602 PtrElemTy
= Type::getIntNTy(Ctx
, Size
* 8);
604 PtrElemTy
= VectorType::get(Type::getInt64Ty(Ctx
), Size
/ 8);
605 unsigned PtrArgLoc
= CI
->getNumArgOperands() - 3;
606 auto PtrArg
= CI
->getArgOperand(PtrArgLoc
);
607 unsigned PtrArgAS
= PtrArg
->getType()->getPointerAddressSpace();
608 auto *PtrTy
= llvm::PointerType::get(PtrElemTy
, PtrArgAS
);
610 SmallVector
<llvm::Type
*, 6> ArgTys
;
611 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
612 ArgTys
.push_back(CI
->getArgOperand(I
)->getType());
613 ArgTys
.push_back(PtrTy
);
615 Name
= Name
+ "_" + std::to_string(Size
);
616 auto *FTy
= FunctionType::get(Callee
->getReturnType(),
617 ArrayRef
<Type
*>(ArgTys
), false);
618 AMDGPULibFunc
NewLibFunc(Name
, FTy
);
619 FunctionCallee F
= AMDGPULibFunc::getOrInsertFunction(M
, NewLibFunc
);
623 auto *BCast
= B
.CreatePointerCast(PtrArg
, PtrTy
);
624 SmallVector
<Value
*, 6> Args
;
625 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
626 Args
.push_back(CI
->getArgOperand(I
));
627 Args
.push_back(BCast
);
629 auto *NCI
= B
.CreateCall(F
, Args
);
630 NCI
->setAttributes(CI
->getAttributes());
631 CI
->replaceAllUsesWith(NCI
);
632 CI
->dropAllReferences();
633 CI
->eraseFromParent();
638 // This function returns false if no change; return true otherwise.
639 bool AMDGPULibCalls::fold(CallInst
*CI
, AliasAnalysis
*AA
) {
641 Function
*Callee
= CI
->getCalledFunction();
643 // Ignore indirect calls.
644 if (Callee
== 0) return false;
646 BasicBlock
*BB
= CI
->getParent();
647 LLVMContext
&Context
= CI
->getParent()->getContext();
648 IRBuilder
<> B(Context
);
650 // Set the builder to the instruction after the call.
651 B
.SetInsertPoint(BB
, CI
->getIterator());
653 // Copy fast flags from the original call.
654 if (const FPMathOperator
*FPOp
= dyn_cast
<const FPMathOperator
>(CI
))
655 B
.setFastMathFlags(FPOp
->getFastMathFlags());
657 switch (Callee
->getIntrinsicID()) {
660 case Intrinsic::amdgcn_wavefrontsize
:
661 return !EnablePreLink
&& fold_wavefrontsize(CI
, B
);
665 if (!parseFunctionName(Callee
->getName(), &FInfo
))
668 // Further check the number of arguments to see if they match.
669 if (CI
->getNumArgOperands() != FInfo
.getNumArgs())
672 if (TDOFold(CI
, FInfo
))
675 // Under unsafe-math, evaluate calls if possible.
676 // According to Brian Sumner, we can do this for all f32 function calls
677 // using host's double function calls.
678 if (isUnsafeMath(CI
) && evaluateCall(CI
, FInfo
))
681 // Specilized optimizations for each function call
682 switch (FInfo
.getId()) {
683 case AMDGPULibFunc::EI_RECIP
:
684 // skip vector function
685 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
686 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
687 "recip must be an either native or half function");
688 return (getVecSize(FInfo
) != 1) ? false : fold_recip(CI
, B
, FInfo
);
690 case AMDGPULibFunc::EI_DIVIDE
:
691 // skip vector function
692 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
693 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
694 "divide must be an either native or half function");
695 return (getVecSize(FInfo
) != 1) ? false : fold_divide(CI
, B
, FInfo
);
697 case AMDGPULibFunc::EI_POW
:
698 case AMDGPULibFunc::EI_POWR
:
699 case AMDGPULibFunc::EI_POWN
:
700 return fold_pow(CI
, B
, FInfo
);
702 case AMDGPULibFunc::EI_ROOTN
:
703 // skip vector function
704 return (getVecSize(FInfo
) != 1) ? false : fold_rootn(CI
, B
, FInfo
);
706 case AMDGPULibFunc::EI_FMA
:
707 case AMDGPULibFunc::EI_MAD
:
708 case AMDGPULibFunc::EI_NFMA
:
709 // skip vector function
710 return (getVecSize(FInfo
) != 1) ? false : fold_fma_mad(CI
, B
, FInfo
);
712 case AMDGPULibFunc::EI_SQRT
:
713 return isUnsafeMath(CI
) && fold_sqrt(CI
, B
, FInfo
);
714 case AMDGPULibFunc::EI_COS
:
715 case AMDGPULibFunc::EI_SIN
:
716 if ((getArgType(FInfo
) == AMDGPULibFunc::F32
||
717 getArgType(FInfo
) == AMDGPULibFunc::F64
)
718 && (FInfo
.getPrefix() == AMDGPULibFunc::NOPFX
))
719 return fold_sincos(CI
, B
, AA
);
722 case AMDGPULibFunc::EI_READ_PIPE_2
:
723 case AMDGPULibFunc::EI_READ_PIPE_4
:
724 case AMDGPULibFunc::EI_WRITE_PIPE_2
:
725 case AMDGPULibFunc::EI_WRITE_PIPE_4
:
726 return fold_read_write_pipe(CI
, B
, FInfo
);
735 bool AMDGPULibCalls::TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
) {
736 // Table-Driven optimization
737 const TableRef tr
= getOptTable(FInfo
.getId());
741 int const sz
= (int)tr
.size
;
742 const TableEntry
* const ftbl
= tr
.table
;
743 Value
*opr0
= CI
->getArgOperand(0);
745 if (getVecSize(FInfo
) > 1) {
746 if (ConstantDataVector
*CV
= dyn_cast
<ConstantDataVector
>(opr0
)) {
747 SmallVector
<double, 0> DVal
;
748 for (int eltNo
= 0; eltNo
< getVecSize(FInfo
); ++eltNo
) {
749 ConstantFP
*eltval
= dyn_cast
<ConstantFP
>(
750 CV
->getElementAsConstant((unsigned)eltNo
));
751 assert(eltval
&& "Non-FP arguments in math function!");
753 for (int i
=0; i
< sz
; ++i
) {
754 if (eltval
->isExactlyValue(ftbl
[i
].input
)) {
755 DVal
.push_back(ftbl
[i
].result
);
761 // This vector constants not handled yet.
765 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
767 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
768 SmallVector
<float, 0> FVal
;
769 for (unsigned i
= 0; i
< DVal
.size(); ++i
) {
770 FVal
.push_back((float)DVal
[i
]);
772 ArrayRef
<float> tmp(FVal
);
773 nval
= ConstantDataVector::get(context
, tmp
);
775 ArrayRef
<double> tmp(DVal
);
776 nval
= ConstantDataVector::get(context
, tmp
);
778 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
784 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
785 for (int i
= 0; i
< sz
; ++i
) {
786 if (CF
->isExactlyValue(ftbl
[i
].input
)) {
787 Value
*nval
= ConstantFP::get(CF
->getType(), ftbl
[i
].result
);
788 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
799 bool AMDGPULibCalls::replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
) {
800 Module
*M
= CI
->getModule();
801 if (getArgType(FInfo
) != AMDGPULibFunc::F32
||
802 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
803 !HasNative(FInfo
.getId()))
806 AMDGPULibFunc nf
= FInfo
;
807 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
808 if (FunctionCallee FPExpr
= getFunction(M
, nf
)) {
809 LLVM_DEBUG(dbgs() << "AMDIC: " << *CI
<< " ---> ");
811 CI
->setCalledFunction(FPExpr
);
813 LLVM_DEBUG(dbgs() << *CI
<< '\n');
820 // [native_]half_recip(c) ==> 1.0/c
821 bool AMDGPULibCalls::fold_recip(CallInst
*CI
, IRBuilder
<> &B
,
822 const FuncInfo
&FInfo
) {
823 Value
*opr0
= CI
->getArgOperand(0);
824 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
825 // Just create a normal div. Later, InstCombine will be able
826 // to compute the divide into a constant (avoid check float infinity
827 // or subnormal at this point).
828 Value
*nval
= B
.CreateFDiv(ConstantFP::get(CF
->getType(), 1.0),
831 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
838 // [native_]half_divide(x, c) ==> x/c
839 bool AMDGPULibCalls::fold_divide(CallInst
*CI
, IRBuilder
<> &B
,
840 const FuncInfo
&FInfo
) {
841 Value
*opr0
= CI
->getArgOperand(0);
842 Value
*opr1
= CI
->getArgOperand(1);
843 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
844 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
846 if ((CF0
&& CF1
) || // both are constants
847 (CF1
&& (getArgType(FInfo
) == AMDGPULibFunc::F32
)))
848 // CF1 is constant && f32 divide
850 Value
*nval1
= B
.CreateFDiv(ConstantFP::get(opr1
->getType(), 1.0),
851 opr1
, "__div2recip");
852 Value
*nval
= B
.CreateFMul(opr0
, nval1
, "__div2mul");
860 static double log2(double V
) {
861 #if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
864 return log(V
) / numbers::ln2
;
869 bool AMDGPULibCalls::fold_pow(CallInst
*CI
, IRBuilder
<> &B
,
870 const FuncInfo
&FInfo
) {
871 assert((FInfo
.getId() == AMDGPULibFunc::EI_POW
||
872 FInfo
.getId() == AMDGPULibFunc::EI_POWR
||
873 FInfo
.getId() == AMDGPULibFunc::EI_POWN
) &&
874 "fold_pow: encounter a wrong function call");
879 ConstantAggregateZero
*CZero
;
882 opr0
= CI
->getArgOperand(0);
883 opr1
= CI
->getArgOperand(1);
884 CZero
= dyn_cast
<ConstantAggregateZero
>(opr1
);
885 if (getVecSize(FInfo
) == 1) {
886 eltType
= opr0
->getType();
887 CF
= dyn_cast
<ConstantFP
>(opr1
);
888 CINT
= dyn_cast
<ConstantInt
>(opr1
);
890 VectorType
*VTy
= dyn_cast
<VectorType
>(opr0
->getType());
891 assert(VTy
&& "Oprand of vector function should be of vectortype");
892 eltType
= VTy
->getElementType();
893 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
);
895 // Now, only Handle vector const whose elements have the same value.
896 CF
= CDV
? dyn_cast_or_null
<ConstantFP
>(CDV
->getSplatValue()) : nullptr;
897 CINT
= CDV
? dyn_cast_or_null
<ConstantInt
>(CDV
->getSplatValue()) : nullptr;
900 // No unsafe math , no constant argument, do nothing
901 if (!isUnsafeMath(CI
) && !CF
&& !CINT
&& !CZero
)
904 // 0x1111111 means that we don't do anything for this call.
905 int ci_opr1
= (CINT
? (int)CINT
->getSExtValue() : 0x1111111);
907 if ((CF
&& CF
->isZero()) || (CINT
&& ci_opr1
== 0) || CZero
) {
908 // pow/powr/pown(x, 0) == 1
909 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1\n");
910 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
911 if (getVecSize(FInfo
) > 1) {
912 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
917 if ((CF
&& CF
->isExactlyValue(1.0)) || (CINT
&& ci_opr1
== 1)) {
918 // pow/powr/pown(x, 1.0) = x
919 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
923 if ((CF
&& CF
->isExactlyValue(2.0)) || (CINT
&& ci_opr1
== 2)) {
924 // pow/powr/pown(x, 2.0) = x*x
925 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * " << *opr0
927 Value
*nval
= B
.CreateFMul(opr0
, opr0
, "__pow2");
931 if ((CF
&& CF
->isExactlyValue(-1.0)) || (CINT
&& ci_opr1
== -1)) {
932 // pow/powr/pown(x, -1.0) = 1.0/x
933 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1 / " << *opr0
<< "\n");
934 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
935 if (getVecSize(FInfo
) > 1) {
936 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
938 Value
*nval
= B
.CreateFDiv(cnval
, opr0
, "__powrecip");
943 Module
*M
= CI
->getModule();
944 if (CF
&& (CF
->isExactlyValue(0.5) || CF
->isExactlyValue(-0.5))) {
945 // pow[r](x, [-]0.5) = sqrt(x)
946 bool issqrt
= CF
->isExactlyValue(0.5);
947 if (FunctionCallee FPExpr
=
948 getFunction(M
, AMDGPULibFunc(issqrt
? AMDGPULibFunc::EI_SQRT
949 : AMDGPULibFunc::EI_RSQRT
,
951 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
952 << FInfo
.getName().c_str() << "(" << *opr0
<< ")\n");
953 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, issqrt
? "__pow2sqrt"
960 if (!isUnsafeMath(CI
))
963 // Unsafe Math optimization
965 // Remember that ci_opr1 is set if opr1 is integral
967 double dval
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
968 ? (double)CF
->getValueAPF().convertToFloat()
969 : CF
->getValueAPF().convertToDouble();
970 int ival
= (int)dval
;
971 if ((double)ival
== dval
) {
974 ci_opr1
= 0x11111111;
977 // pow/powr/pown(x, c) = [1/](x*x*..x); where
978 // trunc(c) == c && the number of x == c && |c| <= 12
979 unsigned abs_opr1
= (ci_opr1
< 0) ? -ci_opr1
: ci_opr1
;
980 if (abs_opr1
<= 12) {
984 cnval
= ConstantFP::get(eltType
, 1.0);
985 if (getVecSize(FInfo
) > 1) {
986 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
990 Value
*valx2
= nullptr;
992 while (abs_opr1
> 0) {
993 valx2
= valx2
? B
.CreateFMul(valx2
, valx2
, "__powx2") : opr0
;
995 nval
= nval
? B
.CreateFMul(nval
, valx2
, "__powprod") : valx2
;
1002 cnval
= ConstantFP::get(eltType
, 1.0);
1003 if (getVecSize(FInfo
) > 1) {
1004 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
1006 nval
= B
.CreateFDiv(cnval
, nval
, "__1powprod");
1008 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1009 << ((ci_opr1
< 0) ? "1/prod(" : "prod(") << *opr0
1015 // powr ---> exp2(y * log2(x))
1016 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
1017 FunctionCallee ExpExpr
=
1018 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2
, FInfo
));
1022 bool needlog
= false;
1023 bool needabs
= false;
1024 bool needcopysign
= false;
1025 Constant
*cnval
= nullptr;
1026 if (getVecSize(FInfo
) == 1) {
1027 CF
= dyn_cast
<ConstantFP
>(opr0
);
1030 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1031 ? (double)CF
->getValueAPF().convertToFloat()
1032 : CF
->getValueAPF().convertToDouble();
1034 V
= log2(std::abs(V
));
1035 cnval
= ConstantFP::get(eltType
, V
);
1036 needcopysign
= (FInfo
.getId() != AMDGPULibFunc::EI_POWR
) &&
1040 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
&&
1041 (!CF
|| CF
->isNegative());
1044 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr0
);
1048 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
;
1050 assert ((int)CDV
->getNumElements() == getVecSize(FInfo
) &&
1051 "Wrong vector size detected");
1053 SmallVector
<double, 0> DVal
;
1054 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1055 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1056 ? (double)CDV
->getElementAsFloat(i
)
1057 : CDV
->getElementAsDouble(i
);
1058 if (V
< 0.0) needcopysign
= true;
1059 V
= log2(std::abs(V
));
1062 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1063 SmallVector
<float, 0> FVal
;
1064 for (unsigned i
=0; i
< DVal
.size(); ++i
) {
1065 FVal
.push_back((float)DVal
[i
]);
1067 ArrayRef
<float> tmp(FVal
);
1068 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1070 ArrayRef
<double> tmp(DVal
);
1071 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1076 if (needcopysign
&& (FInfo
.getId() == AMDGPULibFunc::EI_POW
)) {
1077 // We cannot handle corner cases for a general pow() function, give up
1078 // unless y is a constant integral value. Then proceed as if it were pown.
1079 if (getVecSize(FInfo
) == 1) {
1080 if (const ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr1
)) {
1081 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1082 ? (double)CF
->getValueAPF().convertToFloat()
1083 : CF
->getValueAPF().convertToDouble();
1084 if (y
!= (double)(int64_t)y
)
1089 if (const ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
)) {
1090 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1091 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1092 ? (double)CDV
->getElementAsFloat(i
)
1093 : CDV
->getElementAsDouble(i
);
1094 if (y
!= (double)(int64_t)y
)
1104 FunctionCallee AbsExpr
=
1105 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_FABS
, FInfo
));
1108 nval
= CreateCallEx(B
, AbsExpr
, opr0
, "__fabs");
1110 nval
= cnval
? cnval
: opr0
;
1113 FunctionCallee LogExpr
=
1114 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2
, FInfo
));
1117 nval
= CreateCallEx(B
,LogExpr
, nval
, "__log2");
1120 if (FInfo
.getId() == AMDGPULibFunc::EI_POWN
) {
1121 // convert int(32) to fp(f32 or f64)
1122 opr1
= B
.CreateSIToFP(opr1
, nval
->getType(), "pownI2F");
1124 nval
= B
.CreateFMul(opr1
, nval
, "__ylogx");
1125 nval
= CreateCallEx(B
,ExpExpr
, nval
, "__exp2");
1129 Type
* rTy
= opr0
->getType();
1130 Type
* nTyS
= eltType
->isDoubleTy() ? B
.getInt64Ty() : B
.getInt32Ty();
1132 if (const VectorType
*vTy
= dyn_cast
<VectorType
>(rTy
))
1133 nTy
= VectorType::get(nTyS
, vTy
->getNumElements());
1134 unsigned size
= nTy
->getScalarSizeInBits();
1135 opr_n
= CI
->getArgOperand(1);
1136 if (opr_n
->getType()->isIntegerTy())
1137 opr_n
= B
.CreateZExtOrBitCast(opr_n
, nTy
, "__ytou");
1139 opr_n
= B
.CreateFPToSI(opr1
, nTy
, "__ytou");
1141 Value
*sign
= B
.CreateShl(opr_n
, size
-1, "__yeven");
1142 sign
= B
.CreateAnd(B
.CreateBitCast(opr0
, nTy
), sign
, "__pow_sign");
1143 nval
= B
.CreateOr(B
.CreateBitCast(nval
, nTy
), sign
);
1144 nval
= B
.CreateBitCast(nval
, opr0
->getType());
1147 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1148 << "exp2(" << *opr1
<< " * log2(" << *opr0
<< "))\n");
1154 bool AMDGPULibCalls::fold_rootn(CallInst
*CI
, IRBuilder
<> &B
,
1155 const FuncInfo
&FInfo
) {
1156 Value
*opr0
= CI
->getArgOperand(0);
1157 Value
*opr1
= CI
->getArgOperand(1);
1159 ConstantInt
*CINT
= dyn_cast
<ConstantInt
>(opr1
);
1163 int ci_opr1
= (int)CINT
->getSExtValue();
1164 if (ci_opr1
== 1) { // rootn(x, 1) = x
1165 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
1169 if (ci_opr1
== 2) { // rootn(x, 2) = sqrt(x)
1170 std::vector
<const Type
*> ParamsTys
;
1171 ParamsTys
.push_back(opr0
->getType());
1172 Module
*M
= CI
->getModule();
1173 if (FunctionCallee FPExpr
=
1174 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
, FInfo
))) {
1175 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> sqrt(" << *opr0
<< ")\n");
1176 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2sqrt");
1180 } else if (ci_opr1
== 3) { // rootn(x, 3) = cbrt(x)
1181 Module
*M
= CI
->getModule();
1182 if (FunctionCallee FPExpr
=
1183 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT
, FInfo
))) {
1184 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> cbrt(" << *opr0
<< ")\n");
1185 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2cbrt");
1189 } else if (ci_opr1
== -1) { // rootn(x, -1) = 1.0/x
1190 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1.0 / " << *opr0
<< "\n");
1191 Value
*nval
= B
.CreateFDiv(ConstantFP::get(opr0
->getType(), 1.0),
1196 } else if (ci_opr1
== -2) { // rootn(x, -2) = rsqrt(x)
1197 std::vector
<const Type
*> ParamsTys
;
1198 ParamsTys
.push_back(opr0
->getType());
1199 Module
*M
= CI
->getModule();
1200 if (FunctionCallee FPExpr
=
1201 getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT
, FInfo
))) {
1202 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> rsqrt(" << *opr0
1204 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2rsqrt");
1212 bool AMDGPULibCalls::fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
,
1213 const FuncInfo
&FInfo
) {
1214 Value
*opr0
= CI
->getArgOperand(0);
1215 Value
*opr1
= CI
->getArgOperand(1);
1216 Value
*opr2
= CI
->getArgOperand(2);
1218 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
1219 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
1220 if ((CF0
&& CF0
->isZero()) || (CF1
&& CF1
->isZero())) {
1221 // fma/mad(a, b, c) = c if a=0 || b=0
1222 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr2
<< "\n");
1226 if (CF0
&& CF0
->isExactlyValue(1.0f
)) {
1227 // fma/mad(a, b, c) = b+c if a=1
1228 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr1
<< " + " << *opr2
1230 Value
*nval
= B
.CreateFAdd(opr1
, opr2
, "fmaadd");
1234 if (CF1
&& CF1
->isExactlyValue(1.0f
)) {
1235 // fma/mad(a, b, c) = a+c if b=1
1236 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " + " << *opr2
1238 Value
*nval
= B
.CreateFAdd(opr0
, opr2
, "fmaadd");
1242 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr2
)) {
1244 // fma/mad(a, b, c) = a*b if c=0
1245 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * "
1247 Value
*nval
= B
.CreateFMul(opr0
, opr1
, "fmamul");
1256 // Get a scalar native builtin signle argument FP function
1257 FunctionCallee
AMDGPULibCalls::getNativeFunction(Module
*M
,
1258 const FuncInfo
&FInfo
) {
1259 if (getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()))
1261 FuncInfo nf
= FInfo
;
1262 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
1263 return getFunction(M
, nf
);
1266 // fold sqrt -> native_sqrt (x)
1267 bool AMDGPULibCalls::fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
,
1268 const FuncInfo
&FInfo
) {
1269 if (getArgType(FInfo
) == AMDGPULibFunc::F32
&& (getVecSize(FInfo
) == 1) &&
1270 (FInfo
.getPrefix() != AMDGPULibFunc::NATIVE
)) {
1271 if (FunctionCallee FPExpr
= getNativeFunction(
1272 CI
->getModule(), AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
, FInfo
))) {
1273 Value
*opr0
= CI
->getArgOperand(0);
1274 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1275 << "sqrt(" << *opr0
<< ")\n");
1276 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__sqrt");
1284 // fold sin, cos -> sincos.
1285 bool AMDGPULibCalls::fold_sincos(CallInst
*CI
, IRBuilder
<> &B
,
1286 AliasAnalysis
*AA
) {
1287 AMDGPULibFunc fInfo
;
1288 if (!AMDGPULibFunc::parse(CI
->getCalledFunction()->getName(), fInfo
))
1291 assert(fInfo
.getId() == AMDGPULibFunc::EI_SIN
||
1292 fInfo
.getId() == AMDGPULibFunc::EI_COS
);
1293 bool const isSin
= fInfo
.getId() == AMDGPULibFunc::EI_SIN
;
1295 Value
*CArgVal
= CI
->getArgOperand(0);
1296 BasicBlock
* const CBB
= CI
->getParent();
1298 int const MaxScan
= 30;
1300 { // fold in load value.
1301 LoadInst
*LI
= dyn_cast
<LoadInst
>(CArgVal
);
1302 if (LI
&& LI
->getParent() == CBB
) {
1303 BasicBlock::iterator BBI
= LI
->getIterator();
1304 Value
*AvailableVal
= FindAvailableLoadedValue(LI
, CBB
, BBI
, MaxScan
, AA
);
1306 CArgVal
->replaceAllUsesWith(AvailableVal
);
1307 if (CArgVal
->getNumUses() == 0)
1308 LI
->eraseFromParent();
1309 CArgVal
= CI
->getArgOperand(0);
1314 Module
*M
= CI
->getModule();
1315 fInfo
.setId(isSin
? AMDGPULibFunc::EI_COS
: AMDGPULibFunc::EI_SIN
);
1316 std::string
const PairName
= fInfo
.mangle();
1318 CallInst
*UI
= nullptr;
1319 for (User
* U
: CArgVal
->users()) {
1320 CallInst
*XI
= dyn_cast_or_null
<CallInst
>(U
);
1321 if (!XI
|| XI
== CI
|| XI
->getParent() != CBB
)
1324 Function
*UCallee
= XI
->getCalledFunction();
1325 if (!UCallee
|| !UCallee
->getName().equals(PairName
))
1328 BasicBlock::iterator BBI
= CI
->getIterator();
1329 if (BBI
== CI
->getParent()->begin())
1332 for (int I
= MaxScan
; I
> 0 && BBI
!= CBB
->begin(); --BBI
, --I
) {
1333 if (cast
<Instruction
>(BBI
) == XI
) {
1341 if (!UI
) return false;
1343 // Merge the sin and cos.
1345 // for OpenCL 2.0 we have only generic implementation of sincos
1347 AMDGPULibFunc
nf(AMDGPULibFunc::EI_SINCOS
, fInfo
);
1348 nf
.getLeads()[0].PtrKind
= AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS
);
1349 FunctionCallee Fsincos
= getFunction(M
, nf
);
1350 if (!Fsincos
) return false;
1352 BasicBlock::iterator ItOld
= B
.GetInsertPoint();
1353 AllocaInst
*Alloc
= insertAlloca(UI
, B
, "__sincos_");
1354 B
.SetInsertPoint(UI
);
1357 Type
*PTy
= Fsincos
.getFunctionType()->getParamType(1);
1358 // The allocaInst allocates the memory in private address space. This need
1359 // to be bitcasted to point to the address space of cos pointer type.
1360 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1361 if (PTy
->getPointerAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS
)
1362 P
= B
.CreateAddrSpaceCast(Alloc
, PTy
);
1363 CallInst
*Call
= CreateCallEx2(B
, Fsincos
, UI
->getArgOperand(0), P
);
1365 LLVM_DEBUG(errs() << "AMDIC: fold_sincos (" << *CI
<< ", " << *UI
<< ") with "
1368 if (!isSin
) { // CI->cos, UI->sin
1369 B
.SetInsertPoint(&*ItOld
);
1370 UI
->replaceAllUsesWith(&*Call
);
1371 Instruction
*Reload
= B
.CreateLoad(Alloc
->getAllocatedType(), Alloc
);
1372 CI
->replaceAllUsesWith(Reload
);
1373 UI
->eraseFromParent();
1374 CI
->eraseFromParent();
1375 } else { // CI->sin, UI->cos
1376 Instruction
*Reload
= B
.CreateLoad(Alloc
->getAllocatedType(), Alloc
);
1377 UI
->replaceAllUsesWith(Reload
);
1378 CI
->replaceAllUsesWith(Call
);
1379 UI
->eraseFromParent();
1380 CI
->eraseFromParent();
1385 bool AMDGPULibCalls::fold_wavefrontsize(CallInst
*CI
, IRBuilder
<> &B
) {
1389 StringRef CPU
= TM
->getTargetCPU();
1390 StringRef Features
= TM
->getTargetFeatureString();
1391 if ((CPU
.empty() || CPU
.equals_lower("generic")) &&
1392 (Features
.empty() ||
1393 Features
.find_lower("wavefrontsize") == StringRef::npos
))
1396 Function
*F
= CI
->getParent()->getParent();
1397 const GCNSubtarget
&ST
= TM
->getSubtarget
<GCNSubtarget
>(*F
);
1398 unsigned N
= ST
.getWavefrontSize();
1400 LLVM_DEBUG(errs() << "AMDIC: fold_wavefrontsize (" << *CI
<< ") with "
1403 CI
->replaceAllUsesWith(ConstantInt::get(B
.getInt32Ty(), N
));
1404 CI
->eraseFromParent();
1408 // Get insertion point at entry.
1409 BasicBlock::iterator
AMDGPULibCalls::getEntryIns(CallInst
* UI
) {
1410 Function
* Func
= UI
->getParent()->getParent();
1411 BasicBlock
* BB
= &Func
->getEntryBlock();
1412 assert(BB
&& "Entry block not found!");
1413 BasicBlock::iterator ItNew
= BB
->begin();
1417 // Insert a AllocsInst at the beginning of function entry block.
1418 AllocaInst
* AMDGPULibCalls::insertAlloca(CallInst
*UI
, IRBuilder
<> &B
,
1419 const char *prefix
) {
1420 BasicBlock::iterator ItNew
= getEntryIns(UI
);
1421 Function
*UCallee
= UI
->getCalledFunction();
1422 Type
*RetType
= UCallee
->getReturnType();
1423 B
.SetInsertPoint(&*ItNew
);
1424 AllocaInst
*Alloc
= B
.CreateAlloca(RetType
, 0,
1425 std::string(prefix
) + UI
->getName());
1426 Alloc
->setAlignment(MaybeAlign(
1427 UCallee
->getParent()->getDataLayout().getTypeAllocSize(RetType
)));
1431 bool AMDGPULibCalls::evaluateScalarMathFunc(FuncInfo
&FInfo
,
1432 double& Res0
, double& Res1
,
1433 Constant
*copr0
, Constant
*copr1
,
1435 // By default, opr0/opr1/opr3 holds values of float/double type.
1436 // If they are not float/double, each function has to its
1437 // operand separately.
1438 double opr0
=0.0, opr1
=0.0, opr2
=0.0;
1439 ConstantFP
*fpopr0
= dyn_cast_or_null
<ConstantFP
>(copr0
);
1440 ConstantFP
*fpopr1
= dyn_cast_or_null
<ConstantFP
>(copr1
);
1441 ConstantFP
*fpopr2
= dyn_cast_or_null
<ConstantFP
>(copr2
);
1443 opr0
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1444 ? fpopr0
->getValueAPF().convertToDouble()
1445 : (double)fpopr0
->getValueAPF().convertToFloat();
1449 opr1
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1450 ? fpopr1
->getValueAPF().convertToDouble()
1451 : (double)fpopr1
->getValueAPF().convertToFloat();
1455 opr2
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1456 ? fpopr2
->getValueAPF().convertToDouble()
1457 : (double)fpopr2
->getValueAPF().convertToFloat();
1460 switch (FInfo
.getId()) {
1461 default : return false;
1463 case AMDGPULibFunc::EI_ACOS
:
1467 case AMDGPULibFunc::EI_ACOSH
:
1468 // acosh(x) == log(x + sqrt(x*x - 1))
1469 Res0
= log(opr0
+ sqrt(opr0
*opr0
- 1.0));
1472 case AMDGPULibFunc::EI_ACOSPI
:
1473 Res0
= acos(opr0
) / MATH_PI
;
1476 case AMDGPULibFunc::EI_ASIN
:
1480 case AMDGPULibFunc::EI_ASINH
:
1481 // asinh(x) == log(x + sqrt(x*x + 1))
1482 Res0
= log(opr0
+ sqrt(opr0
*opr0
+ 1.0));
1485 case AMDGPULibFunc::EI_ASINPI
:
1486 Res0
= asin(opr0
) / MATH_PI
;
1489 case AMDGPULibFunc::EI_ATAN
:
1493 case AMDGPULibFunc::EI_ATANH
:
1494 // atanh(x) == (log(x+1) - log(x-1))/2;
1495 Res0
= (log(opr0
+ 1.0) - log(opr0
- 1.0))/2.0;
1498 case AMDGPULibFunc::EI_ATANPI
:
1499 Res0
= atan(opr0
) / MATH_PI
;
1502 case AMDGPULibFunc::EI_CBRT
:
1503 Res0
= (opr0
< 0.0) ? -pow(-opr0
, 1.0/3.0) : pow(opr0
, 1.0/3.0);
1506 case AMDGPULibFunc::EI_COS
:
1510 case AMDGPULibFunc::EI_COSH
:
1514 case AMDGPULibFunc::EI_COSPI
:
1515 Res0
= cos(MATH_PI
* opr0
);
1518 case AMDGPULibFunc::EI_EXP
:
1522 case AMDGPULibFunc::EI_EXP2
:
1523 Res0
= pow(2.0, opr0
);
1526 case AMDGPULibFunc::EI_EXP10
:
1527 Res0
= pow(10.0, opr0
);
1530 case AMDGPULibFunc::EI_EXPM1
:
1531 Res0
= exp(opr0
) - 1.0;
1534 case AMDGPULibFunc::EI_LOG
:
1538 case AMDGPULibFunc::EI_LOG2
:
1539 Res0
= log(opr0
) / log(2.0);
1542 case AMDGPULibFunc::EI_LOG10
:
1543 Res0
= log(opr0
) / log(10.0);
1546 case AMDGPULibFunc::EI_RSQRT
:
1547 Res0
= 1.0 / sqrt(opr0
);
1550 case AMDGPULibFunc::EI_SIN
:
1554 case AMDGPULibFunc::EI_SINH
:
1558 case AMDGPULibFunc::EI_SINPI
:
1559 Res0
= sin(MATH_PI
* opr0
);
1562 case AMDGPULibFunc::EI_SQRT
:
1566 case AMDGPULibFunc::EI_TAN
:
1570 case AMDGPULibFunc::EI_TANH
:
1574 case AMDGPULibFunc::EI_TANPI
:
1575 Res0
= tan(MATH_PI
* opr0
);
1578 case AMDGPULibFunc::EI_RECIP
:
1582 // two-arg functions
1583 case AMDGPULibFunc::EI_DIVIDE
:
1587 case AMDGPULibFunc::EI_POW
:
1588 case AMDGPULibFunc::EI_POWR
:
1589 Res0
= pow(opr0
, opr1
);
1592 case AMDGPULibFunc::EI_POWN
: {
1593 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1594 double val
= (double)iopr1
->getSExtValue();
1595 Res0
= pow(opr0
, val
);
1601 case AMDGPULibFunc::EI_ROOTN
: {
1602 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1603 double val
= (double)iopr1
->getSExtValue();
1604 Res0
= pow(opr0
, 1.0 / val
);
1611 case AMDGPULibFunc::EI_SINCOS
:
1616 // three-arg functions
1617 case AMDGPULibFunc::EI_FMA
:
1618 case AMDGPULibFunc::EI_MAD
:
1619 Res0
= opr0
* opr1
+ opr2
;
1626 bool AMDGPULibCalls::evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
) {
1627 int numArgs
= (int)aCI
->getNumArgOperands();
1631 Constant
*copr0
= nullptr;
1632 Constant
*copr1
= nullptr;
1633 Constant
*copr2
= nullptr;
1635 if ((copr0
= dyn_cast
<Constant
>(aCI
->getArgOperand(0))) == nullptr)
1640 if ((copr1
= dyn_cast
<Constant
>(aCI
->getArgOperand(1))) == nullptr) {
1641 if (FInfo
.getId() != AMDGPULibFunc::EI_SINCOS
)
1647 if ((copr2
= dyn_cast
<Constant
>(aCI
->getArgOperand(2))) == nullptr)
1651 // At this point, all arguments to aCI are constants.
1653 // max vector size is 16, and sincos will generate two results.
1654 double DVal0
[16], DVal1
[16];
1655 bool hasTwoResults
= (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
);
1656 if (getVecSize(FInfo
) == 1) {
1657 if (!evaluateScalarMathFunc(FInfo
, DVal0
[0],
1658 DVal1
[0], copr0
, copr1
, copr2
)) {
1662 ConstantDataVector
*CDV0
= dyn_cast_or_null
<ConstantDataVector
>(copr0
);
1663 ConstantDataVector
*CDV1
= dyn_cast_or_null
<ConstantDataVector
>(copr1
);
1664 ConstantDataVector
*CDV2
= dyn_cast_or_null
<ConstantDataVector
>(copr2
);
1665 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1666 Constant
*celt0
= CDV0
? CDV0
->getElementAsConstant(i
) : nullptr;
1667 Constant
*celt1
= CDV1
? CDV1
->getElementAsConstant(i
) : nullptr;
1668 Constant
*celt2
= CDV2
? CDV2
->getElementAsConstant(i
) : nullptr;
1669 if (!evaluateScalarMathFunc(FInfo
, DVal0
[i
],
1670 DVal1
[i
], celt0
, celt1
, celt2
)) {
1676 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
1677 Constant
*nval0
, *nval1
;
1678 if (getVecSize(FInfo
) == 1) {
1679 nval0
= ConstantFP::get(CI
->getType(), DVal0
[0]);
1681 nval1
= ConstantFP::get(CI
->getType(), DVal1
[0]);
1683 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1684 SmallVector
<float, 0> FVal0
, FVal1
;
1685 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1686 FVal0
.push_back((float)DVal0
[i
]);
1687 ArrayRef
<float> tmp0(FVal0
);
1688 nval0
= ConstantDataVector::get(context
, tmp0
);
1689 if (hasTwoResults
) {
1690 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1691 FVal1
.push_back((float)DVal1
[i
]);
1692 ArrayRef
<float> tmp1(FVal1
);
1693 nval1
= ConstantDataVector::get(context
, tmp1
);
1696 ArrayRef
<double> tmp0(DVal0
);
1697 nval0
= ConstantDataVector::get(context
, tmp0
);
1698 if (hasTwoResults
) {
1699 ArrayRef
<double> tmp1(DVal1
);
1700 nval1
= ConstantDataVector::get(context
, tmp1
);
1705 if (hasTwoResults
) {
1707 assert(FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
&&
1708 "math function with ptr arg not supported yet");
1709 new StoreInst(nval1
, aCI
->getArgOperand(1), aCI
);
1716 // Public interface to the Simplify LibCalls pass.
1717 FunctionPass
*llvm::createAMDGPUSimplifyLibCallsPass(const TargetOptions
&Opt
,
1718 const TargetMachine
*TM
) {
1719 return new AMDGPUSimplifyLibCalls(Opt
, TM
);
1722 FunctionPass
*llvm::createAMDGPUUseNativeCallsPass() {
1723 return new AMDGPUUseNativeCalls();
1726 static bool setFastFlags(Function
&F
, const TargetOptions
&Options
) {
1729 if (Options
.UnsafeFPMath
|| Options
.NoInfsFPMath
)
1730 B
.addAttribute("no-infs-fp-math", "true");
1731 if (Options
.UnsafeFPMath
|| Options
.NoNaNsFPMath
)
1732 B
.addAttribute("no-nans-fp-math", "true");
1733 if (Options
.UnsafeFPMath
) {
1734 B
.addAttribute("less-precise-fpmad", "true");
1735 B
.addAttribute("unsafe-fp-math", "true");
1738 if (!B
.hasAttributes())
1741 F
.addAttributes(AttributeList::FunctionIndex
, B
);
1746 bool AMDGPUSimplifyLibCalls::runOnFunction(Function
&F
) {
1747 if (skipFunction(F
))
1750 bool Changed
= false;
1751 auto AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
1753 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1754 F
.printAsOperand(dbgs(), false, F
.getParent()); dbgs() << '\n';);
1757 Changed
|= setFastFlags(F
, Options
);
1759 for (auto &BB
: F
) {
1760 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1761 // Ignore non-calls.
1762 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1766 // Ignore indirect calls.
1767 Function
*Callee
= CI
->getCalledFunction();
1768 if (Callee
== 0) continue;
1770 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI
<< "\n";
1772 if(Simplifier
.fold(CI
, AA
))
1779 bool AMDGPUUseNativeCalls::runOnFunction(Function
&F
) {
1780 if (skipFunction(F
) || UseNative
.empty())
1783 bool Changed
= false;
1784 for (auto &BB
: F
) {
1785 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1786 // Ignore non-calls.
1787 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1791 // Ignore indirect calls.
1792 Function
*Callee
= CI
->getCalledFunction();
1793 if (Callee
== 0) continue;
1795 if(Simplifier
.useNative(CI
))