1 //===-- IPO/OpenMPOpt.cpp - Collection of OpenMP specific optimizations ---===// 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 // OpenMP specific optimizations: 10 // 11 // - Deduplication of runtime calls, e.g., omp_get_thread_num. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/IPO/OpenMPOpt.h" 16 17 #include "llvm/ADT/EnumeratedArray.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/CallGraph.h" 20 #include "llvm/Analysis/CallGraphSCCPass.h" 21 #include "llvm/Frontend/OpenMP/OMPConstants.h" 22 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 23 #include "llvm/IR/CallSite.h" 24 #include "llvm/InitializePasses.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Transforms/IPO.h" 27 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 28 29 using namespace llvm; 30 using namespace omp; 31 using namespace types; 32 33 #define DEBUG_TYPE "openmp-opt" 34 35 static cl::opt<bool> DisableOpenMPOptimizations( 36 "openmp-opt-disable", cl::ZeroOrMore, 37 cl::desc("Disable OpenMP specific optimizations."), cl::Hidden, 38 cl::init(false)); 39 40 STATISTIC(NumOpenMPRuntimeCallsDeduplicated, 41 "Number of OpenMP runtime calls deduplicated"); 42 STATISTIC(NumOpenMPRuntimeFunctionsIdentified, 43 "Number of OpenMP runtime functions identified"); 44 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified, 45 "Number of OpenMP runtime function uses identified"); 46 47 #if !defined(NDEBUG) 48 static constexpr auto TAG = "[" DEBUG_TYPE "]"; 49 #endif 50 51 namespace { 52 struct OpenMPOpt { 53 54 OpenMPOpt(SmallPtrSetImpl<Function *> &SCC, 55 SmallPtrSetImpl<Function *> &ModuleSlice, 56 CallGraphUpdater &CGUpdater) 57 : M(*(*SCC.begin())->getParent()), SCC(SCC), ModuleSlice(ModuleSlice), 58 OMPBuilder(M), CGUpdater(CGUpdater) { 59 initializeTypes(M); 60 initializeRuntimeFunctions(); 61 OMPBuilder.initialize(); 62 } 63 64 /// Generic information that describes a runtime function 65 struct RuntimeFunctionInfo { 66 /// The kind, as described by the RuntimeFunction enum. 67 RuntimeFunction Kind; 68 69 /// The name of the function. 70 StringRef Name; 71 72 /// Flag to indicate a variadic function. 73 bool IsVarArg; 74 75 /// The return type of the function. 76 Type *ReturnType; 77 78 /// The argument types of the function. 79 SmallVector<Type *, 8> ArgumentTypes; 80 81 /// The declaration if available. 82 Function *Declaration; 83 84 /// Uses of this runtime function per function containing the use. 85 DenseMap<Function *, SmallPtrSet<Use *, 16>> UsesMap; 86 87 /// Return the number of arguments (or the minimal number for variadic 88 /// functions). 89 size_t getNumArgs() const { return ArgumentTypes.size(); } 90 91 /// Run the callback \p CB on each use and forget the use if the result is 92 /// true. The callback will be fed the function in which the use was 93 /// encountered as second argument. 94 void foreachUse(function_ref<bool(Use &, Function &)> CB) { 95 SmallVector<Use *, 8> ToBeDeleted; 96 for (auto &It : UsesMap) { 97 ToBeDeleted.clear(); 98 for (Use *U : It.second) 99 if (CB(*U, *It.first)) 100 ToBeDeleted.push_back(U); 101 for (Use *U : ToBeDeleted) 102 It.second.erase(U); 103 } 104 } 105 }; 106 107 /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice. 108 bool run() { 109 bool Changed = false; 110 111 LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size() 112 << " functions in a slice with " << ModuleSlice.size() 113 << " functions\n"); 114 115 Changed |= deduplicateRuntimeCalls(); 116 Changed |= deleteParallelRegions(); 117 118 return Changed; 119 } 120 121 private: 122 /// Try to delete parallel regions if possible 123 bool deleteParallelRegions() { 124 const unsigned CallbackCalleeOperand = 2; 125 126 RuntimeFunctionInfo &RFI = RFIs[OMPRTL___kmpc_fork_call]; 127 if (!RFI.Declaration) 128 return false; 129 130 bool Changed = false; 131 auto DeleteCallCB = [&](Use &U, Function &) { 132 CallInst *CI = getCallIfRegularCall(U); 133 if (!CI) 134 return false; 135 auto *Fn = dyn_cast<Function>( 136 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts()); 137 if (!Fn) 138 return false; 139 if (!Fn->onlyReadsMemory()) 140 return false; 141 if (!Fn->hasFnAttribute(Attribute::WillReturn)) 142 return false; 143 144 LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in " 145 << CI->getCaller()->getName() << "\n"); 146 CGUpdater.removeCallSite(*CI); 147 CI->eraseFromParent(); 148 Changed = true; 149 return true; 150 }; 151 152 RFI.foreachUse(DeleteCallCB); 153 154 return Changed; 155 } 156 157 /// Try to eliminiate runtime calls by reusing existing ones. 158 bool deduplicateRuntimeCalls() { 159 bool Changed = false; 160 161 RuntimeFunction DeduplicableRuntimeCallIDs[] = { 162 OMPRTL_omp_get_num_threads, 163 OMPRTL_omp_in_parallel, 164 OMPRTL_omp_get_cancellation, 165 OMPRTL_omp_get_thread_limit, 166 OMPRTL_omp_get_supported_active_levels, 167 OMPRTL_omp_get_level, 168 OMPRTL_omp_get_ancestor_thread_num, 169 OMPRTL_omp_get_team_size, 170 OMPRTL_omp_get_active_level, 171 OMPRTL_omp_in_final, 172 OMPRTL_omp_get_proc_bind, 173 OMPRTL_omp_get_num_places, 174 OMPRTL_omp_get_num_procs, 175 OMPRTL_omp_get_place_num, 176 OMPRTL_omp_get_partition_num_places, 177 OMPRTL_omp_get_partition_place_nums}; 178 179 // Global-tid is handled separatly. 180 SmallSetVector<Value *, 16> GTIdArgs; 181 collectGlobalThreadIdArguments(GTIdArgs); 182 LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size() 183 << " global thread ID arguments\n"); 184 185 for (Function *F : SCC) { 186 for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs) 187 deduplicateRuntimeCalls(*F, RFIs[DeduplicableRuntimeCallID]); 188 189 // __kmpc_global_thread_num is special as we can replace it with an 190 // argument in enough cases to make it worth trying. 191 Value *GTIdArg = nullptr; 192 for (Argument &Arg : F->args()) 193 if (GTIdArgs.count(&Arg)) { 194 GTIdArg = &Arg; 195 break; 196 } 197 Changed |= deduplicateRuntimeCalls( 198 *F, RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg); 199 } 200 201 return Changed; 202 } 203 204 static Value *combinedIdentStruct(Value *Ident0, Value *Ident1, 205 bool GlobalOnly) { 206 // TODO: Figure out how to actually combine multiple debug locations. For 207 // now we just keep the first we find. 208 if (Ident0) 209 return Ident0; 210 if (!GlobalOnly || isa<GlobalValue>(Ident1)) 211 return Ident1; 212 return nullptr; 213 } 214 215 /// Return an `struct ident_t*` value that represents the ones used in the 216 /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not 217 /// return a local `struct ident_t*`. For now, if we cannot find a suitable 218 /// return value we create one from scratch. We also do not yet combine 219 /// information, e.g., the source locations, see combinedIdentStruct. 220 Value *getCombinedIdentFromCallUsesIn(RuntimeFunctionInfo &RFI, Function &F, 221 bool GlobalOnly) { 222 Value *Ident = nullptr; 223 auto CombineIdentStruct = [&](Use &U, Function &Caller) { 224 CallInst *CI = getCallIfRegularCall(U, &RFI); 225 if (!CI || &F != &Caller) 226 return false; 227 Ident = combinedIdentStruct(Ident, CI->getArgOperand(0), 228 /* GlobalOnly */ true); 229 return false; 230 }; 231 RFI.foreachUse(CombineIdentStruct); 232 233 if (!Ident) { 234 // The IRBuilder uses the insertion block to get to the module, this is 235 // unfortunate but we work around it for now. 236 if (!OMPBuilder.getInsertionPoint().getBlock()) 237 OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy( 238 &F.getEntryBlock(), F.getEntryBlock().begin())); 239 // Create a fallback location if non was found. 240 // TODO: Use the debug locations of the calls instead. 241 Constant *Loc = OMPBuilder.getOrCreateDefaultSrcLocStr(); 242 Ident = OMPBuilder.getOrCreateIdent(Loc); 243 } 244 return Ident; 245 } 246 247 /// Try to eliminiate calls of \p RFI in \p F by reusing an existing one or 248 /// \p ReplVal if given. 249 bool deduplicateRuntimeCalls(Function &F, RuntimeFunctionInfo &RFI, 250 Value *ReplVal = nullptr) { 251 auto &Uses = RFI.UsesMap[&F]; 252 if (Uses.size() + (ReplVal != nullptr) < 2) 253 return false; 254 255 LLVM_DEBUG(dbgs() << TAG << "Deduplicate " << Uses.size() << " uses of " 256 << RFI.Name 257 << (ReplVal ? " with an existing value\n" : "\n") 258 << "\n"); 259 assert((!ReplVal || (isa<Argument>(ReplVal) && 260 cast<Argument>(ReplVal)->getParent() == &F)) && 261 "Unexpected replacement value!"); 262 263 // TODO: Use dominance to find a good position instead. 264 auto CanBeMoved = [](CallBase &CB) { 265 unsigned NumArgs = CB.getNumArgOperands(); 266 if (NumArgs == 0) 267 return true; 268 if (CB.getArgOperand(0)->getType() != IdentPtr) 269 return false; 270 for (unsigned u = 1; u < NumArgs; ++u) 271 if (isa<Instruction>(CB.getArgOperand(u))) 272 return false; 273 return true; 274 }; 275 276 if (!ReplVal) { 277 for (Use *U : Uses) 278 if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) { 279 if (!CanBeMoved(*CI)) 280 continue; 281 CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt()); 282 ReplVal = CI; 283 break; 284 } 285 if (!ReplVal) 286 return false; 287 } 288 289 // If we use a call as a replacement value we need to make sure the ident is 290 // valid at the new location. For now we just pick a global one, either 291 // existing and used by one of the calls, or created from scratch. 292 if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) { 293 if (CI->getNumArgOperands() > 0 && 294 CI->getArgOperand(0)->getType() == IdentPtr) { 295 Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F, 296 /* GlobalOnly */ true); 297 CI->setArgOperand(0, Ident); 298 } 299 } 300 301 bool Changed = false; 302 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 303 CallInst *CI = getCallIfRegularCall(U, &RFI); 304 if (!CI || CI == ReplVal || &F != &Caller) 305 return false; 306 assert(CI->getCaller() == &F && "Unexpected call!"); 307 CGUpdater.removeCallSite(*CI); 308 CI->replaceAllUsesWith(ReplVal); 309 CI->eraseFromParent(); 310 ++NumOpenMPRuntimeCallsDeduplicated; 311 Changed = true; 312 return true; 313 }; 314 RFI.foreachUse(ReplaceAndDeleteCB); 315 316 return Changed; 317 } 318 319 /// Collect arguments that represent the global thread id in \p GTIdArgs. 320 void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> >IdArgs) { 321 // TODO: Below we basically perform a fixpoint iteration with a pessimistic 322 // initialization. We could define an AbstractAttribute instead and 323 // run the Attributor here once it can be run as an SCC pass. 324 325 // Helper to check the argument \p ArgNo at all call sites of \p F for 326 // a GTId. 327 auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) { 328 if (!F.hasLocalLinkage()) 329 return false; 330 for (Use &U : F.uses()) { 331 if (CallInst *CI = getCallIfRegularCall(U)) { 332 Value *ArgOp = CI->getArgOperand(ArgNo); 333 if (CI == &RefCI || GTIdArgs.count(ArgOp) || 334 getCallIfRegularCall(*ArgOp, 335 &RFIs[OMPRTL___kmpc_global_thread_num])) 336 continue; 337 } 338 return false; 339 } 340 return true; 341 }; 342 343 // Helper to identify uses of a GTId as GTId arguments. 344 auto AddUserArgs = [&](Value >Id) { 345 for (Use &U : GTId.uses()) 346 if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) 347 if (CI->isArgOperand(&U)) 348 if (Function *Callee = CI->getCalledFunction()) 349 if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI)) 350 GTIdArgs.insert(Callee->getArg(U.getOperandNo())); 351 }; 352 353 // The argument users of __kmpc_global_thread_num calls are GTIds. 354 RuntimeFunctionInfo &GlobThreadNumRFI = 355 RFIs[OMPRTL___kmpc_global_thread_num]; 356 for (auto &It : GlobThreadNumRFI.UsesMap) 357 for (Use *U : It.second) 358 if (CallInst *CI = getCallIfRegularCall(*U, &GlobThreadNumRFI)) 359 AddUserArgs(*CI); 360 361 // Transitively search for more arguments by looking at the users of the 362 // ones we know already. During the search the GTIdArgs vector is extended 363 // so we cannot cache the size nor can we use a range based for. 364 for (unsigned u = 0; u < GTIdArgs.size(); ++u) 365 AddUserArgs(*GTIdArgs[u]); 366 } 367 368 /// Return the call if \p U is a callee use in a regular call. If \p RFI is 369 /// given it has to be the callee or a nullptr is returned. 370 CallInst *getCallIfRegularCall(Use &U, RuntimeFunctionInfo *RFI = nullptr) { 371 CallInst *CI = dyn_cast<CallInst>(U.getUser()); 372 if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() && 373 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 374 return CI; 375 return nullptr; 376 } 377 378 /// Return the call if \p V is a regular call. If \p RFI is given it has to be 379 /// the callee or a nullptr is returned. 380 CallInst *getCallIfRegularCall(Value &V, RuntimeFunctionInfo *RFI = nullptr) { 381 CallInst *CI = dyn_cast<CallInst>(&V); 382 if (CI && !CI->hasOperandBundles() && 383 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 384 return CI; 385 return nullptr; 386 } 387 388 /// Helper to initialize all runtime function information for those defined in 389 /// OpenMPKinds.def. 390 void initializeRuntimeFunctions() { 391 // Helper to collect all uses of the decleration in the UsesMap. 392 auto CollectUses = [&](RuntimeFunctionInfo &RFI) { 393 unsigned NumUses = 0; 394 if (!RFI.Declaration) 395 return NumUses; 396 OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration); 397 398 NumOpenMPRuntimeFunctionsIdentified += 1; 399 NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses(); 400 401 // TODO: We directly convert uses into proper calls and unknown uses. 402 for (Use &U : RFI.Declaration->uses()) { 403 if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) { 404 if (ModuleSlice.count(UserI->getFunction())) { 405 RFI.UsesMap[UserI->getFunction()].insert(&U); 406 ++NumUses; 407 } 408 } else { 409 RFI.UsesMap[nullptr].insert(&U); 410 ++NumUses; 411 } 412 } 413 return NumUses; 414 }; 415 416 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \ 417 { \ 418 auto &RFI = RFIs[_Enum]; \ 419 RFI.Kind = _Enum; \ 420 RFI.Name = _Name; \ 421 RFI.IsVarArg = _IsVarArg; \ 422 RFI.ReturnType = _ReturnType; \ 423 RFI.ArgumentTypes = SmallVector<Type *, 8>({__VA_ARGS__}); \ 424 RFI.Declaration = M.getFunction(_Name); \ 425 unsigned NumUses = CollectUses(RFI); \ 426 (void)NumUses; \ 427 LLVM_DEBUG({ \ 428 dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \ 429 << " found\n"; \ 430 if (RFI.Declaration) \ 431 dbgs() << TAG << "-> got " << NumUses << " uses in " \ 432 << RFI.UsesMap.size() << " different functions.\n"; \ 433 }); \ 434 } 435 #include "llvm/Frontend/OpenMP/OMPKinds.def" 436 437 // TODO: We should validate the declaration agains the types we expect. 438 // TODO: We should attach the attributes defined in OMPKinds.def. 439 } 440 441 /// The underyling module. 442 Module &M; 443 444 /// The SCC we are operating on. 445 SmallPtrSetImpl<Function *> &SCC; 446 447 /// The slice of the module we are allowed to look at. 448 SmallPtrSetImpl<Function *> &ModuleSlice; 449 450 /// An OpenMP-IR-Builder instance 451 OpenMPIRBuilder OMPBuilder; 452 453 /// Callback to update the call graph, the first argument is a removed call, 454 /// the second an optional replacement call. 455 CallGraphUpdater &CGUpdater; 456 457 /// Map from runtime function kind to the runtime function description. 458 EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction, 459 RuntimeFunction::OMPRTL___last> 460 RFIs; 461 }; 462 } // namespace 463 464 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C, 465 CGSCCAnalysisManager &AM, 466 LazyCallGraph &CG, CGSCCUpdateResult &UR) { 467 if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule)) 468 return PreservedAnalyses::all(); 469 470 if (DisableOpenMPOptimizations) 471 return PreservedAnalyses::all(); 472 473 SmallPtrSet<Function *, 16> SCC; 474 for (LazyCallGraph::Node &N : C) 475 SCC.insert(&N.getFunction()); 476 477 if (SCC.empty()) 478 return PreservedAnalyses::all(); 479 480 CallGraphUpdater CGUpdater; 481 CGUpdater.initialize(CG, C, AM, UR); 482 // TODO: Compute the module slice we are allowed to look at. 483 OpenMPOpt OMPOpt(SCC, SCC, CGUpdater); 484 bool Changed = OMPOpt.run(); 485 (void)Changed; 486 return PreservedAnalyses::all(); 487 } 488 489 namespace { 490 491 struct OpenMPOptLegacyPass : public CallGraphSCCPass { 492 CallGraphUpdater CGUpdater; 493 OpenMPInModule OMPInModule; 494 static char ID; 495 496 OpenMPOptLegacyPass() : CallGraphSCCPass(ID) { 497 initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry()); 498 } 499 500 void getAnalysisUsage(AnalysisUsage &AU) const override { 501 CallGraphSCCPass::getAnalysisUsage(AU); 502 } 503 504 bool doInitialization(CallGraph &CG) override { 505 // Disable the pass if there is no OpenMP (runtime call) in the module. 506 containsOpenMP(CG.getModule(), OMPInModule); 507 return false; 508 } 509 510 bool runOnSCC(CallGraphSCC &CGSCC) override { 511 if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule)) 512 return false; 513 if (DisableOpenMPOptimizations || skipSCC(CGSCC)) 514 return false; 515 516 SmallPtrSet<Function *, 16> SCC; 517 for (CallGraphNode *CGN : CGSCC) 518 if (Function *Fn = CGN->getFunction()) 519 if (!Fn->isDeclaration()) 520 SCC.insert(Fn); 521 522 if (SCC.empty()) 523 return false; 524 525 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 526 CGUpdater.initialize(CG, CGSCC); 527 528 // TODO: Compute the module slice we are allowed to look at. 529 OpenMPOpt OMPOpt(SCC, SCC, CGUpdater); 530 return OMPOpt.run(); 531 } 532 533 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 534 }; 535 536 } // end anonymous namespace 537 538 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) { 539 if (OMPInModule.isKnown()) 540 return OMPInModule; 541 542 #define OMP_RTL(_Enum, _Name, ...) \ 543 if (M.getFunction(_Name)) \ 544 return OMPInModule = true; 545 #include "llvm/Frontend/OpenMP/OMPKinds.def" 546 return OMPInModule = false; 547 } 548 549 char OpenMPOptLegacyPass::ID = 0; 550 551 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt", 552 "OpenMP specific optimizations", false, false) 553 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 554 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt", 555 "OpenMP specific optimizations", false, false) 556 557 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); } 558