xref: /llvm-project/llvm/lib/Target/AMDGPU/AMDGPULibCalls.cpp (revision 699685b7185bfe196a6ae24df6daa9f68c79148e)
1 //===- AMDGPULibCalls.cpp -------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file does AMD library function optimizations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPU.h"
15 #include "AMDGPULibFunc.h"
16 #include "GCNSubtarget.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/IRBuilder.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/IntrinsicsAMDGPU.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/InitializePasses.h"
26 #include <cmath>
27 
28 #define DEBUG_TYPE "amdgpu-simplifylib"
29 
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32 
33 static cl::opt<bool> EnablePreLink("amdgpu-prelink",
34   cl::desc("Enable pre-link mode optimizations"),
35   cl::init(false),
36   cl::Hidden);
37 
38 static cl::list<std::string> UseNative("amdgpu-use-native",
39   cl::desc("Comma separated list of functions to replace with native, or all"),
40   cl::CommaSeparated, cl::ValueOptional,
41   cl::Hidden);
42 
43 #define MATH_PI      numbers::pi
44 #define MATH_E       numbers::e
45 #define MATH_SQRT2   numbers::sqrt2
46 #define MATH_SQRT1_2 numbers::inv_sqrt2
47 
48 namespace llvm {
49 
50 class AMDGPULibCalls {
51 private:
52   const TargetLibraryInfo *TLInfo = nullptr;
53   AssumptionCache *AC = nullptr;
54   DominatorTree *DT = nullptr;
55 
56   typedef llvm::AMDGPULibFunc FuncInfo;
57 
58   bool UnsafeFPMath = false;
59 
60   // -fuse-native.
61   bool AllNative = false;
62 
63   bool useNativeFunc(const StringRef F) const;
64 
65   // Return a pointer (pointer expr) to the function if function definition with
66   // "FuncName" exists. It may create a new function prototype in pre-link mode.
67   FunctionCallee getFunction(Module *M, const FuncInfo &fInfo);
68 
69   bool parseFunctionName(const StringRef &FMangledName, FuncInfo &FInfo);
70 
71   bool TDOFold(CallInst *CI, const FuncInfo &FInfo);
72 
73   /* Specialized optimizations */
74 
75   // pow/powr/pown
76   bool fold_pow(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
77 
78   // rootn
79   bool fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
80 
81   // -fuse-native for sincos
82   bool sincosUseNative(CallInst *aCI, const FuncInfo &FInfo);
83 
84   // evaluate calls if calls' arguments are constants.
85   bool evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0, double &Res1,
86                               Constant *copr0, Constant *copr1);
87   bool evaluateCall(CallInst *aCI, const FuncInfo &FInfo);
88 
89   // sqrt
90   bool fold_sqrt(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
91 
92   /// Insert a value to sincos function \p Fsincos. Returns (value of sin, value
93   /// of cos, sincos call).
94   std::tuple<Value *, Value *, Value *> insertSinCos(Value *Arg,
95                                                      FastMathFlags FMF,
96                                                      IRBuilder<> &B,
97                                                      FunctionCallee Fsincos);
98 
99   // sin/cos
100   bool fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B, const FuncInfo &FInfo);
101 
102   // __read_pipe/__write_pipe
103   bool fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
104                             const FuncInfo &FInfo);
105 
106   // Get a scalar native builtin single argument FP function
107   FunctionCallee getNativeFunction(Module *M, const FuncInfo &FInfo);
108 
109   /// Substitute a call to a known libcall with an intrinsic call. If \p
110   /// AllowMinSize is true, allow the replacement in a minsize function.
111   bool shouldReplaceLibcallWithIntrinsic(const CallInst *CI,
112                                          bool AllowMinSizeF32 = false,
113                                          bool AllowF64 = false,
114                                          bool AllowStrictFP = false);
115   void replaceLibCallWithSimpleIntrinsic(IRBuilder<> &B, CallInst *CI,
116                                          Intrinsic::ID IntrID);
117 
118   bool tryReplaceLibcallWithSimpleIntrinsic(IRBuilder<> &B, CallInst *CI,
119                                             Intrinsic::ID IntrID,
120                                             bool AllowMinSizeF32 = false,
121                                             bool AllowF64 = false,
122                                             bool AllowStrictFP = false);
123 
124 protected:
125   bool isUnsafeMath(const FPMathOperator *FPOp) const;
126   bool isUnsafeFiniteOnlyMath(const FPMathOperator *FPOp) const;
127 
128   bool canIncreasePrecisionOfConstantFold(const FPMathOperator *FPOp) const;
129 
130   static void replaceCall(Instruction *I, Value *With) {
131     I->replaceAllUsesWith(With);
132     I->eraseFromParent();
133   }
134 
135   static void replaceCall(FPMathOperator *I, Value *With) {
136     replaceCall(cast<Instruction>(I), With);
137   }
138 
139 public:
140   AMDGPULibCalls() {}
141 
142   bool fold(CallInst *CI);
143 
144   void initFunction(Function &F, FunctionAnalysisManager &FAM);
145   void initNativeFuncs();
146 
147   // Replace a normal math function call with that native version
148   bool useNative(CallInst *CI);
149 };
150 
151 } // end llvm namespace
152 
153 template <typename IRB>
154 static CallInst *CreateCallEx(IRB &B, FunctionCallee Callee, Value *Arg,
155                               const Twine &Name = "") {
156   CallInst *R = B.CreateCall(Callee, Arg, Name);
157   if (Function *F = dyn_cast<Function>(Callee.getCallee()))
158     R->setCallingConv(F->getCallingConv());
159   return R;
160 }
161 
162 template <typename IRB>
163 static CallInst *CreateCallEx2(IRB &B, FunctionCallee Callee, Value *Arg1,
164                                Value *Arg2, const Twine &Name = "") {
165   CallInst *R = B.CreateCall(Callee, {Arg1, Arg2}, Name);
166   if (Function *F = dyn_cast<Function>(Callee.getCallee()))
167     R->setCallingConv(F->getCallingConv());
168   return R;
169 }
170 
171 //  Data structures for table-driven optimizations.
172 //  FuncTbl works for both f32 and f64 functions with 1 input argument
173 
174 struct TableEntry {
175   double   result;
176   double   input;
177 };
178 
179 /* a list of {result, input} */
180 static const TableEntry tbl_acos[] = {
181   {MATH_PI / 2.0, 0.0},
182   {MATH_PI / 2.0, -0.0},
183   {0.0, 1.0},
184   {MATH_PI, -1.0}
185 };
186 static const TableEntry tbl_acosh[] = {
187   {0.0, 1.0}
188 };
189 static const TableEntry tbl_acospi[] = {
190   {0.5, 0.0},
191   {0.5, -0.0},
192   {0.0, 1.0},
193   {1.0, -1.0}
194 };
195 static const TableEntry tbl_asin[] = {
196   {0.0, 0.0},
197   {-0.0, -0.0},
198   {MATH_PI / 2.0, 1.0},
199   {-MATH_PI / 2.0, -1.0}
200 };
201 static const TableEntry tbl_asinh[] = {
202   {0.0, 0.0},
203   {-0.0, -0.0}
204 };
205 static const TableEntry tbl_asinpi[] = {
206   {0.0, 0.0},
207   {-0.0, -0.0},
208   {0.5, 1.0},
209   {-0.5, -1.0}
210 };
211 static const TableEntry tbl_atan[] = {
212   {0.0, 0.0},
213   {-0.0, -0.0},
214   {MATH_PI / 4.0, 1.0},
215   {-MATH_PI / 4.0, -1.0}
216 };
217 static const TableEntry tbl_atanh[] = {
218   {0.0, 0.0},
219   {-0.0, -0.0}
220 };
221 static const TableEntry tbl_atanpi[] = {
222   {0.0, 0.0},
223   {-0.0, -0.0},
224   {0.25, 1.0},
225   {-0.25, -1.0}
226 };
227 static const TableEntry tbl_cbrt[] = {
228   {0.0, 0.0},
229   {-0.0, -0.0},
230   {1.0, 1.0},
231   {-1.0, -1.0},
232 };
233 static const TableEntry tbl_cos[] = {
234   {1.0, 0.0},
235   {1.0, -0.0}
236 };
237 static const TableEntry tbl_cosh[] = {
238   {1.0, 0.0},
239   {1.0, -0.0}
240 };
241 static const TableEntry tbl_cospi[] = {
242   {1.0, 0.0},
243   {1.0, -0.0}
244 };
245 static const TableEntry tbl_erfc[] = {
246   {1.0, 0.0},
247   {1.0, -0.0}
248 };
249 static const TableEntry tbl_erf[] = {
250   {0.0, 0.0},
251   {-0.0, -0.0}
252 };
253 static const TableEntry tbl_exp[] = {
254   {1.0, 0.0},
255   {1.0, -0.0},
256   {MATH_E, 1.0}
257 };
258 static const TableEntry tbl_exp2[] = {
259   {1.0, 0.0},
260   {1.0, -0.0},
261   {2.0, 1.0}
262 };
263 static const TableEntry tbl_exp10[] = {
264   {1.0, 0.0},
265   {1.0, -0.0},
266   {10.0, 1.0}
267 };
268 static const TableEntry tbl_expm1[] = {
269   {0.0, 0.0},
270   {-0.0, -0.0}
271 };
272 static const TableEntry tbl_log[] = {
273   {0.0, 1.0},
274   {1.0, MATH_E}
275 };
276 static const TableEntry tbl_log2[] = {
277   {0.0, 1.0},
278   {1.0, 2.0}
279 };
280 static const TableEntry tbl_log10[] = {
281   {0.0, 1.0},
282   {1.0, 10.0}
283 };
284 static const TableEntry tbl_rsqrt[] = {
285   {1.0, 1.0},
286   {MATH_SQRT1_2, 2.0}
287 };
288 static const TableEntry tbl_sin[] = {
289   {0.0, 0.0},
290   {-0.0, -0.0}
291 };
292 static const TableEntry tbl_sinh[] = {
293   {0.0, 0.0},
294   {-0.0, -0.0}
295 };
296 static const TableEntry tbl_sinpi[] = {
297   {0.0, 0.0},
298   {-0.0, -0.0}
299 };
300 static const TableEntry tbl_sqrt[] = {
301   {0.0, 0.0},
302   {1.0, 1.0},
303   {MATH_SQRT2, 2.0}
304 };
305 static const TableEntry tbl_tan[] = {
306   {0.0, 0.0},
307   {-0.0, -0.0}
308 };
309 static const TableEntry tbl_tanh[] = {
310   {0.0, 0.0},
311   {-0.0, -0.0}
312 };
313 static const TableEntry tbl_tanpi[] = {
314   {0.0, 0.0},
315   {-0.0, -0.0}
316 };
317 static const TableEntry tbl_tgamma[] = {
318   {1.0, 1.0},
319   {1.0, 2.0},
320   {2.0, 3.0},
321   {6.0, 4.0}
322 };
323 
324 static bool HasNative(AMDGPULibFunc::EFuncId id) {
325   switch(id) {
326   case AMDGPULibFunc::EI_DIVIDE:
327   case AMDGPULibFunc::EI_COS:
328   case AMDGPULibFunc::EI_EXP:
329   case AMDGPULibFunc::EI_EXP2:
330   case AMDGPULibFunc::EI_EXP10:
331   case AMDGPULibFunc::EI_LOG:
332   case AMDGPULibFunc::EI_LOG2:
333   case AMDGPULibFunc::EI_LOG10:
334   case AMDGPULibFunc::EI_POWR:
335   case AMDGPULibFunc::EI_RECIP:
336   case AMDGPULibFunc::EI_RSQRT:
337   case AMDGPULibFunc::EI_SIN:
338   case AMDGPULibFunc::EI_SINCOS:
339   case AMDGPULibFunc::EI_SQRT:
340   case AMDGPULibFunc::EI_TAN:
341     return true;
342   default:;
343   }
344   return false;
345 }
346 
347 using TableRef = ArrayRef<TableEntry>;
348 
349 static TableRef getOptTable(AMDGPULibFunc::EFuncId id) {
350   switch(id) {
351   case AMDGPULibFunc::EI_ACOS:    return TableRef(tbl_acos);
352   case AMDGPULibFunc::EI_ACOSH:   return TableRef(tbl_acosh);
353   case AMDGPULibFunc::EI_ACOSPI:  return TableRef(tbl_acospi);
354   case AMDGPULibFunc::EI_ASIN:    return TableRef(tbl_asin);
355   case AMDGPULibFunc::EI_ASINH:   return TableRef(tbl_asinh);
356   case AMDGPULibFunc::EI_ASINPI:  return TableRef(tbl_asinpi);
357   case AMDGPULibFunc::EI_ATAN:    return TableRef(tbl_atan);
358   case AMDGPULibFunc::EI_ATANH:   return TableRef(tbl_atanh);
359   case AMDGPULibFunc::EI_ATANPI:  return TableRef(tbl_atanpi);
360   case AMDGPULibFunc::EI_CBRT:    return TableRef(tbl_cbrt);
361   case AMDGPULibFunc::EI_NCOS:
362   case AMDGPULibFunc::EI_COS:     return TableRef(tbl_cos);
363   case AMDGPULibFunc::EI_COSH:    return TableRef(tbl_cosh);
364   case AMDGPULibFunc::EI_COSPI:   return TableRef(tbl_cospi);
365   case AMDGPULibFunc::EI_ERFC:    return TableRef(tbl_erfc);
366   case AMDGPULibFunc::EI_ERF:     return TableRef(tbl_erf);
367   case AMDGPULibFunc::EI_EXP:     return TableRef(tbl_exp);
368   case AMDGPULibFunc::EI_NEXP2:
369   case AMDGPULibFunc::EI_EXP2:    return TableRef(tbl_exp2);
370   case AMDGPULibFunc::EI_EXP10:   return TableRef(tbl_exp10);
371   case AMDGPULibFunc::EI_EXPM1:   return TableRef(tbl_expm1);
372   case AMDGPULibFunc::EI_LOG:     return TableRef(tbl_log);
373   case AMDGPULibFunc::EI_NLOG2:
374   case AMDGPULibFunc::EI_LOG2:    return TableRef(tbl_log2);
375   case AMDGPULibFunc::EI_LOG10:   return TableRef(tbl_log10);
376   case AMDGPULibFunc::EI_NRSQRT:
377   case AMDGPULibFunc::EI_RSQRT:   return TableRef(tbl_rsqrt);
378   case AMDGPULibFunc::EI_NSIN:
379   case AMDGPULibFunc::EI_SIN:     return TableRef(tbl_sin);
380   case AMDGPULibFunc::EI_SINH:    return TableRef(tbl_sinh);
381   case AMDGPULibFunc::EI_SINPI:   return TableRef(tbl_sinpi);
382   case AMDGPULibFunc::EI_NSQRT:
383   case AMDGPULibFunc::EI_SQRT:    return TableRef(tbl_sqrt);
384   case AMDGPULibFunc::EI_TAN:     return TableRef(tbl_tan);
385   case AMDGPULibFunc::EI_TANH:    return TableRef(tbl_tanh);
386   case AMDGPULibFunc::EI_TANPI:   return TableRef(tbl_tanpi);
387   case AMDGPULibFunc::EI_TGAMMA:  return TableRef(tbl_tgamma);
388   default:;
389   }
390   return TableRef();
391 }
392 
393 static inline int getVecSize(const AMDGPULibFunc& FInfo) {
394   return FInfo.getLeads()[0].VectorSize;
395 }
396 
397 static inline AMDGPULibFunc::EType getArgType(const AMDGPULibFunc& FInfo) {
398   return (AMDGPULibFunc::EType)FInfo.getLeads()[0].ArgType;
399 }
400 
401 FunctionCallee AMDGPULibCalls::getFunction(Module *M, const FuncInfo &fInfo) {
402   // If we are doing PreLinkOpt, the function is external. So it is safe to
403   // use getOrInsertFunction() at this stage.
404 
405   return EnablePreLink ? AMDGPULibFunc::getOrInsertFunction(M, fInfo)
406                        : AMDGPULibFunc::getFunction(M, fInfo);
407 }
408 
409 bool AMDGPULibCalls::parseFunctionName(const StringRef &FMangledName,
410                                        FuncInfo &FInfo) {
411   return AMDGPULibFunc::parse(FMangledName, FInfo);
412 }
413 
414 bool AMDGPULibCalls::isUnsafeMath(const FPMathOperator *FPOp) const {
415   return UnsafeFPMath || FPOp->isFast();
416 }
417 
418 bool AMDGPULibCalls::isUnsafeFiniteOnlyMath(const FPMathOperator *FPOp) const {
419   return UnsafeFPMath ||
420          (FPOp->hasApproxFunc() && FPOp->hasNoNaNs() && FPOp->hasNoInfs());
421 }
422 
423 bool AMDGPULibCalls::canIncreasePrecisionOfConstantFold(
424     const FPMathOperator *FPOp) const {
425   // TODO: Refine to approxFunc or contract
426   return isUnsafeMath(FPOp);
427 }
428 
429 void AMDGPULibCalls::initFunction(Function &F, FunctionAnalysisManager &FAM) {
430   UnsafeFPMath = F.getFnAttribute("unsafe-fp-math").getValueAsBool();
431   AC = &FAM.getResult<AssumptionAnalysis>(F);
432   TLInfo = &FAM.getResult<TargetLibraryAnalysis>(F);
433   DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
434 }
435 
436 bool AMDGPULibCalls::useNativeFunc(const StringRef F) const {
437   return AllNative || llvm::is_contained(UseNative, F);
438 }
439 
440 void AMDGPULibCalls::initNativeFuncs() {
441   AllNative = useNativeFunc("all") ||
442               (UseNative.getNumOccurrences() && UseNative.size() == 1 &&
443                UseNative.begin()->empty());
444 }
445 
446 bool AMDGPULibCalls::sincosUseNative(CallInst *aCI, const FuncInfo &FInfo) {
447   bool native_sin = useNativeFunc("sin");
448   bool native_cos = useNativeFunc("cos");
449 
450   if (native_sin && native_cos) {
451     Module *M = aCI->getModule();
452     Value *opr0 = aCI->getArgOperand(0);
453 
454     AMDGPULibFunc nf;
455     nf.getLeads()[0].ArgType = FInfo.getLeads()[0].ArgType;
456     nf.getLeads()[0].VectorSize = FInfo.getLeads()[0].VectorSize;
457 
458     nf.setPrefix(AMDGPULibFunc::NATIVE);
459     nf.setId(AMDGPULibFunc::EI_SIN);
460     FunctionCallee sinExpr = getFunction(M, nf);
461 
462     nf.setPrefix(AMDGPULibFunc::NATIVE);
463     nf.setId(AMDGPULibFunc::EI_COS);
464     FunctionCallee cosExpr = getFunction(M, nf);
465     if (sinExpr && cosExpr) {
466       Value *sinval = CallInst::Create(sinExpr, opr0, "splitsin", aCI);
467       Value *cosval = CallInst::Create(cosExpr, opr0, "splitcos", aCI);
468       new StoreInst(cosval, aCI->getArgOperand(1), aCI);
469 
470       DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
471                                           << " with native version of sin/cos");
472 
473       replaceCall(aCI, sinval);
474       return true;
475     }
476   }
477   return false;
478 }
479 
480 bool AMDGPULibCalls::useNative(CallInst *aCI) {
481   Function *Callee = aCI->getCalledFunction();
482   if (!Callee || aCI->isNoBuiltin())
483     return false;
484 
485   FuncInfo FInfo;
486   if (!parseFunctionName(Callee->getName(), FInfo) || !FInfo.isMangled() ||
487       FInfo.getPrefix() != AMDGPULibFunc::NOPFX ||
488       getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()) ||
489       !(AllNative || useNativeFunc(FInfo.getName()))) {
490     return false;
491   }
492 
493   if (FInfo.getId() == AMDGPULibFunc::EI_SINCOS)
494     return sincosUseNative(aCI, FInfo);
495 
496   FInfo.setPrefix(AMDGPULibFunc::NATIVE);
497   FunctionCallee F = getFunction(aCI->getModule(), FInfo);
498   if (!F)
499     return false;
500 
501   aCI->setCalledFunction(F);
502   DEBUG_WITH_TYPE("usenative", dbgs() << "<useNative> replace " << *aCI
503                                       << " with native version");
504   return true;
505 }
506 
507 // Clang emits call of __read_pipe_2 or __read_pipe_4 for OpenCL read_pipe
508 // builtin, with appended type size and alignment arguments, where 2 or 4
509 // indicates the original number of arguments. The library has optimized version
510 // of __read_pipe_2/__read_pipe_4 when the type size and alignment has the same
511 // power of 2 value. This function transforms __read_pipe_2 to __read_pipe_2_N
512 // for such cases where N is the size in bytes of the type (N = 1, 2, 4, 8, ...,
513 // 128). The same for __read_pipe_4, write_pipe_2, and write_pipe_4.
514 bool AMDGPULibCalls::fold_read_write_pipe(CallInst *CI, IRBuilder<> &B,
515                                           const FuncInfo &FInfo) {
516   auto *Callee = CI->getCalledFunction();
517   if (!Callee->isDeclaration())
518     return false;
519 
520   assert(Callee->hasName() && "Invalid read_pipe/write_pipe function");
521   auto *M = Callee->getParent();
522   std::string Name = std::string(Callee->getName());
523   auto NumArg = CI->arg_size();
524   if (NumArg != 4 && NumArg != 6)
525     return false;
526   ConstantInt *PacketSize =
527       dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 2));
528   ConstantInt *PacketAlign =
529       dyn_cast<ConstantInt>(CI->getArgOperand(NumArg - 1));
530   if (!PacketSize || !PacketAlign)
531     return false;
532 
533   unsigned Size = PacketSize->getZExtValue();
534   Align Alignment = PacketAlign->getAlignValue();
535   if (Alignment != Size)
536     return false;
537 
538   unsigned PtrArgLoc = CI->arg_size() - 3;
539   Value *PtrArg = CI->getArgOperand(PtrArgLoc);
540   Type *PtrTy = PtrArg->getType();
541 
542   SmallVector<llvm::Type *, 6> ArgTys;
543   for (unsigned I = 0; I != PtrArgLoc; ++I)
544     ArgTys.push_back(CI->getArgOperand(I)->getType());
545   ArgTys.push_back(PtrTy);
546 
547   Name = Name + "_" + std::to_string(Size);
548   auto *FTy = FunctionType::get(Callee->getReturnType(),
549                                 ArrayRef<Type *>(ArgTys), false);
550   AMDGPULibFunc NewLibFunc(Name, FTy);
551   FunctionCallee F = AMDGPULibFunc::getOrInsertFunction(M, NewLibFunc);
552   if (!F)
553     return false;
554 
555   auto *BCast = B.CreatePointerCast(PtrArg, PtrTy);
556   SmallVector<Value *, 6> Args;
557   for (unsigned I = 0; I != PtrArgLoc; ++I)
558     Args.push_back(CI->getArgOperand(I));
559   Args.push_back(BCast);
560 
561   auto *NCI = B.CreateCall(F, Args);
562   NCI->setAttributes(CI->getAttributes());
563   CI->replaceAllUsesWith(NCI);
564   CI->dropAllReferences();
565   CI->eraseFromParent();
566 
567   return true;
568 }
569 
570 static bool isKnownIntegral(const Value *V) {
571   if (isa<UndefValue>(V))
572     return true;
573 
574   if (const ConstantFP *CF = dyn_cast<ConstantFP>(V))
575     return CF->getValueAPF().isInteger();
576 
577   if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
578     for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
579       Constant *ConstElt = CDV->getElementAsConstant(i);
580       if (isa<UndefValue>(ConstElt))
581         continue;
582       const ConstantFP *CFP = dyn_cast<ConstantFP>(ConstElt);
583       if (!CFP || !CFP->getValue().isInteger())
584         return false;
585     }
586 
587     return true;
588   }
589 
590   return false;
591 }
592 
593 // This function returns false if no change; return true otherwise.
594 bool AMDGPULibCalls::fold(CallInst *CI) {
595   Function *Callee = CI->getCalledFunction();
596   // Ignore indirect calls.
597   if (!Callee || Callee->isIntrinsic() || CI->isNoBuiltin())
598     return false;
599 
600   FuncInfo FInfo;
601   if (!parseFunctionName(Callee->getName(), FInfo))
602     return false;
603 
604   // Further check the number of arguments to see if they match.
605   // TODO: Check calling convention matches too
606   if (!FInfo.isCompatibleSignature(CI->getFunctionType()))
607     return false;
608 
609   LLVM_DEBUG(dbgs() << "AMDIC: try folding " << *CI << '\n');
610 
611   if (TDOFold(CI, FInfo))
612     return true;
613 
614   IRBuilder<> B(CI);
615 
616   if (FPMathOperator *FPOp = dyn_cast<FPMathOperator>(CI)) {
617     // Under unsafe-math, evaluate calls if possible.
618     // According to Brian Sumner, we can do this for all f32 function calls
619     // using host's double function calls.
620     if (canIncreasePrecisionOfConstantFold(FPOp) && evaluateCall(CI, FInfo))
621       return true;
622 
623     // Copy fast flags from the original call.
624     FastMathFlags FMF = FPOp->getFastMathFlags();
625     B.setFastMathFlags(FMF);
626 
627     // Specialized optimizations for each function call.
628     //
629     // TODO: Handle other simple intrinsic wrappers. Sqrt.
630     //
631     // TODO: Handle native functions
632     switch (FInfo.getId()) {
633     case AMDGPULibFunc::EI_EXP:
634       if (FMF.none())
635         return false;
636       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp,
637                                                   FMF.approxFunc());
638     case AMDGPULibFunc::EI_EXP2:
639       if (FMF.none())
640         return false;
641       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::exp2,
642                                                   FMF.approxFunc());
643     case AMDGPULibFunc::EI_LOG:
644       if (FMF.none())
645         return false;
646       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log,
647                                                   FMF.approxFunc());
648     case AMDGPULibFunc::EI_LOG2:
649       if (FMF.none())
650         return false;
651       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log2,
652                                                   FMF.approxFunc());
653     case AMDGPULibFunc::EI_LOG10:
654       if (FMF.none())
655         return false;
656       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::log10,
657                                                   FMF.approxFunc());
658     case AMDGPULibFunc::EI_FMIN:
659       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::minnum,
660                                                   true, true);
661     case AMDGPULibFunc::EI_FMAX:
662       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::maxnum,
663                                                   true, true);
664     case AMDGPULibFunc::EI_FMA:
665       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fma, true,
666                                                   true);
667     case AMDGPULibFunc::EI_MAD:
668       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fmuladd,
669                                                   true, true);
670     case AMDGPULibFunc::EI_FABS:
671       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::fabs, true,
672                                                   true, true);
673     case AMDGPULibFunc::EI_COPYSIGN:
674       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::copysign,
675                                                   true, true, true);
676     case AMDGPULibFunc::EI_FLOOR:
677       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::floor, true,
678                                                   true);
679     case AMDGPULibFunc::EI_CEIL:
680       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::ceil, true,
681                                                   true);
682     case AMDGPULibFunc::EI_TRUNC:
683       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::trunc, true,
684                                                   true);
685     case AMDGPULibFunc::EI_RINT:
686       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::rint, true,
687                                                   true);
688     case AMDGPULibFunc::EI_ROUND:
689       return tryReplaceLibcallWithSimpleIntrinsic(B, CI, Intrinsic::round, true,
690                                                   true);
691     case AMDGPULibFunc::EI_LDEXP: {
692       if (!shouldReplaceLibcallWithIntrinsic(CI, true, true))
693         return false;
694 
695       Value *Arg1 = CI->getArgOperand(1);
696       if (VectorType *VecTy = dyn_cast<VectorType>(CI->getType());
697           VecTy && !isa<VectorType>(Arg1->getType())) {
698         Value *SplatArg1 = B.CreateVectorSplat(VecTy->getElementCount(), Arg1);
699         CI->setArgOperand(1, SplatArg1);
700       }
701 
702       CI->setCalledFunction(Intrinsic::getDeclaration(
703           CI->getModule(), Intrinsic::ldexp,
704           {CI->getType(), CI->getArgOperand(1)->getType()}));
705       return true;
706     }
707     case AMDGPULibFunc::EI_POW: {
708       Module *M = Callee->getParent();
709       AMDGPULibFunc PowrInfo(AMDGPULibFunc::EI_POWR, FInfo);
710       FunctionCallee PowrFunc = getFunction(M, PowrInfo);
711       CallInst *Call = cast<CallInst>(FPOp);
712 
713       // pow(x, y) -> powr(x, y) for x >= -0.0
714       // TODO: Account for flags on current call
715       if (PowrFunc &&
716           cannotBeOrderedLessThanZero(FPOp->getOperand(0), M->getDataLayout(),
717                                       TLInfo, 0, AC, Call, DT)) {
718         Call->setCalledFunction(PowrFunc);
719         return fold_pow(FPOp, B, PowrInfo) || true;
720       }
721 
722       return fold_pow(FPOp, B, FInfo);
723     }
724     case AMDGPULibFunc::EI_POWR:
725     case AMDGPULibFunc::EI_POWN:
726       return fold_pow(FPOp, B, FInfo);
727     case AMDGPULibFunc::EI_ROOTN:
728       return fold_rootn(FPOp, B, FInfo);
729     case AMDGPULibFunc::EI_SQRT:
730       return fold_sqrt(FPOp, B, FInfo);
731     case AMDGPULibFunc::EI_COS:
732     case AMDGPULibFunc::EI_SIN:
733       return fold_sincos(FPOp, B, FInfo);
734     default:
735       break;
736     }
737   } else {
738     // Specialized optimizations for each function call
739     switch (FInfo.getId()) {
740     case AMDGPULibFunc::EI_READ_PIPE_2:
741     case AMDGPULibFunc::EI_READ_PIPE_4:
742     case AMDGPULibFunc::EI_WRITE_PIPE_2:
743     case AMDGPULibFunc::EI_WRITE_PIPE_4:
744       return fold_read_write_pipe(CI, B, FInfo);
745     default:
746       break;
747     }
748   }
749 
750   return false;
751 }
752 
753 bool AMDGPULibCalls::TDOFold(CallInst *CI, const FuncInfo &FInfo) {
754   // Table-Driven optimization
755   const TableRef tr = getOptTable(FInfo.getId());
756   if (tr.empty())
757     return false;
758 
759   int const sz = (int)tr.size();
760   Value *opr0 = CI->getArgOperand(0);
761 
762   if (getVecSize(FInfo) > 1) {
763     if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(opr0)) {
764       SmallVector<double, 0> DVal;
765       for (int eltNo = 0; eltNo < getVecSize(FInfo); ++eltNo) {
766         ConstantFP *eltval = dyn_cast<ConstantFP>(
767                                CV->getElementAsConstant((unsigned)eltNo));
768         assert(eltval && "Non-FP arguments in math function!");
769         bool found = false;
770         for (int i=0; i < sz; ++i) {
771           if (eltval->isExactlyValue(tr[i].input)) {
772             DVal.push_back(tr[i].result);
773             found = true;
774             break;
775           }
776         }
777         if (!found) {
778           // This vector constants not handled yet.
779           return false;
780         }
781       }
782       LLVMContext &context = CI->getParent()->getParent()->getContext();
783       Constant *nval;
784       if (getArgType(FInfo) == AMDGPULibFunc::F32) {
785         SmallVector<float, 0> FVal;
786         for (unsigned i = 0; i < DVal.size(); ++i) {
787           FVal.push_back((float)DVal[i]);
788         }
789         ArrayRef<float> tmp(FVal);
790         nval = ConstantDataVector::get(context, tmp);
791       } else { // F64
792         ArrayRef<double> tmp(DVal);
793         nval = ConstantDataVector::get(context, tmp);
794       }
795       LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
796       replaceCall(CI, nval);
797       return true;
798     }
799   } else {
800     // Scalar version
801     if (ConstantFP *CF = dyn_cast<ConstantFP>(opr0)) {
802       for (int i = 0; i < sz; ++i) {
803         if (CF->isExactlyValue(tr[i].input)) {
804           Value *nval = ConstantFP::get(CF->getType(), tr[i].result);
805           LLVM_DEBUG(errs() << "AMDIC: " << *CI << " ---> " << *nval << "\n");
806           replaceCall(CI, nval);
807           return true;
808         }
809       }
810     }
811   }
812 
813   return false;
814 }
815 
816 namespace llvm {
817 static double log2(double V) {
818 #if _XOPEN_SOURCE >= 600 || defined(_ISOC99_SOURCE) || _POSIX_C_SOURCE >= 200112L
819   return ::log2(V);
820 #else
821   return log(V) / numbers::ln2;
822 #endif
823 }
824 }
825 
826 bool AMDGPULibCalls::fold_pow(FPMathOperator *FPOp, IRBuilder<> &B,
827                               const FuncInfo &FInfo) {
828   assert((FInfo.getId() == AMDGPULibFunc::EI_POW ||
829           FInfo.getId() == AMDGPULibFunc::EI_POWR ||
830           FInfo.getId() == AMDGPULibFunc::EI_POWN) &&
831          "fold_pow: encounter a wrong function call");
832 
833   Module *M = B.GetInsertBlock()->getModule();
834   Type *eltType = FPOp->getType()->getScalarType();
835   Value *opr0 = FPOp->getOperand(0);
836   Value *opr1 = FPOp->getOperand(1);
837 
838   const APFloat *CF = nullptr;
839   const APInt *CINT = nullptr;
840   if (!match(opr1, m_APFloatAllowUndef(CF)))
841     match(opr1, m_APIntAllowUndef(CINT));
842 
843   // 0x1111111 means that we don't do anything for this call.
844   int ci_opr1 = (CINT ? (int)CINT->getSExtValue() : 0x1111111);
845 
846   if ((CF && CF->isZero()) || (CINT && ci_opr1 == 0)) {
847     //  pow/powr/pown(x, 0) == 1
848     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1\n");
849     Constant *cnval = ConstantFP::get(eltType, 1.0);
850     if (getVecSize(FInfo) > 1) {
851       cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
852     }
853     replaceCall(FPOp, cnval);
854     return true;
855   }
856   if ((CF && CF->isExactlyValue(1.0)) || (CINT && ci_opr1 == 1)) {
857     // pow/powr/pown(x, 1.0) = x
858     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
859     replaceCall(FPOp, opr0);
860     return true;
861   }
862   if ((CF && CF->isExactlyValue(2.0)) || (CINT && ci_opr1 == 2)) {
863     // pow/powr/pown(x, 2.0) = x*x
864     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << " * "
865                       << *opr0 << "\n");
866     Value *nval = B.CreateFMul(opr0, opr0, "__pow2");
867     replaceCall(FPOp, nval);
868     return true;
869   }
870   if ((CF && CF->isExactlyValue(-1.0)) || (CINT && ci_opr1 == -1)) {
871     // pow/powr/pown(x, -1.0) = 1.0/x
872     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1 / " << *opr0 << "\n");
873     Constant *cnval = ConstantFP::get(eltType, 1.0);
874     if (getVecSize(FInfo) > 1) {
875       cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
876     }
877     Value *nval = B.CreateFDiv(cnval, opr0, "__powrecip");
878     replaceCall(FPOp, nval);
879     return true;
880   }
881 
882   if (CF && (CF->isExactlyValue(0.5) || CF->isExactlyValue(-0.5))) {
883     // pow[r](x, [-]0.5) = sqrt(x)
884     bool issqrt = CF->isExactlyValue(0.5);
885     if (FunctionCallee FPExpr =
886             getFunction(M, AMDGPULibFunc(issqrt ? AMDGPULibFunc::EI_SQRT
887                                                 : AMDGPULibFunc::EI_RSQRT,
888                                          FInfo))) {
889       LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << FInfo.getName()
890                         << '(' << *opr0 << ")\n");
891       Value *nval = CreateCallEx(B,FPExpr, opr0, issqrt ? "__pow2sqrt"
892                                                         : "__pow2rsqrt");
893       replaceCall(FPOp, nval);
894       return true;
895     }
896   }
897 
898   if (!isUnsafeFiniteOnlyMath(FPOp))
899     return false;
900 
901   // Unsafe Math optimization
902 
903   // Remember that ci_opr1 is set if opr1 is integral
904   if (CF) {
905     double dval = (getArgType(FInfo) == AMDGPULibFunc::F32)
906                       ? (double)CF->convertToFloat()
907                       : CF->convertToDouble();
908     int ival = (int)dval;
909     if ((double)ival == dval) {
910       ci_opr1 = ival;
911     } else
912       ci_opr1 = 0x11111111;
913   }
914 
915   // pow/powr/pown(x, c) = [1/](x*x*..x); where
916   //   trunc(c) == c && the number of x == c && |c| <= 12
917   unsigned abs_opr1 = (ci_opr1 < 0) ? -ci_opr1 : ci_opr1;
918   if (abs_opr1 <= 12) {
919     Constant *cnval;
920     Value *nval;
921     if (abs_opr1 == 0) {
922       cnval = ConstantFP::get(eltType, 1.0);
923       if (getVecSize(FInfo) > 1) {
924         cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
925       }
926       nval = cnval;
927     } else {
928       Value *valx2 = nullptr;
929       nval = nullptr;
930       while (abs_opr1 > 0) {
931         valx2 = valx2 ? B.CreateFMul(valx2, valx2, "__powx2") : opr0;
932         if (abs_opr1 & 1) {
933           nval = nval ? B.CreateFMul(nval, valx2, "__powprod") : valx2;
934         }
935         abs_opr1 >>= 1;
936       }
937     }
938 
939     if (ci_opr1 < 0) {
940       cnval = ConstantFP::get(eltType, 1.0);
941       if (getVecSize(FInfo) > 1) {
942         cnval = ConstantDataVector::getSplat(getVecSize(FInfo), cnval);
943       }
944       nval = B.CreateFDiv(cnval, nval, "__1powprod");
945     }
946     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
947                       << ((ci_opr1 < 0) ? "1/prod(" : "prod(") << *opr0
948                       << ")\n");
949     replaceCall(FPOp, nval);
950     return true;
951   }
952 
953   // powr ---> exp2(y * log2(x))
954   // pown/pow ---> powr(fabs(x), y) | (x & ((int)y << 31))
955   FunctionCallee ExpExpr =
956       getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_EXP2, FInfo));
957   if (!ExpExpr)
958     return false;
959 
960   bool needlog = false;
961   bool needabs = false;
962   bool needcopysign = false;
963   Constant *cnval = nullptr;
964   if (getVecSize(FInfo) == 1) {
965     CF = nullptr;
966     match(opr0, m_APFloatAllowUndef(CF));
967 
968     if (CF) {
969       double V = (getArgType(FInfo) == AMDGPULibFunc::F32)
970                      ? (double)CF->convertToFloat()
971                      : CF->convertToDouble();
972 
973       V = log2(std::abs(V));
974       cnval = ConstantFP::get(eltType, V);
975       needcopysign = (FInfo.getId() != AMDGPULibFunc::EI_POWR) &&
976                      CF->isNegative();
977     } else {
978       needlog = true;
979       needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR &&
980                                (!CF || CF->isNegative());
981     }
982   } else {
983     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(opr0);
984 
985     if (!CDV) {
986       needlog = true;
987       needcopysign = needabs = FInfo.getId() != AMDGPULibFunc::EI_POWR;
988     } else {
989       assert ((int)CDV->getNumElements() == getVecSize(FInfo) &&
990               "Wrong vector size detected");
991 
992       SmallVector<double, 0> DVal;
993       for (int i=0; i < getVecSize(FInfo); ++i) {
994         double V = CDV->getElementAsAPFloat(i).convertToDouble();
995         if (V < 0.0) needcopysign = true;
996         V = log2(std::abs(V));
997         DVal.push_back(V);
998       }
999       if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1000         SmallVector<float, 0> FVal;
1001         for (unsigned i=0; i < DVal.size(); ++i) {
1002           FVal.push_back((float)DVal[i]);
1003         }
1004         ArrayRef<float> tmp(FVal);
1005         cnval = ConstantDataVector::get(M->getContext(), tmp);
1006       } else {
1007         ArrayRef<double> tmp(DVal);
1008         cnval = ConstantDataVector::get(M->getContext(), tmp);
1009       }
1010     }
1011   }
1012 
1013   if (needcopysign && (FInfo.getId() == AMDGPULibFunc::EI_POW)) {
1014     // We cannot handle corner cases for a general pow() function, give up
1015     // unless y is a constant integral value. Then proceed as if it were pown.
1016     if (!isKnownIntegral(opr1))
1017       return false;
1018   }
1019 
1020   Value *nval;
1021   if (needabs) {
1022     nval = B.CreateUnaryIntrinsic(Intrinsic::fabs, opr0, nullptr, "__fabs");
1023   } else {
1024     nval = cnval ? cnval : opr0;
1025   }
1026   if (needlog) {
1027     FunctionCallee LogExpr =
1028         getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_LOG2, FInfo));
1029     if (!LogExpr)
1030       return false;
1031     nval = CreateCallEx(B,LogExpr, nval, "__log2");
1032   }
1033 
1034   if (FInfo.getId() == AMDGPULibFunc::EI_POWN) {
1035     // convert int(32) to fp(f32 or f64)
1036     opr1 = B.CreateSIToFP(opr1, nval->getType(), "pownI2F");
1037   }
1038   nval = B.CreateFMul(opr1, nval, "__ylogx");
1039   nval = CreateCallEx(B,ExpExpr, nval, "__exp2");
1040 
1041   if (needcopysign) {
1042     Value *opr_n;
1043     Type* rTy = opr0->getType();
1044     Type* nTyS = B.getIntNTy(eltType->getPrimitiveSizeInBits());
1045     Type *nTy = nTyS;
1046     if (const auto *vTy = dyn_cast<FixedVectorType>(rTy))
1047       nTy = FixedVectorType::get(nTyS, vTy);
1048     unsigned size = nTy->getScalarSizeInBits();
1049     opr_n = FPOp->getOperand(1);
1050     if (opr_n->getType()->isIntegerTy())
1051       opr_n = B.CreateZExtOrTrunc(opr_n, nTy, "__ytou");
1052     else
1053       opr_n = B.CreateFPToSI(opr1, nTy, "__ytou");
1054 
1055     Value *sign = B.CreateShl(opr_n, size-1, "__yeven");
1056     sign = B.CreateAnd(B.CreateBitCast(opr0, nTy), sign, "__pow_sign");
1057     nval = B.CreateOr(B.CreateBitCast(nval, nTy), sign);
1058     nval = B.CreateBitCast(nval, opr0->getType());
1059   }
1060 
1061   LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1062                     << "exp2(" << *opr1 << " * log2(" << *opr0 << "))\n");
1063   replaceCall(FPOp, nval);
1064 
1065   return true;
1066 }
1067 
1068 bool AMDGPULibCalls::fold_rootn(FPMathOperator *FPOp, IRBuilder<> &B,
1069                                 const FuncInfo &FInfo) {
1070   // skip vector function
1071   if (getVecSize(FInfo) != 1)
1072     return false;
1073 
1074   Value *opr0 = FPOp->getOperand(0);
1075   Value *opr1 = FPOp->getOperand(1);
1076 
1077   ConstantInt *CINT = dyn_cast<ConstantInt>(opr1);
1078   if (!CINT) {
1079     return false;
1080   }
1081   int ci_opr1 = (int)CINT->getSExtValue();
1082   if (ci_opr1 == 1) {  // rootn(x, 1) = x
1083     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> " << *opr0 << "\n");
1084     replaceCall(FPOp, opr0);
1085     return true;
1086   }
1087 
1088   Module *M = B.GetInsertBlock()->getModule();
1089   if (ci_opr1 == 2) { // rootn(x, 2) = sqrt(x)
1090     if (FunctionCallee FPExpr =
1091             getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1092       LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> sqrt(" << *opr0
1093                         << ")\n");
1094       Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2sqrt");
1095       replaceCall(FPOp, nval);
1096       return true;
1097     }
1098   } else if (ci_opr1 == 3) { // rootn(x, 3) = cbrt(x)
1099     if (FunctionCallee FPExpr =
1100             getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_CBRT, FInfo))) {
1101       LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> cbrt(" << *opr0
1102                         << ")\n");
1103       Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2cbrt");
1104       replaceCall(FPOp, nval);
1105       return true;
1106     }
1107   } else if (ci_opr1 == -1) { // rootn(x, -1) = 1.0/x
1108     LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> 1.0 / " << *opr0 << "\n");
1109     Value *nval = B.CreateFDiv(ConstantFP::get(opr0->getType(), 1.0),
1110                                opr0,
1111                                "__rootn2div");
1112     replaceCall(FPOp, nval);
1113     return true;
1114   } else if (ci_opr1 == -2) { // rootn(x, -2) = rsqrt(x)
1115     if (FunctionCallee FPExpr =
1116             getFunction(M, AMDGPULibFunc(AMDGPULibFunc::EI_RSQRT, FInfo))) {
1117       LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> rsqrt(" << *opr0
1118                         << ")\n");
1119       Value *nval = CreateCallEx(B,FPExpr, opr0, "__rootn2rsqrt");
1120       replaceCall(FPOp, nval);
1121       return true;
1122     }
1123   }
1124   return false;
1125 }
1126 
1127 // Get a scalar native builtin single argument FP function
1128 FunctionCallee AMDGPULibCalls::getNativeFunction(Module *M,
1129                                                  const FuncInfo &FInfo) {
1130   if (getArgType(FInfo) == AMDGPULibFunc::F64 || !HasNative(FInfo.getId()))
1131     return nullptr;
1132   FuncInfo nf = FInfo;
1133   nf.setPrefix(AMDGPULibFunc::NATIVE);
1134   return getFunction(M, nf);
1135 }
1136 
1137 // Some library calls are just wrappers around llvm intrinsics, but compiled
1138 // conservatively. Preserve the flags from the original call site by
1139 // substituting them with direct calls with all the flags.
1140 bool AMDGPULibCalls::shouldReplaceLibcallWithIntrinsic(const CallInst *CI,
1141                                                        bool AllowMinSizeF32,
1142                                                        bool AllowF64,
1143                                                        bool AllowStrictFP) {
1144   Type *FltTy = CI->getType()->getScalarType();
1145   const bool IsF32 = FltTy->isFloatTy();
1146 
1147   // f64 intrinsics aren't implemented for most operations.
1148   if (!IsF32 && !FltTy->isHalfTy() && (!AllowF64 || !FltTy->isDoubleTy()))
1149     return false;
1150 
1151   // We're implicitly inlining by replacing the libcall with the intrinsic, so
1152   // don't do it for noinline call sites.
1153   if (CI->isNoInline())
1154     return false;
1155 
1156   const Function *ParentF = CI->getFunction();
1157   // TODO: Handle strictfp
1158   if (!AllowStrictFP && ParentF->hasFnAttribute(Attribute::StrictFP))
1159     return false;
1160 
1161   if (IsF32 && !AllowMinSizeF32 && ParentF->hasMinSize())
1162     return false;
1163   return true;
1164 }
1165 
1166 void AMDGPULibCalls::replaceLibCallWithSimpleIntrinsic(IRBuilder<> &B,
1167                                                        CallInst *CI,
1168                                                        Intrinsic::ID IntrID) {
1169   if (CI->arg_size() == 2) {
1170     Value *Arg0 = CI->getArgOperand(0);
1171     Value *Arg1 = CI->getArgOperand(1);
1172     VectorType *Arg0VecTy = dyn_cast<VectorType>(Arg0->getType());
1173     VectorType *Arg1VecTy = dyn_cast<VectorType>(Arg1->getType());
1174     if (Arg0VecTy && !Arg1VecTy) {
1175       Value *SplatRHS = B.CreateVectorSplat(Arg0VecTy->getElementCount(), Arg1);
1176       CI->setArgOperand(1, SplatRHS);
1177     } else if (!Arg0VecTy && Arg1VecTy) {
1178       Value *SplatLHS = B.CreateVectorSplat(Arg1VecTy->getElementCount(), Arg0);
1179       CI->setArgOperand(0, SplatLHS);
1180     }
1181   }
1182 
1183   CI->setCalledFunction(
1184       Intrinsic::getDeclaration(CI->getModule(), IntrID, {CI->getType()}));
1185 }
1186 
1187 bool AMDGPULibCalls::tryReplaceLibcallWithSimpleIntrinsic(
1188     IRBuilder<> &B, CallInst *CI, Intrinsic::ID IntrID, bool AllowMinSizeF32,
1189     bool AllowF64, bool AllowStrictFP) {
1190   if (!shouldReplaceLibcallWithIntrinsic(CI, AllowMinSizeF32, AllowF64,
1191                                          AllowStrictFP))
1192     return false;
1193   replaceLibCallWithSimpleIntrinsic(B, CI, IntrID);
1194   return true;
1195 }
1196 
1197 // fold sqrt -> native_sqrt (x)
1198 bool AMDGPULibCalls::fold_sqrt(FPMathOperator *FPOp, IRBuilder<> &B,
1199                                const FuncInfo &FInfo) {
1200   if (!isUnsafeMath(FPOp))
1201     return false;
1202 
1203   if (getArgType(FInfo) == AMDGPULibFunc::F32 && (getVecSize(FInfo) == 1) &&
1204       (FInfo.getPrefix() != AMDGPULibFunc::NATIVE)) {
1205     Module *M = B.GetInsertBlock()->getModule();
1206 
1207     if (FunctionCallee FPExpr = getNativeFunction(
1208             M, AMDGPULibFunc(AMDGPULibFunc::EI_SQRT, FInfo))) {
1209       Value *opr0 = FPOp->getOperand(0);
1210       LLVM_DEBUG(errs() << "AMDIC: " << *FPOp << " ---> "
1211                         << "sqrt(" << *opr0 << ")\n");
1212       Value *nval = CreateCallEx(B,FPExpr, opr0, "__sqrt");
1213       replaceCall(FPOp, nval);
1214       return true;
1215     }
1216   }
1217   return false;
1218 }
1219 
1220 std::tuple<Value *, Value *, Value *>
1221 AMDGPULibCalls::insertSinCos(Value *Arg, FastMathFlags FMF, IRBuilder<> &B,
1222                              FunctionCallee Fsincos) {
1223   DebugLoc DL = B.getCurrentDebugLocation();
1224   Function *F = B.GetInsertBlock()->getParent();
1225   B.SetInsertPointPastAllocas(F);
1226 
1227   AllocaInst *Alloc = B.CreateAlloca(Arg->getType(), nullptr, "__sincos_");
1228 
1229   if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
1230     // If the argument is an instruction, it must dominate all uses so put our
1231     // sincos call there. Otherwise, right after the allocas works well enough
1232     // if it's an argument or constant.
1233 
1234     B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
1235 
1236     // SetInsertPoint unwelcomely always tries to set the debug loc.
1237     B.SetCurrentDebugLocation(DL);
1238   }
1239 
1240   Type *CosPtrTy = Fsincos.getFunctionType()->getParamType(1);
1241 
1242   // The allocaInst allocates the memory in private address space. This need
1243   // to be addrspacecasted to point to the address space of cos pointer type.
1244   // In OpenCL 2.0 this is generic, while in 1.2 that is private.
1245   Value *CastAlloc = B.CreateAddrSpaceCast(Alloc, CosPtrTy);
1246 
1247   CallInst *SinCos = CreateCallEx2(B, Fsincos, Arg, CastAlloc);
1248 
1249   // TODO: Is it worth trying to preserve the location for the cos calls for the
1250   // load?
1251 
1252   LoadInst *LoadCos = B.CreateLoad(Alloc->getAllocatedType(), Alloc);
1253   return {SinCos, LoadCos, SinCos};
1254 }
1255 
1256 // fold sin, cos -> sincos.
1257 bool AMDGPULibCalls::fold_sincos(FPMathOperator *FPOp, IRBuilder<> &B,
1258                                  const FuncInfo &fInfo) {
1259   assert(fInfo.getId() == AMDGPULibFunc::EI_SIN ||
1260          fInfo.getId() == AMDGPULibFunc::EI_COS);
1261 
1262   if ((getArgType(fInfo) != AMDGPULibFunc::F32 &&
1263        getArgType(fInfo) != AMDGPULibFunc::F64) ||
1264       fInfo.getPrefix() != AMDGPULibFunc::NOPFX)
1265     return false;
1266 
1267   bool const isSin = fInfo.getId() == AMDGPULibFunc::EI_SIN;
1268 
1269   Value *CArgVal = FPOp->getOperand(0);
1270   CallInst *CI = cast<CallInst>(FPOp);
1271 
1272   Function *F = B.GetInsertBlock()->getParent();
1273   Module *M = F->getParent();
1274 
1275   // Merge the sin and cos. For OpenCL 2.0, there may only be a generic pointer
1276   // implementation. Prefer the private form if available.
1277   AMDGPULibFunc SinCosLibFuncPrivate(AMDGPULibFunc::EI_SINCOS, fInfo);
1278   SinCosLibFuncPrivate.getLeads()[0].PtrKind =
1279       AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::PRIVATE_ADDRESS);
1280 
1281   AMDGPULibFunc SinCosLibFuncGeneric(AMDGPULibFunc::EI_SINCOS, fInfo);
1282   SinCosLibFuncGeneric.getLeads()[0].PtrKind =
1283       AMDGPULibFunc::getEPtrKindFromAddrSpace(AMDGPUAS::FLAT_ADDRESS);
1284 
1285   FunctionCallee FSinCosPrivate = getFunction(M, SinCosLibFuncPrivate);
1286   FunctionCallee FSinCosGeneric = getFunction(M, SinCosLibFuncGeneric);
1287   FunctionCallee FSinCos = FSinCosPrivate ? FSinCosPrivate : FSinCosGeneric;
1288   if (!FSinCos)
1289     return false;
1290 
1291   SmallVector<CallInst *> SinCalls;
1292   SmallVector<CallInst *> CosCalls;
1293   SmallVector<CallInst *> SinCosCalls;
1294   FuncInfo PartnerInfo(isSin ? AMDGPULibFunc::EI_COS : AMDGPULibFunc::EI_SIN,
1295                        fInfo);
1296   const std::string PairName = PartnerInfo.mangle();
1297 
1298   StringRef SinName = isSin ? CI->getCalledFunction()->getName() : PairName;
1299   StringRef CosName = isSin ? PairName : CI->getCalledFunction()->getName();
1300   const std::string SinCosPrivateName = SinCosLibFuncPrivate.mangle();
1301   const std::string SinCosGenericName = SinCosLibFuncGeneric.mangle();
1302 
1303   // Intersect the two sets of flags.
1304   FastMathFlags FMF = FPOp->getFastMathFlags();
1305   MDNode *FPMath = CI->getMetadata(LLVMContext::MD_fpmath);
1306 
1307   SmallVector<DILocation *> MergeDbgLocs = {CI->getDebugLoc()};
1308 
1309   for (User* U : CArgVal->users()) {
1310     CallInst *XI = dyn_cast<CallInst>(U);
1311     if (!XI || XI->getFunction() != F || XI->isNoBuiltin())
1312       continue;
1313 
1314     Function *UCallee = XI->getCalledFunction();
1315     if (!UCallee)
1316       continue;
1317 
1318     bool Handled = true;
1319 
1320     if (UCallee->getName() == SinName)
1321       SinCalls.push_back(XI);
1322     else if (UCallee->getName() == CosName)
1323       CosCalls.push_back(XI);
1324     else if (UCallee->getName() == SinCosPrivateName ||
1325              UCallee->getName() == SinCosGenericName)
1326       SinCosCalls.push_back(XI);
1327     else
1328       Handled = false;
1329 
1330     if (Handled) {
1331       MergeDbgLocs.push_back(XI->getDebugLoc());
1332       auto *OtherOp = cast<FPMathOperator>(XI);
1333       FMF &= OtherOp->getFastMathFlags();
1334       FPMath = MDNode::getMostGenericFPMath(
1335           FPMath, XI->getMetadata(LLVMContext::MD_fpmath));
1336     }
1337   }
1338 
1339   if (SinCalls.empty() || CosCalls.empty())
1340     return false;
1341 
1342   B.setFastMathFlags(FMF);
1343   B.setDefaultFPMathTag(FPMath);
1344   DILocation *DbgLoc = DILocation::getMergedLocations(MergeDbgLocs);
1345   B.SetCurrentDebugLocation(DbgLoc);
1346 
1347   auto [Sin, Cos, SinCos] = insertSinCos(CArgVal, FMF, B, FSinCos);
1348 
1349   auto replaceTrigInsts = [](ArrayRef<CallInst *> Calls, Value *Res) {
1350     for (CallInst *C : Calls)
1351       C->replaceAllUsesWith(Res);
1352 
1353     // Leave the other dead instructions to avoid clobbering iterators.
1354   };
1355 
1356   replaceTrigInsts(SinCalls, Sin);
1357   replaceTrigInsts(CosCalls, Cos);
1358   replaceTrigInsts(SinCosCalls, SinCos);
1359 
1360   // It's safe to delete the original now.
1361   CI->eraseFromParent();
1362   return true;
1363 }
1364 
1365 bool AMDGPULibCalls::evaluateScalarMathFunc(const FuncInfo &FInfo, double &Res0,
1366                                             double &Res1, Constant *copr0,
1367                                             Constant *copr1) {
1368   // By default, opr0/opr1/opr3 holds values of float/double type.
1369   // If they are not float/double, each function has to its
1370   // operand separately.
1371   double opr0 = 0.0, opr1 = 0.0;
1372   ConstantFP *fpopr0 = dyn_cast_or_null<ConstantFP>(copr0);
1373   ConstantFP *fpopr1 = dyn_cast_or_null<ConstantFP>(copr1);
1374   if (fpopr0) {
1375     opr0 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1376              ? fpopr0->getValueAPF().convertToDouble()
1377              : (double)fpopr0->getValueAPF().convertToFloat();
1378   }
1379 
1380   if (fpopr1) {
1381     opr1 = (getArgType(FInfo) == AMDGPULibFunc::F64)
1382              ? fpopr1->getValueAPF().convertToDouble()
1383              : (double)fpopr1->getValueAPF().convertToFloat();
1384   }
1385 
1386   switch (FInfo.getId()) {
1387   default : return false;
1388 
1389   case AMDGPULibFunc::EI_ACOS:
1390     Res0 = acos(opr0);
1391     return true;
1392 
1393   case AMDGPULibFunc::EI_ACOSH:
1394     // acosh(x) == log(x + sqrt(x*x - 1))
1395     Res0 = log(opr0 + sqrt(opr0*opr0 - 1.0));
1396     return true;
1397 
1398   case AMDGPULibFunc::EI_ACOSPI:
1399     Res0 = acos(opr0) / MATH_PI;
1400     return true;
1401 
1402   case AMDGPULibFunc::EI_ASIN:
1403     Res0 = asin(opr0);
1404     return true;
1405 
1406   case AMDGPULibFunc::EI_ASINH:
1407     // asinh(x) == log(x + sqrt(x*x + 1))
1408     Res0 = log(opr0 + sqrt(opr0*opr0 + 1.0));
1409     return true;
1410 
1411   case AMDGPULibFunc::EI_ASINPI:
1412     Res0 = asin(opr0) / MATH_PI;
1413     return true;
1414 
1415   case AMDGPULibFunc::EI_ATAN:
1416     Res0 = atan(opr0);
1417     return true;
1418 
1419   case AMDGPULibFunc::EI_ATANH:
1420     // atanh(x) == (log(x+1) - log(x-1))/2;
1421     Res0 = (log(opr0 + 1.0) - log(opr0 - 1.0))/2.0;
1422     return true;
1423 
1424   case AMDGPULibFunc::EI_ATANPI:
1425     Res0 = atan(opr0) / MATH_PI;
1426     return true;
1427 
1428   case AMDGPULibFunc::EI_CBRT:
1429     Res0 = (opr0 < 0.0) ? -pow(-opr0, 1.0/3.0) : pow(opr0, 1.0/3.0);
1430     return true;
1431 
1432   case AMDGPULibFunc::EI_COS:
1433     Res0 = cos(opr0);
1434     return true;
1435 
1436   case AMDGPULibFunc::EI_COSH:
1437     Res0 = cosh(opr0);
1438     return true;
1439 
1440   case AMDGPULibFunc::EI_COSPI:
1441     Res0 = cos(MATH_PI * opr0);
1442     return true;
1443 
1444   case AMDGPULibFunc::EI_EXP:
1445     Res0 = exp(opr0);
1446     return true;
1447 
1448   case AMDGPULibFunc::EI_EXP2:
1449     Res0 = pow(2.0, opr0);
1450     return true;
1451 
1452   case AMDGPULibFunc::EI_EXP10:
1453     Res0 = pow(10.0, opr0);
1454     return true;
1455 
1456   case AMDGPULibFunc::EI_LOG:
1457     Res0 = log(opr0);
1458     return true;
1459 
1460   case AMDGPULibFunc::EI_LOG2:
1461     Res0 = log(opr0) / log(2.0);
1462     return true;
1463 
1464   case AMDGPULibFunc::EI_LOG10:
1465     Res0 = log(opr0) / log(10.0);
1466     return true;
1467 
1468   case AMDGPULibFunc::EI_RSQRT:
1469     Res0 = 1.0 / sqrt(opr0);
1470     return true;
1471 
1472   case AMDGPULibFunc::EI_SIN:
1473     Res0 = sin(opr0);
1474     return true;
1475 
1476   case AMDGPULibFunc::EI_SINH:
1477     Res0 = sinh(opr0);
1478     return true;
1479 
1480   case AMDGPULibFunc::EI_SINPI:
1481     Res0 = sin(MATH_PI * opr0);
1482     return true;
1483 
1484   case AMDGPULibFunc::EI_TAN:
1485     Res0 = tan(opr0);
1486     return true;
1487 
1488   case AMDGPULibFunc::EI_TANH:
1489     Res0 = tanh(opr0);
1490     return true;
1491 
1492   case AMDGPULibFunc::EI_TANPI:
1493     Res0 = tan(MATH_PI * opr0);
1494     return true;
1495 
1496   // two-arg functions
1497   case AMDGPULibFunc::EI_POW:
1498   case AMDGPULibFunc::EI_POWR:
1499     Res0 = pow(opr0, opr1);
1500     return true;
1501 
1502   case AMDGPULibFunc::EI_POWN: {
1503     if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1504       double val = (double)iopr1->getSExtValue();
1505       Res0 = pow(opr0, val);
1506       return true;
1507     }
1508     return false;
1509   }
1510 
1511   case AMDGPULibFunc::EI_ROOTN: {
1512     if (ConstantInt *iopr1 = dyn_cast_or_null<ConstantInt>(copr1)) {
1513       double val = (double)iopr1->getSExtValue();
1514       Res0 = pow(opr0, 1.0 / val);
1515       return true;
1516     }
1517     return false;
1518   }
1519 
1520   // with ptr arg
1521   case AMDGPULibFunc::EI_SINCOS:
1522     Res0 = sin(opr0);
1523     Res1 = cos(opr0);
1524     return true;
1525   }
1526 
1527   return false;
1528 }
1529 
1530 bool AMDGPULibCalls::evaluateCall(CallInst *aCI, const FuncInfo &FInfo) {
1531   int numArgs = (int)aCI->arg_size();
1532   if (numArgs > 3)
1533     return false;
1534 
1535   Constant *copr0 = nullptr;
1536   Constant *copr1 = nullptr;
1537   if (numArgs > 0) {
1538     if ((copr0 = dyn_cast<Constant>(aCI->getArgOperand(0))) == nullptr)
1539       return false;
1540   }
1541 
1542   if (numArgs > 1) {
1543     if ((copr1 = dyn_cast<Constant>(aCI->getArgOperand(1))) == nullptr) {
1544       if (FInfo.getId() != AMDGPULibFunc::EI_SINCOS)
1545         return false;
1546     }
1547   }
1548 
1549   // At this point, all arguments to aCI are constants.
1550 
1551   // max vector size is 16, and sincos will generate two results.
1552   double DVal0[16], DVal1[16];
1553   int FuncVecSize = getVecSize(FInfo);
1554   bool hasTwoResults = (FInfo.getId() == AMDGPULibFunc::EI_SINCOS);
1555   if (FuncVecSize == 1) {
1556     if (!evaluateScalarMathFunc(FInfo, DVal0[0], DVal1[0], copr0, copr1)) {
1557       return false;
1558     }
1559   } else {
1560     ConstantDataVector *CDV0 = dyn_cast_or_null<ConstantDataVector>(copr0);
1561     ConstantDataVector *CDV1 = dyn_cast_or_null<ConstantDataVector>(copr1);
1562     for (int i = 0; i < FuncVecSize; ++i) {
1563       Constant *celt0 = CDV0 ? CDV0->getElementAsConstant(i) : nullptr;
1564       Constant *celt1 = CDV1 ? CDV1->getElementAsConstant(i) : nullptr;
1565       if (!evaluateScalarMathFunc(FInfo, DVal0[i], DVal1[i], celt0, celt1)) {
1566         return false;
1567       }
1568     }
1569   }
1570 
1571   LLVMContext &context = aCI->getContext();
1572   Constant *nval0, *nval1;
1573   if (FuncVecSize == 1) {
1574     nval0 = ConstantFP::get(aCI->getType(), DVal0[0]);
1575     if (hasTwoResults)
1576       nval1 = ConstantFP::get(aCI->getType(), DVal1[0]);
1577   } else {
1578     if (getArgType(FInfo) == AMDGPULibFunc::F32) {
1579       SmallVector <float, 0> FVal0, FVal1;
1580       for (int i = 0; i < FuncVecSize; ++i)
1581         FVal0.push_back((float)DVal0[i]);
1582       ArrayRef<float> tmp0(FVal0);
1583       nval0 = ConstantDataVector::get(context, tmp0);
1584       if (hasTwoResults) {
1585         for (int i = 0; i < FuncVecSize; ++i)
1586           FVal1.push_back((float)DVal1[i]);
1587         ArrayRef<float> tmp1(FVal1);
1588         nval1 = ConstantDataVector::get(context, tmp1);
1589       }
1590     } else {
1591       ArrayRef<double> tmp0(DVal0);
1592       nval0 = ConstantDataVector::get(context, tmp0);
1593       if (hasTwoResults) {
1594         ArrayRef<double> tmp1(DVal1);
1595         nval1 = ConstantDataVector::get(context, tmp1);
1596       }
1597     }
1598   }
1599 
1600   if (hasTwoResults) {
1601     // sincos
1602     assert(FInfo.getId() == AMDGPULibFunc::EI_SINCOS &&
1603            "math function with ptr arg not supported yet");
1604     new StoreInst(nval1, aCI->getArgOperand(1), aCI);
1605   }
1606 
1607   replaceCall(aCI, nval0);
1608   return true;
1609 }
1610 
1611 PreservedAnalyses AMDGPUSimplifyLibCallsPass::run(Function &F,
1612                                                   FunctionAnalysisManager &AM) {
1613   AMDGPULibCalls Simplifier;
1614   Simplifier.initNativeFuncs();
1615   Simplifier.initFunction(F, AM);
1616 
1617   bool Changed = false;
1618 
1619   LLVM_DEBUG(dbgs() << "AMDIC: process function ";
1620              F.printAsOperand(dbgs(), false, F.getParent()); dbgs() << '\n';);
1621 
1622   for (auto &BB : F) {
1623     for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1624       // Ignore non-calls.
1625       CallInst *CI = dyn_cast<CallInst>(I);
1626       ++I;
1627 
1628       if (CI) {
1629         if (Simplifier.fold(CI))
1630           Changed = true;
1631       }
1632     }
1633   }
1634   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1635 }
1636 
1637 PreservedAnalyses AMDGPUUseNativeCallsPass::run(Function &F,
1638                                                 FunctionAnalysisManager &AM) {
1639   if (UseNative.empty())
1640     return PreservedAnalyses::all();
1641 
1642   AMDGPULibCalls Simplifier;
1643   Simplifier.initNativeFuncs();
1644   Simplifier.initFunction(F, AM);
1645 
1646   bool Changed = false;
1647   for (auto &BB : F) {
1648     for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E;) {
1649       // Ignore non-calls.
1650       CallInst *CI = dyn_cast<CallInst>(I);
1651       ++I;
1652       if (CI && Simplifier.useNative(CI))
1653         Changed = true;
1654     }
1655   }
1656   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
1657 }
1658