1 //===- AMDGPULibCalls.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file does AMD library function optimizations.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "amdgpu-simplifylib"
18 #include "AMDGPULibFunc.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/IRBuilder.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/ValueSymbolTable.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetOptions.h"
39 static cl::opt
<bool> EnablePreLink("amdgpu-prelink",
40 cl::desc("Enable pre-link mode optimizations"),
44 static cl::list
<std::string
> UseNative("amdgpu-use-native",
45 cl::desc("Comma separated list of functions to replace with native, or all"),
46 cl::CommaSeparated
, cl::ValueOptional
,
49 #define MATH_PI 3.14159265358979323846264338327950288419716939937511
50 #define MATH_E 2.71828182845904523536028747135266249775724709369996
51 #define MATH_SQRT2 1.41421356237309504880168872420969807856967187537695
53 #define MATH_LOG2E 1.4426950408889634073599246810018921374266459541529859
54 #define MATH_LOG10E 0.4342944819032518276511289189166050822943970058036665
56 #define MATH_LOG2_10 3.3219280948873623478703194294893901758648313930245806
57 // Value of 1 / log2(10)
58 #define MATH_RLOG2_10 0.3010299956639811952137388947244930267681898814621085
59 // Value of 1 / M_LOG2E_F = 1 / log2(e)
60 #define MATH_RLOG2_E 0.6931471805599453094172321214581765680755001343602552
64 class AMDGPULibCalls
{
67 typedef llvm::AMDGPULibFunc FuncInfo
;
70 bool AllNative
= false;
72 bool useNativeFunc(const StringRef F
) const;
74 // Return a pointer (pointer expr) to the function if function defintion with
75 // "FuncName" exists. It may create a new function prototype in pre-link mode.
76 Constant
*getFunction(Module
*M
, const FuncInfo
& fInfo
);
78 // Replace a normal function with its native version.
79 bool replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
);
81 bool parseFunctionName(const StringRef
& FMangledName
,
82 FuncInfo
*FInfo
=nullptr /*out*/);
84 bool TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
);
86 /* Specialized optimizations */
88 // recip (half or native)
89 bool fold_recip(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
91 // divide (half or native)
92 bool fold_divide(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
95 bool fold_pow(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
98 bool fold_rootn(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
101 bool fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
103 // -fuse-native for sincos
104 bool sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
);
106 // evaluate calls if calls' arguments are constants.
107 bool evaluateScalarMathFunc(FuncInfo
&FInfo
, double& Res0
,
108 double& Res1
, Constant
*copr0
, Constant
*copr1
, Constant
*copr2
);
109 bool evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
);
112 bool fold_exp(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
115 bool fold_exp2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
118 bool fold_exp10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
121 bool fold_log(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
124 bool fold_log2(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
127 bool fold_log10(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
130 bool fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
, const FuncInfo
&FInfo
);
133 bool fold_sincos(CallInst
* CI
, IRBuilder
<> &B
, AliasAnalysis
* AA
);
135 // __read_pipe/__write_pipe
136 bool fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
, FuncInfo
&FInfo
);
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 Constant
* 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 bool fold(CallInst
*CI
, AliasAnalysis
*AA
= nullptr);
158 void initNativeFuncs();
160 // Replace a normal math function call with that native version
161 bool useNative(CallInst
*CI
);
164 } // end llvm namespace
168 class AMDGPUSimplifyLibCalls
: public FunctionPass
{
170 AMDGPULibCalls Simplifier
;
172 const TargetOptions Options
;
175 static char ID
; // Pass identification
177 AMDGPUSimplifyLibCalls(const TargetOptions
&Opt
= TargetOptions())
178 : FunctionPass(ID
), Options(Opt
) {
179 initializeAMDGPUSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
182 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
183 AU
.addRequired
<AAResultsWrapperPass
>();
186 bool runOnFunction(Function
&M
) override
;
189 class AMDGPUUseNativeCalls
: public FunctionPass
{
191 AMDGPULibCalls Simplifier
;
194 static char ID
; // Pass identification
196 AMDGPUUseNativeCalls() : FunctionPass(ID
) {
197 initializeAMDGPUUseNativeCallsPass(*PassRegistry::getPassRegistry());
198 Simplifier
.initNativeFuncs();
201 bool runOnFunction(Function
&F
) override
;
204 } // end anonymous namespace.
206 char AMDGPUSimplifyLibCalls::ID
= 0;
207 char AMDGPUUseNativeCalls::ID
= 0;
209 INITIALIZE_PASS_BEGIN(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
210 "Simplify well-known AMD library calls", false, false)
211 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
212 INITIALIZE_PASS_END(AMDGPUSimplifyLibCalls
, "amdgpu-simplifylib",
213 "Simplify well-known AMD library calls", false, false)
215 INITIALIZE_PASS(AMDGPUUseNativeCalls
, "amdgpu-usenative",
216 "Replace builtin math calls with that native versions.",
219 template <typename IRB
>
220 static CallInst
*CreateCallEx(IRB
&B
, Value
*Callee
, Value
*Arg
,
221 const Twine
&Name
= "") {
222 CallInst
*R
= B
.CreateCall(Callee
, Arg
, Name
);
223 if (Function
* F
= dyn_cast
<Function
>(Callee
))
224 R
->setCallingConv(F
->getCallingConv());
228 template <typename IRB
>
229 static CallInst
*CreateCallEx2(IRB
&B
, Value
*Callee
, Value
*Arg1
, Value
*Arg2
,
230 const Twine
&Name
= "") {
231 CallInst
*R
= B
.CreateCall(Callee
, {Arg1
, Arg2
}, Name
);
232 if (Function
* F
= dyn_cast
<Function
>(Callee
))
233 R
->setCallingConv(F
->getCallingConv());
237 // Data structures for table-driven optimizations.
238 // FuncTbl works for both f32 and f64 functions with 1 input argument
245 /* a list of {result, input} */
246 static const TableEntry tbl_acos
[] = {
252 static const TableEntry tbl_acosh
[] = {
255 static const TableEntry tbl_acospi
[] = {
261 static const TableEntry tbl_asin
[] = {
267 static const TableEntry tbl_asinh
[] = {
271 static const TableEntry tbl_asinpi
[] = {
277 static const TableEntry tbl_atan
[] = {
283 static const TableEntry tbl_atanh
[] = {
287 static const TableEntry tbl_atanpi
[] = {
293 static const TableEntry tbl_cbrt
[] = {
299 static const TableEntry tbl_cos
[] = {
303 static const TableEntry tbl_cosh
[] = {
307 static const TableEntry tbl_cospi
[] = {
311 static const TableEntry tbl_erfc
[] = {
315 static const TableEntry tbl_erf
[] = {
319 static const TableEntry tbl_exp
[] = {
324 static const TableEntry tbl_exp2
[] = {
329 static const TableEntry tbl_exp10
[] = {
334 static const TableEntry tbl_expm1
[] = {
338 static const TableEntry tbl_log
[] = {
342 static const TableEntry tbl_log2
[] = {
346 static const TableEntry tbl_log10
[] = {
350 static const TableEntry tbl_rsqrt
[] = {
352 {1.0/MATH_SQRT2
, 2.0}
354 static const TableEntry tbl_sin
[] = {
358 static const TableEntry tbl_sinh
[] = {
362 static const TableEntry tbl_sinpi
[] = {
366 static const TableEntry tbl_sqrt
[] = {
371 static const TableEntry tbl_tan
[] = {
375 static const TableEntry tbl_tanh
[] = {
379 static const TableEntry tbl_tanpi
[] = {
383 static const TableEntry tbl_tgamma
[] = {
390 static bool HasNative(AMDGPULibFunc::EFuncId id
) {
392 case AMDGPULibFunc::EI_DIVIDE
:
393 case AMDGPULibFunc::EI_COS
:
394 case AMDGPULibFunc::EI_EXP
:
395 case AMDGPULibFunc::EI_EXP2
:
396 case AMDGPULibFunc::EI_EXP10
:
397 case AMDGPULibFunc::EI_LOG
:
398 case AMDGPULibFunc::EI_LOG2
:
399 case AMDGPULibFunc::EI_LOG10
:
400 case AMDGPULibFunc::EI_POWR
:
401 case AMDGPULibFunc::EI_RECIP
:
402 case AMDGPULibFunc::EI_RSQRT
:
403 case AMDGPULibFunc::EI_SIN
:
404 case AMDGPULibFunc::EI_SINCOS
:
405 case AMDGPULibFunc::EI_SQRT
:
406 case AMDGPULibFunc::EI_TAN
:
415 const TableEntry
*table
; // variable size: from 0 to (size - 1)
417 TableRef() : size(0), table(nullptr) {}
420 TableRef(const TableEntry (&tbl
)[N
]) : size(N
), table(&tbl
[0]) {}
423 static TableRef
getOptTable(AMDGPULibFunc::EFuncId id
) {
425 case AMDGPULibFunc::EI_ACOS
: return TableRef(tbl_acos
);
426 case AMDGPULibFunc::EI_ACOSH
: return TableRef(tbl_acosh
);
427 case AMDGPULibFunc::EI_ACOSPI
: return TableRef(tbl_acospi
);
428 case AMDGPULibFunc::EI_ASIN
: return TableRef(tbl_asin
);
429 case AMDGPULibFunc::EI_ASINH
: return TableRef(tbl_asinh
);
430 case AMDGPULibFunc::EI_ASINPI
: return TableRef(tbl_asinpi
);
431 case AMDGPULibFunc::EI_ATAN
: return TableRef(tbl_atan
);
432 case AMDGPULibFunc::EI_ATANH
: return TableRef(tbl_atanh
);
433 case AMDGPULibFunc::EI_ATANPI
: return TableRef(tbl_atanpi
);
434 case AMDGPULibFunc::EI_CBRT
: return TableRef(tbl_cbrt
);
435 case AMDGPULibFunc::EI_NCOS
:
436 case AMDGPULibFunc::EI_COS
: return TableRef(tbl_cos
);
437 case AMDGPULibFunc::EI_COSH
: return TableRef(tbl_cosh
);
438 case AMDGPULibFunc::EI_COSPI
: return TableRef(tbl_cospi
);
439 case AMDGPULibFunc::EI_ERFC
: return TableRef(tbl_erfc
);
440 case AMDGPULibFunc::EI_ERF
: return TableRef(tbl_erf
);
441 case AMDGPULibFunc::EI_EXP
: return TableRef(tbl_exp
);
442 case AMDGPULibFunc::EI_NEXP2
:
443 case AMDGPULibFunc::EI_EXP2
: return TableRef(tbl_exp2
);
444 case AMDGPULibFunc::EI_EXP10
: return TableRef(tbl_exp10
);
445 case AMDGPULibFunc::EI_EXPM1
: return TableRef(tbl_expm1
);
446 case AMDGPULibFunc::EI_LOG
: return TableRef(tbl_log
);
447 case AMDGPULibFunc::EI_NLOG2
:
448 case AMDGPULibFunc::EI_LOG2
: return TableRef(tbl_log2
);
449 case AMDGPULibFunc::EI_LOG10
: return TableRef(tbl_log10
);
450 case AMDGPULibFunc::EI_NRSQRT
:
451 case AMDGPULibFunc::EI_RSQRT
: return TableRef(tbl_rsqrt
);
452 case AMDGPULibFunc::EI_NSIN
:
453 case AMDGPULibFunc::EI_SIN
: return TableRef(tbl_sin
);
454 case AMDGPULibFunc::EI_SINH
: return TableRef(tbl_sinh
);
455 case AMDGPULibFunc::EI_SINPI
: return TableRef(tbl_sinpi
);
456 case AMDGPULibFunc::EI_NSQRT
:
457 case AMDGPULibFunc::EI_SQRT
: return TableRef(tbl_sqrt
);
458 case AMDGPULibFunc::EI_TAN
: return TableRef(tbl_tan
);
459 case AMDGPULibFunc::EI_TANH
: return TableRef(tbl_tanh
);
460 case AMDGPULibFunc::EI_TANPI
: return TableRef(tbl_tanpi
);
461 case AMDGPULibFunc::EI_TGAMMA
: return TableRef(tbl_tgamma
);
467 static inline int getVecSize(const AMDGPULibFunc
& FInfo
) {
468 return FInfo
.getLeads()[0].VectorSize
;
471 static inline AMDGPULibFunc::EType
getArgType(const AMDGPULibFunc
& FInfo
) {
472 return (AMDGPULibFunc::EType
)FInfo
.getLeads()[0].ArgType
;
475 Constant
*AMDGPULibCalls::getFunction(Module
*M
, const FuncInfo
& fInfo
) {
476 // If we are doing PreLinkOpt, the function is external. So it is safe to
477 // use getOrInsertFunction() at this stage.
479 return EnablePreLink
? AMDGPULibFunc::getOrInsertFunction(M
, fInfo
)
480 : AMDGPULibFunc::getFunction(M
, fInfo
);
483 bool AMDGPULibCalls::parseFunctionName(const StringRef
& FMangledName
,
485 return AMDGPULibFunc::parse(FMangledName
, *FInfo
);
488 bool AMDGPULibCalls::isUnsafeMath(const CallInst
*CI
) const {
489 if (auto Op
= dyn_cast
<FPMathOperator
>(CI
))
492 const Function
*F
= CI
->getParent()->getParent();
493 Attribute Attr
= F
->getFnAttribute("unsafe-fp-math");
494 return Attr
.getValueAsString() == "true";
497 bool AMDGPULibCalls::useNativeFunc(const StringRef F
) const {
499 std::find(UseNative
.begin(), UseNative
.end(), F
) != UseNative
.end();
502 void AMDGPULibCalls::initNativeFuncs() {
503 AllNative
= useNativeFunc("all") ||
504 (UseNative
.getNumOccurrences() && UseNative
.size() == 1 &&
505 UseNative
.begin()->empty());
508 bool AMDGPULibCalls::sincosUseNative(CallInst
*aCI
, const FuncInfo
&FInfo
) {
509 bool native_sin
= useNativeFunc("sin");
510 bool native_cos
= useNativeFunc("cos");
512 if (native_sin
&& native_cos
) {
513 Module
*M
= aCI
->getModule();
514 Value
*opr0
= aCI
->getArgOperand(0);
517 nf
.getLeads()[0].ArgType
= FInfo
.getLeads()[0].ArgType
;
518 nf
.getLeads()[0].VectorSize
= FInfo
.getLeads()[0].VectorSize
;
520 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
521 nf
.setId(AMDGPULibFunc::EI_SIN
);
522 Constant
*sinExpr
= getFunction(M
, nf
);
524 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
525 nf
.setId(AMDGPULibFunc::EI_COS
);
526 Constant
*cosExpr
= getFunction(M
, nf
);
527 if (sinExpr
&& cosExpr
) {
528 Value
*sinval
= CallInst::Create(sinExpr
, opr0
, "splitsin", aCI
);
529 Value
*cosval
= CallInst::Create(cosExpr
, opr0
, "splitcos", aCI
);
530 new StoreInst(cosval
, aCI
->getArgOperand(1), aCI
);
532 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
533 << " with native version of sin/cos");
542 bool AMDGPULibCalls::useNative(CallInst
*aCI
) {
544 Function
*Callee
= aCI
->getCalledFunction();
547 if (!parseFunctionName(Callee
->getName(), &FInfo
) || !FInfo
.isMangled() ||
548 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
549 getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()) ||
550 !(AllNative
|| useNativeFunc(FInfo
.getName()))) {
554 if (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
)
555 return sincosUseNative(aCI
, FInfo
);
557 FInfo
.setPrefix(AMDGPULibFunc::NATIVE
);
558 Constant
*F
= getFunction(aCI
->getModule(), FInfo
);
562 aCI
->setCalledFunction(F
);
563 DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
564 << " with native version");
568 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
569 // builtin, with appended type size and alignment arguments, where 2 or 4
570 // indicates the original number of arguments. The library has optimized version
571 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
572 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
573 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
574 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
575 bool AMDGPULibCalls::fold_read_write_pipe(CallInst
*CI
, IRBuilder
<> &B
,
577 auto *Callee
= CI
->getCalledFunction();
578 if (!Callee
->isDeclaration())
581 assert(Callee
->hasName() && "Invalid read_pipe/write_pipe function");
582 auto *M
= Callee
->getParent();
583 auto &Ctx
= M
->getContext();
584 std::string Name
= Callee
->getName();
585 auto NumArg
= CI
->getNumArgOperands();
586 if (NumArg
!= 4 && NumArg
!= 6)
588 auto *PacketSize
= CI
->getArgOperand(NumArg
- 2);
589 auto *PacketAlign
= CI
->getArgOperand(NumArg
- 1);
590 if (!isa
<ConstantInt
>(PacketSize
) || !isa
<ConstantInt
>(PacketAlign
))
592 unsigned Size
= cast
<ConstantInt
>(PacketSize
)->getZExtValue();
593 unsigned Align
= cast
<ConstantInt
>(PacketAlign
)->getZExtValue();
594 if (Size
!= Align
|| !isPowerOf2_32(Size
))
599 PtrElemTy
= Type::getIntNTy(Ctx
, Size
* 8);
601 PtrElemTy
= VectorType::get(Type::getInt64Ty(Ctx
), Size
/ 8);
602 unsigned PtrArgLoc
= CI
->getNumArgOperands() - 3;
603 auto PtrArg
= CI
->getArgOperand(PtrArgLoc
);
604 unsigned PtrArgAS
= PtrArg
->getType()->getPointerAddressSpace();
605 auto *PtrTy
= llvm::PointerType::get(PtrElemTy
, PtrArgAS
);
607 SmallVector
<llvm::Type
*, 6> ArgTys
;
608 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
609 ArgTys
.push_back(CI
->getArgOperand(I
)->getType());
610 ArgTys
.push_back(PtrTy
);
612 Name
= Name
+ "_" + std::to_string(Size
);
613 auto *FTy
= FunctionType::get(Callee
->getReturnType(),
614 ArrayRef
<Type
*>(ArgTys
), false);
615 AMDGPULibFunc
NewLibFunc(Name
, FTy
);
616 auto *F
= AMDGPULibFunc::getOrInsertFunction(M
, NewLibFunc
);
620 auto *BCast
= B
.CreatePointerCast(PtrArg
, PtrTy
);
621 SmallVector
<Value
*, 6> Args
;
622 for (unsigned I
= 0; I
!= PtrArgLoc
; ++I
)
623 Args
.push_back(CI
->getArgOperand(I
));
624 Args
.push_back(BCast
);
626 auto *NCI
= B
.CreateCall(F
, Args
);
627 NCI
->setAttributes(CI
->getAttributes());
628 CI
->replaceAllUsesWith(NCI
);
629 CI
->dropAllReferences();
630 CI
->eraseFromParent();
635 // This function returns false if no change; return true otherwise.
636 bool AMDGPULibCalls::fold(CallInst
*CI
, AliasAnalysis
*AA
) {
638 Function
*Callee
= CI
->getCalledFunction();
640 // Ignore indirect calls.
641 if (Callee
== 0) return false;
644 if (!parseFunctionName(Callee
->getName(), &FInfo
))
647 // Further check the number of arguments to see if they match.
648 if (CI
->getNumArgOperands() != FInfo
.getNumArgs())
651 BasicBlock
*BB
= CI
->getParent();
652 LLVMContext
&Context
= CI
->getParent()->getContext();
653 IRBuilder
<> B(Context
);
655 // Set the builder to the instruction after the call.
656 B
.SetInsertPoint(BB
, CI
->getIterator());
658 // Copy fast flags from the original call.
659 if (const FPMathOperator
*FPOp
= dyn_cast
<const FPMathOperator
>(CI
))
660 B
.setFastMathFlags(FPOp
->getFastMathFlags());
662 if (TDOFold(CI
, FInfo
))
665 // Under unsafe-math, evaluate calls if possible.
666 // According to Brian Sumner, we can do this for all f32 function calls
667 // using host's double function calls.
668 if (isUnsafeMath(CI
) && evaluateCall(CI
, FInfo
))
671 // Specilized optimizations for each function call
672 switch (FInfo
.getId()) {
673 case AMDGPULibFunc::EI_RECIP
:
674 // skip vector function
675 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
676 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
677 "recip must be an either native or half function");
678 return (getVecSize(FInfo
) != 1) ? false : fold_recip(CI
, B
, FInfo
);
680 case AMDGPULibFunc::EI_DIVIDE
:
681 // skip vector function
682 assert ((FInfo
.getPrefix() == AMDGPULibFunc::NATIVE
||
683 FInfo
.getPrefix() == AMDGPULibFunc::HALF
) &&
684 "divide must be an either native or half function");
685 return (getVecSize(FInfo
) != 1) ? false : fold_divide(CI
, B
, FInfo
);
687 case AMDGPULibFunc::EI_POW
:
688 case AMDGPULibFunc::EI_POWR
:
689 case AMDGPULibFunc::EI_POWN
:
690 return fold_pow(CI
, B
, FInfo
);
692 case AMDGPULibFunc::EI_ROOTN
:
693 // skip vector function
694 return (getVecSize(FInfo
) != 1) ? false : fold_rootn(CI
, B
, FInfo
);
696 case AMDGPULibFunc::EI_FMA
:
697 case AMDGPULibFunc::EI_MAD
:
698 case AMDGPULibFunc::EI_NFMA
:
699 // skip vector function
700 return (getVecSize(FInfo
) != 1) ? false : fold_fma_mad(CI
, B
, FInfo
);
702 case AMDGPULibFunc::EI_SQRT
:
703 return isUnsafeMath(CI
) && fold_sqrt(CI
, B
, FInfo
);
704 case AMDGPULibFunc::EI_COS
:
705 case AMDGPULibFunc::EI_SIN
:
706 if ((getArgType(FInfo
) == AMDGPULibFunc::F32
||
707 getArgType(FInfo
) == AMDGPULibFunc::F64
)
708 && (FInfo
.getPrefix() == AMDGPULibFunc::NOPFX
))
709 return fold_sincos(CI
, B
, AA
);
712 case AMDGPULibFunc::EI_READ_PIPE_2
:
713 case AMDGPULibFunc::EI_READ_PIPE_4
:
714 case AMDGPULibFunc::EI_WRITE_PIPE_2
:
715 case AMDGPULibFunc::EI_WRITE_PIPE_4
:
716 return fold_read_write_pipe(CI
, B
, FInfo
);
725 bool AMDGPULibCalls::TDOFold(CallInst
*CI
, const FuncInfo
&FInfo
) {
726 // Table-Driven optimization
727 const TableRef tr
= getOptTable(FInfo
.getId());
731 int const sz
= (int)tr
.size
;
732 const TableEntry
* const ftbl
= tr
.table
;
733 Value
*opr0
= CI
->getArgOperand(0);
735 if (getVecSize(FInfo
) > 1) {
736 if (ConstantDataVector
*CV
= dyn_cast
<ConstantDataVector
>(opr0
)) {
737 SmallVector
<double, 0> DVal
;
738 for (int eltNo
= 0; eltNo
< getVecSize(FInfo
); ++eltNo
) {
739 ConstantFP
*eltval
= dyn_cast
<ConstantFP
>(
740 CV
->getElementAsConstant((unsigned)eltNo
));
741 assert(eltval
&& "Non-FP arguments in math function!");
743 for (int i
=0; i
< sz
; ++i
) {
744 if (eltval
->isExactlyValue(ftbl
[i
].input
)) {
745 DVal
.push_back(ftbl
[i
].result
);
751 // This vector constants not handled yet.
755 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
757 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
758 SmallVector
<float, 0> FVal
;
759 for (unsigned i
= 0; i
< DVal
.size(); ++i
) {
760 FVal
.push_back((float)DVal
[i
]);
762 ArrayRef
<float> tmp(FVal
);
763 nval
= ConstantDataVector::get(context
, tmp
);
765 ArrayRef
<double> tmp(DVal
);
766 nval
= ConstantDataVector::get(context
, tmp
);
768 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
774 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
775 for (int i
= 0; i
< sz
; ++i
) {
776 if (CF
->isExactlyValue(ftbl
[i
].input
)) {
777 Value
*nval
= ConstantFP::get(CF
->getType(), ftbl
[i
].result
);
778 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
789 bool AMDGPULibCalls::replaceWithNative(CallInst
*CI
, const FuncInfo
&FInfo
) {
790 Module
*M
= CI
->getModule();
791 if (getArgType(FInfo
) != AMDGPULibFunc::F32
||
792 FInfo
.getPrefix() != AMDGPULibFunc::NOPFX
||
793 !HasNative(FInfo
.getId()))
796 AMDGPULibFunc nf
= FInfo
;
797 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
798 if (Constant
*FPExpr
= getFunction(M
, nf
)) {
799 LLVM_DEBUG(dbgs() << "AMDIC: " << *CI
<< " ---> ");
801 CI
->setCalledFunction(FPExpr
);
803 LLVM_DEBUG(dbgs() << *CI
<< '\n');
810 // [native_]half_recip(c) ==> 1.0/c
811 bool AMDGPULibCalls::fold_recip(CallInst
*CI
, IRBuilder
<> &B
,
812 const FuncInfo
&FInfo
) {
813 Value
*opr0
= CI
->getArgOperand(0);
814 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr0
)) {
815 // Just create a normal div. Later, InstCombine will be able
816 // to compute the divide into a constant (avoid check float infinity
817 // or subnormal at this point).
818 Value
*nval
= B
.CreateFDiv(ConstantFP::get(CF
->getType(), 1.0),
821 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *nval
<< "\n");
828 // [native_]half_divide(x, c) ==> x/c
829 bool AMDGPULibCalls::fold_divide(CallInst
*CI
, IRBuilder
<> &B
,
830 const FuncInfo
&FInfo
) {
831 Value
*opr0
= CI
->getArgOperand(0);
832 Value
*opr1
= CI
->getArgOperand(1);
833 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
834 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
836 if ((CF0
&& CF1
) || // both are constants
837 (CF1
&& (getArgType(FInfo
) == AMDGPULibFunc::F32
)))
838 // CF1 is constant && f32 divide
840 Value
*nval1
= B
.CreateFDiv(ConstantFP::get(opr1
->getType(), 1.0),
841 opr1
, "__div2recip");
842 Value
*nval
= B
.CreateFMul(opr0
, nval1
, "__div2mul");
850 static double log2(double V
) {
851 #if _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
854 return log(V
) / 0.693147180559945309417;
859 bool AMDGPULibCalls::fold_pow(CallInst
*CI
, IRBuilder
<> &B
,
860 const FuncInfo
&FInfo
) {
861 assert((FInfo
.getId() == AMDGPULibFunc::EI_POW
||
862 FInfo
.getId() == AMDGPULibFunc::EI_POWR
||
863 FInfo
.getId() == AMDGPULibFunc::EI_POWN
) &&
864 "fold_pow: encounter a wrong function call");
869 ConstantAggregateZero
*CZero
;
872 opr0
= CI
->getArgOperand(0);
873 opr1
= CI
->getArgOperand(1);
874 CZero
= dyn_cast
<ConstantAggregateZero
>(opr1
);
875 if (getVecSize(FInfo
) == 1) {
876 eltType
= opr0
->getType();
877 CF
= dyn_cast
<ConstantFP
>(opr1
);
878 CINT
= dyn_cast
<ConstantInt
>(opr1
);
880 VectorType
*VTy
= dyn_cast
<VectorType
>(opr0
->getType());
881 assert(VTy
&& "Oprand of vector function should be of vectortype");
882 eltType
= VTy
->getElementType();
883 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
);
885 // Now, only Handle vector const whose elements have the same value.
886 CF
= CDV
? dyn_cast_or_null
<ConstantFP
>(CDV
->getSplatValue()) : nullptr;
887 CINT
= CDV
? dyn_cast_or_null
<ConstantInt
>(CDV
->getSplatValue()) : nullptr;
890 // No unsafe math , no constant argument, do nothing
891 if (!isUnsafeMath(CI
) && !CF
&& !CINT
&& !CZero
)
894 // 0x1111111 means that we don't do anything for this call.
895 int ci_opr1
= (CINT
? (int)CINT
->getSExtValue() : 0x1111111);
897 if ((CF
&& CF
->isZero()) || (CINT
&& ci_opr1
== 0) || CZero
) {
898 // pow/powr/pown(x, 0) == 1
899 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1\n");
900 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
901 if (getVecSize(FInfo
) > 1) {
902 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
907 if ((CF
&& CF
->isExactlyValue(1.0)) || (CINT
&& ci_opr1
== 1)) {
908 // pow/powr/pown(x, 1.0) = x
909 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
913 if ((CF
&& CF
->isExactlyValue(2.0)) || (CINT
&& ci_opr1
== 2)) {
914 // pow/powr/pown(x, 2.0) = x*x
915 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * " << *opr0
917 Value
*nval
= B
.CreateFMul(opr0
, opr0
, "__pow2");
921 if ((CF
&& CF
->isExactlyValue(-1.0)) || (CINT
&& ci_opr1
== -1)) {
922 // pow/powr/pown(x, -1.0) = 1.0/x
923 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1 / " << *opr0
<< "\n");
924 Constant
*cnval
= ConstantFP::get(eltType
, 1.0);
925 if (getVecSize(FInfo
) > 1) {
926 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
928 Value
*nval
= B
.CreateFDiv(cnval
, opr0
, "__powrecip");
933 Module
*M
= CI
->getModule();
934 if (CF
&& (CF
->isExactlyValue(0.5) || CF
->isExactlyValue(-0.5))) {
935 // pow[r](x, [-]0.5) = sqrt(x)
936 bool issqrt
= CF
->isExactlyValue(0.5);
937 if (Constant
*FPExpr
= getFunction(M
,
938 AMDGPULibFunc(issqrt
? AMDGPULibFunc::EI_SQRT
939 : AMDGPULibFunc::EI_RSQRT
, FInfo
))) {
940 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
941 << FInfo
.getName().c_str() << "(" << *opr0
<< ")\n");
942 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, issqrt
? "__pow2sqrt"
949 if (!isUnsafeMath(CI
))
952 // Unsafe Math optimization
954 // Remember that ci_opr1 is set if opr1 is integral
956 double dval
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
957 ? (double)CF
->getValueAPF().convertToFloat()
958 : CF
->getValueAPF().convertToDouble();
959 int ival
= (int)dval
;
960 if ((double)ival
== dval
) {
963 ci_opr1
= 0x11111111;
966 // pow/powr/pown(x, c) = [1/](x*x*..x); where
967 // trunc(c) == c && the number of x == c && |c| <= 12
968 unsigned abs_opr1
= (ci_opr1
< 0) ? -ci_opr1
: ci_opr1
;
969 if (abs_opr1
<= 12) {
973 cnval
= ConstantFP::get(eltType
, 1.0);
974 if (getVecSize(FInfo
) > 1) {
975 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
979 Value
*valx2
= nullptr;
981 while (abs_opr1
> 0) {
982 valx2
= valx2
? B
.CreateFMul(valx2
, valx2
, "__powx2") : opr0
;
984 nval
= nval
? B
.CreateFMul(nval
, valx2
, "__powprod") : valx2
;
991 cnval
= ConstantFP::get(eltType
, 1.0);
992 if (getVecSize(FInfo
) > 1) {
993 cnval
= ConstantDataVector::getSplat(getVecSize(FInfo
), cnval
);
995 nval
= B
.CreateFDiv(cnval
, nval
, "__1powprod");
997 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
998 << ((ci_opr1
< 0) ? "1/prod(" : "prod(") << *opr0
1004 // powr ---> exp2(y * log2(x))
1005 // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
1006 Constant
*ExpExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2
,
1011 bool needlog
= false;
1012 bool needabs
= false;
1013 bool needcopysign
= false;
1014 Constant
*cnval
= nullptr;
1015 if (getVecSize(FInfo
) == 1) {
1016 CF
= dyn_cast
<ConstantFP
>(opr0
);
1019 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1020 ? (double)CF
->getValueAPF().convertToFloat()
1021 : CF
->getValueAPF().convertToDouble();
1023 V
= log2(std::abs(V
));
1024 cnval
= ConstantFP::get(eltType
, V
);
1025 needcopysign
= (FInfo
.getId() != AMDGPULibFunc::EI_POWR
) &&
1029 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
&&
1030 (!CF
|| CF
->isNegative());
1033 ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr0
);
1037 needcopysign
= needabs
= FInfo
.getId() != AMDGPULibFunc::EI_POWR
;
1039 assert ((int)CDV
->getNumElements() == getVecSize(FInfo
) &&
1040 "Wrong vector size detected");
1042 SmallVector
<double, 0> DVal
;
1043 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1044 double V
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1045 ? (double)CDV
->getElementAsFloat(i
)
1046 : CDV
->getElementAsDouble(i
);
1047 if (V
< 0.0) needcopysign
= true;
1048 V
= log2(std::abs(V
));
1051 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1052 SmallVector
<float, 0> FVal
;
1053 for (unsigned i
=0; i
< DVal
.size(); ++i
) {
1054 FVal
.push_back((float)DVal
[i
]);
1056 ArrayRef
<float> tmp(FVal
);
1057 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1059 ArrayRef
<double> tmp(DVal
);
1060 cnval
= ConstantDataVector::get(M
->getContext(), tmp
);
1065 if (needcopysign
&& (FInfo
.getId() == AMDGPULibFunc::EI_POW
)) {
1066 // We cannot handle corner cases for a general pow() function, give up
1067 // unless y is a constant integral value. Then proceed as if it were pown.
1068 if (getVecSize(FInfo
) == 1) {
1069 if (const ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr1
)) {
1070 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1071 ? (double)CF
->getValueAPF().convertToFloat()
1072 : CF
->getValueAPF().convertToDouble();
1073 if (y
!= (double)(int64_t)y
)
1078 if (const ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(opr1
)) {
1079 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1080 double y
= (getArgType(FInfo
) == AMDGPULibFunc::F32
)
1081 ? (double)CDV
->getElementAsFloat(i
)
1082 : CDV
->getElementAsDouble(i
);
1083 if (y
!= (double)(int64_t)y
)
1093 Constant
*AbsExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_FABS
,
1097 nval
= CreateCallEx(B
, AbsExpr
, opr0
, "__fabs");
1099 nval
= cnval
? cnval
: opr0
;
1102 Constant
*LogExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2
,
1106 nval
= CreateCallEx(B
,LogExpr
, nval
, "__log2");
1109 if (FInfo
.getId() == AMDGPULibFunc::EI_POWN
) {
1110 // convert int(32) to fp(f32 or f64)
1111 opr1
= B
.CreateSIToFP(opr1
, nval
->getType(), "pownI2F");
1113 nval
= B
.CreateFMul(opr1
, nval
, "__ylogx");
1114 nval
= CreateCallEx(B
,ExpExpr
, nval
, "__exp2");
1118 Type
* rTy
= opr0
->getType();
1119 Type
* nTyS
= eltType
->isDoubleTy() ? B
.getInt64Ty() : B
.getInt32Ty();
1121 if (const VectorType
*vTy
= dyn_cast
<VectorType
>(rTy
))
1122 nTy
= VectorType::get(nTyS
, vTy
->getNumElements());
1123 unsigned size
= nTy
->getScalarSizeInBits();
1124 opr_n
= CI
->getArgOperand(1);
1125 if (opr_n
->getType()->isIntegerTy())
1126 opr_n
= B
.CreateZExtOrBitCast(opr_n
, nTy
, "__ytou");
1128 opr_n
= B
.CreateFPToSI(opr1
, nTy
, "__ytou");
1130 Value
*sign
= B
.CreateShl(opr_n
, size
-1, "__yeven");
1131 sign
= B
.CreateAnd(B
.CreateBitCast(opr0
, nTy
), sign
, "__pow_sign");
1132 nval
= B
.CreateOr(B
.CreateBitCast(nval
, nTy
), sign
);
1133 nval
= B
.CreateBitCast(nval
, opr0
->getType());
1136 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1137 << "exp2(" << *opr1
<< " * log2(" << *opr0
<< "))\n");
1143 bool AMDGPULibCalls::fold_rootn(CallInst
*CI
, IRBuilder
<> &B
,
1144 const FuncInfo
&FInfo
) {
1145 Value
*opr0
= CI
->getArgOperand(0);
1146 Value
*opr1
= CI
->getArgOperand(1);
1148 ConstantInt
*CINT
= dyn_cast
<ConstantInt
>(opr1
);
1152 int ci_opr1
= (int)CINT
->getSExtValue();
1153 if (ci_opr1
== 1) { // rootn(x, 1) = x
1154 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< "\n");
1158 if (ci_opr1
== 2) { // rootn(x, 2) = sqrt(x)
1159 std::vector
<const Type
*> ParamsTys
;
1160 ParamsTys
.push_back(opr0
->getType());
1161 Module
*M
= CI
->getModule();
1162 if (Constant
*FPExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
,
1164 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> sqrt(" << *opr0
<< ")\n");
1165 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2sqrt");
1169 } else if (ci_opr1
== 3) { // rootn(x, 3) = cbrt(x)
1170 Module
*M
= CI
->getModule();
1171 if (Constant
*FPExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT
,
1173 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> cbrt(" << *opr0
<< ")\n");
1174 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2cbrt");
1178 } else if (ci_opr1
== -1) { // rootn(x, -1) = 1.0/x
1179 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> 1.0 / " << *opr0
<< "\n");
1180 Value
*nval
= B
.CreateFDiv(ConstantFP::get(opr0
->getType(), 1.0),
1185 } else if (ci_opr1
== -2) { // rootn(x, -2) = rsqrt(x)
1186 std::vector
<const Type
*> ParamsTys
;
1187 ParamsTys
.push_back(opr0
->getType());
1188 Module
*M
= CI
->getModule();
1189 if (Constant
*FPExpr
= getFunction(M
, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT
,
1191 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> rsqrt(" << *opr0
1193 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__rootn2rsqrt");
1201 bool AMDGPULibCalls::fold_fma_mad(CallInst
*CI
, IRBuilder
<> &B
,
1202 const FuncInfo
&FInfo
) {
1203 Value
*opr0
= CI
->getArgOperand(0);
1204 Value
*opr1
= CI
->getArgOperand(1);
1205 Value
*opr2
= CI
->getArgOperand(2);
1207 ConstantFP
*CF0
= dyn_cast
<ConstantFP
>(opr0
);
1208 ConstantFP
*CF1
= dyn_cast
<ConstantFP
>(opr1
);
1209 if ((CF0
&& CF0
->isZero()) || (CF1
&& CF1
->isZero())) {
1210 // fma/mad(a, b, c) = c if a=0 || b=0
1211 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr2
<< "\n");
1215 if (CF0
&& CF0
->isExactlyValue(1.0f
)) {
1216 // fma/mad(a, b, c) = b+c if a=1
1217 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr1
<< " + " << *opr2
1219 Value
*nval
= B
.CreateFAdd(opr1
, opr2
, "fmaadd");
1223 if (CF1
&& CF1
->isExactlyValue(1.0f
)) {
1224 // fma/mad(a, b, c) = a+c if b=1
1225 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " + " << *opr2
1227 Value
*nval
= B
.CreateFAdd(opr0
, opr2
, "fmaadd");
1231 if (ConstantFP
*CF
= dyn_cast
<ConstantFP
>(opr2
)) {
1233 // fma/mad(a, b, c) = a*b if c=0
1234 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> " << *opr0
<< " * "
1236 Value
*nval
= B
.CreateFMul(opr0
, opr1
, "fmamul");
1245 // Get a scalar native builtin signle argument FP function
1246 Constant
* AMDGPULibCalls::getNativeFunction(Module
* M
, const FuncInfo
& FInfo
) {
1247 if (getArgType(FInfo
) == AMDGPULibFunc::F64
|| !HasNative(FInfo
.getId()))
1249 FuncInfo nf
= FInfo
;
1250 nf
.setPrefix(AMDGPULibFunc::NATIVE
);
1251 return getFunction(M
, nf
);
1254 // fold sqrt -> native_sqrt (x)
1255 bool AMDGPULibCalls::fold_sqrt(CallInst
*CI
, IRBuilder
<> &B
,
1256 const FuncInfo
&FInfo
) {
1257 if (getArgType(FInfo
) == AMDGPULibFunc::F32
&& (getVecSize(FInfo
) == 1) &&
1258 (FInfo
.getPrefix() != AMDGPULibFunc::NATIVE
)) {
1259 if (Constant
*FPExpr
= getNativeFunction(
1260 CI
->getModule(), AMDGPULibFunc(AMDGPULibFunc::EI_SQRT
, FInfo
))) {
1261 Value
*opr0
= CI
->getArgOperand(0);
1262 LLVM_DEBUG(errs() << "AMDIC: " << *CI
<< " ---> "
1263 << "sqrt(" << *opr0
<< ")\n");
1264 Value
*nval
= CreateCallEx(B
,FPExpr
, opr0
, "__sqrt");
1272 // fold sin, cos -> sincos.
1273 bool AMDGPULibCalls::fold_sincos(CallInst
*CI
, IRBuilder
<> &B
,
1274 AliasAnalysis
*AA
) {
1275 AMDGPULibFunc fInfo
;
1276 if (!AMDGPULibFunc::parse(CI
->getCalledFunction()->getName(), fInfo
))
1279 assert(fInfo
.getId() == AMDGPULibFunc::EI_SIN
||
1280 fInfo
.getId() == AMDGPULibFunc::EI_COS
);
1281 bool const isSin
= fInfo
.getId() == AMDGPULibFunc::EI_SIN
;
1283 Value
*CArgVal
= CI
->getArgOperand(0);
1284 BasicBlock
* const CBB
= CI
->getParent();
1286 int const MaxScan
= 30;
1288 { // fold in load value.
1289 LoadInst
*LI
= dyn_cast
<LoadInst
>(CArgVal
);
1290 if (LI
&& LI
->getParent() == CBB
) {
1291 BasicBlock::iterator BBI
= LI
->getIterator();
1292 Value
*AvailableVal
= FindAvailableLoadedValue(LI
, CBB
, BBI
, MaxScan
, AA
);
1294 CArgVal
->replaceAllUsesWith(AvailableVal
);
1295 if (CArgVal
->getNumUses() == 0)
1296 LI
->eraseFromParent();
1297 CArgVal
= CI
->getArgOperand(0);
1302 Module
*M
= CI
->getModule();
1303 fInfo
.setId(isSin
? AMDGPULibFunc::EI_COS
: AMDGPULibFunc::EI_SIN
);
1304 std::string
const PairName
= fInfo
.mangle();
1306 CallInst
*UI
= nullptr;
1307 for (User
* U
: CArgVal
->users()) {
1308 CallInst
*XI
= dyn_cast_or_null
<CallInst
>(U
);
1309 if (!XI
|| XI
== CI
|| XI
->getParent() != CBB
)
1312 Function
*UCallee
= XI
->getCalledFunction();
1313 if (!UCallee
|| !UCallee
->getName().equals(PairName
))
1316 BasicBlock::iterator BBI
= CI
->getIterator();
1317 if (BBI
== CI
->getParent()->begin())
1320 for (int I
= MaxScan
; I
> 0 && BBI
!= CBB
->begin(); --BBI
, --I
) {
1321 if (cast
<Instruction
>(BBI
) == XI
) {
1329 if (!UI
) return false;
1331 // Merge the sin and cos.
1333 // for OpenCL 2.0 we have only generic implementation of sincos
1335 AMDGPULibFunc
nf(AMDGPULibFunc::EI_SINCOS
, fInfo
);
1336 nf
.getLeads()[0].PtrKind
= AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS
);
1337 Function
*Fsincos
= dyn_cast_or_null
<Function
>(getFunction(M
, nf
));
1338 if (!Fsincos
) return false;
1340 BasicBlock::iterator ItOld
= B
.GetInsertPoint();
1341 AllocaInst
*Alloc
= insertAlloca(UI
, B
, "__sincos_");
1342 B
.SetInsertPoint(UI
);
1345 Type
*PTy
= Fsincos
->getFunctionType()->getParamType(1);
1346 // The allocaInst allocates the memory in private address space. This need
1347 // to be bitcasted to point to the address space of cos pointer type.
1348 // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1349 if (PTy
->getPointerAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS
)
1350 P
= B
.CreateAddrSpaceCast(Alloc
, PTy
);
1351 CallInst
*Call
= CreateCallEx2(B
, Fsincos
, UI
->getArgOperand(0), P
);
1353 LLVM_DEBUG(errs() << "AMDIC: fold_sincos (" << *CI
<< ", " << *UI
<< ") with "
1356 if (!isSin
) { // CI->cos, UI->sin
1357 B
.SetInsertPoint(&*ItOld
);
1358 UI
->replaceAllUsesWith(&*Call
);
1359 Instruction
*Reload
= B
.CreateLoad(Alloc
);
1360 CI
->replaceAllUsesWith(Reload
);
1361 UI
->eraseFromParent();
1362 CI
->eraseFromParent();
1363 } else { // CI->sin, UI->cos
1364 Instruction
*Reload
= B
.CreateLoad(Alloc
);
1365 UI
->replaceAllUsesWith(Reload
);
1366 CI
->replaceAllUsesWith(Call
);
1367 UI
->eraseFromParent();
1368 CI
->eraseFromParent();
1373 // Get insertion point at entry.
1374 BasicBlock::iterator
AMDGPULibCalls::getEntryIns(CallInst
* UI
) {
1375 Function
* Func
= UI
->getParent()->getParent();
1376 BasicBlock
* BB
= &Func
->getEntryBlock();
1377 assert(BB
&& "Entry block not found!");
1378 BasicBlock::iterator ItNew
= BB
->begin();
1382 // Insert a AllocsInst at the beginning of function entry block.
1383 AllocaInst
* AMDGPULibCalls::insertAlloca(CallInst
*UI
, IRBuilder
<> &B
,
1384 const char *prefix
) {
1385 BasicBlock::iterator ItNew
= getEntryIns(UI
);
1386 Function
*UCallee
= UI
->getCalledFunction();
1387 Type
*RetType
= UCallee
->getReturnType();
1388 B
.SetInsertPoint(&*ItNew
);
1389 AllocaInst
*Alloc
= B
.CreateAlloca(RetType
, 0,
1390 std::string(prefix
) + UI
->getName());
1391 Alloc
->setAlignment(UCallee
->getParent()->getDataLayout()
1392 .getTypeAllocSize(RetType
));
1396 bool AMDGPULibCalls::evaluateScalarMathFunc(FuncInfo
&FInfo
,
1397 double& Res0
, double& Res1
,
1398 Constant
*copr0
, Constant
*copr1
,
1400 // By default, opr0/opr1/opr3 holds values of float/double type.
1401 // If they are not float/double, each function has to its
1402 // operand separately.
1403 double opr0
=0.0, opr1
=0.0, opr2
=0.0;
1404 ConstantFP
*fpopr0
= dyn_cast_or_null
<ConstantFP
>(copr0
);
1405 ConstantFP
*fpopr1
= dyn_cast_or_null
<ConstantFP
>(copr1
);
1406 ConstantFP
*fpopr2
= dyn_cast_or_null
<ConstantFP
>(copr2
);
1408 opr0
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1409 ? fpopr0
->getValueAPF().convertToDouble()
1410 : (double)fpopr0
->getValueAPF().convertToFloat();
1414 opr1
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1415 ? fpopr1
->getValueAPF().convertToDouble()
1416 : (double)fpopr1
->getValueAPF().convertToFloat();
1420 opr2
= (getArgType(FInfo
) == AMDGPULibFunc::F64
)
1421 ? fpopr2
->getValueAPF().convertToDouble()
1422 : (double)fpopr2
->getValueAPF().convertToFloat();
1425 switch (FInfo
.getId()) {
1426 default : return false;
1428 case AMDGPULibFunc::EI_ACOS
:
1432 case AMDGPULibFunc::EI_ACOSH
:
1433 // acosh(x) == log(x + sqrt(x*x - 1))
1434 Res0
= log(opr0
+ sqrt(opr0
*opr0
- 1.0));
1437 case AMDGPULibFunc::EI_ACOSPI
:
1438 Res0
= acos(opr0
) / MATH_PI
;
1441 case AMDGPULibFunc::EI_ASIN
:
1445 case AMDGPULibFunc::EI_ASINH
:
1446 // asinh(x) == log(x + sqrt(x*x + 1))
1447 Res0
= log(opr0
+ sqrt(opr0
*opr0
+ 1.0));
1450 case AMDGPULibFunc::EI_ASINPI
:
1451 Res0
= asin(opr0
) / MATH_PI
;
1454 case AMDGPULibFunc::EI_ATAN
:
1458 case AMDGPULibFunc::EI_ATANH
:
1459 // atanh(x) == (log(x+1) - log(x-1))/2;
1460 Res0
= (log(opr0
+ 1.0) - log(opr0
- 1.0))/2.0;
1463 case AMDGPULibFunc::EI_ATANPI
:
1464 Res0
= atan(opr0
) / MATH_PI
;
1467 case AMDGPULibFunc::EI_CBRT
:
1468 Res0
= (opr0
< 0.0) ? -pow(-opr0
, 1.0/3.0) : pow(opr0
, 1.0/3.0);
1471 case AMDGPULibFunc::EI_COS
:
1475 case AMDGPULibFunc::EI_COSH
:
1479 case AMDGPULibFunc::EI_COSPI
:
1480 Res0
= cos(MATH_PI
* opr0
);
1483 case AMDGPULibFunc::EI_EXP
:
1487 case AMDGPULibFunc::EI_EXP2
:
1488 Res0
= pow(2.0, opr0
);
1491 case AMDGPULibFunc::EI_EXP10
:
1492 Res0
= pow(10.0, opr0
);
1495 case AMDGPULibFunc::EI_EXPM1
:
1496 Res0
= exp(opr0
) - 1.0;
1499 case AMDGPULibFunc::EI_LOG
:
1503 case AMDGPULibFunc::EI_LOG2
:
1504 Res0
= log(opr0
) / log(2.0);
1507 case AMDGPULibFunc::EI_LOG10
:
1508 Res0
= log(opr0
) / log(10.0);
1511 case AMDGPULibFunc::EI_RSQRT
:
1512 Res0
= 1.0 / sqrt(opr0
);
1515 case AMDGPULibFunc::EI_SIN
:
1519 case AMDGPULibFunc::EI_SINH
:
1523 case AMDGPULibFunc::EI_SINPI
:
1524 Res0
= sin(MATH_PI
* opr0
);
1527 case AMDGPULibFunc::EI_SQRT
:
1531 case AMDGPULibFunc::EI_TAN
:
1535 case AMDGPULibFunc::EI_TANH
:
1539 case AMDGPULibFunc::EI_TANPI
:
1540 Res0
= tan(MATH_PI
* opr0
);
1543 case AMDGPULibFunc::EI_RECIP
:
1547 // two-arg functions
1548 case AMDGPULibFunc::EI_DIVIDE
:
1552 case AMDGPULibFunc::EI_POW
:
1553 case AMDGPULibFunc::EI_POWR
:
1554 Res0
= pow(opr0
, opr1
);
1557 case AMDGPULibFunc::EI_POWN
: {
1558 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1559 double val
= (double)iopr1
->getSExtValue();
1560 Res0
= pow(opr0
, val
);
1566 case AMDGPULibFunc::EI_ROOTN
: {
1567 if (ConstantInt
*iopr1
= dyn_cast_or_null
<ConstantInt
>(copr1
)) {
1568 double val
= (double)iopr1
->getSExtValue();
1569 Res0
= pow(opr0
, 1.0 / val
);
1576 case AMDGPULibFunc::EI_SINCOS
:
1581 // three-arg functions
1582 case AMDGPULibFunc::EI_FMA
:
1583 case AMDGPULibFunc::EI_MAD
:
1584 Res0
= opr0
* opr1
+ opr2
;
1591 bool AMDGPULibCalls::evaluateCall(CallInst
*aCI
, FuncInfo
&FInfo
) {
1592 int numArgs
= (int)aCI
->getNumArgOperands();
1596 Constant
*copr0
= nullptr;
1597 Constant
*copr1
= nullptr;
1598 Constant
*copr2
= nullptr;
1600 if ((copr0
= dyn_cast
<Constant
>(aCI
->getArgOperand(0))) == nullptr)
1605 if ((copr1
= dyn_cast
<Constant
>(aCI
->getArgOperand(1))) == nullptr) {
1606 if (FInfo
.getId() != AMDGPULibFunc::EI_SINCOS
)
1612 if ((copr2
= dyn_cast
<Constant
>(aCI
->getArgOperand(2))) == nullptr)
1616 // At this point, all arguments to aCI are constants.
1618 // max vector size is 16, and sincos will generate two results.
1619 double DVal0
[16], DVal1
[16];
1620 bool hasTwoResults
= (FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
);
1621 if (getVecSize(FInfo
) == 1) {
1622 if (!evaluateScalarMathFunc(FInfo
, DVal0
[0],
1623 DVal1
[0], copr0
, copr1
, copr2
)) {
1627 ConstantDataVector
*CDV0
= dyn_cast_or_null
<ConstantDataVector
>(copr0
);
1628 ConstantDataVector
*CDV1
= dyn_cast_or_null
<ConstantDataVector
>(copr1
);
1629 ConstantDataVector
*CDV2
= dyn_cast_or_null
<ConstantDataVector
>(copr2
);
1630 for (int i
=0; i
< getVecSize(FInfo
); ++i
) {
1631 Constant
*celt0
= CDV0
? CDV0
->getElementAsConstant(i
) : nullptr;
1632 Constant
*celt1
= CDV1
? CDV1
->getElementAsConstant(i
) : nullptr;
1633 Constant
*celt2
= CDV2
? CDV2
->getElementAsConstant(i
) : nullptr;
1634 if (!evaluateScalarMathFunc(FInfo
, DVal0
[i
],
1635 DVal1
[i
], celt0
, celt1
, celt2
)) {
1641 LLVMContext
&context
= CI
->getParent()->getParent()->getContext();
1642 Constant
*nval0
, *nval1
;
1643 if (getVecSize(FInfo
) == 1) {
1644 nval0
= ConstantFP::get(CI
->getType(), DVal0
[0]);
1646 nval1
= ConstantFP::get(CI
->getType(), DVal1
[0]);
1648 if (getArgType(FInfo
) == AMDGPULibFunc::F32
) {
1649 SmallVector
<float, 0> FVal0
, FVal1
;
1650 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1651 FVal0
.push_back((float)DVal0
[i
]);
1652 ArrayRef
<float> tmp0(FVal0
);
1653 nval0
= ConstantDataVector::get(context
, tmp0
);
1654 if (hasTwoResults
) {
1655 for (int i
=0; i
< getVecSize(FInfo
); ++i
)
1656 FVal1
.push_back((float)DVal1
[i
]);
1657 ArrayRef
<float> tmp1(FVal1
);
1658 nval1
= ConstantDataVector::get(context
, tmp1
);
1661 ArrayRef
<double> tmp0(DVal0
);
1662 nval0
= ConstantDataVector::get(context
, tmp0
);
1663 if (hasTwoResults
) {
1664 ArrayRef
<double> tmp1(DVal1
);
1665 nval1
= ConstantDataVector::get(context
, tmp1
);
1670 if (hasTwoResults
) {
1672 assert(FInfo
.getId() == AMDGPULibFunc::EI_SINCOS
&&
1673 "math function with ptr arg not supported yet");
1674 new StoreInst(nval1
, aCI
->getArgOperand(1), aCI
);
1681 // Public interface to the Simplify LibCalls pass.
1682 FunctionPass
*llvm::createAMDGPUSimplifyLibCallsPass(const TargetOptions
&Opt
) {
1683 return new AMDGPUSimplifyLibCalls(Opt
);
1686 FunctionPass
*llvm::createAMDGPUUseNativeCallsPass() {
1687 return new AMDGPUUseNativeCalls();
1690 static bool setFastFlags(Function
&F
, const TargetOptions
&Options
) {
1693 if (Options
.UnsafeFPMath
|| Options
.NoInfsFPMath
)
1694 B
.addAttribute("no-infs-fp-math", "true");
1695 if (Options
.UnsafeFPMath
|| Options
.NoNaNsFPMath
)
1696 B
.addAttribute("no-nans-fp-math", "true");
1697 if (Options
.UnsafeFPMath
) {
1698 B
.addAttribute("less-precise-fpmad", "true");
1699 B
.addAttribute("unsafe-fp-math", "true");
1702 if (!B
.hasAttributes())
1705 F
.addAttributes(AttributeList::FunctionIndex
, B
);
1710 bool AMDGPUSimplifyLibCalls::runOnFunction(Function
&F
) {
1711 if (skipFunction(F
))
1714 bool Changed
= false;
1715 auto AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
1717 LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1718 F
.printAsOperand(dbgs(), false, F
.getParent()); dbgs() << '\n';);
1721 Changed
|= setFastFlags(F
, Options
);
1723 for (auto &BB
: F
) {
1724 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1725 // Ignore non-calls.
1726 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1730 // Ignore indirect calls.
1731 Function
*Callee
= CI
->getCalledFunction();
1732 if (Callee
== 0) continue;
1734 LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI
<< "\n";
1736 if(Simplifier
.fold(CI
, AA
))
1743 bool AMDGPUUseNativeCalls::runOnFunction(Function
&F
) {
1744 if (skipFunction(F
) || UseNative
.empty())
1747 bool Changed
= false;
1748 for (auto &BB
: F
) {
1749 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ) {
1750 // Ignore non-calls.
1751 CallInst
*CI
= dyn_cast
<CallInst
>(I
);
1755 // Ignore indirect calls.
1756 Function
*Callee
= CI
->getCalledFunction();
1757 if (Callee
== 0) continue;
1759 if(Simplifier
.useNative(CI
))