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 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels", 43 cl::init(false), cl::Hidden); 44 45 STATISTIC(NumOpenMPRuntimeCallsDeduplicated, 46 "Number of OpenMP runtime calls deduplicated"); 47 STATISTIC(NumOpenMPParallelRegionsDeleted, 48 "Number of OpenMP parallel regions deleted"); 49 STATISTIC(NumOpenMPRuntimeFunctionsIdentified, 50 "Number of OpenMP runtime functions identified"); 51 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified, 52 "Number of OpenMP runtime function uses identified"); 53 STATISTIC(NumOpenMPTargetRegionKernels, 54 "Number of OpenMP target region entry points (=kernels) identified"); 55 STATISTIC( 56 NumOpenMPParallelRegionsReplacedInGPUStateMachine, 57 "Number of OpenMP parallel regions replaced with ID in GPU state machines"); 58 59 #if !defined(NDEBUG) 60 static constexpr auto TAG = "[" DEBUG_TYPE "]"; 61 #endif 62 63 /// Apply \p CB to all uses of \p F. If \p LookThroughConstantExprUses is 64 /// true, constant expression users are not given to \p CB but their uses are 65 /// traversed transitively. 66 template <typename CBTy> 67 static void foreachUse(Function &F, CBTy CB, 68 bool LookThroughConstantExprUses = true) { 69 SmallVector<Use *, 8> Worklist(make_pointer_range(F.uses())); 70 71 for (unsigned idx = 0; idx < Worklist.size(); ++idx) { 72 Use &U = *Worklist[idx]; 73 74 // Allow use in constant bitcasts and simply look through them. 75 if (LookThroughConstantExprUses && isa<ConstantExpr>(U.getUser())) { 76 for (Use &CEU : cast<ConstantExpr>(U.getUser())->uses()) 77 Worklist.push_back(&CEU); 78 continue; 79 } 80 81 CB(U); 82 } 83 } 84 85 /// Helper struct to store tracked ICV values at specif instructions. 86 struct ICVValue { 87 Instruction *Inst; 88 Value *TrackedValue; 89 90 ICVValue(Instruction *I, Value *Val) : Inst(I), TrackedValue(Val) {} 91 }; 92 93 namespace llvm { 94 95 // Provide DenseMapInfo for ICVValue 96 template <> struct DenseMapInfo<ICVValue> { 97 using InstInfo = DenseMapInfo<Instruction *>; 98 using ValueInfo = DenseMapInfo<Value *>; 99 100 static inline ICVValue getEmptyKey() { 101 return ICVValue(InstInfo::getEmptyKey(), ValueInfo::getEmptyKey()); 102 }; 103 104 static inline ICVValue getTombstoneKey() { 105 return ICVValue(InstInfo::getTombstoneKey(), ValueInfo::getTombstoneKey()); 106 }; 107 108 static unsigned getHashValue(const ICVValue &ICVVal) { 109 return detail::combineHashValue( 110 InstInfo::getHashValue(ICVVal.Inst), 111 ValueInfo::getHashValue(ICVVal.TrackedValue)); 112 } 113 114 static bool isEqual(const ICVValue &LHS, const ICVValue &RHS) { 115 return InstInfo::isEqual(LHS.Inst, RHS.Inst) && 116 ValueInfo::isEqual(LHS.TrackedValue, RHS.TrackedValue); 117 } 118 }; 119 120 } // end namespace llvm 121 122 namespace { 123 124 struct AAICVTracker; 125 126 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for 127 /// Attributor runs. 128 struct OMPInformationCache : public InformationCache { 129 OMPInformationCache(Module &M, AnalysisGetter &AG, 130 BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC, 131 SmallPtrSetImpl<Kernel> &Kernels) 132 : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M), 133 Kernels(Kernels) { 134 initializeModuleSlice(CGSCC); 135 136 OMPBuilder.initialize(); 137 initializeRuntimeFunctions(); 138 initializeInternalControlVars(); 139 } 140 141 /// Generic information that describes an internal control variable. 142 struct InternalControlVarInfo { 143 /// The kind, as described by InternalControlVar enum. 144 InternalControlVar Kind; 145 146 /// The name of the ICV. 147 StringRef Name; 148 149 /// Environment variable associated with this ICV. 150 StringRef EnvVarName; 151 152 /// Initial value kind. 153 ICVInitValue InitKind; 154 155 /// Initial value. 156 ConstantInt *InitValue; 157 158 /// Setter RTL function associated with this ICV. 159 RuntimeFunction Setter; 160 161 /// Getter RTL function associated with this ICV. 162 RuntimeFunction Getter; 163 164 /// RTL Function corresponding to the override clause of this ICV 165 RuntimeFunction Clause; 166 }; 167 168 /// Generic information that describes a runtime function 169 struct RuntimeFunctionInfo { 170 171 /// The kind, as described by the RuntimeFunction enum. 172 RuntimeFunction Kind; 173 174 /// The name of the function. 175 StringRef Name; 176 177 /// Flag to indicate a variadic function. 178 bool IsVarArg; 179 180 /// The return type of the function. 181 Type *ReturnType; 182 183 /// The argument types of the function. 184 SmallVector<Type *, 8> ArgumentTypes; 185 186 /// The declaration if available. 187 Function *Declaration = nullptr; 188 189 /// Uses of this runtime function per function containing the use. 190 using UseVector = SmallVector<Use *, 16>; 191 192 /// Clear UsesMap for runtime function. 193 void clearUsesMap() { UsesMap.clear(); } 194 195 /// Boolean conversion that is true if the runtime function was found. 196 operator bool() const { return Declaration; } 197 198 /// Return the vector of uses in function \p F. 199 UseVector &getOrCreateUseVector(Function *F) { 200 std::shared_ptr<UseVector> &UV = UsesMap[F]; 201 if (!UV) 202 UV = std::make_shared<UseVector>(); 203 return *UV; 204 } 205 206 /// Return the vector of uses in function \p F or `nullptr` if there are 207 /// none. 208 const UseVector *getUseVector(Function &F) const { 209 auto I = UsesMap.find(&F); 210 if (I != UsesMap.end()) 211 return I->second.get(); 212 return nullptr; 213 } 214 215 /// Return how many functions contain uses of this runtime function. 216 size_t getNumFunctionsWithUses() const { return UsesMap.size(); } 217 218 /// Return the number of arguments (or the minimal number for variadic 219 /// functions). 220 size_t getNumArgs() const { return ArgumentTypes.size(); } 221 222 /// Run the callback \p CB on each use and forget the use if the result is 223 /// true. The callback will be fed the function in which the use was 224 /// encountered as second argument. 225 void foreachUse(SmallVectorImpl<Function *> &SCC, 226 function_ref<bool(Use &, Function &)> CB) { 227 for (Function *F : SCC) 228 foreachUse(CB, F); 229 } 230 231 /// Run the callback \p CB on each use within the function \p F and forget 232 /// the use if the result is true. 233 void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) { 234 SmallVector<unsigned, 8> ToBeDeleted; 235 ToBeDeleted.clear(); 236 237 unsigned Idx = 0; 238 UseVector &UV = getOrCreateUseVector(F); 239 240 for (Use *U : UV) { 241 if (CB(*U, *F)) 242 ToBeDeleted.push_back(Idx); 243 ++Idx; 244 } 245 246 // Remove the to-be-deleted indices in reverse order as prior 247 // modifications will not modify the smaller indices. 248 while (!ToBeDeleted.empty()) { 249 unsigned Idx = ToBeDeleted.pop_back_val(); 250 UV[Idx] = UV.back(); 251 UV.pop_back(); 252 } 253 } 254 255 private: 256 /// Map from functions to all uses of this runtime function contained in 257 /// them. 258 DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap; 259 }; 260 261 /// Initialize the ModuleSlice member based on \p SCC. ModuleSlices contains 262 /// (a subset of) all functions that we can look at during this SCC traversal. 263 /// This includes functions (transitively) called from the SCC and the 264 /// (transitive) callers of SCC functions. We also can look at a function if 265 /// there is a "reference edge", i.a., if the function somehow uses (!=calls) 266 /// a function in the SCC or a caller of a function in the SCC. 267 void initializeModuleSlice(SetVector<Function *> &SCC) { 268 ModuleSlice.insert(SCC.begin(), SCC.end()); 269 270 SmallPtrSet<Function *, 16> Seen; 271 SmallVector<Function *, 16> Worklist(SCC.begin(), SCC.end()); 272 while (!Worklist.empty()) { 273 Function *F = Worklist.pop_back_val(); 274 ModuleSlice.insert(F); 275 276 for (Instruction &I : instructions(*F)) 277 if (auto *CB = dyn_cast<CallBase>(&I)) 278 if (Function *Callee = CB->getCalledFunction()) 279 if (Seen.insert(Callee).second) 280 Worklist.push_back(Callee); 281 } 282 283 Seen.clear(); 284 Worklist.append(SCC.begin(), SCC.end()); 285 while (!Worklist.empty()) { 286 Function *F = Worklist.pop_back_val(); 287 ModuleSlice.insert(F); 288 289 // Traverse all transitive uses. 290 foreachUse(*F, [&](Use &U) { 291 if (auto *UsrI = dyn_cast<Instruction>(U.getUser())) 292 if (Seen.insert(UsrI->getFunction()).second) 293 Worklist.push_back(UsrI->getFunction()); 294 }); 295 } 296 } 297 298 /// The slice of the module we are allowed to look at. 299 SmallPtrSet<Function *, 8> ModuleSlice; 300 301 /// An OpenMP-IR-Builder instance 302 OpenMPIRBuilder OMPBuilder; 303 304 /// Map from runtime function kind to the runtime function description. 305 EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction, 306 RuntimeFunction::OMPRTL___last> 307 RFIs; 308 309 /// Map from ICV kind to the ICV description. 310 EnumeratedArray<InternalControlVarInfo, InternalControlVar, 311 InternalControlVar::ICV___last> 312 ICVs; 313 314 /// Helper to initialize all internal control variable information for those 315 /// defined in OMPKinds.def. 316 void initializeInternalControlVars() { 317 #define ICV_RT_SET(_Name, RTL) \ 318 { \ 319 auto &ICV = ICVs[_Name]; \ 320 ICV.Setter = RTL; \ 321 } 322 #define ICV_RT_GET(Name, RTL) \ 323 { \ 324 auto &ICV = ICVs[Name]; \ 325 ICV.Getter = RTL; \ 326 } 327 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init) \ 328 { \ 329 auto &ICV = ICVs[Enum]; \ 330 ICV.Name = _Name; \ 331 ICV.Kind = Enum; \ 332 ICV.InitKind = Init; \ 333 ICV.EnvVarName = _EnvVarName; \ 334 switch (ICV.InitKind) { \ 335 case ICV_IMPLEMENTATION_DEFINED: \ 336 ICV.InitValue = nullptr; \ 337 break; \ 338 case ICV_ZERO: \ 339 ICV.InitValue = ConstantInt::get( \ 340 Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0); \ 341 break; \ 342 case ICV_FALSE: \ 343 ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext()); \ 344 break; \ 345 case ICV_LAST: \ 346 break; \ 347 } \ 348 } 349 #include "llvm/Frontend/OpenMP/OMPKinds.def" 350 } 351 352 /// Returns true if the function declaration \p F matches the runtime 353 /// function types, that is, return type \p RTFRetType, and argument types 354 /// \p RTFArgTypes. 355 static bool declMatchesRTFTypes(Function *F, Type *RTFRetType, 356 SmallVector<Type *, 8> &RTFArgTypes) { 357 // TODO: We should output information to the user (under debug output 358 // and via remarks). 359 360 if (!F) 361 return false; 362 if (F->getReturnType() != RTFRetType) 363 return false; 364 if (F->arg_size() != RTFArgTypes.size()) 365 return false; 366 367 auto RTFTyIt = RTFArgTypes.begin(); 368 for (Argument &Arg : F->args()) { 369 if (Arg.getType() != *RTFTyIt) 370 return false; 371 372 ++RTFTyIt; 373 } 374 375 return true; 376 } 377 378 // Helper to collect all uses of the declaration in the UsesMap. 379 unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) { 380 unsigned NumUses = 0; 381 if (!RFI.Declaration) 382 return NumUses; 383 OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration); 384 385 if (CollectStats) { 386 NumOpenMPRuntimeFunctionsIdentified += 1; 387 NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses(); 388 } 389 390 // TODO: We directly convert uses into proper calls and unknown uses. 391 for (Use &U : RFI.Declaration->uses()) { 392 if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) { 393 if (ModuleSlice.count(UserI->getFunction())) { 394 RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U); 395 ++NumUses; 396 } 397 } else { 398 RFI.getOrCreateUseVector(nullptr).push_back(&U); 399 ++NumUses; 400 } 401 } 402 return NumUses; 403 } 404 405 // Helper function to recollect uses of all runtime functions. 406 void recollectUses() { 407 for (int Idx = 0; Idx < RFIs.size(); ++Idx) { 408 auto &RFI = RFIs[static_cast<RuntimeFunction>(Idx)]; 409 RFI.clearUsesMap(); 410 collectUses(RFI, /*CollectStats*/ false); 411 } 412 } 413 414 /// Helper to initialize all runtime function information for those defined 415 /// in OpenMPKinds.def. 416 void initializeRuntimeFunctions() { 417 Module &M = *((*ModuleSlice.begin())->getParent()); 418 419 // Helper macros for handling __VA_ARGS__ in OMP_RTL 420 #define OMP_TYPE(VarName, ...) \ 421 Type *VarName = OMPBuilder.VarName; \ 422 (void)VarName; 423 424 #define OMP_ARRAY_TYPE(VarName, ...) \ 425 ArrayType *VarName##Ty = OMPBuilder.VarName##Ty; \ 426 (void)VarName##Ty; \ 427 PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy; \ 428 (void)VarName##PtrTy; 429 430 #define OMP_FUNCTION_TYPE(VarName, ...) \ 431 FunctionType *VarName = OMPBuilder.VarName; \ 432 (void)VarName; \ 433 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 434 (void)VarName##Ptr; 435 436 #define OMP_STRUCT_TYPE(VarName, ...) \ 437 StructType *VarName = OMPBuilder.VarName; \ 438 (void)VarName; \ 439 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 440 (void)VarName##Ptr; 441 442 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \ 443 { \ 444 SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__}); \ 445 Function *F = M.getFunction(_Name); \ 446 if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) { \ 447 auto &RFI = RFIs[_Enum]; \ 448 RFI.Kind = _Enum; \ 449 RFI.Name = _Name; \ 450 RFI.IsVarArg = _IsVarArg; \ 451 RFI.ReturnType = OMPBuilder._ReturnType; \ 452 RFI.ArgumentTypes = std::move(ArgsTypes); \ 453 RFI.Declaration = F; \ 454 unsigned NumUses = collectUses(RFI); \ 455 (void)NumUses; \ 456 LLVM_DEBUG({ \ 457 dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \ 458 << " found\n"; \ 459 if (RFI.Declaration) \ 460 dbgs() << TAG << "-> got " << NumUses << " uses in " \ 461 << RFI.getNumFunctionsWithUses() \ 462 << " different functions.\n"; \ 463 }); \ 464 } \ 465 } 466 #include "llvm/Frontend/OpenMP/OMPKinds.def" 467 468 // TODO: We should attach the attributes defined in OMPKinds.def. 469 } 470 471 /// Collection of known kernels (\see Kernel) in the module. 472 SmallPtrSetImpl<Kernel> &Kernels; 473 }; 474 475 struct OpenMPOpt { 476 477 using OptimizationRemarkGetter = 478 function_ref<OptimizationRemarkEmitter &(Function *)>; 479 480 OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater, 481 OptimizationRemarkGetter OREGetter, 482 OMPInformationCache &OMPInfoCache, Attributor &A) 483 : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater), 484 OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {} 485 486 /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice. 487 bool run() { 488 if (SCC.empty()) 489 return false; 490 491 bool Changed = false; 492 493 LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size() 494 << " functions in a slice with " 495 << OMPInfoCache.ModuleSlice.size() << " functions\n"); 496 497 if (PrintICVValues) 498 printICVs(); 499 if (PrintOpenMPKernels) 500 printKernels(); 501 502 Changed |= rewriteDeviceCodeStateMachine(); 503 504 Changed |= runAttributor(); 505 506 // Recollect uses, in case Attributor deleted any. 507 OMPInfoCache.recollectUses(); 508 509 Changed |= deduplicateRuntimeCalls(); 510 Changed |= deleteParallelRegions(); 511 512 return Changed; 513 } 514 515 /// Print initial ICV values for testing. 516 /// FIXME: This should be done from the Attributor once it is added. 517 void printICVs() const { 518 InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel}; 519 520 for (Function *F : OMPInfoCache.ModuleSlice) { 521 for (auto ICV : ICVs) { 522 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 523 auto Remark = [&](OptimizationRemark OR) { 524 return OR << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name) 525 << " Value: " 526 << (ICVInfo.InitValue 527 ? ICVInfo.InitValue->getValue().toString(10, true) 528 : "IMPLEMENTATION_DEFINED"); 529 }; 530 531 emitRemarkOnFunction(F, "OpenMPICVTracker", Remark); 532 } 533 } 534 } 535 536 /// Print OpenMP GPU kernels for testing. 537 void printKernels() const { 538 for (Function *F : SCC) { 539 if (!OMPInfoCache.Kernels.count(F)) 540 continue; 541 542 auto Remark = [&](OptimizationRemark OR) { 543 return OR << "OpenMP GPU kernel " 544 << ore::NV("OpenMPGPUKernel", F->getName()) << "\n"; 545 }; 546 547 emitRemarkOnFunction(F, "OpenMPGPU", Remark); 548 } 549 } 550 551 /// Return the call if \p U is a callee use in a regular call. If \p RFI is 552 /// given it has to be the callee or a nullptr is returned. 553 static CallInst *getCallIfRegularCall( 554 Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 555 CallInst *CI = dyn_cast<CallInst>(U.getUser()); 556 if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() && 557 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 558 return CI; 559 return nullptr; 560 } 561 562 /// Return the call if \p V is a regular call. If \p RFI is given it has to be 563 /// the callee or a nullptr is returned. 564 static CallInst *getCallIfRegularCall( 565 Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 566 CallInst *CI = dyn_cast<CallInst>(&V); 567 if (CI && !CI->hasOperandBundles() && 568 (!RFI || CI->getCalledFunction() == RFI->Declaration)) 569 return CI; 570 return nullptr; 571 } 572 573 private: 574 /// Try to delete parallel regions if possible. 575 bool deleteParallelRegions() { 576 const unsigned CallbackCalleeOperand = 2; 577 578 OMPInformationCache::RuntimeFunctionInfo &RFI = 579 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 580 581 if (!RFI.Declaration) 582 return false; 583 584 bool Changed = false; 585 auto DeleteCallCB = [&](Use &U, Function &) { 586 CallInst *CI = getCallIfRegularCall(U); 587 if (!CI) 588 return false; 589 auto *Fn = dyn_cast<Function>( 590 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts()); 591 if (!Fn) 592 return false; 593 if (!Fn->onlyReadsMemory()) 594 return false; 595 if (!Fn->hasFnAttribute(Attribute::WillReturn)) 596 return false; 597 598 LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in " 599 << CI->getCaller()->getName() << "\n"); 600 601 auto Remark = [&](OptimizationRemark OR) { 602 return OR << "Parallel region in " 603 << ore::NV("OpenMPParallelDelete", CI->getCaller()->getName()) 604 << " deleted"; 605 }; 606 emitRemark<OptimizationRemark>(CI, "OpenMPParallelRegionDeletion", 607 Remark); 608 609 CGUpdater.removeCallSite(*CI); 610 CI->eraseFromParent(); 611 Changed = true; 612 ++NumOpenMPParallelRegionsDeleted; 613 return true; 614 }; 615 616 RFI.foreachUse(SCC, DeleteCallCB); 617 618 return Changed; 619 } 620 621 /// Try to eliminate runtime calls by reusing existing ones. 622 bool deduplicateRuntimeCalls() { 623 bool Changed = false; 624 625 RuntimeFunction DeduplicableRuntimeCallIDs[] = { 626 OMPRTL_omp_get_num_threads, 627 OMPRTL_omp_in_parallel, 628 OMPRTL_omp_get_cancellation, 629 OMPRTL_omp_get_thread_limit, 630 OMPRTL_omp_get_supported_active_levels, 631 OMPRTL_omp_get_level, 632 OMPRTL_omp_get_ancestor_thread_num, 633 OMPRTL_omp_get_team_size, 634 OMPRTL_omp_get_active_level, 635 OMPRTL_omp_in_final, 636 OMPRTL_omp_get_proc_bind, 637 OMPRTL_omp_get_num_places, 638 OMPRTL_omp_get_num_procs, 639 OMPRTL_omp_get_place_num, 640 OMPRTL_omp_get_partition_num_places, 641 OMPRTL_omp_get_partition_place_nums}; 642 643 // Global-tid is handled separately. 644 SmallSetVector<Value *, 16> GTIdArgs; 645 collectGlobalThreadIdArguments(GTIdArgs); 646 LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size() 647 << " global thread ID arguments\n"); 648 649 for (Function *F : SCC) { 650 for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs) 651 deduplicateRuntimeCalls(*F, 652 OMPInfoCache.RFIs[DeduplicableRuntimeCallID]); 653 654 // __kmpc_global_thread_num is special as we can replace it with an 655 // argument in enough cases to make it worth trying. 656 Value *GTIdArg = nullptr; 657 for (Argument &Arg : F->args()) 658 if (GTIdArgs.count(&Arg)) { 659 GTIdArg = &Arg; 660 break; 661 } 662 Changed |= deduplicateRuntimeCalls( 663 *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg); 664 } 665 666 return Changed; 667 } 668 669 static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent, 670 bool GlobalOnly, bool &SingleChoice) { 671 if (CurrentIdent == NextIdent) 672 return CurrentIdent; 673 674 // TODO: Figure out how to actually combine multiple debug locations. For 675 // now we just keep an existing one if there is a single choice. 676 if (!GlobalOnly || isa<GlobalValue>(NextIdent)) { 677 SingleChoice = !CurrentIdent; 678 return NextIdent; 679 } 680 return nullptr; 681 } 682 683 /// Return an `struct ident_t*` value that represents the ones used in the 684 /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not 685 /// return a local `struct ident_t*`. For now, if we cannot find a suitable 686 /// return value we create one from scratch. We also do not yet combine 687 /// information, e.g., the source locations, see combinedIdentStruct. 688 Value * 689 getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI, 690 Function &F, bool GlobalOnly) { 691 bool SingleChoice = true; 692 Value *Ident = nullptr; 693 auto CombineIdentStruct = [&](Use &U, Function &Caller) { 694 CallInst *CI = getCallIfRegularCall(U, &RFI); 695 if (!CI || &F != &Caller) 696 return false; 697 Ident = combinedIdentStruct(Ident, CI->getArgOperand(0), 698 /* GlobalOnly */ true, SingleChoice); 699 return false; 700 }; 701 RFI.foreachUse(SCC, CombineIdentStruct); 702 703 if (!Ident || !SingleChoice) { 704 // The IRBuilder uses the insertion block to get to the module, this is 705 // unfortunate but we work around it for now. 706 if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock()) 707 OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy( 708 &F.getEntryBlock(), F.getEntryBlock().begin())); 709 // Create a fallback location if non was found. 710 // TODO: Use the debug locations of the calls instead. 711 Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr(); 712 Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc); 713 } 714 return Ident; 715 } 716 717 /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or 718 /// \p ReplVal if given. 719 bool deduplicateRuntimeCalls(Function &F, 720 OMPInformationCache::RuntimeFunctionInfo &RFI, 721 Value *ReplVal = nullptr) { 722 auto *UV = RFI.getUseVector(F); 723 if (!UV || UV->size() + (ReplVal != nullptr) < 2) 724 return false; 725 726 LLVM_DEBUG( 727 dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name 728 << (ReplVal ? " with an existing value\n" : "\n") << "\n"); 729 730 assert((!ReplVal || (isa<Argument>(ReplVal) && 731 cast<Argument>(ReplVal)->getParent() == &F)) && 732 "Unexpected replacement value!"); 733 734 // TODO: Use dominance to find a good position instead. 735 auto CanBeMoved = [this](CallBase &CB) { 736 unsigned NumArgs = CB.getNumArgOperands(); 737 if (NumArgs == 0) 738 return true; 739 if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr) 740 return false; 741 for (unsigned u = 1; u < NumArgs; ++u) 742 if (isa<Instruction>(CB.getArgOperand(u))) 743 return false; 744 return true; 745 }; 746 747 if (!ReplVal) { 748 for (Use *U : *UV) 749 if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) { 750 if (!CanBeMoved(*CI)) 751 continue; 752 753 auto Remark = [&](OptimizationRemark OR) { 754 auto newLoc = &*F.getEntryBlock().getFirstInsertionPt(); 755 return OR << "OpenMP runtime call " 756 << ore::NV("OpenMPOptRuntime", RFI.Name) << " moved to " 757 << ore::NV("OpenMPRuntimeMoves", newLoc->getDebugLoc()); 758 }; 759 emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeCodeMotion", Remark); 760 761 CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt()); 762 ReplVal = CI; 763 break; 764 } 765 if (!ReplVal) 766 return false; 767 } 768 769 // If we use a call as a replacement value we need to make sure the ident is 770 // valid at the new location. For now we just pick a global one, either 771 // existing and used by one of the calls, or created from scratch. 772 if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) { 773 if (CI->getNumArgOperands() > 0 && 774 CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) { 775 Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F, 776 /* GlobalOnly */ true); 777 CI->setArgOperand(0, Ident); 778 } 779 } 780 781 bool Changed = false; 782 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 783 CallInst *CI = getCallIfRegularCall(U, &RFI); 784 if (!CI || CI == ReplVal || &F != &Caller) 785 return false; 786 assert(CI->getCaller() == &F && "Unexpected call!"); 787 788 auto Remark = [&](OptimizationRemark OR) { 789 return OR << "OpenMP runtime call " 790 << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated"; 791 }; 792 emitRemark<OptimizationRemark>(CI, "OpenMPRuntimeDeduplicated", Remark); 793 794 CGUpdater.removeCallSite(*CI); 795 CI->replaceAllUsesWith(ReplVal); 796 CI->eraseFromParent(); 797 ++NumOpenMPRuntimeCallsDeduplicated; 798 Changed = true; 799 return true; 800 }; 801 RFI.foreachUse(SCC, ReplaceAndDeleteCB); 802 803 return Changed; 804 } 805 806 /// Collect arguments that represent the global thread id in \p GTIdArgs. 807 void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> >IdArgs) { 808 // TODO: Below we basically perform a fixpoint iteration with a pessimistic 809 // initialization. We could define an AbstractAttribute instead and 810 // run the Attributor here once it can be run as an SCC pass. 811 812 // Helper to check the argument \p ArgNo at all call sites of \p F for 813 // a GTId. 814 auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) { 815 if (!F.hasLocalLinkage()) 816 return false; 817 for (Use &U : F.uses()) { 818 if (CallInst *CI = getCallIfRegularCall(U)) { 819 Value *ArgOp = CI->getArgOperand(ArgNo); 820 if (CI == &RefCI || GTIdArgs.count(ArgOp) || 821 getCallIfRegularCall( 822 *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num])) 823 continue; 824 } 825 return false; 826 } 827 return true; 828 }; 829 830 // Helper to identify uses of a GTId as GTId arguments. 831 auto AddUserArgs = [&](Value >Id) { 832 for (Use &U : GTId.uses()) 833 if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) 834 if (CI->isArgOperand(&U)) 835 if (Function *Callee = CI->getCalledFunction()) 836 if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI)) 837 GTIdArgs.insert(Callee->getArg(U.getOperandNo())); 838 }; 839 840 // The argument users of __kmpc_global_thread_num calls are GTIds. 841 OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI = 842 OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]; 843 844 GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) { 845 if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI)) 846 AddUserArgs(*CI); 847 return false; 848 }); 849 850 // Transitively search for more arguments by looking at the users of the 851 // ones we know already. During the search the GTIdArgs vector is extended 852 // so we cannot cache the size nor can we use a range based for. 853 for (unsigned u = 0; u < GTIdArgs.size(); ++u) 854 AddUserArgs(*GTIdArgs[u]); 855 } 856 857 /// Kernel (=GPU) optimizations and utility functions 858 /// 859 ///{{ 860 861 /// Check if \p F is a kernel, hence entry point for target offloading. 862 bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); } 863 864 /// Cache to remember the unique kernel for a function. 865 DenseMap<Function *, Optional<Kernel>> UniqueKernelMap; 866 867 /// Find the unique kernel that will execute \p F, if any. 868 Kernel getUniqueKernelFor(Function &F); 869 870 /// Find the unique kernel that will execute \p I, if any. 871 Kernel getUniqueKernelFor(Instruction &I) { 872 return getUniqueKernelFor(*I.getFunction()); 873 } 874 875 /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in 876 /// the cases we can avoid taking the address of a function. 877 bool rewriteDeviceCodeStateMachine(); 878 879 /// 880 ///}} 881 882 /// Emit a remark generically 883 /// 884 /// This template function can be used to generically emit a remark. The 885 /// RemarkKind should be one of the following: 886 /// - OptimizationRemark to indicate a successful optimization attempt 887 /// - OptimizationRemarkMissed to report a failed optimization attempt 888 /// - OptimizationRemarkAnalysis to provide additional information about an 889 /// optimization attempt 890 /// 891 /// The remark is built using a callback function provided by the caller that 892 /// takes a RemarkKind as input and returns a RemarkKind. 893 template <typename RemarkKind, 894 typename RemarkCallBack = function_ref<RemarkKind(RemarkKind &&)>> 895 void emitRemark(Instruction *Inst, StringRef RemarkName, 896 RemarkCallBack &&RemarkCB) const { 897 Function *F = Inst->getParent()->getParent(); 898 auto &ORE = OREGetter(F); 899 900 ORE.emit( 901 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, Inst)); }); 902 } 903 904 /// Emit a remark on a function. Since only OptimizationRemark is supporting 905 /// this, it can't be made generic. 906 void 907 emitRemarkOnFunction(Function *F, StringRef RemarkName, 908 function_ref<OptimizationRemark(OptimizationRemark &&)> 909 &&RemarkCB) const { 910 auto &ORE = OREGetter(F); 911 912 ORE.emit([&]() { 913 return RemarkCB(OptimizationRemark(DEBUG_TYPE, RemarkName, F)); 914 }); 915 } 916 917 /// The underlying module. 918 Module &M; 919 920 /// The SCC we are operating on. 921 SmallVectorImpl<Function *> &SCC; 922 923 /// Callback to update the call graph, the first argument is a removed call, 924 /// the second an optional replacement call. 925 CallGraphUpdater &CGUpdater; 926 927 /// Callback to get an OptimizationRemarkEmitter from a Function * 928 OptimizationRemarkGetter OREGetter; 929 930 /// OpenMP-specific information cache. Also Used for Attributor runs. 931 OMPInformationCache &OMPInfoCache; 932 933 /// Attributor instance. 934 Attributor &A; 935 936 /// Helper function to run Attributor on SCC. 937 bool runAttributor() { 938 if (SCC.empty()) 939 return false; 940 941 registerAAs(); 942 943 ChangeStatus Changed = A.run(); 944 945 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size() 946 << " functions, result: " << Changed << ".\n"); 947 948 return Changed == ChangeStatus::CHANGED; 949 } 950 951 /// Populate the Attributor with abstract attribute opportunities in the 952 /// function. 953 void registerAAs() { 954 for (Function *F : SCC) { 955 if (F->isDeclaration()) 956 continue; 957 958 A.getOrCreateAAFor<AAICVTracker>(IRPosition::function(*F)); 959 } 960 } 961 }; 962 963 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) { 964 if (!OMPInfoCache.ModuleSlice.count(&F)) 965 return nullptr; 966 967 // Use a scope to keep the lifetime of the CachedKernel short. 968 { 969 Optional<Kernel> &CachedKernel = UniqueKernelMap[&F]; 970 if (CachedKernel) 971 return *CachedKernel; 972 973 // TODO: We should use an AA to create an (optimistic and callback 974 // call-aware) call graph. For now we stick to simple patterns that 975 // are less powerful, basically the worst fixpoint. 976 if (isKernel(F)) { 977 CachedKernel = Kernel(&F); 978 return *CachedKernel; 979 } 980 981 CachedKernel = nullptr; 982 if (!F.hasLocalLinkage()) 983 return nullptr; 984 } 985 986 auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel { 987 if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 988 // Allow use in equality comparisons. 989 if (Cmp->isEquality()) 990 return getUniqueKernelFor(*Cmp); 991 return nullptr; 992 } 993 if (auto *CB = dyn_cast<CallBase>(U.getUser())) { 994 // Allow direct calls. 995 if (CB->isCallee(&U)) 996 return getUniqueKernelFor(*CB); 997 // Allow the use in __kmpc_kernel_prepare_parallel calls. 998 if (Function *Callee = CB->getCalledFunction()) 999 if (Callee->getName() == "__kmpc_kernel_prepare_parallel") 1000 return getUniqueKernelFor(*CB); 1001 return nullptr; 1002 } 1003 // Disallow every other use. 1004 return nullptr; 1005 }; 1006 1007 // TODO: In the future we want to track more than just a unique kernel. 1008 SmallPtrSet<Kernel, 2> PotentialKernels; 1009 foreachUse(F, [&](const Use &U) { 1010 PotentialKernels.insert(GetUniqueKernelForUse(U)); 1011 }); 1012 1013 Kernel K = nullptr; 1014 if (PotentialKernels.size() == 1) 1015 K = *PotentialKernels.begin(); 1016 1017 // Cache the result. 1018 UniqueKernelMap[&F] = K; 1019 1020 return K; 1021 } 1022 1023 bool OpenMPOpt::rewriteDeviceCodeStateMachine() { 1024 OMPInformationCache::RuntimeFunctionInfo &KernelPrepareParallelRFI = 1025 OMPInfoCache.RFIs[OMPRTL___kmpc_kernel_prepare_parallel]; 1026 1027 bool Changed = false; 1028 if (!KernelPrepareParallelRFI) 1029 return Changed; 1030 1031 for (Function *F : SCC) { 1032 1033 // Check if the function is uses in a __kmpc_kernel_prepare_parallel call at 1034 // all. 1035 bool UnknownUse = false; 1036 unsigned NumDirectCalls = 0; 1037 1038 SmallVector<Use *, 2> ToBeReplacedStateMachineUses; 1039 foreachUse(*F, [&](Use &U) { 1040 if (auto *CB = dyn_cast<CallBase>(U.getUser())) 1041 if (CB->isCallee(&U)) { 1042 ++NumDirectCalls; 1043 return; 1044 } 1045 1046 if (isa<ICmpInst>(U.getUser())) { 1047 ToBeReplacedStateMachineUses.push_back(&U); 1048 return; 1049 } 1050 if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), 1051 &KernelPrepareParallelRFI)) { 1052 ToBeReplacedStateMachineUses.push_back(&U); 1053 return; 1054 } 1055 UnknownUse = true; 1056 }); 1057 1058 // If this ever hits, we should investigate. 1059 if (UnknownUse || NumDirectCalls != 1) 1060 continue; 1061 1062 // TODO: This is not a necessary restriction and should be lifted. 1063 if (ToBeReplacedStateMachineUses.size() != 2) 1064 continue; 1065 1066 // Even if we have __kmpc_kernel_prepare_parallel calls, we (for now) give 1067 // up if the function is not called from a unique kernel. 1068 Kernel K = getUniqueKernelFor(*F); 1069 if (!K) 1070 continue; 1071 1072 // We now know F is a parallel body function called only from the kernel K. 1073 // We also identified the state machine uses in which we replace the 1074 // function pointer by a new global symbol for identification purposes. This 1075 // ensures only direct calls to the function are left. 1076 1077 Module &M = *F->getParent(); 1078 Type *Int8Ty = Type::getInt8Ty(M.getContext()); 1079 1080 auto *ID = new GlobalVariable( 1081 M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage, 1082 UndefValue::get(Int8Ty), F->getName() + ".ID"); 1083 1084 for (Use *U : ToBeReplacedStateMachineUses) 1085 U->set(ConstantExpr::getBitCast(ID, U->get()->getType())); 1086 1087 ++NumOpenMPParallelRegionsReplacedInGPUStateMachine; 1088 1089 Changed = true; 1090 } 1091 1092 return Changed; 1093 } 1094 1095 /// Abstract Attribute for tracking ICV values. 1096 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> { 1097 using Base = StateWrapper<BooleanState, AbstractAttribute>; 1098 AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 1099 1100 /// Returns true if value is assumed to be tracked. 1101 bool isAssumedTracked() const { return getAssumed(); } 1102 1103 /// Returns true if value is known to be tracked. 1104 bool isKnownTracked() const { return getAssumed(); } 1105 1106 /// Create an abstract attribute biew for the position \p IRP. 1107 static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A); 1108 1109 /// Return the value with which \p I can be replaced for specific \p ICV. 1110 virtual Value *getReplacementValue(InternalControlVar ICV, 1111 const Instruction *I, Attributor &A) = 0; 1112 1113 /// See AbstractAttribute::getName() 1114 const std::string getName() const override { return "AAICVTracker"; } 1115 1116 static const char ID; 1117 }; 1118 1119 struct AAICVTrackerFunction : public AAICVTracker { 1120 AAICVTrackerFunction(const IRPosition &IRP, Attributor &A) 1121 : AAICVTracker(IRP, A) {} 1122 1123 // FIXME: come up with better string. 1124 const std::string getAsStr() const override { return "ICVTracker"; } 1125 1126 // FIXME: come up with some stats. 1127 void trackStatistics() const override {} 1128 1129 /// TODO: decide whether to deduplicate here, or use current 1130 /// deduplicateRuntimeCalls function. 1131 ChangeStatus manifest(Attributor &A) override { 1132 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1133 1134 for (InternalControlVar &ICV : TrackableICVs) 1135 if (deduplicateICVGetters(ICV, A)) 1136 Changed = ChangeStatus::CHANGED; 1137 1138 return Changed; 1139 } 1140 1141 bool deduplicateICVGetters(InternalControlVar &ICV, Attributor &A) { 1142 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 1143 auto &ICVInfo = OMPInfoCache.ICVs[ICV]; 1144 auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter]; 1145 1146 bool Changed = false; 1147 1148 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 1149 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI); 1150 Instruction *UserI = cast<Instruction>(U.getUser()); 1151 Value *ReplVal = getReplacementValue(ICV, UserI, A); 1152 1153 if (!ReplVal || !CI) 1154 return false; 1155 1156 A.removeCallSite(CI); 1157 CI->replaceAllUsesWith(ReplVal); 1158 CI->eraseFromParent(); 1159 Changed = true; 1160 return true; 1161 }; 1162 1163 GetterRFI.foreachUse(ReplaceAndDeleteCB, getAnchorScope()); 1164 return Changed; 1165 } 1166 1167 // Map of ICV to their values at specific program point. 1168 EnumeratedArray<SmallSetVector<ICVValue, 4>, InternalControlVar, 1169 InternalControlVar::ICV___last> 1170 ICVValuesMap; 1171 1172 // Currently only nthreads is being tracked. 1173 // this array will only grow with time. 1174 InternalControlVar TrackableICVs[1] = {ICV_nthreads}; 1175 1176 ChangeStatus updateImpl(Attributor &A) override { 1177 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 1178 1179 Function *F = getAnchorScope(); 1180 1181 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 1182 1183 for (InternalControlVar ICV : TrackableICVs) { 1184 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 1185 1186 auto TrackValues = [&](Use &U, Function &) { 1187 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U); 1188 if (!CI) 1189 return false; 1190 1191 // FIXME: handle setters with more that 1 arguments. 1192 /// Track new value. 1193 if (ICVValuesMap[ICV].insert(ICVValue(CI, CI->getArgOperand(0)))) 1194 HasChanged = ChangeStatus::CHANGED; 1195 1196 return false; 1197 }; 1198 1199 SetterRFI.foreachUse(TrackValues, F); 1200 } 1201 1202 return HasChanged; 1203 } 1204 1205 /// Return the value with which \p I can be replaced for specific \p ICV. 1206 Value *getReplacementValue(InternalControlVar ICV, const Instruction *I, 1207 Attributor &A) override { 1208 const BasicBlock *CurrBB = I->getParent(); 1209 1210 auto &ValuesSet = ICVValuesMap[ICV]; 1211 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 1212 auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter]; 1213 1214 for (const auto &ICVVal : ValuesSet) { 1215 if (CurrBB == ICVVal.Inst->getParent()) { 1216 if (!ICVVal.Inst->comesBefore(I)) 1217 continue; 1218 1219 // both instructions are in the same BB and at \p I we know the ICV 1220 // value. 1221 while (I != ICVVal.Inst) { 1222 // we don't yet know if a call might update an ICV. 1223 // TODO: check callsite AA for value. 1224 if (const auto *CB = dyn_cast<CallBase>(I)) 1225 if (CB->getCalledFunction() != GetterRFI.Declaration) 1226 return nullptr; 1227 1228 I = I->getPrevNode(); 1229 } 1230 1231 // No call in between, return the value. 1232 return ICVVal.TrackedValue; 1233 } 1234 } 1235 1236 // No value was tracked. 1237 return nullptr; 1238 } 1239 }; 1240 } // namespace 1241 1242 const char AAICVTracker::ID = 0; 1243 1244 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP, 1245 Attributor &A) { 1246 AAICVTracker *AA = nullptr; 1247 switch (IRP.getPositionKind()) { 1248 case IRPosition::IRP_INVALID: 1249 case IRPosition::IRP_FLOAT: 1250 case IRPosition::IRP_ARGUMENT: 1251 case IRPosition::IRP_RETURNED: 1252 case IRPosition::IRP_CALL_SITE_RETURNED: 1253 case IRPosition::IRP_CALL_SITE_ARGUMENT: 1254 case IRPosition::IRP_CALL_SITE: 1255 llvm_unreachable("ICVTracker can only be created for function position!"); 1256 case IRPosition::IRP_FUNCTION: 1257 AA = new (A.Allocator) AAICVTrackerFunction(IRP, A); 1258 break; 1259 } 1260 1261 return *AA; 1262 } 1263 1264 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C, 1265 CGSCCAnalysisManager &AM, 1266 LazyCallGraph &CG, CGSCCUpdateResult &UR) { 1267 if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule)) 1268 return PreservedAnalyses::all(); 1269 1270 if (DisableOpenMPOptimizations) 1271 return PreservedAnalyses::all(); 1272 1273 SmallVector<Function *, 16> SCC; 1274 for (LazyCallGraph::Node &N : C) 1275 SCC.push_back(&N.getFunction()); 1276 1277 if (SCC.empty()) 1278 return PreservedAnalyses::all(); 1279 1280 FunctionAnalysisManager &FAM = 1281 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 1282 1283 AnalysisGetter AG(FAM); 1284 1285 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 1286 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 1287 }; 1288 1289 CallGraphUpdater CGUpdater; 1290 CGUpdater.initialize(CG, C, AM, UR); 1291 1292 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 1293 BumpPtrAllocator Allocator; 1294 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator, 1295 /*CGSCC*/ Functions, OMPInModule.getKernels()); 1296 1297 Attributor A(Functions, InfoCache, CGUpdater); 1298 1299 // TODO: Compute the module slice we are allowed to look at. 1300 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 1301 bool Changed = OMPOpt.run(); 1302 (void)Changed; 1303 return PreservedAnalyses::all(); 1304 } 1305 1306 namespace { 1307 1308 struct OpenMPOptLegacyPass : public CallGraphSCCPass { 1309 CallGraphUpdater CGUpdater; 1310 OpenMPInModule OMPInModule; 1311 static char ID; 1312 1313 OpenMPOptLegacyPass() : CallGraphSCCPass(ID) { 1314 initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry()); 1315 } 1316 1317 void getAnalysisUsage(AnalysisUsage &AU) const override { 1318 CallGraphSCCPass::getAnalysisUsage(AU); 1319 } 1320 1321 bool doInitialization(CallGraph &CG) override { 1322 // Disable the pass if there is no OpenMP (runtime call) in the module. 1323 containsOpenMP(CG.getModule(), OMPInModule); 1324 return false; 1325 } 1326 1327 bool runOnSCC(CallGraphSCC &CGSCC) override { 1328 if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule)) 1329 return false; 1330 if (DisableOpenMPOptimizations || skipSCC(CGSCC)) 1331 return false; 1332 1333 SmallVector<Function *, 16> SCC; 1334 for (CallGraphNode *CGN : CGSCC) 1335 if (Function *Fn = CGN->getFunction()) 1336 if (!Fn->isDeclaration()) 1337 SCC.push_back(Fn); 1338 1339 if (SCC.empty()) 1340 return false; 1341 1342 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 1343 CGUpdater.initialize(CG, CGSCC); 1344 1345 // Maintain a map of functions to avoid rebuilding the ORE 1346 DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap; 1347 auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & { 1348 std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F]; 1349 if (!ORE) 1350 ORE = std::make_unique<OptimizationRemarkEmitter>(F); 1351 return *ORE; 1352 }; 1353 1354 AnalysisGetter AG; 1355 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 1356 BumpPtrAllocator Allocator; 1357 OMPInformationCache InfoCache( 1358 *(Functions.back()->getParent()), AG, Allocator, 1359 /*CGSCC*/ Functions, OMPInModule.getKernels()); 1360 1361 Attributor A(Functions, InfoCache, CGUpdater); 1362 1363 // TODO: Compute the module slice we are allowed to look at. 1364 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 1365 return OMPOpt.run(); 1366 } 1367 1368 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 1369 }; 1370 1371 } // end anonymous namespace 1372 1373 void OpenMPInModule::identifyKernels(Module &M) { 1374 1375 NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations"); 1376 if (!MD) 1377 return; 1378 1379 for (auto *Op : MD->operands()) { 1380 if (Op->getNumOperands() < 2) 1381 continue; 1382 MDString *KindID = dyn_cast<MDString>(Op->getOperand(1)); 1383 if (!KindID || KindID->getString() != "kernel") 1384 continue; 1385 1386 Function *KernelFn = 1387 mdconst::dyn_extract_or_null<Function>(Op->getOperand(0)); 1388 if (!KernelFn) 1389 continue; 1390 1391 ++NumOpenMPTargetRegionKernels; 1392 1393 Kernels.insert(KernelFn); 1394 } 1395 } 1396 1397 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) { 1398 if (OMPInModule.isKnown()) 1399 return OMPInModule; 1400 1401 // MSVC doesn't like long if-else chains for some reason and instead just 1402 // issues an error. Work around it.. 1403 do { 1404 #define OMP_RTL(_Enum, _Name, ...) \ 1405 if (M.getFunction(_Name)) { \ 1406 OMPInModule = true; \ 1407 break; \ 1408 } 1409 #include "llvm/Frontend/OpenMP/OMPKinds.def" 1410 } while (false); 1411 1412 // Identify kernels once. TODO: We should split the OMPInformationCache into a 1413 // module and an SCC part. The kernel information, among other things, could 1414 // go into the module part. 1415 if (OMPInModule.isKnown() && OMPInModule) { 1416 OMPInModule.identifyKernels(M); 1417 return true; 1418 } 1419 1420 return OMPInModule = false; 1421 } 1422 1423 char OpenMPOptLegacyPass::ID = 0; 1424 1425 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt", 1426 "OpenMP specific optimizations", false, false) 1427 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1428 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt", 1429 "OpenMP specific optimizations", false, false) 1430 1431 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); } 1432