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