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