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