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