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/Analysis/OptimizationRemarkEmitter.h" 22 #include "llvm/Frontend/OpenMP/OMPConstants.h" 23 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 24 #include "llvm/InitializePasses.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Transforms/IPO.h" 27 #include "llvm/Transforms/IPO/Attributor.h" 28 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 29 30 using namespace llvm; 31 using namespace omp; 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 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false), 41 cl::Hidden); 42 43 STATISTIC(NumOpenMPRuntimeCallsDeduplicated, 44 "Number of OpenMP runtime calls deduplicated"); 45 STATISTIC(NumOpenMPParallelRegionsDeleted, 46 "Number of OpenMP parallel regions deleted"); 47 STATISTIC(NumOpenMPRuntimeFunctionsIdentified, 48 "Number of OpenMP runtime functions identified"); 49 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified, 50 "Number of OpenMP runtime function uses identified"); 51 52 #if !defined(NDEBUG) 53 static constexpr auto TAG = "[" DEBUG_TYPE "]"; 54 #endif 55 56 /// Helper struct to store tracked ICV values at specif instructions. 57 struct ICVValue { 58 Instruction *Inst; 59 Value *TrackedValue; 60 61 ICVValue(Instruction *I, Value *Val) : Inst(I), TrackedValue(Val) {} 62 }; 63 64 namespace llvm { 65 66 // Provide DenseMapInfo for ICVValue 67 template <> struct DenseMapInfo<ICVValue> { 68 using InstInfo = DenseMapInfo<Instruction *>; 69 using ValueInfo = DenseMapInfo<Value *>; 70 71 static inline ICVValue getEmptyKey() { 72 return ICVValue(InstInfo::getEmptyKey(), ValueInfo::getEmptyKey()); 73 }; 74 75 static inline ICVValue getTombstoneKey() { 76 return ICVValue(InstInfo::getTombstoneKey(), ValueInfo::getTombstoneKey()); 77 }; 78 79 static unsigned getHashValue(const ICVValue &ICVVal) { 80 return detail::combineHashValue( 81 InstInfo::getHashValue(ICVVal.Inst), 82 ValueInfo::getHashValue(ICVVal.TrackedValue)); 83 } 84 85 static bool isEqual(const ICVValue &LHS, const ICVValue &RHS) { 86 return InstInfo::isEqual(LHS.Inst, RHS.Inst) && 87 ValueInfo::isEqual(LHS.TrackedValue, RHS.TrackedValue); 88 } 89 }; 90 91 } // end namespace llvm 92 93 namespace { 94 95 struct AAICVTracker; 96 97 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for 98 /// Attributor runs. 99 struct OMPInformationCache : public InformationCache { 100 OMPInformationCache(Module &M, AnalysisGetter &AG, 101 BumpPtrAllocator &Allocator, SetVector<Function *> *CGSCC, 102 SmallPtrSetImpl<Function *> &ModuleSlice) 103 : InformationCache(M, AG, Allocator, CGSCC), ModuleSlice(ModuleSlice), 104 OMPBuilder(M) { 105 OMPBuilder.initialize(); 106 initializeRuntimeFunctions(); 107 initializeInternalControlVars(); 108 } 109 110 /// Generic information that describes an internal control variable. 111 struct InternalControlVarInfo { 112 /// The kind, as described by InternalControlVar enum. 113 InternalControlVar Kind; 114 115 /// The name of the ICV. 116 StringRef Name; 117 118 /// Environment variable associated with this ICV. 119 StringRef EnvVarName; 120 121 /// Initial value kind. 122 ICVInitValue InitKind; 123 124 /// Initial value. 125 ConstantInt *InitValue; 126 127 /// Setter RTL function associated with this ICV. 128 RuntimeFunction Setter; 129 130 /// Getter RTL function associated with this ICV. 131 RuntimeFunction Getter; 132 133 /// RTL Function corresponding to the override clause of this ICV 134 RuntimeFunction Clause; 135 }; 136 137 /// Generic information that describes a runtime function 138 struct RuntimeFunctionInfo { 139 140 /// The kind, as described by the RuntimeFunction enum. 141 RuntimeFunction Kind; 142 143 /// The name of the function. 144 StringRef Name; 145 146 /// Flag to indicate a variadic function. 147 bool IsVarArg; 148 149 /// The return type of the function. 150 Type *ReturnType; 151 152 /// The argument types of the function. 153 SmallVector<Type *, 8> ArgumentTypes; 154 155 /// The declaration if available. 156 Function *Declaration = nullptr; 157 158 /// Uses of this runtime function per function containing the use. 159 using UseVector = SmallVector<Use *, 16>; 160 161 /// Return the vector of uses in function \p F. 162 UseVector &getOrCreateUseVector(Function *F) { 163 std::shared_ptr<UseVector> &UV = UsesMap[F]; 164 if (!UV) 165 UV = std::make_shared<UseVector>(); 166 return *UV; 167 } 168 169 /// Return the vector of uses in function \p F or `nullptr` if there are 170 /// none. 171 const UseVector *getUseVector(Function &F) const { 172 auto I = UsesMap.find(&F); 173 if (I != UsesMap.end()) 174 return I->second.get(); 175 return nullptr; 176 } 177 178 /// Return how many functions contain uses of this runtime function. 179 size_t getNumFunctionsWithUses() const { return UsesMap.size(); } 180 181 /// Return the number of arguments (or the minimal number for variadic 182 /// functions). 183 size_t getNumArgs() const { return ArgumentTypes.size(); } 184 185 /// Run the callback \p CB on each use and forget the use if the result is 186 /// true. The callback will be fed the function in which the use was 187 /// encountered as second argument. 188 void foreachUse(function_ref<bool(Use &, Function &)> CB) { 189 for (auto &It : UsesMap) 190 foreachUse(CB, It.first, It.second.get()); 191 } 192 193 /// Run the callback \p CB on each use within the function \p F and forget 194 /// the use if the result is true. 195 void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F, 196 UseVector *Uses = nullptr) { 197 SmallVector<unsigned, 8> ToBeDeleted; 198 ToBeDeleted.clear(); 199 200 unsigned Idx = 0; 201 UseVector &UV = Uses ? *Uses : getOrCreateUseVector(F); 202 203 for (Use *U : UV) { 204 if (CB(*U, *F)) 205 ToBeDeleted.push_back(Idx); 206 ++Idx; 207 } 208 209 // Remove the to-be-deleted indices in reverse order as prior 210 // modifcations will not modify the smaller indices. 211 while (!ToBeDeleted.empty()) { 212 unsigned Idx = ToBeDeleted.pop_back_val(); 213 UV[Idx] = UV.back(); 214 UV.pop_back(); 215 } 216 } 217 218 private: 219 /// Map from functions to all uses of this runtime function contained in 220 /// them. 221 DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap; 222 }; 223 224 /// The slice of the module we are allowed to look at. 225 SmallPtrSetImpl<Function *> &ModuleSlice; 226 227 /// An OpenMP-IR-Builder instance 228 OpenMPIRBuilder OMPBuilder; 229 230 /// Map from runtime function kind to the runtime function description. 231 EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction, 232 RuntimeFunction::OMPRTL___last> 233 RFIs; 234 235 /// Map from ICV kind to the ICV description. 236 EnumeratedArray<InternalControlVarInfo, InternalControlVar, 237 InternalControlVar::ICV___last> 238 ICVs; 239 240 /// Helper to initialize all internal control variable information for those 241 /// defined in OMPKinds.def. 242 void initializeInternalControlVars() { 243 #define ICV_RT_SET(_Name, RTL) \ 244 { \ 245 auto &ICV = ICVs[_Name]; \ 246 ICV.Setter = RTL; \ 247 } 248 #define ICV_RT_GET(Name, RTL) \ 249 { \ 250 auto &ICV = ICVs[Name]; \ 251 ICV.Getter = RTL; \ 252 } 253 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init) \ 254 { \ 255 auto &ICV = ICVs[Enum]; \ 256 ICV.Name = _Name; \ 257 ICV.Kind = Enum; \ 258 ICV.InitKind = Init; \ 259 ICV.EnvVarName = _EnvVarName; \ 260 switch (ICV.InitKind) { \ 261 case ICV_IMPLEMENTATION_DEFINED: \ 262 ICV.InitValue = nullptr; \ 263 break; \ 264 case ICV_ZERO: \ 265 ICV.InitValue = ConstantInt::get( \ 266 Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0); \ 267 break; \ 268 case ICV_FALSE: \ 269 ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext()); \ 270 break; \ 271 case ICV_LAST: \ 272 break; \ 273 } \ 274 } 275 #include "llvm/Frontend/OpenMP/OMPKinds.def" 276 } 277 278 /// Returns true if the function declaration \p F matches the runtime 279 /// function types, that is, return type \p RTFRetType, and argument types 280 /// \p RTFArgTypes. 281 static bool declMatchesRTFTypes(Function *F, Type *RTFRetType, 282 SmallVector<Type *, 8> &RTFArgTypes) { 283 // TODO: We should output information to the user (under debug output 284 // and via remarks). 285 286 if (!F) 287 return false; 288 if (F->getReturnType() != RTFRetType) 289 return false; 290 if (F->arg_size() != RTFArgTypes.size()) 291 return false; 292 293 auto RTFTyIt = RTFArgTypes.begin(); 294 for (Argument &Arg : F->args()) { 295 if (Arg.getType() != *RTFTyIt) 296 return false; 297 298 ++RTFTyIt; 299 } 300 301 return true; 302 } 303 304 /// Helper to initialize all runtime function information for those defined 305 /// in OpenMPKinds.def. 306 void initializeRuntimeFunctions() { 307 // Helper to collect all uses of the decleration in the UsesMap. 308 auto CollectUses = [&](RuntimeFunctionInfo &RFI) { 309 unsigned NumUses = 0; 310 if (!RFI.Declaration) 311 return NumUses; 312 OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration); 313 314 NumOpenMPRuntimeFunctionsIdentified += 1; 315 NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses(); 316 317 // TODO: We directly convert uses into proper calls and unknown uses. 318 for (Use &U : RFI.Declaration->uses()) { 319 if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) { 320 if (ModuleSlice.count(UserI->getFunction())) { 321 RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U); 322 ++NumUses; 323 } 324 } else { 325 RFI.getOrCreateUseVector(nullptr).push_back(&U); 326 ++NumUses; 327 } 328 } 329 return NumUses; 330 }; 331 332 Module &M = *((*ModuleSlice.begin())->getParent()); 333 334 // Helper macros for handling __VA_ARGS__ in OMP_RTL 335 #define OMP_TYPE(VarName, ...) \ 336 Type *VarName = OMPBuilder.VarName; \ 337 (void)VarName; 338 339 #define OMP_ARRAY_TYPE(VarName, ...) \ 340 ArrayType *VarName##Ty = OMPBuilder.VarName##Ty; \ 341 (void)VarName##Ty; \ 342 PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy; \ 343 (void)VarName##PtrTy; 344 345 #define OMP_FUNCTION_TYPE(VarName, ...) \ 346 FunctionType *VarName = OMPBuilder.VarName; \ 347 (void)VarName; \ 348 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 349 (void)VarName##Ptr; 350 351 #define OMP_STRUCT_TYPE(VarName, ...) \ 352 StructType *VarName = OMPBuilder.VarName; \ 353 (void)VarName; \ 354 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 355 (void)VarName##Ptr; 356 357 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \ 358 { \ 359 SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__}); \ 360 Function *F = M.getFunction(_Name); \ 361 if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) { \ 362 auto &RFI = RFIs[_Enum]; \ 363 RFI.Kind = _Enum; \ 364 RFI.Name = _Name; \ 365 RFI.IsVarArg = _IsVarArg; \ 366 RFI.ReturnType = OMPBuilder._ReturnType; \ 367 RFI.ArgumentTypes = std::move(ArgsTypes); \ 368 RFI.Declaration = F; \ 369 unsigned NumUses = CollectUses(RFI); \ 370 (void)NumUses; \ 371 LLVM_DEBUG({ \ 372 dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \ 373 << " found\n"; \ 374 if (RFI.Declaration) \ 375 dbgs() << TAG << "-> got " << NumUses << " uses in " \ 376 << RFI.getNumFunctionsWithUses() \ 377 << " different functions.\n"; \ 378 }); \ 379 } \ 380 } 381 #include "llvm/Frontend/OpenMP/OMPKinds.def" 382 383 // TODO: We should attach the attributes defined in OMPKinds.def. 384 } 385 }; 386 387 struct OpenMPOpt { 388 389 using OptimizationRemarkGetter = 390 function_ref<OptimizationRemarkEmitter &(Function *)>; 391 392 OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater, 393 OptimizationRemarkGetter OREGetter, 394 OMPInformationCache &OMPInfoCache, Attributor &A) 395 : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater), 396 OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {} 397 398 /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice. 399 bool run() { 400 bool Changed = false; 401 402 LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size() 403 << " functions in a slice with " 404 << OMPInfoCache.ModuleSlice.size() << " functions\n"); 405 406 /// Print initial ICV values for testing. 407 /// FIXME: This should be done from the Attributor once it is added. 408 if (PrintICVValues) { 409 InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel}; 410 411 for (Function *F : OMPInfoCache.ModuleSlice) { 412 for (auto ICV : ICVs) { 413 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 414 auto Remark = [&](OptimizationRemark OR) { 415 return OR << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name) 416 << " Value: " 417 << (ICVInfo.InitValue 418 ? ICVInfo.InitValue->getValue().toString(10, true) 419 : "IMPLEMENTATION_DEFINED"); 420 }; 421 422 emitRemarkOnFunction(F, "OpenMPICVTracker", Remark); 423 } 424 } 425 } 426 427 Changed |= runAttributor(); 428 Changed |= deduplicateRuntimeCalls(); 429 Changed |= deleteParallelRegions(); 430 431 return Changed; 432 } 433 434 /// Return the call if \p U is a callee use in a regular call. If \p RFI is 435 /// given it has to be the callee or a nullptr is returned. 436 static CallInst *getCallIfRegularCall( 437 Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 438 CallInst *CI = dyn_cast<CallInst>(U.getUser()); 439 if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() && 440 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 441 return CI; 442 return nullptr; 443 } 444 445 /// Return the call if \p V is a regular call. If \p RFI is given it has to be 446 /// the callee or a nullptr is returned. 447 static CallInst *getCallIfRegularCall( 448 Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 449 CallInst *CI = dyn_cast<CallInst>(&V); 450 if (CI && !CI->hasOperandBundles() && 451 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 452 return CI; 453 return nullptr; 454 } 455 456 private: 457 /// Try to delete parallel regions if possible. 458 bool deleteParallelRegions() { 459 const unsigned CallbackCalleeOperand = 2; 460 461 OMPInformationCache::RuntimeFunctionInfo &RFI = 462 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 463 464 if (!RFI.Declaration) 465 return false; 466 467 bool Changed = false; 468 auto DeleteCallCB = [&](Use &U, Function &) { 469 CallInst *CI = getCallIfRegularCall(U); 470 if (!CI) 471 return false; 472 auto *Fn = dyn_cast<Function>( 473 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts()); 474 if (!Fn) 475 return false; 476 if (!Fn->onlyReadsMemory()) 477 return false; 478 if (!Fn->hasFnAttribute(Attribute::WillReturn)) 479 return false; 480 481 LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in " 482 << CI->getCaller()->getName() << "\n"); 483 484 auto Remark = [&](OptimizationRemark OR) { 485 return OR << "Parallel region in " 486 << ore::NV("OpenMPParallelDelete", CI->getCaller()->getName()) 487 << " deleted"; 488 }; 489 emitRemark<OptimizationRemark>(CI, "OpenMPParallelRegionDeletion", 490 Remark); 491 492 CGUpdater.removeCallSite(*CI); 493 CI->eraseFromParent(); 494 Changed = true; 495 ++NumOpenMPParallelRegionsDeleted; 496 return true; 497 }; 498 499 RFI.foreachUse(DeleteCallCB); 500 501 return Changed; 502 } 503 504 /// Try to eliminiate runtime calls by reusing existing ones. 505 bool deduplicateRuntimeCalls() { 506 bool Changed = false; 507 508 RuntimeFunction DeduplicableRuntimeCallIDs[] = { 509 OMPRTL_omp_get_num_threads, 510 OMPRTL_omp_in_parallel, 511 OMPRTL_omp_get_cancellation, 512 OMPRTL_omp_get_thread_limit, 513 OMPRTL_omp_get_supported_active_levels, 514 OMPRTL_omp_get_level, 515 OMPRTL_omp_get_ancestor_thread_num, 516 OMPRTL_omp_get_team_size, 517 OMPRTL_omp_get_active_level, 518 OMPRTL_omp_in_final, 519 OMPRTL_omp_get_proc_bind, 520 OMPRTL_omp_get_num_places, 521 OMPRTL_omp_get_num_procs, 522 OMPRTL_omp_get_place_num, 523 OMPRTL_omp_get_partition_num_places, 524 OMPRTL_omp_get_partition_place_nums}; 525 526 // Global-tid is handled separately. 527 SmallSetVector<Value *, 16> GTIdArgs; 528 collectGlobalThreadIdArguments(GTIdArgs); 529 LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size() 530 << " global thread ID arguments\n"); 531 532 for (Function *F : SCC) { 533 for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs) 534 deduplicateRuntimeCalls(*F, 535 OMPInfoCache.RFIs[DeduplicableRuntimeCallID]); 536 537 // __kmpc_global_thread_num is special as we can replace it with an 538 // argument in enough cases to make it worth trying. 539 Value *GTIdArg = nullptr; 540 for (Argument &Arg : F->args()) 541 if (GTIdArgs.count(&Arg)) { 542 GTIdArg = &Arg; 543 break; 544 } 545 Changed |= deduplicateRuntimeCalls( 546 *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg); 547 } 548 549 return Changed; 550 } 551 552 static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent, 553 bool GlobalOnly, bool &SingleChoice) { 554 if (CurrentIdent == NextIdent) 555 return CurrentIdent; 556 557 // TODO: Figure out how to actually combine multiple debug locations. For 558 // now we just keep an existing one if there is a single choice. 559 if (!GlobalOnly || isa<GlobalValue>(NextIdent)) { 560 SingleChoice = !CurrentIdent; 561 return NextIdent; 562 } 563 return nullptr; 564 } 565 566 /// Return an `struct ident_t*` value that represents the ones used in the 567 /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not 568 /// return a local `struct ident_t*`. For now, if we cannot find a suitable 569 /// return value we create one from scratch. We also do not yet combine 570 /// information, e.g., the source locations, see combinedIdentStruct. 571 Value * 572 getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI, 573 Function &F, bool GlobalOnly) { 574 bool SingleChoice = true; 575 Value *Ident = nullptr; 576 auto CombineIdentStruct = [&](Use &U, Function &Caller) { 577 CallInst *CI = getCallIfRegularCall(U, &RFI); 578 if (!CI || &F != &Caller) 579 return false; 580 Ident = combinedIdentStruct(Ident, CI->getArgOperand(0), 581 /* GlobalOnly */ true, SingleChoice); 582 return false; 583 }; 584 RFI.foreachUse(CombineIdentStruct); 585 586 if (!Ident || !SingleChoice) { 587 // The IRBuilder uses the insertion block to get to the module, this is 588 // unfortunate but we work around it for now. 589 if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock()) 590 OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy( 591 &F.getEntryBlock(), F.getEntryBlock().begin())); 592 // Create a fallback location if non was found. 593 // TODO: Use the debug locations of the calls instead. 594 Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr(); 595 Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc); 596 } 597 return Ident; 598 } 599 600 /// Try to eliminiate calls of \p RFI in \p F by reusing an existing one or 601 /// \p ReplVal if given. 602 bool deduplicateRuntimeCalls(Function &F, 603 OMPInformationCache::RuntimeFunctionInfo &RFI, 604 Value *ReplVal = nullptr) { 605 auto *UV = RFI.getUseVector(F); 606 if (!UV || UV->size() + (ReplVal != nullptr) < 2) 607 return false; 608 609 LLVM_DEBUG( 610 dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name 611 << (ReplVal ? " with an existing value\n" : "\n") << "\n"); 612 613 assert((!ReplVal || (isa<Argument>(ReplVal) && 614 cast<Argument>(ReplVal)->getParent() == &F)) && 615 "Unexpected replacement value!"); 616 617 // TODO: Use dominance to find a good position instead. 618 auto CanBeMoved = [this](CallBase &CB) { 619 unsigned NumArgs = CB.getNumArgOperands(); 620 if (NumArgs == 0) 621 return true; 622 if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr) 623 return false; 624 for (unsigned u = 1; u < NumArgs; ++u) 625 if (isa<Instruction>(CB.getArgOperand(u))) 626 return false; 627 return true; 628 }; 629 630 if (!ReplVal) { 631 for (Use *U : *UV) 632 if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) { 633 if (!CanBeMoved(*CI)) 634 continue; 635 636 auto Remark = [&](OptimizationRemark OR) { 637 auto newLoc = &*F.getEntryBlock().getFirstInsertionPt(); 638 return OR << "OpenMP runtime call " 639 << ore::NV("OpenMPOptRuntime", RFI.Name) << " moved to " 640 << ore::NV("OpenMPRuntimeMoves", newLoc->getDebugLoc()); 641 }; 642 emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeCodeMotion", Remark); 643 644 CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt()); 645 ReplVal = CI; 646 break; 647 } 648 if (!ReplVal) 649 return false; 650 } 651 652 // If we use a call as a replacement value we need to make sure the ident is 653 // valid at the new location. For now we just pick a global one, either 654 // existing and used by one of the calls, or created from scratch. 655 if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) { 656 if (CI->getNumArgOperands() > 0 && 657 CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) { 658 Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F, 659 /* GlobalOnly */ true); 660 CI->setArgOperand(0, Ident); 661 } 662 } 663 664 bool Changed = false; 665 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 666 CallInst *CI = getCallIfRegularCall(U, &RFI); 667 if (!CI || CI == ReplVal || &F != &Caller) 668 return false; 669 assert(CI->getCaller() == &F && "Unexpected call!"); 670 671 auto Remark = [&](OptimizationRemark OR) { 672 return OR << "OpenMP runtime call " 673 << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated"; 674 }; 675 emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeDeduplicated", Remark); 676 677 CGUpdater.removeCallSite(*CI); 678 CI->replaceAllUsesWith(ReplVal); 679 CI->eraseFromParent(); 680 ++NumOpenMPRuntimeCallsDeduplicated; 681 Changed = true; 682 return true; 683 }; 684 RFI.foreachUse(ReplaceAndDeleteCB); 685 686 return Changed; 687 } 688 689 /// Collect arguments that represent the global thread id in \p GTIdArgs. 690 void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> >IdArgs) { 691 // TODO: Below we basically perform a fixpoint iteration with a pessimistic 692 // initialization. We could define an AbstractAttribute instead and 693 // run the Attributor here once it can be run as an SCC pass. 694 695 // Helper to check the argument \p ArgNo at all call sites of \p F for 696 // a GTId. 697 auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) { 698 if (!F.hasLocalLinkage()) 699 return false; 700 for (Use &U : F.uses()) { 701 if (CallInst *CI = getCallIfRegularCall(U)) { 702 Value *ArgOp = CI->getArgOperand(ArgNo); 703 if (CI == &RefCI || GTIdArgs.count(ArgOp) || 704 getCallIfRegularCall( 705 *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num])) 706 continue; 707 } 708 return false; 709 } 710 return true; 711 }; 712 713 // Helper to identify uses of a GTId as GTId arguments. 714 auto AddUserArgs = [&](Value >Id) { 715 for (Use &U : GTId.uses()) 716 if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) 717 if (CI->isArgOperand(&U)) 718 if (Function *Callee = CI->getCalledFunction()) 719 if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI)) 720 GTIdArgs.insert(Callee->getArg(U.getOperandNo())); 721 }; 722 723 // The argument users of __kmpc_global_thread_num calls are GTIds. 724 OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI = 725 OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]; 726 727 GlobThreadNumRFI.foreachUse([&](Use &U, Function &F) { 728 if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI)) 729 AddUserArgs(*CI); 730 return false; 731 }); 732 733 // Transitively search for more arguments by looking at the users of the 734 // ones we know already. During the search the GTIdArgs vector is extended 735 // so we cannot cache the size nor can we use a range based for. 736 for (unsigned u = 0; u < GTIdArgs.size(); ++u) 737 AddUserArgs(*GTIdArgs[u]); 738 } 739 740 /// Emit a remark generically 741 /// 742 /// This template function can be used to generically emit a remark. The 743 /// RemarkKind should be one of the following: 744 /// - OptimizationRemark to indicate a successful optimization attempt 745 /// - OptimizationRemarkMissed to report a failed optimization attempt 746 /// - OptimizationRemarkAnalysis to provide additional information about an 747 /// optimization attempt 748 /// 749 /// The remark is built using a callback function provided by the caller that 750 /// takes a RemarkKind as input and returns a RemarkKind. 751 template <typename RemarkKind, 752 typename RemarkCallBack = function_ref<RemarkKind(RemarkKind &&)>> 753 void emitRemark(Instruction *Inst, StringRef RemarkName, 754 RemarkCallBack &&RemarkCB) { 755 Function *F = Inst->getParent()->getParent(); 756 auto &ORE = OREGetter(F); 757 758 ORE.emit( 759 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, Inst)); }); 760 } 761 762 /// Emit a remark on a function. Since only OptimizationRemark is supporting 763 /// this, it can't be made generic. 764 void emitRemarkOnFunction( 765 Function *F, StringRef RemarkName, 766 function_ref<OptimizationRemark(OptimizationRemark &&)> &&RemarkCB) { 767 auto &ORE = OREGetter(F); 768 769 ORE.emit([&]() { 770 return RemarkCB(OptimizationRemark(DEBUG_TYPE, RemarkName, F)); 771 }); 772 } 773 774 /// The underyling module. 775 Module &M; 776 777 /// The SCC we are operating on. 778 SmallVectorImpl<Function *> &SCC; 779 780 /// Callback to update the call graph, the first argument is a removed call, 781 /// the second an optional replacement call. 782 CallGraphUpdater &CGUpdater; 783 784 /// Callback to get an OptimizationRemarkEmitter from a Function * 785 OptimizationRemarkGetter OREGetter; 786 787 /// OpenMP-specific information cache. Also Used for Attributor runs. 788 OMPInformationCache &OMPInfoCache; 789 790 /// Attributor instance. 791 Attributor &A; 792 793 /// Helper function to run Attributor on SCC. 794 bool runAttributor() { 795 if (SCC.empty()) 796 return false; 797 798 registerAAs(); 799 800 ChangeStatus Changed = A.run(); 801 802 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size() 803 << " functions, result: " << Changed << ".\n"); 804 805 return Changed == ChangeStatus::CHANGED; 806 } 807 808 /// Populate the Attributor with abstract attribute opportunities in the 809 /// function. 810 void registerAAs() { 811 for (Function *F : SCC) { 812 if (F->isDeclaration()) 813 continue; 814 815 A.getOrCreateAAFor<AAICVTracker>(IRPosition::function(*F)); 816 } 817 } 818 }; 819 820 /// Abstract Attribute for tracking ICV values. 821 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> { 822 using Base = StateWrapper<BooleanState, AbstractAttribute>; 823 AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 824 825 /// Returns true if value is assumed to be tracked. 826 bool isAssumedTracked() const { return getAssumed(); } 827 828 /// Returns true if value is known to be tracked. 829 bool isKnownTracked() const { return getAssumed(); } 830 831 /// Create an abstract attribute biew for the position \p IRP. 832 static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A); 833 834 /// Return the value with which \p I can be replaced for specific \p ICV. 835 virtual Value *getReplacementValue(InternalControlVar ICV, 836 const Instruction *I, Attributor &A) = 0; 837 838 /// See AbstractAttribute::getName() 839 const std::string getName() const override { return "AAICVTracker"; } 840 841 static const char ID; 842 }; 843 844 struct AAICVTrackerFunction : public AAICVTracker { 845 AAICVTrackerFunction(const IRPosition &IRP, Attributor &A) 846 : AAICVTracker(IRP, A) {} 847 848 // FIXME: come up with better string. 849 const std::string getAsStr() const override { return "ICVTracker"; } 850 851 // FIXME: come up with some stats. 852 void trackStatistics() const override {} 853 854 /// TODO: decide whether to deduplicate here, or use current 855 /// deduplicateRuntimeCalls function. 856 ChangeStatus manifest(Attributor &A) override { 857 ChangeStatus Changed = ChangeStatus::UNCHANGED; 858 859 for (InternalControlVar &ICV : TrackableICVs) 860 if (deduplicateICVGetters(ICV, A)) 861 Changed = ChangeStatus::CHANGED; 862 863 return Changed; 864 } 865 866 bool deduplicateICVGetters(InternalControlVar &ICV, Attributor &A) { 867 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 868 auto &ICVInfo = OMPInfoCache.ICVs[ICV]; 869 auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter]; 870 871 bool Changed = false; 872 873 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 874 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI); 875 Instruction *UserI = cast<Instruction>(U.getUser()); 876 Value *ReplVal = getReplacementValue(ICV, UserI, A); 877 878 if (!ReplVal || !CI) 879 return false; 880 881 A.removeCallSite(CI); 882 CI->replaceAllUsesWith(ReplVal); 883 CI->eraseFromParent(); 884 Changed = true; 885 return true; 886 }; 887 888 GetterRFI.foreachUse(ReplaceAndDeleteCB); 889 return Changed; 890 } 891 892 // Map of ICV to their values at specific program point. 893 EnumeratedArray<SmallSetVector<ICVValue, 4>, InternalControlVar, 894 InternalControlVar::ICV___last> 895 ICVValuesMap; 896 897 // Currently only nthreads is being tracked. 898 // this array will only grow with time. 899 InternalControlVar TrackableICVs[1] = {ICV_nthreads}; 900 901 ChangeStatus updateImpl(Attributor &A) override { 902 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 903 904 Function *F = getAnchorScope(); 905 906 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 907 908 for (InternalControlVar ICV : TrackableICVs) { 909 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 910 911 auto TrackValues = [&](Use &U, Function &) { 912 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U); 913 if (!CI) 914 return false; 915 916 // FIXME: handle setters with more that 1 arguments. 917 /// Track new value. 918 if (ICVValuesMap[ICV].insert(ICVValue(CI, CI->getArgOperand(0)))) 919 HasChanged = ChangeStatus::CHANGED; 920 921 return false; 922 }; 923 924 SetterRFI.foreachUse(TrackValues, F); 925 } 926 927 return HasChanged; 928 } 929 930 /// Return the value with which \p I can be replaced for specific \p ICV. 931 Value *getReplacementValue(InternalControlVar ICV, const Instruction *I, 932 Attributor &A) override { 933 const BasicBlock *CurrBB = I->getParent(); 934 935 auto &ValuesSet = ICVValuesMap[ICV]; 936 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 937 auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter]; 938 939 for (const auto &ICVVal : ValuesSet) { 940 if (CurrBB == ICVVal.Inst->getParent()) { 941 if (!ICVVal.Inst->comesBefore(I)) 942 continue; 943 944 // both instructions are in the same BB and at \p I we know the ICV 945 // value. 946 while (I != ICVVal.Inst) { 947 // we don't yet know if a call might update an ICV. 948 // TODO: check callsite AA for value. 949 if (const auto *CB = dyn_cast<CallBase>(I)) 950 if (CB->getCalledFunction() != GetterRFI.Declaration) 951 return nullptr; 952 953 I = I->getPrevNode(); 954 } 955 956 // No call in between, return the value. 957 return ICVVal.TrackedValue; 958 } 959 } 960 961 // No value was tracked. 962 return nullptr; 963 } 964 }; 965 } // namespace 966 967 const char AAICVTracker::ID = 0; 968 969 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP, 970 Attributor &A) { 971 AAICVTracker *AA = nullptr; 972 switch (IRP.getPositionKind()) { 973 case IRPosition::IRP_INVALID: 974 case IRPosition::IRP_FLOAT: 975 case IRPosition::IRP_ARGUMENT: 976 case IRPosition::IRP_RETURNED: 977 case IRPosition::IRP_CALL_SITE_RETURNED: 978 case IRPosition::IRP_CALL_SITE_ARGUMENT: 979 case IRPosition::IRP_CALL_SITE: 980 llvm_unreachable("ICVTracker can only be created for function position!"); 981 case IRPosition::IRP_FUNCTION: 982 AA = new (A.Allocator) AAICVTrackerFunction(IRP, A); 983 break; 984 } 985 986 return *AA; 987 } 988 989 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C, 990 CGSCCAnalysisManager &AM, 991 LazyCallGraph &CG, CGSCCUpdateResult &UR) { 992 if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule)) 993 return PreservedAnalyses::all(); 994 995 if (DisableOpenMPOptimizations) 996 return PreservedAnalyses::all(); 997 998 SmallPtrSet<Function *, 16> ModuleSlice; 999 SmallVector<Function *, 16> SCC; 1000 for (LazyCallGraph::Node &N : C) { 1001 SCC.push_back(&N.getFunction()); 1002 ModuleSlice.insert(SCC.back()); 1003 } 1004 1005 if (SCC.empty()) 1006 return PreservedAnalyses::all(); 1007 1008 FunctionAnalysisManager &FAM = 1009 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 1010 1011 AnalysisGetter AG(FAM); 1012 1013 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 1014 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 1015 }; 1016 1017 CallGraphUpdater CGUpdater; 1018 CGUpdater.initialize(CG, C, AM, UR); 1019 1020 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 1021 BumpPtrAllocator Allocator; 1022 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator, 1023 /*CGSCC*/ &Functions, ModuleSlice); 1024 1025 Attributor A(Functions, InfoCache, CGUpdater); 1026 1027 // TODO: Compute the module slice we are allowed to look at. 1028 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 1029 bool Changed = OMPOpt.run(); 1030 (void)Changed; 1031 return PreservedAnalyses::all(); 1032 } 1033 1034 namespace { 1035 1036 struct OpenMPOptLegacyPass : public CallGraphSCCPass { 1037 CallGraphUpdater CGUpdater; 1038 OpenMPInModule OMPInModule; 1039 static char ID; 1040 1041 OpenMPOptLegacyPass() : CallGraphSCCPass(ID) { 1042 initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry()); 1043 } 1044 1045 void getAnalysisUsage(AnalysisUsage &AU) const override { 1046 CallGraphSCCPass::getAnalysisUsage(AU); 1047 } 1048 1049 bool doInitialization(CallGraph &CG) override { 1050 // Disable the pass if there is no OpenMP (runtime call) in the module. 1051 containsOpenMP(CG.getModule(), OMPInModule); 1052 return false; 1053 } 1054 1055 bool runOnSCC(CallGraphSCC &CGSCC) override { 1056 if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule)) 1057 return false; 1058 if (DisableOpenMPOptimizations || skipSCC(CGSCC)) 1059 return false; 1060 1061 SmallPtrSet<Function *, 16> ModuleSlice; 1062 SmallVector<Function *, 16> SCC; 1063 for (CallGraphNode *CGN : CGSCC) 1064 if (Function *Fn = CGN->getFunction()) 1065 if (!Fn->isDeclaration()) { 1066 SCC.push_back(Fn); 1067 ModuleSlice.insert(Fn); 1068 } 1069 1070 if (SCC.empty()) 1071 return false; 1072 1073 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 1074 CGUpdater.initialize(CG, CGSCC); 1075 1076 // Maintain a map of functions to avoid rebuilding the ORE 1077 DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap; 1078 auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & { 1079 std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F]; 1080 if (!ORE) 1081 ORE = std::make_unique<OptimizationRemarkEmitter>(F); 1082 return *ORE; 1083 }; 1084 1085 AnalysisGetter AG; 1086 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 1087 BumpPtrAllocator Allocator; 1088 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, 1089 Allocator, 1090 /*CGSCC*/ &Functions, ModuleSlice); 1091 1092 Attributor A(Functions, InfoCache, CGUpdater); 1093 1094 // TODO: Compute the module slice we are allowed to look at. 1095 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 1096 return OMPOpt.run(); 1097 } 1098 1099 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 1100 }; 1101 1102 } // end anonymous namespace 1103 1104 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) { 1105 if (OMPInModule.isKnown()) 1106 return OMPInModule; 1107 1108 #define OMP_RTL(_Enum, _Name, ...) \ 1109 if (M.getFunction(_Name)) \ 1110 return OMPInModule = true; 1111 #include "llvm/Frontend/OpenMP/OMPKinds.def" 1112 return OMPInModule = false; 1113 } 1114 1115 char OpenMPOptLegacyPass::ID = 0; 1116 1117 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt", 1118 "OpenMP specific optimizations", false, false) 1119 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1120 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt", 1121 "OpenMP specific optimizations", false, false) 1122 1123 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); } 1124