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