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 // - Replacing globalized device memory with stack memory. 13 // - Replacing globalized device memory with shared memory. 14 // - Parallel region merging. 15 // - Transforming generic-mode device kernels to SPMD mode. 16 // - Specializing the state machine for generic-mode device kernels. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Transforms/IPO/OpenMPOpt.h" 21 22 #include "llvm/ADT/EnumeratedArray.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/CallGraph.h" 26 #include "llvm/Analysis/CallGraphSCCPass.h" 27 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Frontend/OpenMP/OMPConstants.h" 30 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 31 #include "llvm/IR/Assumptions.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/GlobalValue.h" 34 #include "llvm/IR/Instruction.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/InitializePasses.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Transforms/IPO.h" 39 #include "llvm/Transforms/IPO/Attributor.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 42 #include "llvm/Transforms/Utils/CodeExtractor.h" 43 44 using namespace llvm; 45 using namespace omp; 46 47 #define DEBUG_TYPE "openmp-opt" 48 49 static cl::opt<bool> DisableOpenMPOptimizations( 50 "openmp-opt-disable", cl::ZeroOrMore, 51 cl::desc("Disable OpenMP specific optimizations."), cl::Hidden, 52 cl::init(false)); 53 54 static cl::opt<bool> EnableParallelRegionMerging( 55 "openmp-opt-enable-merging", cl::ZeroOrMore, 56 cl::desc("Enable the OpenMP region merging optimization."), cl::Hidden, 57 cl::init(false)); 58 59 static cl::opt<bool> 60 DisableInternalization("openmp-opt-disable-internalization", cl::ZeroOrMore, 61 cl::desc("Disable function internalization."), 62 cl::Hidden, cl::init(false)); 63 64 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false), 65 cl::Hidden); 66 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels", 67 cl::init(false), cl::Hidden); 68 69 static cl::opt<bool> HideMemoryTransferLatency( 70 "openmp-hide-memory-transfer-latency", 71 cl::desc("[WIP] Tries to hide the latency of host to device memory" 72 " transfers"), 73 cl::Hidden, cl::init(false)); 74 75 static cl::opt<bool> DisableOpenMPOptDeglobalization( 76 "openmp-opt-disable-deglobalization", cl::ZeroOrMore, 77 cl::desc("Disable OpenMP optimizations involving deglobalization."), 78 cl::Hidden, cl::init(false)); 79 80 static cl::opt<bool> DisableOpenMPOptSPMDization( 81 "openmp-opt-disable-spmdization", cl::ZeroOrMore, 82 cl::desc("Disable OpenMP optimizations involving SPMD-ization."), 83 cl::Hidden, cl::init(false)); 84 85 static cl::opt<bool> DisableOpenMPOptFolding( 86 "openmp-opt-disable-folding", cl::ZeroOrMore, 87 cl::desc("Disable OpenMP optimizations involving folding."), cl::Hidden, 88 cl::init(false)); 89 90 static cl::opt<bool> DisableOpenMPOptStateMachineRewrite( 91 "openmp-opt-disable-state-machine-rewrite", cl::ZeroOrMore, 92 cl::desc("Disable OpenMP optimizations that replace the state machine."), 93 cl::Hidden, cl::init(false)); 94 95 static cl::opt<bool> PrintModuleAfterOptimizations( 96 "openmp-opt-print-module", cl::ZeroOrMore, 97 cl::desc("Print the current module after OpenMP optimizations."), 98 cl::Hidden, cl::init(false)); 99 100 static cl::opt<bool> AlwaysInlineDeviceFunctions( 101 "openmp-opt-inline-device", cl::ZeroOrMore, 102 cl::desc("Inline all applicible functions on the device."), cl::Hidden, 103 cl::init(false)); 104 105 static cl::opt<bool> 106 EnableVerboseRemarks("openmp-opt-verbose-remarks", cl::ZeroOrMore, 107 cl::desc("Enables more verbose remarks."), cl::Hidden, 108 cl::init(false)); 109 110 STATISTIC(NumOpenMPRuntimeCallsDeduplicated, 111 "Number of OpenMP runtime calls deduplicated"); 112 STATISTIC(NumOpenMPParallelRegionsDeleted, 113 "Number of OpenMP parallel regions deleted"); 114 STATISTIC(NumOpenMPRuntimeFunctionsIdentified, 115 "Number of OpenMP runtime functions identified"); 116 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified, 117 "Number of OpenMP runtime function uses identified"); 118 STATISTIC(NumOpenMPTargetRegionKernels, 119 "Number of OpenMP target region entry points (=kernels) identified"); 120 STATISTIC(NumOpenMPTargetRegionKernelsSPMD, 121 "Number of OpenMP target region entry points (=kernels) executed in " 122 "SPMD-mode instead of generic-mode"); 123 STATISTIC(NumOpenMPTargetRegionKernelsWithoutStateMachine, 124 "Number of OpenMP target region entry points (=kernels) executed in " 125 "generic-mode without a state machines"); 126 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback, 127 "Number of OpenMP target region entry points (=kernels) executed in " 128 "generic-mode with customized state machines with fallback"); 129 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback, 130 "Number of OpenMP target region entry points (=kernels) executed in " 131 "generic-mode with customized state machines without fallback"); 132 STATISTIC( 133 NumOpenMPParallelRegionsReplacedInGPUStateMachine, 134 "Number of OpenMP parallel regions replaced with ID in GPU state machines"); 135 STATISTIC(NumOpenMPParallelRegionsMerged, 136 "Number of OpenMP parallel regions merged"); 137 STATISTIC(NumBytesMovedToSharedMemory, 138 "Amount of memory pushed to shared memory"); 139 140 #if !defined(NDEBUG) 141 static constexpr auto TAG = "[" DEBUG_TYPE "]"; 142 #endif 143 144 namespace { 145 146 enum class AddressSpace : unsigned { 147 Generic = 0, 148 Global = 1, 149 Shared = 3, 150 Constant = 4, 151 Local = 5, 152 }; 153 154 struct AAHeapToShared; 155 156 struct AAICVTracker; 157 158 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for 159 /// Attributor runs. 160 struct OMPInformationCache : public InformationCache { 161 OMPInformationCache(Module &M, AnalysisGetter &AG, 162 BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC, 163 SmallPtrSetImpl<Kernel> &Kernels) 164 : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M), 165 Kernels(Kernels) { 166 167 OMPBuilder.initialize(); 168 initializeRuntimeFunctions(); 169 initializeInternalControlVars(); 170 } 171 172 /// Generic information that describes an internal control variable. 173 struct InternalControlVarInfo { 174 /// The kind, as described by InternalControlVar enum. 175 InternalControlVar Kind; 176 177 /// The name of the ICV. 178 StringRef Name; 179 180 /// Environment variable associated with this ICV. 181 StringRef EnvVarName; 182 183 /// Initial value kind. 184 ICVInitValue InitKind; 185 186 /// Initial value. 187 ConstantInt *InitValue; 188 189 /// Setter RTL function associated with this ICV. 190 RuntimeFunction Setter; 191 192 /// Getter RTL function associated with this ICV. 193 RuntimeFunction Getter; 194 195 /// RTL Function corresponding to the override clause of this ICV 196 RuntimeFunction Clause; 197 }; 198 199 /// Generic information that describes a runtime function 200 struct RuntimeFunctionInfo { 201 202 /// The kind, as described by the RuntimeFunction enum. 203 RuntimeFunction Kind; 204 205 /// The name of the function. 206 StringRef Name; 207 208 /// Flag to indicate a variadic function. 209 bool IsVarArg; 210 211 /// The return type of the function. 212 Type *ReturnType; 213 214 /// The argument types of the function. 215 SmallVector<Type *, 8> ArgumentTypes; 216 217 /// The declaration if available. 218 Function *Declaration = nullptr; 219 220 /// Uses of this runtime function per function containing the use. 221 using UseVector = SmallVector<Use *, 16>; 222 223 /// Clear UsesMap for runtime function. 224 void clearUsesMap() { UsesMap.clear(); } 225 226 /// Boolean conversion that is true if the runtime function was found. 227 operator bool() const { return Declaration; } 228 229 /// Return the vector of uses in function \p F. 230 UseVector &getOrCreateUseVector(Function *F) { 231 std::shared_ptr<UseVector> &UV = UsesMap[F]; 232 if (!UV) 233 UV = std::make_shared<UseVector>(); 234 return *UV; 235 } 236 237 /// Return the vector of uses in function \p F or `nullptr` if there are 238 /// none. 239 const UseVector *getUseVector(Function &F) const { 240 auto I = UsesMap.find(&F); 241 if (I != UsesMap.end()) 242 return I->second.get(); 243 return nullptr; 244 } 245 246 /// Return how many functions contain uses of this runtime function. 247 size_t getNumFunctionsWithUses() const { return UsesMap.size(); } 248 249 /// Return the number of arguments (or the minimal number for variadic 250 /// functions). 251 size_t getNumArgs() const { return ArgumentTypes.size(); } 252 253 /// Run the callback \p CB on each use and forget the use if the result is 254 /// true. The callback will be fed the function in which the use was 255 /// encountered as second argument. 256 void foreachUse(SmallVectorImpl<Function *> &SCC, 257 function_ref<bool(Use &, Function &)> CB) { 258 for (Function *F : SCC) 259 foreachUse(CB, F); 260 } 261 262 /// Run the callback \p CB on each use within the function \p F and forget 263 /// the use if the result is true. 264 void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) { 265 SmallVector<unsigned, 8> ToBeDeleted; 266 ToBeDeleted.clear(); 267 268 unsigned Idx = 0; 269 UseVector &UV = getOrCreateUseVector(F); 270 271 for (Use *U : UV) { 272 if (CB(*U, *F)) 273 ToBeDeleted.push_back(Idx); 274 ++Idx; 275 } 276 277 // Remove the to-be-deleted indices in reverse order as prior 278 // modifications will not modify the smaller indices. 279 while (!ToBeDeleted.empty()) { 280 unsigned Idx = ToBeDeleted.pop_back_val(); 281 UV[Idx] = UV.back(); 282 UV.pop_back(); 283 } 284 } 285 286 private: 287 /// Map from functions to all uses of this runtime function contained in 288 /// them. 289 DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap; 290 291 public: 292 /// Iterators for the uses of this runtime function. 293 decltype(UsesMap)::iterator begin() { return UsesMap.begin(); } 294 decltype(UsesMap)::iterator end() { return UsesMap.end(); } 295 }; 296 297 /// An OpenMP-IR-Builder instance 298 OpenMPIRBuilder OMPBuilder; 299 300 /// Map from runtime function kind to the runtime function description. 301 EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction, 302 RuntimeFunction::OMPRTL___last> 303 RFIs; 304 305 /// Map from function declarations/definitions to their runtime enum type. 306 DenseMap<Function *, RuntimeFunction> RuntimeFunctionIDMap; 307 308 /// Map from ICV kind to the ICV description. 309 EnumeratedArray<InternalControlVarInfo, InternalControlVar, 310 InternalControlVar::ICV___last> 311 ICVs; 312 313 /// Helper to initialize all internal control variable information for those 314 /// defined in OMPKinds.def. 315 void initializeInternalControlVars() { 316 #define ICV_RT_SET(_Name, RTL) \ 317 { \ 318 auto &ICV = ICVs[_Name]; \ 319 ICV.Setter = RTL; \ 320 } 321 #define ICV_RT_GET(Name, RTL) \ 322 { \ 323 auto &ICV = ICVs[Name]; \ 324 ICV.Getter = RTL; \ 325 } 326 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init) \ 327 { \ 328 auto &ICV = ICVs[Enum]; \ 329 ICV.Name = _Name; \ 330 ICV.Kind = Enum; \ 331 ICV.InitKind = Init; \ 332 ICV.EnvVarName = _EnvVarName; \ 333 switch (ICV.InitKind) { \ 334 case ICV_IMPLEMENTATION_DEFINED: \ 335 ICV.InitValue = nullptr; \ 336 break; \ 337 case ICV_ZERO: \ 338 ICV.InitValue = ConstantInt::get( \ 339 Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0); \ 340 break; \ 341 case ICV_FALSE: \ 342 ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext()); \ 343 break; \ 344 case ICV_LAST: \ 345 break; \ 346 } \ 347 } 348 #include "llvm/Frontend/OpenMP/OMPKinds.def" 349 } 350 351 /// Returns true if the function declaration \p F matches the runtime 352 /// function types, that is, return type \p RTFRetType, and argument types 353 /// \p RTFArgTypes. 354 static bool declMatchesRTFTypes(Function *F, Type *RTFRetType, 355 SmallVector<Type *, 8> &RTFArgTypes) { 356 // TODO: We should output information to the user (under debug output 357 // and via remarks). 358 359 if (!F) 360 return false; 361 if (F->getReturnType() != RTFRetType) 362 return false; 363 if (F->arg_size() != RTFArgTypes.size()) 364 return false; 365 366 auto RTFTyIt = RTFArgTypes.begin(); 367 for (Argument &Arg : F->args()) { 368 if (Arg.getType() != *RTFTyIt) 369 return false; 370 371 ++RTFTyIt; 372 } 373 374 return true; 375 } 376 377 // Helper to collect all uses of the declaration in the UsesMap. 378 unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) { 379 unsigned NumUses = 0; 380 if (!RFI.Declaration) 381 return NumUses; 382 OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration); 383 384 if (CollectStats) { 385 NumOpenMPRuntimeFunctionsIdentified += 1; 386 NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses(); 387 } 388 389 // TODO: We directly convert uses into proper calls and unknown uses. 390 for (Use &U : RFI.Declaration->uses()) { 391 if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) { 392 if (ModuleSlice.count(UserI->getFunction())) { 393 RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U); 394 ++NumUses; 395 } 396 } else { 397 RFI.getOrCreateUseVector(nullptr).push_back(&U); 398 ++NumUses; 399 } 400 } 401 return NumUses; 402 } 403 404 // Helper function to recollect uses of a runtime function. 405 void recollectUsesForFunction(RuntimeFunction RTF) { 406 auto &RFI = RFIs[RTF]; 407 RFI.clearUsesMap(); 408 collectUses(RFI, /*CollectStats*/ false); 409 } 410 411 // Helper function to recollect uses of all runtime functions. 412 void recollectUses() { 413 for (int Idx = 0; Idx < RFIs.size(); ++Idx) 414 recollectUsesForFunction(static_cast<RuntimeFunction>(Idx)); 415 } 416 417 /// Helper to initialize all runtime function information for those defined 418 /// in OpenMPKinds.def. 419 void initializeRuntimeFunctions() { 420 Module &M = *((*ModuleSlice.begin())->getParent()); 421 422 // Helper macros for handling __VA_ARGS__ in OMP_RTL 423 #define OMP_TYPE(VarName, ...) \ 424 Type *VarName = OMPBuilder.VarName; \ 425 (void)VarName; 426 427 #define OMP_ARRAY_TYPE(VarName, ...) \ 428 ArrayType *VarName##Ty = OMPBuilder.VarName##Ty; \ 429 (void)VarName##Ty; \ 430 PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy; \ 431 (void)VarName##PtrTy; 432 433 #define OMP_FUNCTION_TYPE(VarName, ...) \ 434 FunctionType *VarName = OMPBuilder.VarName; \ 435 (void)VarName; \ 436 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 437 (void)VarName##Ptr; 438 439 #define OMP_STRUCT_TYPE(VarName, ...) \ 440 StructType *VarName = OMPBuilder.VarName; \ 441 (void)VarName; \ 442 PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr; \ 443 (void)VarName##Ptr; 444 445 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...) \ 446 { \ 447 SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__}); \ 448 Function *F = M.getFunction(_Name); \ 449 RTLFunctions.insert(F); \ 450 if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) { \ 451 RuntimeFunctionIDMap[F] = _Enum; \ 452 F->removeFnAttr(Attribute::NoInline); \ 453 auto &RFI = RFIs[_Enum]; \ 454 RFI.Kind = _Enum; \ 455 RFI.Name = _Name; \ 456 RFI.IsVarArg = _IsVarArg; \ 457 RFI.ReturnType = OMPBuilder._ReturnType; \ 458 RFI.ArgumentTypes = std::move(ArgsTypes); \ 459 RFI.Declaration = F; \ 460 unsigned NumUses = collectUses(RFI); \ 461 (void)NumUses; \ 462 LLVM_DEBUG({ \ 463 dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not") \ 464 << " found\n"; \ 465 if (RFI.Declaration) \ 466 dbgs() << TAG << "-> got " << NumUses << " uses in " \ 467 << RFI.getNumFunctionsWithUses() \ 468 << " different functions.\n"; \ 469 }); \ 470 } \ 471 } 472 #include "llvm/Frontend/OpenMP/OMPKinds.def" 473 474 // TODO: We should attach the attributes defined in OMPKinds.def. 475 } 476 477 /// Collection of known kernels (\see Kernel) in the module. 478 SmallPtrSetImpl<Kernel> &Kernels; 479 480 /// Collection of known OpenMP runtime functions.. 481 DenseSet<const Function *> RTLFunctions; 482 }; 483 484 template <typename Ty, bool InsertInvalidates = true> 485 struct BooleanStateWithSetVector : public BooleanState { 486 bool contains(const Ty &Elem) const { return Set.contains(Elem); } 487 bool insert(const Ty &Elem) { 488 if (InsertInvalidates) 489 BooleanState::indicatePessimisticFixpoint(); 490 return Set.insert(Elem); 491 } 492 493 const Ty &operator[](int Idx) const { return Set[Idx]; } 494 bool operator==(const BooleanStateWithSetVector &RHS) const { 495 return BooleanState::operator==(RHS) && Set == RHS.Set; 496 } 497 bool operator!=(const BooleanStateWithSetVector &RHS) const { 498 return !(*this == RHS); 499 } 500 501 bool empty() const { return Set.empty(); } 502 size_t size() const { return Set.size(); } 503 504 /// "Clamp" this state with \p RHS. 505 BooleanStateWithSetVector &operator^=(const BooleanStateWithSetVector &RHS) { 506 BooleanState::operator^=(RHS); 507 Set.insert(RHS.Set.begin(), RHS.Set.end()); 508 return *this; 509 } 510 511 private: 512 /// A set to keep track of elements. 513 SetVector<Ty> Set; 514 515 public: 516 typename decltype(Set)::iterator begin() { return Set.begin(); } 517 typename decltype(Set)::iterator end() { return Set.end(); } 518 typename decltype(Set)::const_iterator begin() const { return Set.begin(); } 519 typename decltype(Set)::const_iterator end() const { return Set.end(); } 520 }; 521 522 template <typename Ty, bool InsertInvalidates = true> 523 using BooleanStateWithPtrSetVector = 524 BooleanStateWithSetVector<Ty *, InsertInvalidates>; 525 526 struct KernelInfoState : AbstractState { 527 /// Flag to track if we reached a fixpoint. 528 bool IsAtFixpoint = false; 529 530 /// The parallel regions (identified by the outlined parallel functions) that 531 /// can be reached from the associated function. 532 BooleanStateWithPtrSetVector<Function, /* InsertInvalidates */ false> 533 ReachedKnownParallelRegions; 534 535 /// State to track what parallel region we might reach. 536 BooleanStateWithPtrSetVector<CallBase> ReachedUnknownParallelRegions; 537 538 /// State to track if we are in SPMD-mode, assumed or know, and why we decided 539 /// we cannot be. If it is assumed, then RequiresFullRuntime should also be 540 /// false. 541 BooleanStateWithPtrSetVector<Instruction, false> SPMDCompatibilityTracker; 542 543 /// The __kmpc_target_init call in this kernel, if any. If we find more than 544 /// one we abort as the kernel is malformed. 545 CallBase *KernelInitCB = nullptr; 546 547 /// The __kmpc_target_deinit call in this kernel, if any. If we find more than 548 /// one we abort as the kernel is malformed. 549 CallBase *KernelDeinitCB = nullptr; 550 551 /// Flag to indicate if the associated function is a kernel entry. 552 bool IsKernelEntry = false; 553 554 /// State to track what kernel entries can reach the associated function. 555 BooleanStateWithPtrSetVector<Function, false> ReachingKernelEntries; 556 557 /// State to indicate if we can track parallel level of the associated 558 /// function. We will give up tracking if we encounter unknown caller or the 559 /// caller is __kmpc_parallel_51. 560 BooleanStateWithSetVector<uint8_t> ParallelLevels; 561 562 /// Abstract State interface 563 ///{ 564 565 KernelInfoState() {} 566 KernelInfoState(bool BestState) { 567 if (!BestState) 568 indicatePessimisticFixpoint(); 569 } 570 571 /// See AbstractState::isValidState(...) 572 bool isValidState() const override { return true; } 573 574 /// See AbstractState::isAtFixpoint(...) 575 bool isAtFixpoint() const override { return IsAtFixpoint; } 576 577 /// See AbstractState::indicatePessimisticFixpoint(...) 578 ChangeStatus indicatePessimisticFixpoint() override { 579 IsAtFixpoint = true; 580 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 581 ReachedUnknownParallelRegions.indicatePessimisticFixpoint(); 582 return ChangeStatus::CHANGED; 583 } 584 585 /// See AbstractState::indicateOptimisticFixpoint(...) 586 ChangeStatus indicateOptimisticFixpoint() override { 587 IsAtFixpoint = true; 588 return ChangeStatus::UNCHANGED; 589 } 590 591 /// Return the assumed state 592 KernelInfoState &getAssumed() { return *this; } 593 const KernelInfoState &getAssumed() const { return *this; } 594 595 bool operator==(const KernelInfoState &RHS) const { 596 if (SPMDCompatibilityTracker != RHS.SPMDCompatibilityTracker) 597 return false; 598 if (ReachedKnownParallelRegions != RHS.ReachedKnownParallelRegions) 599 return false; 600 if (ReachedUnknownParallelRegions != RHS.ReachedUnknownParallelRegions) 601 return false; 602 if (ReachingKernelEntries != RHS.ReachingKernelEntries) 603 return false; 604 return true; 605 } 606 607 /// Returns true if this kernel contains any OpenMP parallel regions. 608 bool mayContainParallelRegion() { 609 return !ReachedKnownParallelRegions.empty() || 610 !ReachedUnknownParallelRegions.empty(); 611 } 612 613 /// Return empty set as the best state of potential values. 614 static KernelInfoState getBestState() { return KernelInfoState(true); } 615 616 static KernelInfoState getBestState(KernelInfoState &KIS) { 617 return getBestState(); 618 } 619 620 /// Return full set as the worst state of potential values. 621 static KernelInfoState getWorstState() { return KernelInfoState(false); } 622 623 /// "Clamp" this state with \p KIS. 624 KernelInfoState operator^=(const KernelInfoState &KIS) { 625 // Do not merge two different _init and _deinit call sites. 626 if (KIS.KernelInitCB) { 627 if (KernelInitCB && KernelInitCB != KIS.KernelInitCB) 628 indicatePessimisticFixpoint(); 629 KernelInitCB = KIS.KernelInitCB; 630 } 631 if (KIS.KernelDeinitCB) { 632 if (KernelDeinitCB && KernelDeinitCB != KIS.KernelDeinitCB) 633 indicatePessimisticFixpoint(); 634 KernelDeinitCB = KIS.KernelDeinitCB; 635 } 636 SPMDCompatibilityTracker ^= KIS.SPMDCompatibilityTracker; 637 ReachedKnownParallelRegions ^= KIS.ReachedKnownParallelRegions; 638 ReachedUnknownParallelRegions ^= KIS.ReachedUnknownParallelRegions; 639 return *this; 640 } 641 642 KernelInfoState operator&=(const KernelInfoState &KIS) { 643 return (*this ^= KIS); 644 } 645 646 ///} 647 }; 648 649 /// Used to map the values physically (in the IR) stored in an offload 650 /// array, to a vector in memory. 651 struct OffloadArray { 652 /// Physical array (in the IR). 653 AllocaInst *Array = nullptr; 654 /// Mapped values. 655 SmallVector<Value *, 8> StoredValues; 656 /// Last stores made in the offload array. 657 SmallVector<StoreInst *, 8> LastAccesses; 658 659 OffloadArray() = default; 660 661 /// Initializes the OffloadArray with the values stored in \p Array before 662 /// instruction \p Before is reached. Returns false if the initialization 663 /// fails. 664 /// This MUST be used immediately after the construction of the object. 665 bool initialize(AllocaInst &Array, Instruction &Before) { 666 if (!Array.getAllocatedType()->isArrayTy()) 667 return false; 668 669 if (!getValues(Array, Before)) 670 return false; 671 672 this->Array = &Array; 673 return true; 674 } 675 676 static const unsigned DeviceIDArgNum = 1; 677 static const unsigned BasePtrsArgNum = 3; 678 static const unsigned PtrsArgNum = 4; 679 static const unsigned SizesArgNum = 5; 680 681 private: 682 /// Traverses the BasicBlock where \p Array is, collecting the stores made to 683 /// \p Array, leaving StoredValues with the values stored before the 684 /// instruction \p Before is reached. 685 bool getValues(AllocaInst &Array, Instruction &Before) { 686 // Initialize container. 687 const uint64_t NumValues = Array.getAllocatedType()->getArrayNumElements(); 688 StoredValues.assign(NumValues, nullptr); 689 LastAccesses.assign(NumValues, nullptr); 690 691 // TODO: This assumes the instruction \p Before is in the same 692 // BasicBlock as Array. Make it general, for any control flow graph. 693 BasicBlock *BB = Array.getParent(); 694 if (BB != Before.getParent()) 695 return false; 696 697 const DataLayout &DL = Array.getModule()->getDataLayout(); 698 const unsigned int PointerSize = DL.getPointerSize(); 699 700 for (Instruction &I : *BB) { 701 if (&I == &Before) 702 break; 703 704 if (!isa<StoreInst>(&I)) 705 continue; 706 707 auto *S = cast<StoreInst>(&I); 708 int64_t Offset = -1; 709 auto *Dst = 710 GetPointerBaseWithConstantOffset(S->getPointerOperand(), Offset, DL); 711 if (Dst == &Array) { 712 int64_t Idx = Offset / PointerSize; 713 StoredValues[Idx] = getUnderlyingObject(S->getValueOperand()); 714 LastAccesses[Idx] = S; 715 } 716 } 717 718 return isFilled(); 719 } 720 721 /// Returns true if all values in StoredValues and 722 /// LastAccesses are not nullptrs. 723 bool isFilled() { 724 const unsigned NumValues = StoredValues.size(); 725 for (unsigned I = 0; I < NumValues; ++I) { 726 if (!StoredValues[I] || !LastAccesses[I]) 727 return false; 728 } 729 730 return true; 731 } 732 }; 733 734 struct OpenMPOpt { 735 736 using OptimizationRemarkGetter = 737 function_ref<OptimizationRemarkEmitter &(Function *)>; 738 739 OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater, 740 OptimizationRemarkGetter OREGetter, 741 OMPInformationCache &OMPInfoCache, Attributor &A) 742 : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater), 743 OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {} 744 745 /// Check if any remarks are enabled for openmp-opt 746 bool remarksEnabled() { 747 auto &Ctx = M.getContext(); 748 return Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(DEBUG_TYPE); 749 } 750 751 /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice. 752 bool run(bool IsModulePass) { 753 if (SCC.empty()) 754 return false; 755 756 bool Changed = false; 757 758 LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size() 759 << " functions in a slice with " 760 << OMPInfoCache.ModuleSlice.size() << " functions\n"); 761 762 if (IsModulePass) { 763 Changed |= runAttributor(IsModulePass); 764 765 // Recollect uses, in case Attributor deleted any. 766 OMPInfoCache.recollectUses(); 767 768 // TODO: This should be folded into buildCustomStateMachine. 769 Changed |= rewriteDeviceCodeStateMachine(); 770 771 if (remarksEnabled()) 772 analysisGlobalization(); 773 } else { 774 if (PrintICVValues) 775 printICVs(); 776 if (PrintOpenMPKernels) 777 printKernels(); 778 779 Changed |= runAttributor(IsModulePass); 780 781 // Recollect uses, in case Attributor deleted any. 782 OMPInfoCache.recollectUses(); 783 784 Changed |= deleteParallelRegions(); 785 786 if (HideMemoryTransferLatency) 787 Changed |= hideMemTransfersLatency(); 788 Changed |= deduplicateRuntimeCalls(); 789 if (EnableParallelRegionMerging) { 790 if (mergeParallelRegions()) { 791 deduplicateRuntimeCalls(); 792 Changed = true; 793 } 794 } 795 } 796 797 return Changed; 798 } 799 800 /// Print initial ICV values for testing. 801 /// FIXME: This should be done from the Attributor once it is added. 802 void printICVs() const { 803 InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel, 804 ICV_proc_bind}; 805 806 for (Function *F : OMPInfoCache.ModuleSlice) { 807 for (auto ICV : ICVs) { 808 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 809 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 810 return ORA << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name) 811 << " Value: " 812 << (ICVInfo.InitValue 813 ? toString(ICVInfo.InitValue->getValue(), 10, true) 814 : "IMPLEMENTATION_DEFINED"); 815 }; 816 817 emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPICVTracker", Remark); 818 } 819 } 820 } 821 822 /// Print OpenMP GPU kernels for testing. 823 void printKernels() const { 824 for (Function *F : SCC) { 825 if (!OMPInfoCache.Kernels.count(F)) 826 continue; 827 828 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 829 return ORA << "OpenMP GPU kernel " 830 << ore::NV("OpenMPGPUKernel", F->getName()) << "\n"; 831 }; 832 833 emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPGPU", Remark); 834 } 835 } 836 837 /// Return the call if \p U is a callee use in a regular call. If \p RFI is 838 /// given it has to be the callee or a nullptr is returned. 839 static CallInst *getCallIfRegularCall( 840 Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 841 CallInst *CI = dyn_cast<CallInst>(U.getUser()); 842 if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() && 843 (!RFI || 844 (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration))) 845 return CI; 846 return nullptr; 847 } 848 849 /// Return the call if \p V is a regular call. If \p RFI is given it has to be 850 /// the callee or a nullptr is returned. 851 static CallInst *getCallIfRegularCall( 852 Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) { 853 CallInst *CI = dyn_cast<CallInst>(&V); 854 if (CI && !CI->hasOperandBundles() && 855 (!RFI || 856 (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration))) 857 return CI; 858 return nullptr; 859 } 860 861 private: 862 /// Merge parallel regions when it is safe. 863 bool mergeParallelRegions() { 864 const unsigned CallbackCalleeOperand = 2; 865 const unsigned CallbackFirstArgOperand = 3; 866 using InsertPointTy = OpenMPIRBuilder::InsertPointTy; 867 868 // Check if there are any __kmpc_fork_call calls to merge. 869 OMPInformationCache::RuntimeFunctionInfo &RFI = 870 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 871 872 if (!RFI.Declaration) 873 return false; 874 875 // Unmergable calls that prevent merging a parallel region. 876 OMPInformationCache::RuntimeFunctionInfo UnmergableCallsInfo[] = { 877 OMPInfoCache.RFIs[OMPRTL___kmpc_push_proc_bind], 878 OMPInfoCache.RFIs[OMPRTL___kmpc_push_num_threads], 879 }; 880 881 bool Changed = false; 882 LoopInfo *LI = nullptr; 883 DominatorTree *DT = nullptr; 884 885 SmallDenseMap<BasicBlock *, SmallPtrSet<Instruction *, 4>> BB2PRMap; 886 887 BasicBlock *StartBB = nullptr, *EndBB = nullptr; 888 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 889 BasicBlock &ContinuationIP) { 890 BasicBlock *CGStartBB = CodeGenIP.getBlock(); 891 BasicBlock *CGEndBB = 892 SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI); 893 assert(StartBB != nullptr && "StartBB should not be null"); 894 CGStartBB->getTerminator()->setSuccessor(0, StartBB); 895 assert(EndBB != nullptr && "EndBB should not be null"); 896 EndBB->getTerminator()->setSuccessor(0, CGEndBB); 897 }; 898 899 auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &, 900 Value &Inner, Value *&ReplacementValue) -> InsertPointTy { 901 ReplacementValue = &Inner; 902 return CodeGenIP; 903 }; 904 905 auto FiniCB = [&](InsertPointTy CodeGenIP) {}; 906 907 /// Create a sequential execution region within a merged parallel region, 908 /// encapsulated in a master construct with a barrier for synchronization. 909 auto CreateSequentialRegion = [&](Function *OuterFn, 910 BasicBlock *OuterPredBB, 911 Instruction *SeqStartI, 912 Instruction *SeqEndI) { 913 // Isolate the instructions of the sequential region to a separate 914 // block. 915 BasicBlock *ParentBB = SeqStartI->getParent(); 916 BasicBlock *SeqEndBB = 917 SplitBlock(ParentBB, SeqEndI->getNextNode(), DT, LI); 918 BasicBlock *SeqAfterBB = 919 SplitBlock(SeqEndBB, &*SeqEndBB->getFirstInsertionPt(), DT, LI); 920 BasicBlock *SeqStartBB = 921 SplitBlock(ParentBB, SeqStartI, DT, LI, nullptr, "seq.par.merged"); 922 923 assert(ParentBB->getUniqueSuccessor() == SeqStartBB && 924 "Expected a different CFG"); 925 const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc(); 926 ParentBB->getTerminator()->eraseFromParent(); 927 928 auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 929 BasicBlock &ContinuationIP) { 930 BasicBlock *CGStartBB = CodeGenIP.getBlock(); 931 BasicBlock *CGEndBB = 932 SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI); 933 assert(SeqStartBB != nullptr && "SeqStartBB should not be null"); 934 CGStartBB->getTerminator()->setSuccessor(0, SeqStartBB); 935 assert(SeqEndBB != nullptr && "SeqEndBB should not be null"); 936 SeqEndBB->getTerminator()->setSuccessor(0, CGEndBB); 937 }; 938 auto FiniCB = [&](InsertPointTy CodeGenIP) {}; 939 940 // Find outputs from the sequential region to outside users and 941 // broadcast their values to them. 942 for (Instruction &I : *SeqStartBB) { 943 SmallPtrSet<Instruction *, 4> OutsideUsers; 944 for (User *Usr : I.users()) { 945 Instruction &UsrI = *cast<Instruction>(Usr); 946 // Ignore outputs to LT intrinsics, code extraction for the merged 947 // parallel region will fix them. 948 if (UsrI.isLifetimeStartOrEnd()) 949 continue; 950 951 if (UsrI.getParent() != SeqStartBB) 952 OutsideUsers.insert(&UsrI); 953 } 954 955 if (OutsideUsers.empty()) 956 continue; 957 958 // Emit an alloca in the outer region to store the broadcasted 959 // value. 960 const DataLayout &DL = M.getDataLayout(); 961 AllocaInst *AllocaI = new AllocaInst( 962 I.getType(), DL.getAllocaAddrSpace(), nullptr, 963 I.getName() + ".seq.output.alloc", &OuterFn->front().front()); 964 965 // Emit a store instruction in the sequential BB to update the 966 // value. 967 new StoreInst(&I, AllocaI, SeqStartBB->getTerminator()); 968 969 // Emit a load instruction and replace the use of the output value 970 // with it. 971 for (Instruction *UsrI : OutsideUsers) { 972 LoadInst *LoadI = new LoadInst( 973 I.getType(), AllocaI, I.getName() + ".seq.output.load", UsrI); 974 UsrI->replaceUsesOfWith(&I, LoadI); 975 } 976 } 977 978 OpenMPIRBuilder::LocationDescription Loc( 979 InsertPointTy(ParentBB, ParentBB->end()), DL); 980 InsertPointTy SeqAfterIP = 981 OMPInfoCache.OMPBuilder.createMaster(Loc, BodyGenCB, FiniCB); 982 983 OMPInfoCache.OMPBuilder.createBarrier(SeqAfterIP, OMPD_parallel); 984 985 BranchInst::Create(SeqAfterBB, SeqAfterIP.getBlock()); 986 987 LLVM_DEBUG(dbgs() << TAG << "After sequential inlining " << *OuterFn 988 << "\n"); 989 }; 990 991 // Helper to merge the __kmpc_fork_call calls in MergableCIs. They are all 992 // contained in BB and only separated by instructions that can be 993 // redundantly executed in parallel. The block BB is split before the first 994 // call (in MergableCIs) and after the last so the entire region we merge 995 // into a single parallel region is contained in a single basic block 996 // without any other instructions. We use the OpenMPIRBuilder to outline 997 // that block and call the resulting function via __kmpc_fork_call. 998 auto Merge = [&](SmallVectorImpl<CallInst *> &MergableCIs, BasicBlock *BB) { 999 // TODO: Change the interface to allow single CIs expanded, e.g, to 1000 // include an outer loop. 1001 assert(MergableCIs.size() > 1 && "Assumed multiple mergable CIs"); 1002 1003 auto Remark = [&](OptimizationRemark OR) { 1004 OR << "Parallel region merged with parallel region" 1005 << (MergableCIs.size() > 2 ? "s" : "") << " at "; 1006 for (auto *CI : llvm::drop_begin(MergableCIs)) { 1007 OR << ore::NV("OpenMPParallelMerge", CI->getDebugLoc()); 1008 if (CI != MergableCIs.back()) 1009 OR << ", "; 1010 } 1011 return OR << "."; 1012 }; 1013 1014 emitRemark<OptimizationRemark>(MergableCIs.front(), "OMP150", Remark); 1015 1016 Function *OriginalFn = BB->getParent(); 1017 LLVM_DEBUG(dbgs() << TAG << "Merge " << MergableCIs.size() 1018 << " parallel regions in " << OriginalFn->getName() 1019 << "\n"); 1020 1021 // Isolate the calls to merge in a separate block. 1022 EndBB = SplitBlock(BB, MergableCIs.back()->getNextNode(), DT, LI); 1023 BasicBlock *AfterBB = 1024 SplitBlock(EndBB, &*EndBB->getFirstInsertionPt(), DT, LI); 1025 StartBB = SplitBlock(BB, MergableCIs.front(), DT, LI, nullptr, 1026 "omp.par.merged"); 1027 1028 assert(BB->getUniqueSuccessor() == StartBB && "Expected a different CFG"); 1029 const DebugLoc DL = BB->getTerminator()->getDebugLoc(); 1030 BB->getTerminator()->eraseFromParent(); 1031 1032 // Create sequential regions for sequential instructions that are 1033 // in-between mergable parallel regions. 1034 for (auto *It = MergableCIs.begin(), *End = MergableCIs.end() - 1; 1035 It != End; ++It) { 1036 Instruction *ForkCI = *It; 1037 Instruction *NextForkCI = *(It + 1); 1038 1039 // Continue if there are not in-between instructions. 1040 if (ForkCI->getNextNode() == NextForkCI) 1041 continue; 1042 1043 CreateSequentialRegion(OriginalFn, BB, ForkCI->getNextNode(), 1044 NextForkCI->getPrevNode()); 1045 } 1046 1047 OpenMPIRBuilder::LocationDescription Loc(InsertPointTy(BB, BB->end()), 1048 DL); 1049 IRBuilder<>::InsertPoint AllocaIP( 1050 &OriginalFn->getEntryBlock(), 1051 OriginalFn->getEntryBlock().getFirstInsertionPt()); 1052 // Create the merged parallel region with default proc binding, to 1053 // avoid overriding binding settings, and without explicit cancellation. 1054 InsertPointTy AfterIP = OMPInfoCache.OMPBuilder.createParallel( 1055 Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB, nullptr, nullptr, 1056 OMP_PROC_BIND_default, /* IsCancellable */ false); 1057 BranchInst::Create(AfterBB, AfterIP.getBlock()); 1058 1059 // Perform the actual outlining. 1060 OMPInfoCache.OMPBuilder.finalize(OriginalFn, 1061 /* AllowExtractorSinking */ true); 1062 1063 Function *OutlinedFn = MergableCIs.front()->getCaller(); 1064 1065 // Replace the __kmpc_fork_call calls with direct calls to the outlined 1066 // callbacks. 1067 SmallVector<Value *, 8> Args; 1068 for (auto *CI : MergableCIs) { 1069 Value *Callee = 1070 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts(); 1071 FunctionType *FT = 1072 cast<FunctionType>(Callee->getType()->getPointerElementType()); 1073 Args.clear(); 1074 Args.push_back(OutlinedFn->getArg(0)); 1075 Args.push_back(OutlinedFn->getArg(1)); 1076 for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands(); 1077 U < E; ++U) 1078 Args.push_back(CI->getArgOperand(U)); 1079 1080 CallInst *NewCI = CallInst::Create(FT, Callee, Args, "", CI); 1081 if (CI->getDebugLoc()) 1082 NewCI->setDebugLoc(CI->getDebugLoc()); 1083 1084 // Forward parameter attributes from the callback to the callee. 1085 for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands(); 1086 U < E; ++U) 1087 for (const Attribute &A : CI->getAttributes().getParamAttrs(U)) 1088 NewCI->addParamAttr( 1089 U - (CallbackFirstArgOperand - CallbackCalleeOperand), A); 1090 1091 // Emit an explicit barrier to replace the implicit fork-join barrier. 1092 if (CI != MergableCIs.back()) { 1093 // TODO: Remove barrier if the merged parallel region includes the 1094 // 'nowait' clause. 1095 OMPInfoCache.OMPBuilder.createBarrier( 1096 InsertPointTy(NewCI->getParent(), 1097 NewCI->getNextNode()->getIterator()), 1098 OMPD_parallel); 1099 } 1100 1101 CI->eraseFromParent(); 1102 } 1103 1104 assert(OutlinedFn != OriginalFn && "Outlining failed"); 1105 CGUpdater.registerOutlinedFunction(*OriginalFn, *OutlinedFn); 1106 CGUpdater.reanalyzeFunction(*OriginalFn); 1107 1108 NumOpenMPParallelRegionsMerged += MergableCIs.size(); 1109 1110 return true; 1111 }; 1112 1113 // Helper function that identifes sequences of 1114 // __kmpc_fork_call uses in a basic block. 1115 auto DetectPRsCB = [&](Use &U, Function &F) { 1116 CallInst *CI = getCallIfRegularCall(U, &RFI); 1117 BB2PRMap[CI->getParent()].insert(CI); 1118 1119 return false; 1120 }; 1121 1122 BB2PRMap.clear(); 1123 RFI.foreachUse(SCC, DetectPRsCB); 1124 SmallVector<SmallVector<CallInst *, 4>, 4> MergableCIsVector; 1125 // Find mergable parallel regions within a basic block that are 1126 // safe to merge, that is any in-between instructions can safely 1127 // execute in parallel after merging. 1128 // TODO: support merging across basic-blocks. 1129 for (auto &It : BB2PRMap) { 1130 auto &CIs = It.getSecond(); 1131 if (CIs.size() < 2) 1132 continue; 1133 1134 BasicBlock *BB = It.getFirst(); 1135 SmallVector<CallInst *, 4> MergableCIs; 1136 1137 /// Returns true if the instruction is mergable, false otherwise. 1138 /// A terminator instruction is unmergable by definition since merging 1139 /// works within a BB. Instructions before the mergable region are 1140 /// mergable if they are not calls to OpenMP runtime functions that may 1141 /// set different execution parameters for subsequent parallel regions. 1142 /// Instructions in-between parallel regions are mergable if they are not 1143 /// calls to any non-intrinsic function since that may call a non-mergable 1144 /// OpenMP runtime function. 1145 auto IsMergable = [&](Instruction &I, bool IsBeforeMergableRegion) { 1146 // We do not merge across BBs, hence return false (unmergable) if the 1147 // instruction is a terminator. 1148 if (I.isTerminator()) 1149 return false; 1150 1151 if (!isa<CallInst>(&I)) 1152 return true; 1153 1154 CallInst *CI = cast<CallInst>(&I); 1155 if (IsBeforeMergableRegion) { 1156 Function *CalledFunction = CI->getCalledFunction(); 1157 if (!CalledFunction) 1158 return false; 1159 // Return false (unmergable) if the call before the parallel 1160 // region calls an explicit affinity (proc_bind) or number of 1161 // threads (num_threads) compiler-generated function. Those settings 1162 // may be incompatible with following parallel regions. 1163 // TODO: ICV tracking to detect compatibility. 1164 for (const auto &RFI : UnmergableCallsInfo) { 1165 if (CalledFunction == RFI.Declaration) 1166 return false; 1167 } 1168 } else { 1169 // Return false (unmergable) if there is a call instruction 1170 // in-between parallel regions when it is not an intrinsic. It 1171 // may call an unmergable OpenMP runtime function in its callpath. 1172 // TODO: Keep track of possible OpenMP calls in the callpath. 1173 if (!isa<IntrinsicInst>(CI)) 1174 return false; 1175 } 1176 1177 return true; 1178 }; 1179 // Find maximal number of parallel region CIs that are safe to merge. 1180 for (auto It = BB->begin(), End = BB->end(); It != End;) { 1181 Instruction &I = *It; 1182 ++It; 1183 1184 if (CIs.count(&I)) { 1185 MergableCIs.push_back(cast<CallInst>(&I)); 1186 continue; 1187 } 1188 1189 // Continue expanding if the instruction is mergable. 1190 if (IsMergable(I, MergableCIs.empty())) 1191 continue; 1192 1193 // Forward the instruction iterator to skip the next parallel region 1194 // since there is an unmergable instruction which can affect it. 1195 for (; It != End; ++It) { 1196 Instruction &SkipI = *It; 1197 if (CIs.count(&SkipI)) { 1198 LLVM_DEBUG(dbgs() << TAG << "Skip parallel region " << SkipI 1199 << " due to " << I << "\n"); 1200 ++It; 1201 break; 1202 } 1203 } 1204 1205 // Store mergable regions found. 1206 if (MergableCIs.size() > 1) { 1207 MergableCIsVector.push_back(MergableCIs); 1208 LLVM_DEBUG(dbgs() << TAG << "Found " << MergableCIs.size() 1209 << " parallel regions in block " << BB->getName() 1210 << " of function " << BB->getParent()->getName() 1211 << "\n";); 1212 } 1213 1214 MergableCIs.clear(); 1215 } 1216 1217 if (!MergableCIsVector.empty()) { 1218 Changed = true; 1219 1220 for (auto &MergableCIs : MergableCIsVector) 1221 Merge(MergableCIs, BB); 1222 MergableCIsVector.clear(); 1223 } 1224 } 1225 1226 if (Changed) { 1227 /// Re-collect use for fork calls, emitted barrier calls, and 1228 /// any emitted master/end_master calls. 1229 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_fork_call); 1230 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_barrier); 1231 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_master); 1232 OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_end_master); 1233 } 1234 1235 return Changed; 1236 } 1237 1238 /// Try to delete parallel regions if possible. 1239 bool deleteParallelRegions() { 1240 const unsigned CallbackCalleeOperand = 2; 1241 1242 OMPInformationCache::RuntimeFunctionInfo &RFI = 1243 OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call]; 1244 1245 if (!RFI.Declaration) 1246 return false; 1247 1248 bool Changed = false; 1249 auto DeleteCallCB = [&](Use &U, Function &) { 1250 CallInst *CI = getCallIfRegularCall(U); 1251 if (!CI) 1252 return false; 1253 auto *Fn = dyn_cast<Function>( 1254 CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts()); 1255 if (!Fn) 1256 return false; 1257 if (!Fn->onlyReadsMemory()) 1258 return false; 1259 if (!Fn->hasFnAttribute(Attribute::WillReturn)) 1260 return false; 1261 1262 LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in " 1263 << CI->getCaller()->getName() << "\n"); 1264 1265 auto Remark = [&](OptimizationRemark OR) { 1266 return OR << "Removing parallel region with no side-effects."; 1267 }; 1268 emitRemark<OptimizationRemark>(CI, "OMP160", Remark); 1269 1270 CGUpdater.removeCallSite(*CI); 1271 CI->eraseFromParent(); 1272 Changed = true; 1273 ++NumOpenMPParallelRegionsDeleted; 1274 return true; 1275 }; 1276 1277 RFI.foreachUse(SCC, DeleteCallCB); 1278 1279 return Changed; 1280 } 1281 1282 /// Try to eliminate runtime calls by reusing existing ones. 1283 bool deduplicateRuntimeCalls() { 1284 bool Changed = false; 1285 1286 RuntimeFunction DeduplicableRuntimeCallIDs[] = { 1287 OMPRTL_omp_get_num_threads, 1288 OMPRTL_omp_in_parallel, 1289 OMPRTL_omp_get_cancellation, 1290 OMPRTL_omp_get_thread_limit, 1291 OMPRTL_omp_get_supported_active_levels, 1292 OMPRTL_omp_get_level, 1293 OMPRTL_omp_get_ancestor_thread_num, 1294 OMPRTL_omp_get_team_size, 1295 OMPRTL_omp_get_active_level, 1296 OMPRTL_omp_in_final, 1297 OMPRTL_omp_get_proc_bind, 1298 OMPRTL_omp_get_num_places, 1299 OMPRTL_omp_get_num_procs, 1300 OMPRTL_omp_get_place_num, 1301 OMPRTL_omp_get_partition_num_places, 1302 OMPRTL_omp_get_partition_place_nums}; 1303 1304 // Global-tid is handled separately. 1305 SmallSetVector<Value *, 16> GTIdArgs; 1306 collectGlobalThreadIdArguments(GTIdArgs); 1307 LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size() 1308 << " global thread ID arguments\n"); 1309 1310 for (Function *F : SCC) { 1311 for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs) 1312 Changed |= deduplicateRuntimeCalls( 1313 *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]); 1314 1315 // __kmpc_global_thread_num is special as we can replace it with an 1316 // argument in enough cases to make it worth trying. 1317 Value *GTIdArg = nullptr; 1318 for (Argument &Arg : F->args()) 1319 if (GTIdArgs.count(&Arg)) { 1320 GTIdArg = &Arg; 1321 break; 1322 } 1323 Changed |= deduplicateRuntimeCalls( 1324 *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg); 1325 } 1326 1327 return Changed; 1328 } 1329 1330 /// Tries to hide the latency of runtime calls that involve host to 1331 /// device memory transfers by splitting them into their "issue" and "wait" 1332 /// versions. The "issue" is moved upwards as much as possible. The "wait" is 1333 /// moved downards as much as possible. The "issue" issues the memory transfer 1334 /// asynchronously, returning a handle. The "wait" waits in the returned 1335 /// handle for the memory transfer to finish. 1336 bool hideMemTransfersLatency() { 1337 auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper]; 1338 bool Changed = false; 1339 auto SplitMemTransfers = [&](Use &U, Function &Decl) { 1340 auto *RTCall = getCallIfRegularCall(U, &RFI); 1341 if (!RTCall) 1342 return false; 1343 1344 OffloadArray OffloadArrays[3]; 1345 if (!getValuesInOffloadArrays(*RTCall, OffloadArrays)) 1346 return false; 1347 1348 LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays)); 1349 1350 // TODO: Check if can be moved upwards. 1351 bool WasSplit = false; 1352 Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall); 1353 if (WaitMovementPoint) 1354 WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint); 1355 1356 Changed |= WasSplit; 1357 return WasSplit; 1358 }; 1359 RFI.foreachUse(SCC, SplitMemTransfers); 1360 1361 return Changed; 1362 } 1363 1364 void analysisGlobalization() { 1365 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 1366 1367 auto CheckGlobalization = [&](Use &U, Function &Decl) { 1368 if (CallInst *CI = getCallIfRegularCall(U, &RFI)) { 1369 auto Remark = [&](OptimizationRemarkMissed ORM) { 1370 return ORM 1371 << "Found thread data sharing on the GPU. " 1372 << "Expect degraded performance due to data globalization."; 1373 }; 1374 emitRemark<OptimizationRemarkMissed>(CI, "OMP112", Remark); 1375 } 1376 1377 return false; 1378 }; 1379 1380 RFI.foreachUse(SCC, CheckGlobalization); 1381 } 1382 1383 /// Maps the values stored in the offload arrays passed as arguments to 1384 /// \p RuntimeCall into the offload arrays in \p OAs. 1385 bool getValuesInOffloadArrays(CallInst &RuntimeCall, 1386 MutableArrayRef<OffloadArray> OAs) { 1387 assert(OAs.size() == 3 && "Need space for three offload arrays!"); 1388 1389 // A runtime call that involves memory offloading looks something like: 1390 // call void @__tgt_target_data_begin_mapper(arg0, arg1, 1391 // i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes, 1392 // ...) 1393 // So, the idea is to access the allocas that allocate space for these 1394 // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes. 1395 // Therefore: 1396 // i8** %offload_baseptrs. 1397 Value *BasePtrsArg = 1398 RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum); 1399 // i8** %offload_ptrs. 1400 Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum); 1401 // i8** %offload_sizes. 1402 Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum); 1403 1404 // Get values stored in **offload_baseptrs. 1405 auto *V = getUnderlyingObject(BasePtrsArg); 1406 if (!isa<AllocaInst>(V)) 1407 return false; 1408 auto *BasePtrsArray = cast<AllocaInst>(V); 1409 if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall)) 1410 return false; 1411 1412 // Get values stored in **offload_baseptrs. 1413 V = getUnderlyingObject(PtrsArg); 1414 if (!isa<AllocaInst>(V)) 1415 return false; 1416 auto *PtrsArray = cast<AllocaInst>(V); 1417 if (!OAs[1].initialize(*PtrsArray, RuntimeCall)) 1418 return false; 1419 1420 // Get values stored in **offload_sizes. 1421 V = getUnderlyingObject(SizesArg); 1422 // If it's a [constant] global array don't analyze it. 1423 if (isa<GlobalValue>(V)) 1424 return isa<Constant>(V); 1425 if (!isa<AllocaInst>(V)) 1426 return false; 1427 1428 auto *SizesArray = cast<AllocaInst>(V); 1429 if (!OAs[2].initialize(*SizesArray, RuntimeCall)) 1430 return false; 1431 1432 return true; 1433 } 1434 1435 /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG. 1436 /// For now this is a way to test that the function getValuesInOffloadArrays 1437 /// is working properly. 1438 /// TODO: Move this to a unittest when unittests are available for OpenMPOpt. 1439 void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) { 1440 assert(OAs.size() == 3 && "There are three offload arrays to debug!"); 1441 1442 LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n"); 1443 std::string ValuesStr; 1444 raw_string_ostream Printer(ValuesStr); 1445 std::string Separator = " --- "; 1446 1447 for (auto *BP : OAs[0].StoredValues) { 1448 BP->print(Printer); 1449 Printer << Separator; 1450 } 1451 LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n"); 1452 ValuesStr.clear(); 1453 1454 for (auto *P : OAs[1].StoredValues) { 1455 P->print(Printer); 1456 Printer << Separator; 1457 } 1458 LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n"); 1459 ValuesStr.clear(); 1460 1461 for (auto *S : OAs[2].StoredValues) { 1462 S->print(Printer); 1463 Printer << Separator; 1464 } 1465 LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n"); 1466 } 1467 1468 /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be 1469 /// moved. Returns nullptr if the movement is not possible, or not worth it. 1470 Instruction *canBeMovedDownwards(CallInst &RuntimeCall) { 1471 // FIXME: This traverses only the BasicBlock where RuntimeCall is. 1472 // Make it traverse the CFG. 1473 1474 Instruction *CurrentI = &RuntimeCall; 1475 bool IsWorthIt = false; 1476 while ((CurrentI = CurrentI->getNextNode())) { 1477 1478 // TODO: Once we detect the regions to be offloaded we should use the 1479 // alias analysis manager to check if CurrentI may modify one of 1480 // the offloaded regions. 1481 if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) { 1482 if (IsWorthIt) 1483 return CurrentI; 1484 1485 return nullptr; 1486 } 1487 1488 // FIXME: For now if we move it over anything without side effect 1489 // is worth it. 1490 IsWorthIt = true; 1491 } 1492 1493 // Return end of BasicBlock. 1494 return RuntimeCall.getParent()->getTerminator(); 1495 } 1496 1497 /// Splits \p RuntimeCall into its "issue" and "wait" counterparts. 1498 bool splitTargetDataBeginRTC(CallInst &RuntimeCall, 1499 Instruction &WaitMovementPoint) { 1500 // Create stack allocated handle (__tgt_async_info) at the beginning of the 1501 // function. Used for storing information of the async transfer, allowing to 1502 // wait on it later. 1503 auto &IRBuilder = OMPInfoCache.OMPBuilder; 1504 auto *F = RuntimeCall.getCaller(); 1505 Instruction *FirstInst = &(F->getEntryBlock().front()); 1506 AllocaInst *Handle = new AllocaInst( 1507 IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst); 1508 1509 // Add "issue" runtime call declaration: 1510 // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32, 1511 // i8**, i8**, i64*, i64*) 1512 FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction( 1513 M, OMPRTL___tgt_target_data_begin_mapper_issue); 1514 1515 // Change RuntimeCall call site for its asynchronous version. 1516 SmallVector<Value *, 16> Args; 1517 for (auto &Arg : RuntimeCall.args()) 1518 Args.push_back(Arg.get()); 1519 Args.push_back(Handle); 1520 1521 CallInst *IssueCallsite = 1522 CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall); 1523 RuntimeCall.eraseFromParent(); 1524 1525 // Add "wait" runtime call declaration: 1526 // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info) 1527 FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction( 1528 M, OMPRTL___tgt_target_data_begin_mapper_wait); 1529 1530 Value *WaitParams[2] = { 1531 IssueCallsite->getArgOperand( 1532 OffloadArray::DeviceIDArgNum), // device_id. 1533 Handle // handle to wait on. 1534 }; 1535 CallInst::Create(WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint); 1536 1537 return true; 1538 } 1539 1540 static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent, 1541 bool GlobalOnly, bool &SingleChoice) { 1542 if (CurrentIdent == NextIdent) 1543 return CurrentIdent; 1544 1545 // TODO: Figure out how to actually combine multiple debug locations. For 1546 // now we just keep an existing one if there is a single choice. 1547 if (!GlobalOnly || isa<GlobalValue>(NextIdent)) { 1548 SingleChoice = !CurrentIdent; 1549 return NextIdent; 1550 } 1551 return nullptr; 1552 } 1553 1554 /// Return an `struct ident_t*` value that represents the ones used in the 1555 /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not 1556 /// return a local `struct ident_t*`. For now, if we cannot find a suitable 1557 /// return value we create one from scratch. We also do not yet combine 1558 /// information, e.g., the source locations, see combinedIdentStruct. 1559 Value * 1560 getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI, 1561 Function &F, bool GlobalOnly) { 1562 bool SingleChoice = true; 1563 Value *Ident = nullptr; 1564 auto CombineIdentStruct = [&](Use &U, Function &Caller) { 1565 CallInst *CI = getCallIfRegularCall(U, &RFI); 1566 if (!CI || &F != &Caller) 1567 return false; 1568 Ident = combinedIdentStruct(Ident, CI->getArgOperand(0), 1569 /* GlobalOnly */ true, SingleChoice); 1570 return false; 1571 }; 1572 RFI.foreachUse(SCC, CombineIdentStruct); 1573 1574 if (!Ident || !SingleChoice) { 1575 // The IRBuilder uses the insertion block to get to the module, this is 1576 // unfortunate but we work around it for now. 1577 if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock()) 1578 OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy( 1579 &F.getEntryBlock(), F.getEntryBlock().begin())); 1580 // Create a fallback location if non was found. 1581 // TODO: Use the debug locations of the calls instead. 1582 Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr(); 1583 Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc); 1584 } 1585 return Ident; 1586 } 1587 1588 /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or 1589 /// \p ReplVal if given. 1590 bool deduplicateRuntimeCalls(Function &F, 1591 OMPInformationCache::RuntimeFunctionInfo &RFI, 1592 Value *ReplVal = nullptr) { 1593 auto *UV = RFI.getUseVector(F); 1594 if (!UV || UV->size() + (ReplVal != nullptr) < 2) 1595 return false; 1596 1597 LLVM_DEBUG( 1598 dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name 1599 << (ReplVal ? " with an existing value\n" : "\n") << "\n"); 1600 1601 assert((!ReplVal || (isa<Argument>(ReplVal) && 1602 cast<Argument>(ReplVal)->getParent() == &F)) && 1603 "Unexpected replacement value!"); 1604 1605 // TODO: Use dominance to find a good position instead. 1606 auto CanBeMoved = [this](CallBase &CB) { 1607 unsigned NumArgs = CB.getNumArgOperands(); 1608 if (NumArgs == 0) 1609 return true; 1610 if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr) 1611 return false; 1612 for (unsigned u = 1; u < NumArgs; ++u) 1613 if (isa<Instruction>(CB.getArgOperand(u))) 1614 return false; 1615 return true; 1616 }; 1617 1618 if (!ReplVal) { 1619 for (Use *U : *UV) 1620 if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) { 1621 if (!CanBeMoved(*CI)) 1622 continue; 1623 1624 // If the function is a kernel, dedup will move 1625 // the runtime call right after the kernel init callsite. Otherwise, 1626 // it will move it to the beginning of the caller function. 1627 if (isKernel(F)) { 1628 auto &KernelInitRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 1629 auto *KernelInitUV = KernelInitRFI.getUseVector(F); 1630 1631 if (KernelInitUV->empty()) 1632 continue; 1633 1634 assert(KernelInitUV->size() == 1 && 1635 "Expected a single __kmpc_target_init in kernel\n"); 1636 1637 CallInst *KernelInitCI = 1638 getCallIfRegularCall(*KernelInitUV->front(), &KernelInitRFI); 1639 assert(KernelInitCI && 1640 "Expected a call to __kmpc_target_init in kernel\n"); 1641 1642 CI->moveAfter(KernelInitCI); 1643 } else 1644 CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt()); 1645 ReplVal = CI; 1646 break; 1647 } 1648 if (!ReplVal) 1649 return false; 1650 } 1651 1652 // If we use a call as a replacement value we need to make sure the ident is 1653 // valid at the new location. For now we just pick a global one, either 1654 // existing and used by one of the calls, or created from scratch. 1655 if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) { 1656 if (!CI->arg_empty() && 1657 CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) { 1658 Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F, 1659 /* GlobalOnly */ true); 1660 CI->setArgOperand(0, Ident); 1661 } 1662 } 1663 1664 bool Changed = false; 1665 auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) { 1666 CallInst *CI = getCallIfRegularCall(U, &RFI); 1667 if (!CI || CI == ReplVal || &F != &Caller) 1668 return false; 1669 assert(CI->getCaller() == &F && "Unexpected call!"); 1670 1671 auto Remark = [&](OptimizationRemark OR) { 1672 return OR << "OpenMP runtime call " 1673 << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated."; 1674 }; 1675 if (CI->getDebugLoc()) 1676 emitRemark<OptimizationRemark>(CI, "OMP170", Remark); 1677 else 1678 emitRemark<OptimizationRemark>(&F, "OMP170", Remark); 1679 1680 CGUpdater.removeCallSite(*CI); 1681 CI->replaceAllUsesWith(ReplVal); 1682 CI->eraseFromParent(); 1683 ++NumOpenMPRuntimeCallsDeduplicated; 1684 Changed = true; 1685 return true; 1686 }; 1687 RFI.foreachUse(SCC, ReplaceAndDeleteCB); 1688 1689 return Changed; 1690 } 1691 1692 /// Collect arguments that represent the global thread id in \p GTIdArgs. 1693 void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> >IdArgs) { 1694 // TODO: Below we basically perform a fixpoint iteration with a pessimistic 1695 // initialization. We could define an AbstractAttribute instead and 1696 // run the Attributor here once it can be run as an SCC pass. 1697 1698 // Helper to check the argument \p ArgNo at all call sites of \p F for 1699 // a GTId. 1700 auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) { 1701 if (!F.hasLocalLinkage()) 1702 return false; 1703 for (Use &U : F.uses()) { 1704 if (CallInst *CI = getCallIfRegularCall(U)) { 1705 Value *ArgOp = CI->getArgOperand(ArgNo); 1706 if (CI == &RefCI || GTIdArgs.count(ArgOp) || 1707 getCallIfRegularCall( 1708 *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num])) 1709 continue; 1710 } 1711 return false; 1712 } 1713 return true; 1714 }; 1715 1716 // Helper to identify uses of a GTId as GTId arguments. 1717 auto AddUserArgs = [&](Value >Id) { 1718 for (Use &U : GTId.uses()) 1719 if (CallInst *CI = dyn_cast<CallInst>(U.getUser())) 1720 if (CI->isArgOperand(&U)) 1721 if (Function *Callee = CI->getCalledFunction()) 1722 if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI)) 1723 GTIdArgs.insert(Callee->getArg(U.getOperandNo())); 1724 }; 1725 1726 // The argument users of __kmpc_global_thread_num calls are GTIds. 1727 OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI = 1728 OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]; 1729 1730 GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) { 1731 if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI)) 1732 AddUserArgs(*CI); 1733 return false; 1734 }); 1735 1736 // Transitively search for more arguments by looking at the users of the 1737 // ones we know already. During the search the GTIdArgs vector is extended 1738 // so we cannot cache the size nor can we use a range based for. 1739 for (unsigned u = 0; u < GTIdArgs.size(); ++u) 1740 AddUserArgs(*GTIdArgs[u]); 1741 } 1742 1743 /// Kernel (=GPU) optimizations and utility functions 1744 /// 1745 ///{{ 1746 1747 /// Check if \p F is a kernel, hence entry point for target offloading. 1748 bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); } 1749 1750 /// Cache to remember the unique kernel for a function. 1751 DenseMap<Function *, Optional<Kernel>> UniqueKernelMap; 1752 1753 /// Find the unique kernel that will execute \p F, if any. 1754 Kernel getUniqueKernelFor(Function &F); 1755 1756 /// Find the unique kernel that will execute \p I, if any. 1757 Kernel getUniqueKernelFor(Instruction &I) { 1758 return getUniqueKernelFor(*I.getFunction()); 1759 } 1760 1761 /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in 1762 /// the cases we can avoid taking the address of a function. 1763 bool rewriteDeviceCodeStateMachine(); 1764 1765 /// 1766 ///}} 1767 1768 /// Emit a remark generically 1769 /// 1770 /// This template function can be used to generically emit a remark. The 1771 /// RemarkKind should be one of the following: 1772 /// - OptimizationRemark to indicate a successful optimization attempt 1773 /// - OptimizationRemarkMissed to report a failed optimization attempt 1774 /// - OptimizationRemarkAnalysis to provide additional information about an 1775 /// optimization attempt 1776 /// 1777 /// The remark is built using a callback function provided by the caller that 1778 /// takes a RemarkKind as input and returns a RemarkKind. 1779 template <typename RemarkKind, typename RemarkCallBack> 1780 void emitRemark(Instruction *I, StringRef RemarkName, 1781 RemarkCallBack &&RemarkCB) const { 1782 Function *F = I->getParent()->getParent(); 1783 auto &ORE = OREGetter(F); 1784 1785 if (RemarkName.startswith("OMP")) 1786 ORE.emit([&]() { 1787 return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)) 1788 << " [" << RemarkName << "]"; 1789 }); 1790 else 1791 ORE.emit( 1792 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)); }); 1793 } 1794 1795 /// Emit a remark on a function. 1796 template <typename RemarkKind, typename RemarkCallBack> 1797 void emitRemark(Function *F, StringRef RemarkName, 1798 RemarkCallBack &&RemarkCB) const { 1799 auto &ORE = OREGetter(F); 1800 1801 if (RemarkName.startswith("OMP")) 1802 ORE.emit([&]() { 1803 return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)) 1804 << " [" << RemarkName << "]"; 1805 }); 1806 else 1807 ORE.emit( 1808 [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)); }); 1809 } 1810 1811 /// RAII struct to temporarily change an RTL function's linkage to external. 1812 /// This prevents it from being mistakenly removed by other optimizations. 1813 struct ExternalizationRAII { 1814 ExternalizationRAII(OMPInformationCache &OMPInfoCache, 1815 RuntimeFunction RFKind) 1816 : Declaration(OMPInfoCache.RFIs[RFKind].Declaration) { 1817 if (!Declaration) 1818 return; 1819 1820 LinkageType = Declaration->getLinkage(); 1821 Declaration->setLinkage(GlobalValue::ExternalLinkage); 1822 } 1823 1824 ~ExternalizationRAII() { 1825 if (!Declaration) 1826 return; 1827 1828 Declaration->setLinkage(LinkageType); 1829 } 1830 1831 Function *Declaration; 1832 GlobalValue::LinkageTypes LinkageType; 1833 }; 1834 1835 /// The underlying module. 1836 Module &M; 1837 1838 /// The SCC we are operating on. 1839 SmallVectorImpl<Function *> &SCC; 1840 1841 /// Callback to update the call graph, the first argument is a removed call, 1842 /// the second an optional replacement call. 1843 CallGraphUpdater &CGUpdater; 1844 1845 /// Callback to get an OptimizationRemarkEmitter from a Function * 1846 OptimizationRemarkGetter OREGetter; 1847 1848 /// OpenMP-specific information cache. Also Used for Attributor runs. 1849 OMPInformationCache &OMPInfoCache; 1850 1851 /// Attributor instance. 1852 Attributor &A; 1853 1854 /// Helper function to run Attributor on SCC. 1855 bool runAttributor(bool IsModulePass) { 1856 if (SCC.empty()) 1857 return false; 1858 1859 // Temporarily make these function have external linkage so the Attributor 1860 // doesn't remove them when we try to look them up later. 1861 ExternalizationRAII Parallel(OMPInfoCache, OMPRTL___kmpc_kernel_parallel); 1862 ExternalizationRAII EndParallel(OMPInfoCache, 1863 OMPRTL___kmpc_kernel_end_parallel); 1864 ExternalizationRAII BarrierSPMD(OMPInfoCache, 1865 OMPRTL___kmpc_barrier_simple_spmd); 1866 1867 registerAAs(IsModulePass); 1868 1869 ChangeStatus Changed = A.run(); 1870 1871 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size() 1872 << " functions, result: " << Changed << ".\n"); 1873 1874 return Changed == ChangeStatus::CHANGED; 1875 } 1876 1877 void registerFoldRuntimeCall(RuntimeFunction RF); 1878 1879 /// Populate the Attributor with abstract attribute opportunities in the 1880 /// function. 1881 void registerAAs(bool IsModulePass); 1882 }; 1883 1884 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) { 1885 if (!OMPInfoCache.ModuleSlice.count(&F)) 1886 return nullptr; 1887 1888 // Use a scope to keep the lifetime of the CachedKernel short. 1889 { 1890 Optional<Kernel> &CachedKernel = UniqueKernelMap[&F]; 1891 if (CachedKernel) 1892 return *CachedKernel; 1893 1894 // TODO: We should use an AA to create an (optimistic and callback 1895 // call-aware) call graph. For now we stick to simple patterns that 1896 // are less powerful, basically the worst fixpoint. 1897 if (isKernel(F)) { 1898 CachedKernel = Kernel(&F); 1899 return *CachedKernel; 1900 } 1901 1902 CachedKernel = nullptr; 1903 if (!F.hasLocalLinkage()) { 1904 1905 // See https://openmp.llvm.org/remarks/OptimizationRemarks.html 1906 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 1907 return ORA << "Potentially unknown OpenMP target region caller."; 1908 }; 1909 emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark); 1910 1911 return nullptr; 1912 } 1913 } 1914 1915 auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel { 1916 if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) { 1917 // Allow use in equality comparisons. 1918 if (Cmp->isEquality()) 1919 return getUniqueKernelFor(*Cmp); 1920 return nullptr; 1921 } 1922 if (auto *CB = dyn_cast<CallBase>(U.getUser())) { 1923 // Allow direct calls. 1924 if (CB->isCallee(&U)) 1925 return getUniqueKernelFor(*CB); 1926 1927 OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI = 1928 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 1929 // Allow the use in __kmpc_parallel_51 calls. 1930 if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI)) 1931 return getUniqueKernelFor(*CB); 1932 return nullptr; 1933 } 1934 // Disallow every other use. 1935 return nullptr; 1936 }; 1937 1938 // TODO: In the future we want to track more than just a unique kernel. 1939 SmallPtrSet<Kernel, 2> PotentialKernels; 1940 OMPInformationCache::foreachUse(F, [&](const Use &U) { 1941 PotentialKernels.insert(GetUniqueKernelForUse(U)); 1942 }); 1943 1944 Kernel K = nullptr; 1945 if (PotentialKernels.size() == 1) 1946 K = *PotentialKernels.begin(); 1947 1948 // Cache the result. 1949 UniqueKernelMap[&F] = K; 1950 1951 return K; 1952 } 1953 1954 bool OpenMPOpt::rewriteDeviceCodeStateMachine() { 1955 OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI = 1956 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 1957 1958 bool Changed = false; 1959 if (!KernelParallelRFI) 1960 return Changed; 1961 1962 // If we have disabled state machine changes, exit 1963 if (DisableOpenMPOptStateMachineRewrite) 1964 return Changed; 1965 1966 for (Function *F : SCC) { 1967 1968 // Check if the function is a use in a __kmpc_parallel_51 call at 1969 // all. 1970 bool UnknownUse = false; 1971 bool KernelParallelUse = false; 1972 unsigned NumDirectCalls = 0; 1973 1974 SmallVector<Use *, 2> ToBeReplacedStateMachineUses; 1975 OMPInformationCache::foreachUse(*F, [&](Use &U) { 1976 if (auto *CB = dyn_cast<CallBase>(U.getUser())) 1977 if (CB->isCallee(&U)) { 1978 ++NumDirectCalls; 1979 return; 1980 } 1981 1982 if (isa<ICmpInst>(U.getUser())) { 1983 ToBeReplacedStateMachineUses.push_back(&U); 1984 return; 1985 } 1986 1987 // Find wrapper functions that represent parallel kernels. 1988 CallInst *CI = 1989 OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI); 1990 const unsigned int WrapperFunctionArgNo = 6; 1991 if (!KernelParallelUse && CI && 1992 CI->getArgOperandNo(&U) == WrapperFunctionArgNo) { 1993 KernelParallelUse = true; 1994 ToBeReplacedStateMachineUses.push_back(&U); 1995 return; 1996 } 1997 UnknownUse = true; 1998 }); 1999 2000 // Do not emit a remark if we haven't seen a __kmpc_parallel_51 2001 // use. 2002 if (!KernelParallelUse) 2003 continue; 2004 2005 // If this ever hits, we should investigate. 2006 // TODO: Checking the number of uses is not a necessary restriction and 2007 // should be lifted. 2008 if (UnknownUse || NumDirectCalls != 1 || 2009 ToBeReplacedStateMachineUses.size() > 2) { 2010 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 2011 return ORA << "Parallel region is used in " 2012 << (UnknownUse ? "unknown" : "unexpected") 2013 << " ways. Will not attempt to rewrite the state machine."; 2014 }; 2015 emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark); 2016 continue; 2017 } 2018 2019 // Even if we have __kmpc_parallel_51 calls, we (for now) give 2020 // up if the function is not called from a unique kernel. 2021 Kernel K = getUniqueKernelFor(*F); 2022 if (!K) { 2023 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 2024 return ORA << "Parallel region is not called from a unique kernel. " 2025 "Will not attempt to rewrite the state machine."; 2026 }; 2027 emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark); 2028 continue; 2029 } 2030 2031 // We now know F is a parallel body function called only from the kernel K. 2032 // We also identified the state machine uses in which we replace the 2033 // function pointer by a new global symbol for identification purposes. This 2034 // ensures only direct calls to the function are left. 2035 2036 Module &M = *F->getParent(); 2037 Type *Int8Ty = Type::getInt8Ty(M.getContext()); 2038 2039 auto *ID = new GlobalVariable( 2040 M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage, 2041 UndefValue::get(Int8Ty), F->getName() + ".ID"); 2042 2043 for (Use *U : ToBeReplacedStateMachineUses) 2044 U->set(ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2045 ID, U->get()->getType())); 2046 2047 ++NumOpenMPParallelRegionsReplacedInGPUStateMachine; 2048 2049 Changed = true; 2050 } 2051 2052 return Changed; 2053 } 2054 2055 /// Abstract Attribute for tracking ICV values. 2056 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> { 2057 using Base = StateWrapper<BooleanState, AbstractAttribute>; 2058 AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 2059 2060 void initialize(Attributor &A) override { 2061 Function *F = getAnchorScope(); 2062 if (!F || !A.isFunctionIPOAmendable(*F)) 2063 indicatePessimisticFixpoint(); 2064 } 2065 2066 /// Returns true if value is assumed to be tracked. 2067 bool isAssumedTracked() const { return getAssumed(); } 2068 2069 /// Returns true if value is known to be tracked. 2070 bool isKnownTracked() const { return getAssumed(); } 2071 2072 /// Create an abstract attribute biew for the position \p IRP. 2073 static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A); 2074 2075 /// Return the value with which \p I can be replaced for specific \p ICV. 2076 virtual Optional<Value *> getReplacementValue(InternalControlVar ICV, 2077 const Instruction *I, 2078 Attributor &A) const { 2079 return None; 2080 } 2081 2082 /// Return an assumed unique ICV value if a single candidate is found. If 2083 /// there cannot be one, return a nullptr. If it is not clear yet, return the 2084 /// Optional::NoneType. 2085 virtual Optional<Value *> 2086 getUniqueReplacementValue(InternalControlVar ICV) const = 0; 2087 2088 // Currently only nthreads is being tracked. 2089 // this array will only grow with time. 2090 InternalControlVar TrackableICVs[1] = {ICV_nthreads}; 2091 2092 /// See AbstractAttribute::getName() 2093 const std::string getName() const override { return "AAICVTracker"; } 2094 2095 /// See AbstractAttribute::getIdAddr() 2096 const char *getIdAddr() const override { return &ID; } 2097 2098 /// This function should return true if the type of the \p AA is AAICVTracker 2099 static bool classof(const AbstractAttribute *AA) { 2100 return (AA->getIdAddr() == &ID); 2101 } 2102 2103 static const char ID; 2104 }; 2105 2106 struct AAICVTrackerFunction : public AAICVTracker { 2107 AAICVTrackerFunction(const IRPosition &IRP, Attributor &A) 2108 : AAICVTracker(IRP, A) {} 2109 2110 // FIXME: come up with better string. 2111 const std::string getAsStr() const override { return "ICVTrackerFunction"; } 2112 2113 // FIXME: come up with some stats. 2114 void trackStatistics() const override {} 2115 2116 /// We don't manifest anything for this AA. 2117 ChangeStatus manifest(Attributor &A) override { 2118 return ChangeStatus::UNCHANGED; 2119 } 2120 2121 // Map of ICV to their values at specific program point. 2122 EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar, 2123 InternalControlVar::ICV___last> 2124 ICVReplacementValuesMap; 2125 2126 ChangeStatus updateImpl(Attributor &A) override { 2127 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 2128 2129 Function *F = getAnchorScope(); 2130 2131 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2132 2133 for (InternalControlVar ICV : TrackableICVs) { 2134 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 2135 2136 auto &ValuesMap = ICVReplacementValuesMap[ICV]; 2137 auto TrackValues = [&](Use &U, Function &) { 2138 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U); 2139 if (!CI) 2140 return false; 2141 2142 // FIXME: handle setters with more that 1 arguments. 2143 /// Track new value. 2144 if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second) 2145 HasChanged = ChangeStatus::CHANGED; 2146 2147 return false; 2148 }; 2149 2150 auto CallCheck = [&](Instruction &I) { 2151 Optional<Value *> ReplVal = getValueForCall(A, &I, ICV); 2152 if (ReplVal.hasValue() && 2153 ValuesMap.insert(std::make_pair(&I, *ReplVal)).second) 2154 HasChanged = ChangeStatus::CHANGED; 2155 2156 return true; 2157 }; 2158 2159 // Track all changes of an ICV. 2160 SetterRFI.foreachUse(TrackValues, F); 2161 2162 bool UsedAssumedInformation = false; 2163 A.checkForAllInstructions(CallCheck, *this, {Instruction::Call}, 2164 UsedAssumedInformation, 2165 /* CheckBBLivenessOnly */ true); 2166 2167 /// TODO: Figure out a way to avoid adding entry in 2168 /// ICVReplacementValuesMap 2169 Instruction *Entry = &F->getEntryBlock().front(); 2170 if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry)) 2171 ValuesMap.insert(std::make_pair(Entry, nullptr)); 2172 } 2173 2174 return HasChanged; 2175 } 2176 2177 /// Hepler to check if \p I is a call and get the value for it if it is 2178 /// unique. 2179 Optional<Value *> getValueForCall(Attributor &A, const Instruction *I, 2180 InternalControlVar &ICV) const { 2181 2182 const auto *CB = dyn_cast<CallBase>(I); 2183 if (!CB || CB->hasFnAttr("no_openmp") || 2184 CB->hasFnAttr("no_openmp_routines")) 2185 return None; 2186 2187 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2188 auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter]; 2189 auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter]; 2190 Function *CalledFunction = CB->getCalledFunction(); 2191 2192 // Indirect call, assume ICV changes. 2193 if (CalledFunction == nullptr) 2194 return nullptr; 2195 if (CalledFunction == GetterRFI.Declaration) 2196 return None; 2197 if (CalledFunction == SetterRFI.Declaration) { 2198 if (ICVReplacementValuesMap[ICV].count(I)) 2199 return ICVReplacementValuesMap[ICV].lookup(I); 2200 2201 return nullptr; 2202 } 2203 2204 // Since we don't know, assume it changes the ICV. 2205 if (CalledFunction->isDeclaration()) 2206 return nullptr; 2207 2208 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2209 *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED); 2210 2211 if (ICVTrackingAA.isAssumedTracked()) 2212 return ICVTrackingAA.getUniqueReplacementValue(ICV); 2213 2214 // If we don't know, assume it changes. 2215 return nullptr; 2216 } 2217 2218 // We don't check unique value for a function, so return None. 2219 Optional<Value *> 2220 getUniqueReplacementValue(InternalControlVar ICV) const override { 2221 return None; 2222 } 2223 2224 /// Return the value with which \p I can be replaced for specific \p ICV. 2225 Optional<Value *> getReplacementValue(InternalControlVar ICV, 2226 const Instruction *I, 2227 Attributor &A) const override { 2228 const auto &ValuesMap = ICVReplacementValuesMap[ICV]; 2229 if (ValuesMap.count(I)) 2230 return ValuesMap.lookup(I); 2231 2232 SmallVector<const Instruction *, 16> Worklist; 2233 SmallPtrSet<const Instruction *, 16> Visited; 2234 Worklist.push_back(I); 2235 2236 Optional<Value *> ReplVal; 2237 2238 while (!Worklist.empty()) { 2239 const Instruction *CurrInst = Worklist.pop_back_val(); 2240 if (!Visited.insert(CurrInst).second) 2241 continue; 2242 2243 const BasicBlock *CurrBB = CurrInst->getParent(); 2244 2245 // Go up and look for all potential setters/calls that might change the 2246 // ICV. 2247 while ((CurrInst = CurrInst->getPrevNode())) { 2248 if (ValuesMap.count(CurrInst)) { 2249 Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst); 2250 // Unknown value, track new. 2251 if (!ReplVal.hasValue()) { 2252 ReplVal = NewReplVal; 2253 break; 2254 } 2255 2256 // If we found a new value, we can't know the icv value anymore. 2257 if (NewReplVal.hasValue()) 2258 if (ReplVal != NewReplVal) 2259 return nullptr; 2260 2261 break; 2262 } 2263 2264 Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV); 2265 if (!NewReplVal.hasValue()) 2266 continue; 2267 2268 // Unknown value, track new. 2269 if (!ReplVal.hasValue()) { 2270 ReplVal = NewReplVal; 2271 break; 2272 } 2273 2274 // if (NewReplVal.hasValue()) 2275 // We found a new value, we can't know the icv value anymore. 2276 if (ReplVal != NewReplVal) 2277 return nullptr; 2278 } 2279 2280 // If we are in the same BB and we have a value, we are done. 2281 if (CurrBB == I->getParent() && ReplVal.hasValue()) 2282 return ReplVal; 2283 2284 // Go through all predecessors and add terminators for analysis. 2285 for (const BasicBlock *Pred : predecessors(CurrBB)) 2286 if (const Instruction *Terminator = Pred->getTerminator()) 2287 Worklist.push_back(Terminator); 2288 } 2289 2290 return ReplVal; 2291 } 2292 }; 2293 2294 struct AAICVTrackerFunctionReturned : AAICVTracker { 2295 AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A) 2296 : AAICVTracker(IRP, A) {} 2297 2298 // FIXME: come up with better string. 2299 const std::string getAsStr() const override { 2300 return "ICVTrackerFunctionReturned"; 2301 } 2302 2303 // FIXME: come up with some stats. 2304 void trackStatistics() const override {} 2305 2306 /// We don't manifest anything for this AA. 2307 ChangeStatus manifest(Attributor &A) override { 2308 return ChangeStatus::UNCHANGED; 2309 } 2310 2311 // Map of ICV to their values at specific program point. 2312 EnumeratedArray<Optional<Value *>, InternalControlVar, 2313 InternalControlVar::ICV___last> 2314 ICVReplacementValuesMap; 2315 2316 /// Return the value with which \p I can be replaced for specific \p ICV. 2317 Optional<Value *> 2318 getUniqueReplacementValue(InternalControlVar ICV) const override { 2319 return ICVReplacementValuesMap[ICV]; 2320 } 2321 2322 ChangeStatus updateImpl(Attributor &A) override { 2323 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2324 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2325 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 2326 2327 if (!ICVTrackingAA.isAssumedTracked()) 2328 return indicatePessimisticFixpoint(); 2329 2330 for (InternalControlVar ICV : TrackableICVs) { 2331 Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV]; 2332 Optional<Value *> UniqueICVValue; 2333 2334 auto CheckReturnInst = [&](Instruction &I) { 2335 Optional<Value *> NewReplVal = 2336 ICVTrackingAA.getReplacementValue(ICV, &I, A); 2337 2338 // If we found a second ICV value there is no unique returned value. 2339 if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal) 2340 return false; 2341 2342 UniqueICVValue = NewReplVal; 2343 2344 return true; 2345 }; 2346 2347 bool UsedAssumedInformation = false; 2348 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret}, 2349 UsedAssumedInformation, 2350 /* CheckBBLivenessOnly */ true)) 2351 UniqueICVValue = nullptr; 2352 2353 if (UniqueICVValue == ReplVal) 2354 continue; 2355 2356 ReplVal = UniqueICVValue; 2357 Changed = ChangeStatus::CHANGED; 2358 } 2359 2360 return Changed; 2361 } 2362 }; 2363 2364 struct AAICVTrackerCallSite : AAICVTracker { 2365 AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A) 2366 : AAICVTracker(IRP, A) {} 2367 2368 void initialize(Attributor &A) override { 2369 Function *F = getAnchorScope(); 2370 if (!F || !A.isFunctionIPOAmendable(*F)) 2371 indicatePessimisticFixpoint(); 2372 2373 // We only initialize this AA for getters, so we need to know which ICV it 2374 // gets. 2375 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2376 for (InternalControlVar ICV : TrackableICVs) { 2377 auto ICVInfo = OMPInfoCache.ICVs[ICV]; 2378 auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter]; 2379 if (Getter.Declaration == getAssociatedFunction()) { 2380 AssociatedICV = ICVInfo.Kind; 2381 return; 2382 } 2383 } 2384 2385 /// Unknown ICV. 2386 indicatePessimisticFixpoint(); 2387 } 2388 2389 ChangeStatus manifest(Attributor &A) override { 2390 if (!ReplVal.hasValue() || !ReplVal.getValue()) 2391 return ChangeStatus::UNCHANGED; 2392 2393 A.changeValueAfterManifest(*getCtxI(), **ReplVal); 2394 A.deleteAfterManifest(*getCtxI()); 2395 2396 return ChangeStatus::CHANGED; 2397 } 2398 2399 // FIXME: come up with better string. 2400 const std::string getAsStr() const override { return "ICVTrackerCallSite"; } 2401 2402 // FIXME: come up with some stats. 2403 void trackStatistics() const override {} 2404 2405 InternalControlVar AssociatedICV; 2406 Optional<Value *> ReplVal; 2407 2408 ChangeStatus updateImpl(Attributor &A) override { 2409 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2410 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 2411 2412 // We don't have any information, so we assume it changes the ICV. 2413 if (!ICVTrackingAA.isAssumedTracked()) 2414 return indicatePessimisticFixpoint(); 2415 2416 Optional<Value *> NewReplVal = 2417 ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A); 2418 2419 if (ReplVal == NewReplVal) 2420 return ChangeStatus::UNCHANGED; 2421 2422 ReplVal = NewReplVal; 2423 return ChangeStatus::CHANGED; 2424 } 2425 2426 // Return the value with which associated value can be replaced for specific 2427 // \p ICV. 2428 Optional<Value *> 2429 getUniqueReplacementValue(InternalControlVar ICV) const override { 2430 return ReplVal; 2431 } 2432 }; 2433 2434 struct AAICVTrackerCallSiteReturned : AAICVTracker { 2435 AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A) 2436 : AAICVTracker(IRP, A) {} 2437 2438 // FIXME: come up with better string. 2439 const std::string getAsStr() const override { 2440 return "ICVTrackerCallSiteReturned"; 2441 } 2442 2443 // FIXME: come up with some stats. 2444 void trackStatistics() const override {} 2445 2446 /// We don't manifest anything for this AA. 2447 ChangeStatus manifest(Attributor &A) override { 2448 return ChangeStatus::UNCHANGED; 2449 } 2450 2451 // Map of ICV to their values at specific program point. 2452 EnumeratedArray<Optional<Value *>, InternalControlVar, 2453 InternalControlVar::ICV___last> 2454 ICVReplacementValuesMap; 2455 2456 /// Return the value with which associated value can be replaced for specific 2457 /// \p ICV. 2458 Optional<Value *> 2459 getUniqueReplacementValue(InternalControlVar ICV) const override { 2460 return ICVReplacementValuesMap[ICV]; 2461 } 2462 2463 ChangeStatus updateImpl(Attributor &A) override { 2464 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2465 const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>( 2466 *this, IRPosition::returned(*getAssociatedFunction()), 2467 DepClassTy::REQUIRED); 2468 2469 // We don't have any information, so we assume it changes the ICV. 2470 if (!ICVTrackingAA.isAssumedTracked()) 2471 return indicatePessimisticFixpoint(); 2472 2473 for (InternalControlVar ICV : TrackableICVs) { 2474 Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV]; 2475 Optional<Value *> NewReplVal = 2476 ICVTrackingAA.getUniqueReplacementValue(ICV); 2477 2478 if (ReplVal == NewReplVal) 2479 continue; 2480 2481 ReplVal = NewReplVal; 2482 Changed = ChangeStatus::CHANGED; 2483 } 2484 return Changed; 2485 } 2486 }; 2487 2488 struct AAExecutionDomainFunction : public AAExecutionDomain { 2489 AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A) 2490 : AAExecutionDomain(IRP, A) {} 2491 2492 const std::string getAsStr() const override { 2493 return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) + 2494 "/" + std::to_string(NumBBs) + " BBs thread 0 only."; 2495 } 2496 2497 /// See AbstractAttribute::trackStatistics(). 2498 void trackStatistics() const override {} 2499 2500 void initialize(Attributor &A) override { 2501 Function *F = getAnchorScope(); 2502 for (const auto &BB : *F) 2503 SingleThreadedBBs.insert(&BB); 2504 NumBBs = SingleThreadedBBs.size(); 2505 } 2506 2507 ChangeStatus manifest(Attributor &A) override { 2508 LLVM_DEBUG({ 2509 for (const BasicBlock *BB : SingleThreadedBBs) 2510 dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " " 2511 << BB->getName() << " is executed by a single thread.\n"; 2512 }); 2513 return ChangeStatus::UNCHANGED; 2514 } 2515 2516 ChangeStatus updateImpl(Attributor &A) override; 2517 2518 /// Check if an instruction is executed by a single thread. 2519 bool isExecutedByInitialThreadOnly(const Instruction &I) const override { 2520 return isExecutedByInitialThreadOnly(*I.getParent()); 2521 } 2522 2523 bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override { 2524 return isValidState() && SingleThreadedBBs.contains(&BB); 2525 } 2526 2527 /// Set of basic blocks that are executed by a single thread. 2528 DenseSet<const BasicBlock *> SingleThreadedBBs; 2529 2530 /// Total number of basic blocks in this function. 2531 long unsigned NumBBs; 2532 }; 2533 2534 ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) { 2535 Function *F = getAnchorScope(); 2536 ReversePostOrderTraversal<Function *> RPOT(F); 2537 auto NumSingleThreadedBBs = SingleThreadedBBs.size(); 2538 2539 bool AllCallSitesKnown; 2540 auto PredForCallSite = [&](AbstractCallSite ACS) { 2541 const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>( 2542 *this, IRPosition::function(*ACS.getInstruction()->getFunction()), 2543 DepClassTy::REQUIRED); 2544 return ACS.isDirectCall() && 2545 ExecutionDomainAA.isExecutedByInitialThreadOnly( 2546 *ACS.getInstruction()); 2547 }; 2548 2549 if (!A.checkForAllCallSites(PredForCallSite, *this, 2550 /* RequiresAllCallSites */ true, 2551 AllCallSitesKnown)) 2552 SingleThreadedBBs.erase(&F->getEntryBlock()); 2553 2554 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2555 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 2556 2557 // Check if the edge into the successor block compares the __kmpc_target_init 2558 // result with -1. If we are in non-SPMD-mode that signals only the main 2559 // thread will execute the edge. 2560 auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) { 2561 if (!Edge || !Edge->isConditional()) 2562 return false; 2563 if (Edge->getSuccessor(0) != SuccessorBB) 2564 return false; 2565 2566 auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition()); 2567 if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality()) 2568 return false; 2569 2570 ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1)); 2571 if (!C) 2572 return false; 2573 2574 // Match: -1 == __kmpc_target_init (for non-SPMD kernels only!) 2575 if (C->isAllOnesValue()) { 2576 auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0)); 2577 CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr; 2578 if (!CB) 2579 return false; 2580 const int InitIsSPMDArgNo = 1; 2581 auto *IsSPMDModeCI = 2582 dyn_cast<ConstantInt>(CB->getOperand(InitIsSPMDArgNo)); 2583 return IsSPMDModeCI && IsSPMDModeCI->isZero(); 2584 } 2585 2586 return false; 2587 }; 2588 2589 // Merge all the predecessor states into the current basic block. A basic 2590 // block is executed by a single thread if all of its predecessors are. 2591 auto MergePredecessorStates = [&](BasicBlock *BB) { 2592 if (pred_begin(BB) == pred_end(BB)) 2593 return SingleThreadedBBs.contains(BB); 2594 2595 bool IsInitialThread = true; 2596 for (auto PredBB = pred_begin(BB), PredEndBB = pred_end(BB); 2597 PredBB != PredEndBB; ++PredBB) { 2598 if (!IsInitialThreadOnly(dyn_cast<BranchInst>((*PredBB)->getTerminator()), 2599 BB)) 2600 IsInitialThread &= SingleThreadedBBs.contains(*PredBB); 2601 } 2602 2603 return IsInitialThread; 2604 }; 2605 2606 for (auto *BB : RPOT) { 2607 if (!MergePredecessorStates(BB)) 2608 SingleThreadedBBs.erase(BB); 2609 } 2610 2611 return (NumSingleThreadedBBs == SingleThreadedBBs.size()) 2612 ? ChangeStatus::UNCHANGED 2613 : ChangeStatus::CHANGED; 2614 } 2615 2616 /// Try to replace memory allocation calls called by a single thread with a 2617 /// static buffer of shared memory. 2618 struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> { 2619 using Base = StateWrapper<BooleanState, AbstractAttribute>; 2620 AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 2621 2622 /// Create an abstract attribute view for the position \p IRP. 2623 static AAHeapToShared &createForPosition(const IRPosition &IRP, 2624 Attributor &A); 2625 2626 /// Returns true if HeapToShared conversion is assumed to be possible. 2627 virtual bool isAssumedHeapToShared(CallBase &CB) const = 0; 2628 2629 /// Returns true if HeapToShared conversion is assumed and the CB is a 2630 /// callsite to a free operation to be removed. 2631 virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0; 2632 2633 /// See AbstractAttribute::getName(). 2634 const std::string getName() const override { return "AAHeapToShared"; } 2635 2636 /// See AbstractAttribute::getIdAddr(). 2637 const char *getIdAddr() const override { return &ID; } 2638 2639 /// This function should return true if the type of the \p AA is 2640 /// AAHeapToShared. 2641 static bool classof(const AbstractAttribute *AA) { 2642 return (AA->getIdAddr() == &ID); 2643 } 2644 2645 /// Unique ID (due to the unique address) 2646 static const char ID; 2647 }; 2648 2649 struct AAHeapToSharedFunction : public AAHeapToShared { 2650 AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A) 2651 : AAHeapToShared(IRP, A) {} 2652 2653 const std::string getAsStr() const override { 2654 return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) + 2655 " malloc calls eligible."; 2656 } 2657 2658 /// See AbstractAttribute::trackStatistics(). 2659 void trackStatistics() const override {} 2660 2661 /// This functions finds free calls that will be removed by the 2662 /// HeapToShared transformation. 2663 void findPotentialRemovedFreeCalls(Attributor &A) { 2664 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2665 auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared]; 2666 2667 PotentialRemovedFreeCalls.clear(); 2668 // Update free call users of found malloc calls. 2669 for (CallBase *CB : MallocCalls) { 2670 SmallVector<CallBase *, 4> FreeCalls; 2671 for (auto *U : CB->users()) { 2672 CallBase *C = dyn_cast<CallBase>(U); 2673 if (C && C->getCalledFunction() == FreeRFI.Declaration) 2674 FreeCalls.push_back(C); 2675 } 2676 2677 if (FreeCalls.size() != 1) 2678 continue; 2679 2680 PotentialRemovedFreeCalls.insert(FreeCalls.front()); 2681 } 2682 } 2683 2684 void initialize(Attributor &A) override { 2685 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2686 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 2687 2688 for (User *U : RFI.Declaration->users()) 2689 if (CallBase *CB = dyn_cast<CallBase>(U)) 2690 MallocCalls.insert(CB); 2691 2692 findPotentialRemovedFreeCalls(A); 2693 } 2694 2695 bool isAssumedHeapToShared(CallBase &CB) const override { 2696 return isValidState() && MallocCalls.count(&CB); 2697 } 2698 2699 bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override { 2700 return isValidState() && PotentialRemovedFreeCalls.count(&CB); 2701 } 2702 2703 ChangeStatus manifest(Attributor &A) override { 2704 if (MallocCalls.empty()) 2705 return ChangeStatus::UNCHANGED; 2706 2707 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2708 auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared]; 2709 2710 Function *F = getAnchorScope(); 2711 auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this, 2712 DepClassTy::OPTIONAL); 2713 2714 ChangeStatus Changed = ChangeStatus::UNCHANGED; 2715 for (CallBase *CB : MallocCalls) { 2716 // Skip replacing this if HeapToStack has already claimed it. 2717 if (HS && HS->isAssumedHeapToStack(*CB)) 2718 continue; 2719 2720 // Find the unique free call to remove it. 2721 SmallVector<CallBase *, 4> FreeCalls; 2722 for (auto *U : CB->users()) { 2723 CallBase *C = dyn_cast<CallBase>(U); 2724 if (C && C->getCalledFunction() == FreeCall.Declaration) 2725 FreeCalls.push_back(C); 2726 } 2727 if (FreeCalls.size() != 1) 2728 continue; 2729 2730 ConstantInt *AllocSize = dyn_cast<ConstantInt>(CB->getArgOperand(0)); 2731 2732 LLVM_DEBUG(dbgs() << TAG << "Replace globalization call " << *CB 2733 << " with " << AllocSize->getZExtValue() 2734 << " bytes of shared memory\n"); 2735 2736 // Create a new shared memory buffer of the same size as the allocation 2737 // and replace all the uses of the original allocation with it. 2738 Module *M = CB->getModule(); 2739 Type *Int8Ty = Type::getInt8Ty(M->getContext()); 2740 Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue()); 2741 auto *SharedMem = new GlobalVariable( 2742 *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage, 2743 UndefValue::get(Int8ArrTy), CB->getName(), nullptr, 2744 GlobalValue::NotThreadLocal, 2745 static_cast<unsigned>(AddressSpace::Shared)); 2746 auto *NewBuffer = 2747 ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo()); 2748 2749 auto Remark = [&](OptimizationRemark OR) { 2750 return OR << "Replaced globalized variable with " 2751 << ore::NV("SharedMemory", AllocSize->getZExtValue()) 2752 << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ") 2753 << "of shared memory."; 2754 }; 2755 A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark); 2756 2757 SharedMem->setAlignment(MaybeAlign(32)); 2758 2759 A.changeValueAfterManifest(*CB, *NewBuffer); 2760 A.deleteAfterManifest(*CB); 2761 A.deleteAfterManifest(*FreeCalls.front()); 2762 2763 NumBytesMovedToSharedMemory += AllocSize->getZExtValue(); 2764 Changed = ChangeStatus::CHANGED; 2765 } 2766 2767 return Changed; 2768 } 2769 2770 ChangeStatus updateImpl(Attributor &A) override { 2771 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2772 auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 2773 Function *F = getAnchorScope(); 2774 2775 auto NumMallocCalls = MallocCalls.size(); 2776 2777 // Only consider malloc calls executed by a single thread with a constant. 2778 for (User *U : RFI.Declaration->users()) { 2779 const auto &ED = A.getAAFor<AAExecutionDomain>( 2780 *this, IRPosition::function(*F), DepClassTy::REQUIRED); 2781 if (CallBase *CB = dyn_cast<CallBase>(U)) 2782 if (!dyn_cast<ConstantInt>(CB->getArgOperand(0)) || 2783 !ED.isExecutedByInitialThreadOnly(*CB)) 2784 MallocCalls.erase(CB); 2785 } 2786 2787 findPotentialRemovedFreeCalls(A); 2788 2789 if (NumMallocCalls != MallocCalls.size()) 2790 return ChangeStatus::CHANGED; 2791 2792 return ChangeStatus::UNCHANGED; 2793 } 2794 2795 /// Collection of all malloc calls in a function. 2796 SmallPtrSet<CallBase *, 4> MallocCalls; 2797 /// Collection of potentially removed free calls in a function. 2798 SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls; 2799 }; 2800 2801 struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> { 2802 using Base = StateWrapper<KernelInfoState, AbstractAttribute>; 2803 AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 2804 2805 /// Statistics are tracked as part of manifest for now. 2806 void trackStatistics() const override {} 2807 2808 /// See AbstractAttribute::getAsStr() 2809 const std::string getAsStr() const override { 2810 if (!isValidState()) 2811 return "<invalid>"; 2812 return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD" 2813 : "generic") + 2814 std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]" 2815 : "") + 2816 std::string(" #PRs: ") + 2817 std::to_string(ReachedKnownParallelRegions.size()) + 2818 ", #Unknown PRs: " + 2819 std::to_string(ReachedUnknownParallelRegions.size()); 2820 } 2821 2822 /// Create an abstract attribute biew for the position \p IRP. 2823 static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A); 2824 2825 /// See AbstractAttribute::getName() 2826 const std::string getName() const override { return "AAKernelInfo"; } 2827 2828 /// See AbstractAttribute::getIdAddr() 2829 const char *getIdAddr() const override { return &ID; } 2830 2831 /// This function should return true if the type of the \p AA is AAKernelInfo 2832 static bool classof(const AbstractAttribute *AA) { 2833 return (AA->getIdAddr() == &ID); 2834 } 2835 2836 static const char ID; 2837 }; 2838 2839 /// The function kernel info abstract attribute, basically, what can we say 2840 /// about a function with regards to the KernelInfoState. 2841 struct AAKernelInfoFunction : AAKernelInfo { 2842 AAKernelInfoFunction(const IRPosition &IRP, Attributor &A) 2843 : AAKernelInfo(IRP, A) {} 2844 2845 SmallPtrSet<Instruction *, 4> GuardedInstructions; 2846 2847 SmallPtrSetImpl<Instruction *> &getGuardedInstructions() { 2848 return GuardedInstructions; 2849 } 2850 2851 /// See AbstractAttribute::initialize(...). 2852 void initialize(Attributor &A) override { 2853 // This is a high-level transform that might change the constant arguments 2854 // of the init and dinit calls. We need to tell the Attributor about this 2855 // to avoid other parts using the current constant value for simpliication. 2856 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 2857 2858 Function *Fn = getAnchorScope(); 2859 if (!OMPInfoCache.Kernels.count(Fn)) 2860 return; 2861 2862 // Add itself to the reaching kernel and set IsKernelEntry. 2863 ReachingKernelEntries.insert(Fn); 2864 IsKernelEntry = true; 2865 2866 OMPInformationCache::RuntimeFunctionInfo &InitRFI = 2867 OMPInfoCache.RFIs[OMPRTL___kmpc_target_init]; 2868 OMPInformationCache::RuntimeFunctionInfo &DeinitRFI = 2869 OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit]; 2870 2871 // For kernels we perform more initialization work, first we find the init 2872 // and deinit calls. 2873 auto StoreCallBase = [](Use &U, 2874 OMPInformationCache::RuntimeFunctionInfo &RFI, 2875 CallBase *&Storage) { 2876 CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI); 2877 assert(CB && 2878 "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!"); 2879 assert(!Storage && 2880 "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!"); 2881 Storage = CB; 2882 return false; 2883 }; 2884 InitRFI.foreachUse( 2885 [&](Use &U, Function &) { 2886 StoreCallBase(U, InitRFI, KernelInitCB); 2887 return false; 2888 }, 2889 Fn); 2890 DeinitRFI.foreachUse( 2891 [&](Use &U, Function &) { 2892 StoreCallBase(U, DeinitRFI, KernelDeinitCB); 2893 return false; 2894 }, 2895 Fn); 2896 2897 // Ignore kernels without initializers such as global constructors. 2898 if (!KernelInitCB || !KernelDeinitCB) { 2899 indicateOptimisticFixpoint(); 2900 return; 2901 } 2902 2903 // For kernels we might need to initialize/finalize the IsSPMD state and 2904 // we need to register a simplification callback so that the Attributor 2905 // knows the constant arguments to __kmpc_target_init and 2906 // __kmpc_target_deinit might actually change. 2907 2908 Attributor::SimplifictionCallbackTy StateMachineSimplifyCB = 2909 [&](const IRPosition &IRP, const AbstractAttribute *AA, 2910 bool &UsedAssumedInformation) -> Optional<Value *> { 2911 // IRP represents the "use generic state machine" argument of an 2912 // __kmpc_target_init call. We will answer this one with the internal 2913 // state. As long as we are not in an invalid state, we will create a 2914 // custom state machine so the value should be a `i1 false`. If we are 2915 // in an invalid state, we won't change the value that is in the IR. 2916 if (!isValidState()) 2917 return nullptr; 2918 // If we have disabled state machine rewrites, don't make a custom one. 2919 if (DisableOpenMPOptStateMachineRewrite) 2920 return nullptr; 2921 if (AA) 2922 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 2923 UsedAssumedInformation = !isAtFixpoint(); 2924 auto *FalseVal = 2925 ConstantInt::getBool(IRP.getAnchorValue().getContext(), 0); 2926 return FalseVal; 2927 }; 2928 2929 Attributor::SimplifictionCallbackTy IsSPMDModeSimplifyCB = 2930 [&](const IRPosition &IRP, const AbstractAttribute *AA, 2931 bool &UsedAssumedInformation) -> Optional<Value *> { 2932 // IRP represents the "SPMDCompatibilityTracker" argument of an 2933 // __kmpc_target_init or 2934 // __kmpc_target_deinit call. We will answer this one with the internal 2935 // state. 2936 if (!SPMDCompatibilityTracker.isValidState()) 2937 return nullptr; 2938 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 2939 if (AA) 2940 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 2941 UsedAssumedInformation = true; 2942 } else { 2943 UsedAssumedInformation = false; 2944 } 2945 auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(), 2946 SPMDCompatibilityTracker.isAssumed()); 2947 return Val; 2948 }; 2949 2950 Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB = 2951 [&](const IRPosition &IRP, const AbstractAttribute *AA, 2952 bool &UsedAssumedInformation) -> Optional<Value *> { 2953 // IRP represents the "RequiresFullRuntime" argument of an 2954 // __kmpc_target_init or __kmpc_target_deinit call. We will answer this 2955 // one with the internal state of the SPMDCompatibilityTracker, so if 2956 // generic then true, if SPMD then false. 2957 if (!SPMDCompatibilityTracker.isValidState()) 2958 return nullptr; 2959 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 2960 if (AA) 2961 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 2962 UsedAssumedInformation = true; 2963 } else { 2964 UsedAssumedInformation = false; 2965 } 2966 auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(), 2967 !SPMDCompatibilityTracker.isAssumed()); 2968 return Val; 2969 }; 2970 2971 constexpr const int InitIsSPMDArgNo = 1; 2972 constexpr const int DeinitIsSPMDArgNo = 1; 2973 constexpr const int InitUseStateMachineArgNo = 2; 2974 constexpr const int InitRequiresFullRuntimeArgNo = 3; 2975 constexpr const int DeinitRequiresFullRuntimeArgNo = 2; 2976 A.registerSimplificationCallback( 2977 IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo), 2978 StateMachineSimplifyCB); 2979 A.registerSimplificationCallback( 2980 IRPosition::callsite_argument(*KernelInitCB, InitIsSPMDArgNo), 2981 IsSPMDModeSimplifyCB); 2982 A.registerSimplificationCallback( 2983 IRPosition::callsite_argument(*KernelDeinitCB, DeinitIsSPMDArgNo), 2984 IsSPMDModeSimplifyCB); 2985 A.registerSimplificationCallback( 2986 IRPosition::callsite_argument(*KernelInitCB, 2987 InitRequiresFullRuntimeArgNo), 2988 IsGenericModeSimplifyCB); 2989 A.registerSimplificationCallback( 2990 IRPosition::callsite_argument(*KernelDeinitCB, 2991 DeinitRequiresFullRuntimeArgNo), 2992 IsGenericModeSimplifyCB); 2993 2994 // Check if we know we are in SPMD-mode already. 2995 ConstantInt *IsSPMDArg = 2996 dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo)); 2997 if (IsSPMDArg && !IsSPMDArg->isZero()) 2998 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 2999 // This is a generic region but SPMDization is disabled so stop tracking. 3000 else if (DisableOpenMPOptSPMDization) 3001 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3002 } 3003 3004 /// Modify the IR based on the KernelInfoState as the fixpoint iteration is 3005 /// finished now. 3006 ChangeStatus manifest(Attributor &A) override { 3007 // If we are not looking at a kernel with __kmpc_target_init and 3008 // __kmpc_target_deinit call we cannot actually manifest the information. 3009 if (!KernelInitCB || !KernelDeinitCB) 3010 return ChangeStatus::UNCHANGED; 3011 3012 // Known SPMD-mode kernels need no manifest changes. 3013 if (SPMDCompatibilityTracker.isKnown()) 3014 return ChangeStatus::UNCHANGED; 3015 3016 // If we can we change the execution mode to SPMD-mode otherwise we build a 3017 // custom state machine. 3018 if (!mayContainParallelRegion() || !changeToSPMDMode(A)) 3019 buildCustomStateMachine(A); 3020 3021 return ChangeStatus::CHANGED; 3022 } 3023 3024 bool changeToSPMDMode(Attributor &A) { 3025 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3026 3027 if (!SPMDCompatibilityTracker.isAssumed()) { 3028 for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) { 3029 if (!NonCompatibleI) 3030 continue; 3031 3032 // Skip diagnostics on calls to known OpenMP runtime functions for now. 3033 if (auto *CB = dyn_cast<CallBase>(NonCompatibleI)) 3034 if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction())) 3035 continue; 3036 3037 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 3038 ORA << "Value has potential side effects preventing SPMD-mode " 3039 "execution"; 3040 if (isa<CallBase>(NonCompatibleI)) { 3041 ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to " 3042 "the called function to override"; 3043 } 3044 return ORA << "."; 3045 }; 3046 A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121", 3047 Remark); 3048 3049 LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: " 3050 << *NonCompatibleI << "\n"); 3051 } 3052 3053 return false; 3054 } 3055 3056 auto CreateGuardedRegion = [&](Instruction *RegionStartI, 3057 Instruction *RegionEndI) { 3058 LoopInfo *LI = nullptr; 3059 DominatorTree *DT = nullptr; 3060 MemorySSAUpdater *MSU = nullptr; 3061 using InsertPointTy = OpenMPIRBuilder::InsertPointTy; 3062 3063 BasicBlock *ParentBB = RegionStartI->getParent(); 3064 Function *Fn = ParentBB->getParent(); 3065 Module &M = *Fn->getParent(); 3066 3067 // Create all the blocks and logic. 3068 // ParentBB: 3069 // goto RegionCheckTidBB 3070 // RegionCheckTidBB: 3071 // Tid = __kmpc_hardware_thread_id() 3072 // if (Tid != 0) 3073 // goto RegionBarrierBB 3074 // RegionStartBB: 3075 // <execute instructions guarded> 3076 // goto RegionEndBB 3077 // RegionEndBB: 3078 // <store escaping values to shared mem> 3079 // goto RegionBarrierBB 3080 // RegionBarrierBB: 3081 // __kmpc_simple_barrier_spmd() 3082 // // second barrier is omitted if lacking escaping values. 3083 // <load escaping values from shared mem> 3084 // __kmpc_simple_barrier_spmd() 3085 // goto RegionExitBB 3086 // RegionExitBB: 3087 // <execute rest of instructions> 3088 3089 BasicBlock *RegionEndBB = SplitBlock(ParentBB, RegionEndI->getNextNode(), 3090 DT, LI, MSU, "region.guarded.end"); 3091 BasicBlock *RegionBarrierBB = 3092 SplitBlock(RegionEndBB, &*RegionEndBB->getFirstInsertionPt(), DT, LI, 3093 MSU, "region.barrier"); 3094 BasicBlock *RegionExitBB = 3095 SplitBlock(RegionBarrierBB, &*RegionBarrierBB->getFirstInsertionPt(), 3096 DT, LI, MSU, "region.exit"); 3097 BasicBlock *RegionStartBB = 3098 SplitBlock(ParentBB, RegionStartI, DT, LI, MSU, "region.guarded"); 3099 3100 assert(ParentBB->getUniqueSuccessor() == RegionStartBB && 3101 "Expected a different CFG"); 3102 3103 BasicBlock *RegionCheckTidBB = SplitBlock( 3104 ParentBB, ParentBB->getTerminator(), DT, LI, MSU, "region.check.tid"); 3105 3106 // Register basic blocks with the Attributor. 3107 A.registerManifestAddedBasicBlock(*RegionEndBB); 3108 A.registerManifestAddedBasicBlock(*RegionBarrierBB); 3109 A.registerManifestAddedBasicBlock(*RegionExitBB); 3110 A.registerManifestAddedBasicBlock(*RegionStartBB); 3111 A.registerManifestAddedBasicBlock(*RegionCheckTidBB); 3112 3113 bool HasBroadcastValues = false; 3114 // Find escaping outputs from the guarded region to outside users and 3115 // broadcast their values to them. 3116 for (Instruction &I : *RegionStartBB) { 3117 SmallPtrSet<Instruction *, 4> OutsideUsers; 3118 for (User *Usr : I.users()) { 3119 Instruction &UsrI = *cast<Instruction>(Usr); 3120 if (UsrI.getParent() != RegionStartBB) 3121 OutsideUsers.insert(&UsrI); 3122 } 3123 3124 if (OutsideUsers.empty()) 3125 continue; 3126 3127 HasBroadcastValues = true; 3128 3129 // Emit a global variable in shared memory to store the broadcasted 3130 // value. 3131 auto *SharedMem = new GlobalVariable( 3132 M, I.getType(), /* IsConstant */ false, 3133 GlobalValue::InternalLinkage, UndefValue::get(I.getType()), 3134 I.getName() + ".guarded.output.alloc", nullptr, 3135 GlobalValue::NotThreadLocal, 3136 static_cast<unsigned>(AddressSpace::Shared)); 3137 3138 // Emit a store instruction to update the value. 3139 new StoreInst(&I, SharedMem, RegionEndBB->getTerminator()); 3140 3141 LoadInst *LoadI = new LoadInst(I.getType(), SharedMem, 3142 I.getName() + ".guarded.output.load", 3143 RegionBarrierBB->getTerminator()); 3144 3145 // Emit a load instruction and replace uses of the output value. 3146 for (Instruction *UsrI : OutsideUsers) { 3147 assert(UsrI->getParent() == RegionExitBB && 3148 "Expected escaping users in exit region"); 3149 UsrI->replaceUsesOfWith(&I, LoadI); 3150 } 3151 } 3152 3153 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3154 3155 // Go to tid check BB in ParentBB. 3156 const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc(); 3157 ParentBB->getTerminator()->eraseFromParent(); 3158 OpenMPIRBuilder::LocationDescription Loc( 3159 InsertPointTy(ParentBB, ParentBB->end()), DL); 3160 OMPInfoCache.OMPBuilder.updateToLocation(Loc); 3161 auto *SrcLocStr = OMPInfoCache.OMPBuilder.getOrCreateSrcLocStr(Loc); 3162 Value *Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(SrcLocStr); 3163 BranchInst::Create(RegionCheckTidBB, ParentBB)->setDebugLoc(DL); 3164 3165 // Add check for Tid in RegionCheckTidBB 3166 RegionCheckTidBB->getTerminator()->eraseFromParent(); 3167 OpenMPIRBuilder::LocationDescription LocRegionCheckTid( 3168 InsertPointTy(RegionCheckTidBB, RegionCheckTidBB->end()), DL); 3169 OMPInfoCache.OMPBuilder.updateToLocation(LocRegionCheckTid); 3170 FunctionCallee HardwareTidFn = 3171 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3172 M, OMPRTL___kmpc_get_hardware_thread_id_in_block); 3173 Value *Tid = 3174 OMPInfoCache.OMPBuilder.Builder.CreateCall(HardwareTidFn, {}); 3175 Value *TidCheck = OMPInfoCache.OMPBuilder.Builder.CreateIsNull(Tid); 3176 OMPInfoCache.OMPBuilder.Builder 3177 .CreateCondBr(TidCheck, RegionStartBB, RegionBarrierBB) 3178 ->setDebugLoc(DL); 3179 3180 // First barrier for synchronization, ensures main thread has updated 3181 // values. 3182 FunctionCallee BarrierFn = 3183 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3184 M, OMPRTL___kmpc_barrier_simple_spmd); 3185 OMPInfoCache.OMPBuilder.updateToLocation(InsertPointTy( 3186 RegionBarrierBB, RegionBarrierBB->getFirstInsertionPt())); 3187 OMPInfoCache.OMPBuilder.Builder.CreateCall(BarrierFn, {Ident, Tid}) 3188 ->setDebugLoc(DL); 3189 3190 // Second barrier ensures workers have read broadcast values. 3191 if (HasBroadcastValues) 3192 CallInst::Create(BarrierFn, {Ident, Tid}, "", 3193 RegionBarrierBB->getTerminator()) 3194 ->setDebugLoc(DL); 3195 }; 3196 3197 auto &AllocSharedRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 3198 SmallPtrSet<BasicBlock *, 8> Visited; 3199 for (Instruction *GuardedI : SPMDCompatibilityTracker) { 3200 BasicBlock *BB = GuardedI->getParent(); 3201 if (!Visited.insert(BB).second) 3202 continue; 3203 3204 SmallVector<std::pair<Instruction *, Instruction *>> Reorders; 3205 Instruction *LastEffect = nullptr; 3206 BasicBlock::reverse_iterator IP = BB->rbegin(), IPEnd = BB->rend(); 3207 while (++IP != IPEnd) { 3208 if (!IP->mayHaveSideEffects() && !IP->mayReadFromMemory()) 3209 continue; 3210 Instruction *I = &*IP; 3211 if (OpenMPOpt::getCallIfRegularCall(*I, &AllocSharedRFI)) 3212 continue; 3213 if (!I->user_empty() || !SPMDCompatibilityTracker.contains(I)) { 3214 LastEffect = nullptr; 3215 continue; 3216 } 3217 if (LastEffect) 3218 Reorders.push_back({I, LastEffect}); 3219 LastEffect = &*IP; 3220 } 3221 for (auto &Reorder : Reorders) 3222 Reorder.first->moveBefore(Reorder.second); 3223 } 3224 3225 SmallVector<std::pair<Instruction *, Instruction *>, 4> GuardedRegions; 3226 3227 for (Instruction *GuardedI : SPMDCompatibilityTracker) { 3228 BasicBlock *BB = GuardedI->getParent(); 3229 auto *CalleeAA = A.lookupAAFor<AAKernelInfo>( 3230 IRPosition::function(*GuardedI->getFunction()), nullptr, 3231 DepClassTy::NONE); 3232 assert(CalleeAA != nullptr && "Expected Callee AAKernelInfo"); 3233 auto &CalleeAAFunction = *cast<AAKernelInfoFunction>(CalleeAA); 3234 // Continue if instruction is already guarded. 3235 if (CalleeAAFunction.getGuardedInstructions().contains(GuardedI)) 3236 continue; 3237 3238 Instruction *GuardedRegionStart = nullptr, *GuardedRegionEnd = nullptr; 3239 for (Instruction &I : *BB) { 3240 // If instruction I needs to be guarded update the guarded region 3241 // bounds. 3242 if (SPMDCompatibilityTracker.contains(&I)) { 3243 CalleeAAFunction.getGuardedInstructions().insert(&I); 3244 if (GuardedRegionStart) 3245 GuardedRegionEnd = &I; 3246 else 3247 GuardedRegionStart = GuardedRegionEnd = &I; 3248 3249 continue; 3250 } 3251 3252 // Instruction I does not need guarding, store 3253 // any region found and reset bounds. 3254 if (GuardedRegionStart) { 3255 GuardedRegions.push_back( 3256 std::make_pair(GuardedRegionStart, GuardedRegionEnd)); 3257 GuardedRegionStart = nullptr; 3258 GuardedRegionEnd = nullptr; 3259 } 3260 } 3261 } 3262 3263 for (auto &GR : GuardedRegions) 3264 CreateGuardedRegion(GR.first, GR.second); 3265 3266 // Adjust the global exec mode flag that tells the runtime what mode this 3267 // kernel is executed in. 3268 Function *Kernel = getAnchorScope(); 3269 GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable( 3270 (Kernel->getName() + "_exec_mode").str()); 3271 assert(ExecMode && "Kernel without exec mode?"); 3272 assert(ExecMode->getInitializer() && 3273 ExecMode->getInitializer()->isOneValue() && 3274 "Initially non-SPMD kernel has SPMD exec mode!"); 3275 3276 // Set the global exec mode flag to indicate SPMD-Generic mode. 3277 constexpr int SPMDGeneric = 2; 3278 if (!ExecMode->getInitializer()->isZeroValue()) 3279 ExecMode->setInitializer( 3280 ConstantInt::get(ExecMode->getInitializer()->getType(), SPMDGeneric)); 3281 3282 // Next rewrite the init and deinit calls to indicate we use SPMD-mode now. 3283 const int InitIsSPMDArgNo = 1; 3284 const int DeinitIsSPMDArgNo = 1; 3285 const int InitUseStateMachineArgNo = 2; 3286 const int InitRequiresFullRuntimeArgNo = 3; 3287 const int DeinitRequiresFullRuntimeArgNo = 2; 3288 3289 auto &Ctx = getAnchorValue().getContext(); 3290 A.changeUseAfterManifest(KernelInitCB->getArgOperandUse(InitIsSPMDArgNo), 3291 *ConstantInt::getBool(Ctx, 1)); 3292 A.changeUseAfterManifest( 3293 KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), 3294 *ConstantInt::getBool(Ctx, 0)); 3295 A.changeUseAfterManifest( 3296 KernelDeinitCB->getArgOperandUse(DeinitIsSPMDArgNo), 3297 *ConstantInt::getBool(Ctx, 1)); 3298 A.changeUseAfterManifest( 3299 KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo), 3300 *ConstantInt::getBool(Ctx, 0)); 3301 A.changeUseAfterManifest( 3302 KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo), 3303 *ConstantInt::getBool(Ctx, 0)); 3304 3305 ++NumOpenMPTargetRegionKernelsSPMD; 3306 3307 auto Remark = [&](OptimizationRemark OR) { 3308 return OR << "Transformed generic-mode kernel to SPMD-mode."; 3309 }; 3310 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark); 3311 return true; 3312 }; 3313 3314 ChangeStatus buildCustomStateMachine(Attributor &A) { 3315 // If we have disabled state machine rewrites, don't make a custom one 3316 if (DisableOpenMPOptStateMachineRewrite) 3317 return indicatePessimisticFixpoint(); 3318 3319 assert(ReachedKnownParallelRegions.isValidState() && 3320 "Custom state machine with invalid parallel region states?"); 3321 3322 const int InitIsSPMDArgNo = 1; 3323 const int InitUseStateMachineArgNo = 2; 3324 3325 // Check if the current configuration is non-SPMD and generic state machine. 3326 // If we already have SPMD mode or a custom state machine we do not need to 3327 // go any further. If it is anything but a constant something is weird and 3328 // we give up. 3329 ConstantInt *UseStateMachine = dyn_cast<ConstantInt>( 3330 KernelInitCB->getArgOperand(InitUseStateMachineArgNo)); 3331 ConstantInt *IsSPMD = 3332 dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo)); 3333 3334 // If we are stuck with generic mode, try to create a custom device (=GPU) 3335 // state machine which is specialized for the parallel regions that are 3336 // reachable by the kernel. 3337 if (!UseStateMachine || UseStateMachine->isZero() || !IsSPMD || 3338 !IsSPMD->isZero()) 3339 return ChangeStatus::UNCHANGED; 3340 3341 // If not SPMD mode, indicate we use a custom state machine now. 3342 auto &Ctx = getAnchorValue().getContext(); 3343 auto *FalseVal = ConstantInt::getBool(Ctx, 0); 3344 A.changeUseAfterManifest( 3345 KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal); 3346 3347 // If we don't actually need a state machine we are done here. This can 3348 // happen if there simply are no parallel regions. In the resulting kernel 3349 // all worker threads will simply exit right away, leaving the main thread 3350 // to do the work alone. 3351 if (!mayContainParallelRegion()) { 3352 ++NumOpenMPTargetRegionKernelsWithoutStateMachine; 3353 3354 auto Remark = [&](OptimizationRemark OR) { 3355 return OR << "Removing unused state machine from generic-mode kernel."; 3356 }; 3357 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark); 3358 3359 return ChangeStatus::CHANGED; 3360 } 3361 3362 // Keep track in the statistics of our new shiny custom state machine. 3363 if (ReachedUnknownParallelRegions.empty()) { 3364 ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback; 3365 3366 auto Remark = [&](OptimizationRemark OR) { 3367 return OR << "Rewriting generic-mode kernel with a customized state " 3368 "machine."; 3369 }; 3370 A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark); 3371 } else { 3372 ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback; 3373 3374 auto Remark = [&](OptimizationRemarkAnalysis OR) { 3375 return OR << "Generic-mode kernel is executed with a customized state " 3376 "machine that requires a fallback."; 3377 }; 3378 A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark); 3379 3380 // Tell the user why we ended up with a fallback. 3381 for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) { 3382 if (!UnknownParallelRegionCB) 3383 continue; 3384 auto Remark = [&](OptimizationRemarkAnalysis ORA) { 3385 return ORA << "Call may contain unknown parallel regions. Use " 3386 << "`__attribute__((assume(\"omp_no_parallelism\")))` to " 3387 "override."; 3388 }; 3389 A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB, 3390 "OMP133", Remark); 3391 } 3392 } 3393 3394 // Create all the blocks: 3395 // 3396 // InitCB = __kmpc_target_init(...) 3397 // bool IsWorker = InitCB >= 0; 3398 // if (IsWorker) { 3399 // SMBeginBB: __kmpc_barrier_simple_spmd(...); 3400 // void *WorkFn; 3401 // bool Active = __kmpc_kernel_parallel(&WorkFn); 3402 // if (!WorkFn) return; 3403 // SMIsActiveCheckBB: if (Active) { 3404 // SMIfCascadeCurrentBB: if (WorkFn == <ParFn0>) 3405 // ParFn0(...); 3406 // SMIfCascadeCurrentBB: else if (WorkFn == <ParFn1>) 3407 // ParFn1(...); 3408 // ... 3409 // SMIfCascadeCurrentBB: else 3410 // ((WorkFnTy*)WorkFn)(...); 3411 // SMEndParallelBB: __kmpc_kernel_end_parallel(...); 3412 // } 3413 // SMDoneBB: __kmpc_barrier_simple_spmd(...); 3414 // goto SMBeginBB; 3415 // } 3416 // UserCodeEntryBB: // user code 3417 // __kmpc_target_deinit(...) 3418 // 3419 Function *Kernel = getAssociatedFunction(); 3420 assert(Kernel && "Expected an associated function!"); 3421 3422 BasicBlock *InitBB = KernelInitCB->getParent(); 3423 BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock( 3424 KernelInitCB->getNextNode(), "thread.user_code.check"); 3425 BasicBlock *StateMachineBeginBB = BasicBlock::Create( 3426 Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB); 3427 BasicBlock *StateMachineFinishedBB = BasicBlock::Create( 3428 Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB); 3429 BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create( 3430 Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB); 3431 BasicBlock *StateMachineIfCascadeCurrentBB = 3432 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check", 3433 Kernel, UserCodeEntryBB); 3434 BasicBlock *StateMachineEndParallelBB = 3435 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end", 3436 Kernel, UserCodeEntryBB); 3437 BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create( 3438 Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB); 3439 A.registerManifestAddedBasicBlock(*InitBB); 3440 A.registerManifestAddedBasicBlock(*UserCodeEntryBB); 3441 A.registerManifestAddedBasicBlock(*StateMachineBeginBB); 3442 A.registerManifestAddedBasicBlock(*StateMachineFinishedBB); 3443 A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB); 3444 A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB); 3445 A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB); 3446 A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB); 3447 3448 const DebugLoc &DLoc = KernelInitCB->getDebugLoc(); 3449 ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc); 3450 3451 InitBB->getTerminator()->eraseFromParent(); 3452 Instruction *IsWorker = 3453 ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB, 3454 ConstantInt::get(KernelInitCB->getType(), -1), 3455 "thread.is_worker", InitBB); 3456 IsWorker->setDebugLoc(DLoc); 3457 BranchInst::Create(StateMachineBeginBB, UserCodeEntryBB, IsWorker, InitBB); 3458 3459 Module &M = *Kernel->getParent(); 3460 3461 // Create local storage for the work function pointer. 3462 const DataLayout &DL = M.getDataLayout(); 3463 Type *VoidPtrTy = Type::getInt8PtrTy(Ctx); 3464 Instruction *WorkFnAI = 3465 new AllocaInst(VoidPtrTy, DL.getAllocaAddrSpace(), nullptr, 3466 "worker.work_fn.addr", &Kernel->getEntryBlock().front()); 3467 WorkFnAI->setDebugLoc(DLoc); 3468 3469 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3470 OMPInfoCache.OMPBuilder.updateToLocation( 3471 OpenMPIRBuilder::LocationDescription( 3472 IRBuilder<>::InsertPoint(StateMachineBeginBB, 3473 StateMachineBeginBB->end()), 3474 DLoc)); 3475 3476 Value *Ident = KernelInitCB->getArgOperand(0); 3477 Value *GTid = KernelInitCB; 3478 3479 FunctionCallee BarrierFn = 3480 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3481 M, OMPRTL___kmpc_barrier_simple_spmd); 3482 CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB) 3483 ->setDebugLoc(DLoc); 3484 3485 if (WorkFnAI->getType()->getPointerAddressSpace() != 3486 (unsigned int)AddressSpace::Generic) { 3487 WorkFnAI = new AddrSpaceCastInst( 3488 WorkFnAI, 3489 PointerType::getWithSamePointeeType( 3490 cast<PointerType>(WorkFnAI->getType()), 3491 (unsigned int)AddressSpace::Generic), 3492 WorkFnAI->getName() + ".generic", StateMachineBeginBB); 3493 WorkFnAI->setDebugLoc(DLoc); 3494 } 3495 3496 FunctionCallee KernelParallelFn = 3497 OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3498 M, OMPRTL___kmpc_kernel_parallel); 3499 Instruction *IsActiveWorker = CallInst::Create( 3500 KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB); 3501 IsActiveWorker->setDebugLoc(DLoc); 3502 Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn", 3503 StateMachineBeginBB); 3504 WorkFn->setDebugLoc(DLoc); 3505 3506 FunctionType *ParallelRegionFnTy = FunctionType::get( 3507 Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)}, 3508 false); 3509 Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast( 3510 WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast", 3511 StateMachineBeginBB); 3512 3513 Instruction *IsDone = 3514 ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn, 3515 Constant::getNullValue(VoidPtrTy), "worker.is_done", 3516 StateMachineBeginBB); 3517 IsDone->setDebugLoc(DLoc); 3518 BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB, 3519 IsDone, StateMachineBeginBB) 3520 ->setDebugLoc(DLoc); 3521 3522 BranchInst::Create(StateMachineIfCascadeCurrentBB, 3523 StateMachineDoneBarrierBB, IsActiveWorker, 3524 StateMachineIsActiveCheckBB) 3525 ->setDebugLoc(DLoc); 3526 3527 Value *ZeroArg = 3528 Constant::getNullValue(ParallelRegionFnTy->getParamType(0)); 3529 3530 // Now that we have most of the CFG skeleton it is time for the if-cascade 3531 // that checks the function pointer we got from the runtime against the 3532 // parallel regions we expect, if there are any. 3533 for (int i = 0, e = ReachedKnownParallelRegions.size(); i < e; ++i) { 3534 auto *ParallelRegion = ReachedKnownParallelRegions[i]; 3535 BasicBlock *PRExecuteBB = BasicBlock::Create( 3536 Ctx, "worker_state_machine.parallel_region.execute", Kernel, 3537 StateMachineEndParallelBB); 3538 CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB) 3539 ->setDebugLoc(DLoc); 3540 BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB) 3541 ->setDebugLoc(DLoc); 3542 3543 BasicBlock *PRNextBB = 3544 BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check", 3545 Kernel, StateMachineEndParallelBB); 3546 3547 // Check if we need to compare the pointer at all or if we can just 3548 // call the parallel region function. 3549 Value *IsPR; 3550 if (i + 1 < e || !ReachedUnknownParallelRegions.empty()) { 3551 Instruction *CmpI = ICmpInst::Create( 3552 ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion, 3553 "worker.check_parallel_region", StateMachineIfCascadeCurrentBB); 3554 CmpI->setDebugLoc(DLoc); 3555 IsPR = CmpI; 3556 } else { 3557 IsPR = ConstantInt::getTrue(Ctx); 3558 } 3559 3560 BranchInst::Create(PRExecuteBB, PRNextBB, IsPR, 3561 StateMachineIfCascadeCurrentBB) 3562 ->setDebugLoc(DLoc); 3563 StateMachineIfCascadeCurrentBB = PRNextBB; 3564 } 3565 3566 // At the end of the if-cascade we place the indirect function pointer call 3567 // in case we might need it, that is if there can be parallel regions we 3568 // have not handled in the if-cascade above. 3569 if (!ReachedUnknownParallelRegions.empty()) { 3570 StateMachineIfCascadeCurrentBB->setName( 3571 "worker_state_machine.parallel_region.fallback.execute"); 3572 CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "", 3573 StateMachineIfCascadeCurrentBB) 3574 ->setDebugLoc(DLoc); 3575 } 3576 BranchInst::Create(StateMachineEndParallelBB, 3577 StateMachineIfCascadeCurrentBB) 3578 ->setDebugLoc(DLoc); 3579 3580 CallInst::Create(OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction( 3581 M, OMPRTL___kmpc_kernel_end_parallel), 3582 {}, "", StateMachineEndParallelBB) 3583 ->setDebugLoc(DLoc); 3584 BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB) 3585 ->setDebugLoc(DLoc); 3586 3587 CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB) 3588 ->setDebugLoc(DLoc); 3589 BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB) 3590 ->setDebugLoc(DLoc); 3591 3592 return ChangeStatus::CHANGED; 3593 } 3594 3595 /// Fixpoint iteration update function. Will be called every time a dependence 3596 /// changed its state (and in the beginning). 3597 ChangeStatus updateImpl(Attributor &A) override { 3598 KernelInfoState StateBefore = getState(); 3599 3600 // Callback to check a read/write instruction. 3601 auto CheckRWInst = [&](Instruction &I) { 3602 // We handle calls later. 3603 if (isa<CallBase>(I)) 3604 return true; 3605 // We only care about write effects. 3606 if (!I.mayWriteToMemory()) 3607 return true; 3608 if (auto *SI = dyn_cast<StoreInst>(&I)) { 3609 SmallVector<const Value *> Objects; 3610 getUnderlyingObjects(SI->getPointerOperand(), Objects); 3611 if (llvm::all_of(Objects, 3612 [](const Value *Obj) { return isa<AllocaInst>(Obj); })) 3613 return true; 3614 // Check for AAHeapToStack moved objects which must not be guarded. 3615 auto &HS = A.getAAFor<AAHeapToStack>( 3616 *this, IRPosition::function(*I.getFunction()), 3617 DepClassTy::REQUIRED); 3618 if (llvm::all_of(Objects, [&HS](const Value *Obj) { 3619 auto *CB = dyn_cast<CallBase>(Obj); 3620 if (!CB) 3621 return false; 3622 return HS.isAssumedHeapToStack(*CB); 3623 })) { 3624 return true; 3625 } 3626 } 3627 3628 // Insert instruction that needs guarding. 3629 SPMDCompatibilityTracker.insert(&I); 3630 return true; 3631 }; 3632 3633 bool UsedAssumedInformationInCheckRWInst = false; 3634 if (!SPMDCompatibilityTracker.isAtFixpoint()) 3635 if (!A.checkForAllReadWriteInstructions( 3636 CheckRWInst, *this, UsedAssumedInformationInCheckRWInst)) 3637 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3638 3639 if (!IsKernelEntry) { 3640 updateReachingKernelEntries(A); 3641 updateParallelLevels(A); 3642 3643 if (!ParallelLevels.isValidState()) 3644 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3645 } 3646 3647 // Callback to check a call instruction. 3648 bool AllSPMDStatesWereFixed = true; 3649 auto CheckCallInst = [&](Instruction &I) { 3650 auto &CB = cast<CallBase>(I); 3651 auto &CBAA = A.getAAFor<AAKernelInfo>( 3652 *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL); 3653 getState() ^= CBAA.getState(); 3654 AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint(); 3655 return true; 3656 }; 3657 3658 bool UsedAssumedInformationInCheckCallInst = false; 3659 if (!A.checkForAllCallLikeInstructions( 3660 CheckCallInst, *this, UsedAssumedInformationInCheckCallInst)) 3661 return indicatePessimisticFixpoint(); 3662 3663 // If we haven't used any assumed information for the SPMD state we can fix 3664 // it. 3665 if (!UsedAssumedInformationInCheckRWInst && 3666 !UsedAssumedInformationInCheckCallInst && AllSPMDStatesWereFixed) 3667 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 3668 3669 return StateBefore == getState() ? ChangeStatus::UNCHANGED 3670 : ChangeStatus::CHANGED; 3671 } 3672 3673 private: 3674 /// Update info regarding reaching kernels. 3675 void updateReachingKernelEntries(Attributor &A) { 3676 auto PredCallSite = [&](AbstractCallSite ACS) { 3677 Function *Caller = ACS.getInstruction()->getFunction(); 3678 3679 assert(Caller && "Caller is nullptr"); 3680 3681 auto &CAA = A.getOrCreateAAFor<AAKernelInfo>( 3682 IRPosition::function(*Caller), this, DepClassTy::REQUIRED); 3683 if (CAA.ReachingKernelEntries.isValidState()) { 3684 ReachingKernelEntries ^= CAA.ReachingKernelEntries; 3685 return true; 3686 } 3687 3688 // We lost track of the caller of the associated function, any kernel 3689 // could reach now. 3690 ReachingKernelEntries.indicatePessimisticFixpoint(); 3691 3692 return true; 3693 }; 3694 3695 bool AllCallSitesKnown; 3696 if (!A.checkForAllCallSites(PredCallSite, *this, 3697 true /* RequireAllCallSites */, 3698 AllCallSitesKnown)) 3699 ReachingKernelEntries.indicatePessimisticFixpoint(); 3700 } 3701 3702 /// Update info regarding parallel levels. 3703 void updateParallelLevels(Attributor &A) { 3704 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3705 OMPInformationCache::RuntimeFunctionInfo &Parallel51RFI = 3706 OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51]; 3707 3708 auto PredCallSite = [&](AbstractCallSite ACS) { 3709 Function *Caller = ACS.getInstruction()->getFunction(); 3710 3711 assert(Caller && "Caller is nullptr"); 3712 3713 auto &CAA = 3714 A.getOrCreateAAFor<AAKernelInfo>(IRPosition::function(*Caller)); 3715 if (CAA.ParallelLevels.isValidState()) { 3716 // Any function that is called by `__kmpc_parallel_51` will not be 3717 // folded as the parallel level in the function is updated. In order to 3718 // get it right, all the analysis would depend on the implentation. That 3719 // said, if in the future any change to the implementation, the analysis 3720 // could be wrong. As a consequence, we are just conservative here. 3721 if (Caller == Parallel51RFI.Declaration) { 3722 ParallelLevels.indicatePessimisticFixpoint(); 3723 return true; 3724 } 3725 3726 ParallelLevels ^= CAA.ParallelLevels; 3727 3728 return true; 3729 } 3730 3731 // We lost track of the caller of the associated function, any kernel 3732 // could reach now. 3733 ParallelLevels.indicatePessimisticFixpoint(); 3734 3735 return true; 3736 }; 3737 3738 bool AllCallSitesKnown = true; 3739 if (!A.checkForAllCallSites(PredCallSite, *this, 3740 true /* RequireAllCallSites */, 3741 AllCallSitesKnown)) 3742 ParallelLevels.indicatePessimisticFixpoint(); 3743 } 3744 }; 3745 3746 /// The call site kernel info abstract attribute, basically, what can we say 3747 /// about a call site with regards to the KernelInfoState. For now this simply 3748 /// forwards the information from the callee. 3749 struct AAKernelInfoCallSite : AAKernelInfo { 3750 AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A) 3751 : AAKernelInfo(IRP, A) {} 3752 3753 /// See AbstractAttribute::initialize(...). 3754 void initialize(Attributor &A) override { 3755 AAKernelInfo::initialize(A); 3756 3757 CallBase &CB = cast<CallBase>(getAssociatedValue()); 3758 Function *Callee = getAssociatedFunction(); 3759 3760 // Helper to lookup an assumption string. 3761 auto HasAssumption = [](CallBase &CB, StringRef AssumptionStr) { 3762 return hasAssumption(CB, AssumptionStr); 3763 }; 3764 3765 // Check for SPMD-mode assumptions. 3766 if (HasAssumption(CB, "ompx_spmd_amenable")) { 3767 SPMDCompatibilityTracker.indicateOptimisticFixpoint(); 3768 indicateOptimisticFixpoint(); 3769 } 3770 3771 // First weed out calls we do not care about, that is readonly/readnone 3772 // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a 3773 // parallel region or anything else we are looking for. 3774 if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) { 3775 indicateOptimisticFixpoint(); 3776 return; 3777 } 3778 3779 // Next we check if we know the callee. If it is a known OpenMP function 3780 // we will handle them explicitly in the switch below. If it is not, we 3781 // will use an AAKernelInfo object on the callee to gather information and 3782 // merge that into the current state. The latter happens in the updateImpl. 3783 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3784 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee); 3785 if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) { 3786 // Unknown caller or declarations are not analyzable, we give up. 3787 if (!Callee || !A.isFunctionIPOAmendable(*Callee)) { 3788 3789 // Unknown callees might contain parallel regions, except if they have 3790 // an appropriate assumption attached. 3791 if (!(HasAssumption(CB, "omp_no_openmp") || 3792 HasAssumption(CB, "omp_no_parallelism"))) 3793 ReachedUnknownParallelRegions.insert(&CB); 3794 3795 // If SPMDCompatibilityTracker is not fixed, we need to give up on the 3796 // idea we can run something unknown in SPMD-mode. 3797 if (!SPMDCompatibilityTracker.isAtFixpoint()) { 3798 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3799 SPMDCompatibilityTracker.insert(&CB); 3800 } 3801 3802 // We have updated the state for this unknown call properly, there won't 3803 // be any change so we indicate a fixpoint. 3804 indicateOptimisticFixpoint(); 3805 } 3806 // If the callee is known and can be used in IPO, we will update the state 3807 // based on the callee state in updateImpl. 3808 return; 3809 } 3810 3811 const unsigned int WrapperFunctionArgNo = 6; 3812 RuntimeFunction RF = It->getSecond(); 3813 switch (RF) { 3814 // All the functions we know are compatible with SPMD mode. 3815 case OMPRTL___kmpc_is_spmd_exec_mode: 3816 case OMPRTL___kmpc_for_static_fini: 3817 case OMPRTL___kmpc_global_thread_num: 3818 case OMPRTL___kmpc_get_hardware_num_threads_in_block: 3819 case OMPRTL___kmpc_get_hardware_num_blocks: 3820 case OMPRTL___kmpc_single: 3821 case OMPRTL___kmpc_end_single: 3822 case OMPRTL___kmpc_master: 3823 case OMPRTL___kmpc_end_master: 3824 case OMPRTL___kmpc_barrier: 3825 break; 3826 case OMPRTL___kmpc_for_static_init_4: 3827 case OMPRTL___kmpc_for_static_init_4u: 3828 case OMPRTL___kmpc_for_static_init_8: 3829 case OMPRTL___kmpc_for_static_init_8u: { 3830 // Check the schedule and allow static schedule in SPMD mode. 3831 unsigned ScheduleArgOpNo = 2; 3832 auto *ScheduleTypeCI = 3833 dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo)); 3834 unsigned ScheduleTypeVal = 3835 ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0; 3836 switch (OMPScheduleType(ScheduleTypeVal)) { 3837 case OMPScheduleType::Static: 3838 case OMPScheduleType::StaticChunked: 3839 case OMPScheduleType::Distribute: 3840 case OMPScheduleType::DistributeChunked: 3841 break; 3842 default: 3843 SPMDCompatibilityTracker.indicatePessimisticFixpoint(); 3844 SPMDCompatibilityTracker.insert(&CB); 3845 break; 3846 }; 3847 } break; 3848 case OMPRTL___kmpc_target_init: 3849 KernelInitCB = &CB; 3850 break; 3851 case OMPRTL___kmpc_target_deinit: 3852 KernelDeinitCB = &CB; 3853 break; 3854 case OMPRTL___kmpc_parallel_51: 3855 if (auto *ParallelRegion = dyn_cast<Function>( 3856 CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) { 3857 ReachedKnownParallelRegions.insert(ParallelRegion); 3858 break; 3859 } 3860 // The condition above should usually get the parallel region function 3861 // pointer and record it. In the off chance it doesn't we assume the 3862 // worst. 3863 ReachedUnknownParallelRegions.insert(&CB); 3864 break; 3865 case OMPRTL___kmpc_omp_task: 3866 // We do not look into tasks right now, just give up. 3867 SPMDCompatibilityTracker.insert(&CB); 3868 ReachedUnknownParallelRegions.insert(&CB); 3869 indicatePessimisticFixpoint(); 3870 return; 3871 case OMPRTL___kmpc_alloc_shared: 3872 case OMPRTL___kmpc_free_shared: 3873 // Return without setting a fixpoint, to be resolved in updateImpl. 3874 return; 3875 default: 3876 // Unknown OpenMP runtime calls cannot be executed in SPMD-mode, 3877 // generally. 3878 SPMDCompatibilityTracker.insert(&CB); 3879 indicatePessimisticFixpoint(); 3880 return; 3881 } 3882 // All other OpenMP runtime calls will not reach parallel regions so they 3883 // can be safely ignored for now. Since it is a known OpenMP runtime call we 3884 // have now modeled all effects and there is no need for any update. 3885 indicateOptimisticFixpoint(); 3886 } 3887 3888 ChangeStatus updateImpl(Attributor &A) override { 3889 // TODO: Once we have call site specific value information we can provide 3890 // call site specific liveness information and then it makes 3891 // sense to specialize attributes for call sites arguments instead of 3892 // redirecting requests to the callee argument. 3893 Function *F = getAssociatedFunction(); 3894 3895 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 3896 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F); 3897 3898 // If F is not a runtime function, propagate the AAKernelInfo of the callee. 3899 if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) { 3900 const IRPosition &FnPos = IRPosition::function(*F); 3901 auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED); 3902 if (getState() == FnAA.getState()) 3903 return ChangeStatus::UNCHANGED; 3904 getState() = FnAA.getState(); 3905 return ChangeStatus::CHANGED; 3906 } 3907 3908 // F is a runtime function that allocates or frees memory, check 3909 // AAHeapToStack and AAHeapToShared. 3910 KernelInfoState StateBefore = getState(); 3911 assert((It->getSecond() == OMPRTL___kmpc_alloc_shared || 3912 It->getSecond() == OMPRTL___kmpc_free_shared) && 3913 "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call"); 3914 3915 CallBase &CB = cast<CallBase>(getAssociatedValue()); 3916 3917 auto &HeapToStackAA = A.getAAFor<AAHeapToStack>( 3918 *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL); 3919 auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>( 3920 *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL); 3921 3922 RuntimeFunction RF = It->getSecond(); 3923 3924 switch (RF) { 3925 // If neither HeapToStack nor HeapToShared assume the call is removed, 3926 // assume SPMD incompatibility. 3927 case OMPRTL___kmpc_alloc_shared: 3928 if (!HeapToStackAA.isAssumedHeapToStack(CB) && 3929 !HeapToSharedAA.isAssumedHeapToShared(CB)) 3930 SPMDCompatibilityTracker.insert(&CB); 3931 break; 3932 case OMPRTL___kmpc_free_shared: 3933 if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) && 3934 !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB)) 3935 SPMDCompatibilityTracker.insert(&CB); 3936 break; 3937 default: 3938 SPMDCompatibilityTracker.insert(&CB); 3939 } 3940 3941 return StateBefore == getState() ? ChangeStatus::UNCHANGED 3942 : ChangeStatus::CHANGED; 3943 } 3944 }; 3945 3946 struct AAFoldRuntimeCall 3947 : public StateWrapper<BooleanState, AbstractAttribute> { 3948 using Base = StateWrapper<BooleanState, AbstractAttribute>; 3949 3950 AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {} 3951 3952 /// Statistics are tracked as part of manifest for now. 3953 void trackStatistics() const override {} 3954 3955 /// Create an abstract attribute biew for the position \p IRP. 3956 static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP, 3957 Attributor &A); 3958 3959 /// See AbstractAttribute::getName() 3960 const std::string getName() const override { return "AAFoldRuntimeCall"; } 3961 3962 /// See AbstractAttribute::getIdAddr() 3963 const char *getIdAddr() const override { return &ID; } 3964 3965 /// This function should return true if the type of the \p AA is 3966 /// AAFoldRuntimeCall 3967 static bool classof(const AbstractAttribute *AA) { 3968 return (AA->getIdAddr() == &ID); 3969 } 3970 3971 static const char ID; 3972 }; 3973 3974 struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall { 3975 AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A) 3976 : AAFoldRuntimeCall(IRP, A) {} 3977 3978 /// See AbstractAttribute::getAsStr() 3979 const std::string getAsStr() const override { 3980 if (!isValidState()) 3981 return "<invalid>"; 3982 3983 std::string Str("simplified value: "); 3984 3985 if (!SimplifiedValue.hasValue()) 3986 return Str + std::string("none"); 3987 3988 if (!SimplifiedValue.getValue()) 3989 return Str + std::string("nullptr"); 3990 3991 if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue())) 3992 return Str + std::to_string(CI->getSExtValue()); 3993 3994 return Str + std::string("unknown"); 3995 } 3996 3997 void initialize(Attributor &A) override { 3998 if (DisableOpenMPOptFolding) 3999 indicatePessimisticFixpoint(); 4000 4001 Function *Callee = getAssociatedFunction(); 4002 4003 auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache()); 4004 const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee); 4005 assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() && 4006 "Expected a known OpenMP runtime function"); 4007 4008 RFKind = It->getSecond(); 4009 4010 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4011 A.registerSimplificationCallback( 4012 IRPosition::callsite_returned(CB), 4013 [&](const IRPosition &IRP, const AbstractAttribute *AA, 4014 bool &UsedAssumedInformation) -> Optional<Value *> { 4015 assert((isValidState() || (SimplifiedValue.hasValue() && 4016 SimplifiedValue.getValue() == nullptr)) && 4017 "Unexpected invalid state!"); 4018 4019 if (!isAtFixpoint()) { 4020 UsedAssumedInformation = true; 4021 if (AA) 4022 A.recordDependence(*this, *AA, DepClassTy::OPTIONAL); 4023 } 4024 return SimplifiedValue; 4025 }); 4026 } 4027 4028 ChangeStatus updateImpl(Attributor &A) override { 4029 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4030 switch (RFKind) { 4031 case OMPRTL___kmpc_is_spmd_exec_mode: 4032 Changed |= foldIsSPMDExecMode(A); 4033 break; 4034 case OMPRTL___kmpc_is_generic_main_thread_id: 4035 Changed |= foldIsGenericMainThread(A); 4036 break; 4037 case OMPRTL___kmpc_parallel_level: 4038 Changed |= foldParallelLevel(A); 4039 break; 4040 case OMPRTL___kmpc_get_hardware_num_threads_in_block: 4041 Changed = Changed | foldKernelFnAttribute(A, "omp_target_thread_limit"); 4042 break; 4043 case OMPRTL___kmpc_get_hardware_num_blocks: 4044 Changed = Changed | foldKernelFnAttribute(A, "omp_target_num_teams"); 4045 break; 4046 default: 4047 llvm_unreachable("Unhandled OpenMP runtime function!"); 4048 } 4049 4050 return Changed; 4051 } 4052 4053 ChangeStatus manifest(Attributor &A) override { 4054 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4055 4056 if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) { 4057 Instruction &I = *getCtxI(); 4058 A.changeValueAfterManifest(I, **SimplifiedValue); 4059 A.deleteAfterManifest(I); 4060 4061 CallBase *CB = dyn_cast<CallBase>(&I); 4062 auto Remark = [&](OptimizationRemark OR) { 4063 if (auto *C = dyn_cast<ConstantInt>(*SimplifiedValue)) 4064 return OR << "Replacing OpenMP runtime call " 4065 << CB->getCalledFunction()->getName() << " with " 4066 << ore::NV("FoldedValue", C->getZExtValue()) << "."; 4067 else 4068 return OR << "Replacing OpenMP runtime call " 4069 << CB->getCalledFunction()->getName() << "."; 4070 }; 4071 4072 if (CB && EnableVerboseRemarks) 4073 A.emitRemark<OptimizationRemark>(CB, "OMP180", Remark); 4074 4075 LLVM_DEBUG(dbgs() << TAG << "Replacing runtime call: " << I << " with " 4076 << **SimplifiedValue << "\n"); 4077 4078 Changed = ChangeStatus::CHANGED; 4079 } 4080 4081 return Changed; 4082 } 4083 4084 ChangeStatus indicatePessimisticFixpoint() override { 4085 SimplifiedValue = nullptr; 4086 return AAFoldRuntimeCall::indicatePessimisticFixpoint(); 4087 } 4088 4089 private: 4090 /// Fold __kmpc_is_spmd_exec_mode into a constant if possible. 4091 ChangeStatus foldIsSPMDExecMode(Attributor &A) { 4092 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4093 4094 unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0; 4095 unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0; 4096 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4097 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4098 4099 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4100 return indicatePessimisticFixpoint(); 4101 4102 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4103 auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K), 4104 DepClassTy::REQUIRED); 4105 4106 if (!AA.isValidState()) { 4107 SimplifiedValue = nullptr; 4108 return indicatePessimisticFixpoint(); 4109 } 4110 4111 if (AA.SPMDCompatibilityTracker.isAssumed()) { 4112 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4113 ++KnownSPMDCount; 4114 else 4115 ++AssumedSPMDCount; 4116 } else { 4117 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4118 ++KnownNonSPMDCount; 4119 else 4120 ++AssumedNonSPMDCount; 4121 } 4122 } 4123 4124 if ((AssumedSPMDCount + KnownSPMDCount) && 4125 (AssumedNonSPMDCount + KnownNonSPMDCount)) 4126 return indicatePessimisticFixpoint(); 4127 4128 auto &Ctx = getAnchorValue().getContext(); 4129 if (KnownSPMDCount || AssumedSPMDCount) { 4130 assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 && 4131 "Expected only SPMD kernels!"); 4132 // All reaching kernels are in SPMD mode. Update all function calls to 4133 // __kmpc_is_spmd_exec_mode to 1. 4134 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true); 4135 } else if (KnownNonSPMDCount || AssumedNonSPMDCount) { 4136 assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 && 4137 "Expected only non-SPMD kernels!"); 4138 // All reaching kernels are in non-SPMD mode. Update all function 4139 // calls to __kmpc_is_spmd_exec_mode to 0. 4140 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false); 4141 } else { 4142 // We have empty reaching kernels, therefore we cannot tell if the 4143 // associated call site can be folded. At this moment, SimplifiedValue 4144 // must be none. 4145 assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none"); 4146 } 4147 4148 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4149 : ChangeStatus::CHANGED; 4150 } 4151 4152 /// Fold __kmpc_is_generic_main_thread_id into a constant if possible. 4153 ChangeStatus foldIsGenericMainThread(Attributor &A) { 4154 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4155 4156 CallBase &CB = cast<CallBase>(getAssociatedValue()); 4157 Function *F = CB.getFunction(); 4158 const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>( 4159 *this, IRPosition::function(*F), DepClassTy::REQUIRED); 4160 4161 if (!ExecutionDomainAA.isValidState()) 4162 return indicatePessimisticFixpoint(); 4163 4164 auto &Ctx = getAnchorValue().getContext(); 4165 if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB)) 4166 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true); 4167 else 4168 return indicatePessimisticFixpoint(); 4169 4170 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4171 : ChangeStatus::CHANGED; 4172 } 4173 4174 /// Fold __kmpc_parallel_level into a constant if possible. 4175 ChangeStatus foldParallelLevel(Attributor &A) { 4176 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4177 4178 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4179 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4180 4181 if (!CallerKernelInfoAA.ParallelLevels.isValidState()) 4182 return indicatePessimisticFixpoint(); 4183 4184 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4185 return indicatePessimisticFixpoint(); 4186 4187 if (CallerKernelInfoAA.ReachingKernelEntries.empty()) { 4188 assert(!SimplifiedValue.hasValue() && 4189 "SimplifiedValue should keep none at this point"); 4190 return ChangeStatus::UNCHANGED; 4191 } 4192 4193 unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0; 4194 unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0; 4195 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4196 auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K), 4197 DepClassTy::REQUIRED); 4198 if (!AA.SPMDCompatibilityTracker.isValidState()) 4199 return indicatePessimisticFixpoint(); 4200 4201 if (AA.SPMDCompatibilityTracker.isAssumed()) { 4202 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4203 ++KnownSPMDCount; 4204 else 4205 ++AssumedSPMDCount; 4206 } else { 4207 if (AA.SPMDCompatibilityTracker.isAtFixpoint()) 4208 ++KnownNonSPMDCount; 4209 else 4210 ++AssumedNonSPMDCount; 4211 } 4212 } 4213 4214 if ((AssumedSPMDCount + KnownSPMDCount) && 4215 (AssumedNonSPMDCount + KnownNonSPMDCount)) 4216 return indicatePessimisticFixpoint(); 4217 4218 auto &Ctx = getAnchorValue().getContext(); 4219 // If the caller can only be reached by SPMD kernel entries, the parallel 4220 // level is 1. Similarly, if the caller can only be reached by non-SPMD 4221 // kernel entries, it is 0. 4222 if (AssumedSPMDCount || KnownSPMDCount) { 4223 assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 && 4224 "Expected only SPMD kernels!"); 4225 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 1); 4226 } else { 4227 assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 && 4228 "Expected only non-SPMD kernels!"); 4229 SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 0); 4230 } 4231 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4232 : ChangeStatus::CHANGED; 4233 } 4234 4235 ChangeStatus foldKernelFnAttribute(Attributor &A, llvm::StringRef Attr) { 4236 // Specialize only if all the calls agree with the attribute constant value 4237 int32_t CurrentAttrValue = -1; 4238 Optional<Value *> SimplifiedValueBefore = SimplifiedValue; 4239 4240 auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>( 4241 *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED); 4242 4243 if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState()) 4244 return indicatePessimisticFixpoint(); 4245 4246 // Iterate over the kernels that reach this function 4247 for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) { 4248 int32_t NextAttrVal = -1; 4249 if (K->hasFnAttribute(Attr)) 4250 NextAttrVal = 4251 std::stoi(K->getFnAttribute(Attr).getValueAsString().str()); 4252 4253 if (NextAttrVal == -1 || 4254 (CurrentAttrValue != -1 && CurrentAttrValue != NextAttrVal)) 4255 return indicatePessimisticFixpoint(); 4256 CurrentAttrValue = NextAttrVal; 4257 } 4258 4259 if (CurrentAttrValue != -1) { 4260 auto &Ctx = getAnchorValue().getContext(); 4261 SimplifiedValue = 4262 ConstantInt::get(Type::getInt32Ty(Ctx), CurrentAttrValue); 4263 } 4264 return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED 4265 : ChangeStatus::CHANGED; 4266 } 4267 4268 /// An optional value the associated value is assumed to fold to. That is, we 4269 /// assume the associated value (which is a call) can be replaced by this 4270 /// simplified value. 4271 Optional<Value *> SimplifiedValue; 4272 4273 /// The runtime function kind of the callee of the associated call site. 4274 RuntimeFunction RFKind; 4275 }; 4276 4277 } // namespace 4278 4279 /// Register folding callsite 4280 void OpenMPOpt::registerFoldRuntimeCall(RuntimeFunction RF) { 4281 auto &RFI = OMPInfoCache.RFIs[RF]; 4282 RFI.foreachUse(SCC, [&](Use &U, Function &F) { 4283 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &RFI); 4284 if (!CI) 4285 return false; 4286 A.getOrCreateAAFor<AAFoldRuntimeCall>( 4287 IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr, 4288 DepClassTy::NONE, /* ForceUpdate */ false, 4289 /* UpdateAfterInit */ false); 4290 return false; 4291 }); 4292 } 4293 4294 void OpenMPOpt::registerAAs(bool IsModulePass) { 4295 if (SCC.empty()) 4296 4297 return; 4298 if (IsModulePass) { 4299 // Ensure we create the AAKernelInfo AAs first and without triggering an 4300 // update. This will make sure we register all value simplification 4301 // callbacks before any other AA has the chance to create an AAValueSimplify 4302 // or similar. 4303 for (Function *Kernel : OMPInfoCache.Kernels) 4304 A.getOrCreateAAFor<AAKernelInfo>( 4305 IRPosition::function(*Kernel), /* QueryingAA */ nullptr, 4306 DepClassTy::NONE, /* ForceUpdate */ false, 4307 /* UpdateAfterInit */ false); 4308 4309 registerFoldRuntimeCall(OMPRTL___kmpc_is_generic_main_thread_id); 4310 registerFoldRuntimeCall(OMPRTL___kmpc_is_spmd_exec_mode); 4311 registerFoldRuntimeCall(OMPRTL___kmpc_parallel_level); 4312 registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_threads_in_block); 4313 registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_blocks); 4314 } 4315 4316 // Create CallSite AA for all Getters. 4317 for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) { 4318 auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)]; 4319 4320 auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter]; 4321 4322 auto CreateAA = [&](Use &U, Function &Caller) { 4323 CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI); 4324 if (!CI) 4325 return false; 4326 4327 auto &CB = cast<CallBase>(*CI); 4328 4329 IRPosition CBPos = IRPosition::callsite_function(CB); 4330 A.getOrCreateAAFor<AAICVTracker>(CBPos); 4331 return false; 4332 }; 4333 4334 GetterRFI.foreachUse(SCC, CreateAA); 4335 } 4336 auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared]; 4337 auto CreateAA = [&](Use &U, Function &F) { 4338 A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F)); 4339 return false; 4340 }; 4341 if (!DisableOpenMPOptDeglobalization) 4342 GlobalizationRFI.foreachUse(SCC, CreateAA); 4343 4344 // Create an ExecutionDomain AA for every function and a HeapToStack AA for 4345 // every function if there is a device kernel. 4346 if (!isOpenMPDevice(M)) 4347 return; 4348 4349 for (auto *F : SCC) { 4350 if (F->isDeclaration()) 4351 continue; 4352 4353 A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F)); 4354 if (!DisableOpenMPOptDeglobalization) 4355 A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F)); 4356 4357 for (auto &I : instructions(*F)) { 4358 if (auto *LI = dyn_cast<LoadInst>(&I)) { 4359 bool UsedAssumedInformation = false; 4360 A.getAssumedSimplified(IRPosition::value(*LI), /* AA */ nullptr, 4361 UsedAssumedInformation); 4362 } 4363 } 4364 } 4365 } 4366 4367 const char AAICVTracker::ID = 0; 4368 const char AAKernelInfo::ID = 0; 4369 const char AAExecutionDomain::ID = 0; 4370 const char AAHeapToShared::ID = 0; 4371 const char AAFoldRuntimeCall::ID = 0; 4372 4373 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP, 4374 Attributor &A) { 4375 AAICVTracker *AA = nullptr; 4376 switch (IRP.getPositionKind()) { 4377 case IRPosition::IRP_INVALID: 4378 case IRPosition::IRP_FLOAT: 4379 case IRPosition::IRP_ARGUMENT: 4380 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4381 llvm_unreachable("ICVTracker can only be created for function position!"); 4382 case IRPosition::IRP_RETURNED: 4383 AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A); 4384 break; 4385 case IRPosition::IRP_CALL_SITE_RETURNED: 4386 AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A); 4387 break; 4388 case IRPosition::IRP_CALL_SITE: 4389 AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A); 4390 break; 4391 case IRPosition::IRP_FUNCTION: 4392 AA = new (A.Allocator) AAICVTrackerFunction(IRP, A); 4393 break; 4394 } 4395 4396 return *AA; 4397 } 4398 4399 AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP, 4400 Attributor &A) { 4401 AAExecutionDomainFunction *AA = nullptr; 4402 switch (IRP.getPositionKind()) { 4403 case IRPosition::IRP_INVALID: 4404 case IRPosition::IRP_FLOAT: 4405 case IRPosition::IRP_ARGUMENT: 4406 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4407 case IRPosition::IRP_RETURNED: 4408 case IRPosition::IRP_CALL_SITE_RETURNED: 4409 case IRPosition::IRP_CALL_SITE: 4410 llvm_unreachable( 4411 "AAExecutionDomain can only be created for function position!"); 4412 case IRPosition::IRP_FUNCTION: 4413 AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A); 4414 break; 4415 } 4416 4417 return *AA; 4418 } 4419 4420 AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP, 4421 Attributor &A) { 4422 AAHeapToSharedFunction *AA = nullptr; 4423 switch (IRP.getPositionKind()) { 4424 case IRPosition::IRP_INVALID: 4425 case IRPosition::IRP_FLOAT: 4426 case IRPosition::IRP_ARGUMENT: 4427 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4428 case IRPosition::IRP_RETURNED: 4429 case IRPosition::IRP_CALL_SITE_RETURNED: 4430 case IRPosition::IRP_CALL_SITE: 4431 llvm_unreachable( 4432 "AAHeapToShared can only be created for function position!"); 4433 case IRPosition::IRP_FUNCTION: 4434 AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A); 4435 break; 4436 } 4437 4438 return *AA; 4439 } 4440 4441 AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP, 4442 Attributor &A) { 4443 AAKernelInfo *AA = nullptr; 4444 switch (IRP.getPositionKind()) { 4445 case IRPosition::IRP_INVALID: 4446 case IRPosition::IRP_FLOAT: 4447 case IRPosition::IRP_ARGUMENT: 4448 case IRPosition::IRP_RETURNED: 4449 case IRPosition::IRP_CALL_SITE_RETURNED: 4450 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4451 llvm_unreachable("KernelInfo can only be created for function position!"); 4452 case IRPosition::IRP_CALL_SITE: 4453 AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A); 4454 break; 4455 case IRPosition::IRP_FUNCTION: 4456 AA = new (A.Allocator) AAKernelInfoFunction(IRP, A); 4457 break; 4458 } 4459 4460 return *AA; 4461 } 4462 4463 AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP, 4464 Attributor &A) { 4465 AAFoldRuntimeCall *AA = nullptr; 4466 switch (IRP.getPositionKind()) { 4467 case IRPosition::IRP_INVALID: 4468 case IRPosition::IRP_FLOAT: 4469 case IRPosition::IRP_ARGUMENT: 4470 case IRPosition::IRP_RETURNED: 4471 case IRPosition::IRP_FUNCTION: 4472 case IRPosition::IRP_CALL_SITE: 4473 case IRPosition::IRP_CALL_SITE_ARGUMENT: 4474 llvm_unreachable("KernelInfo can only be created for call site position!"); 4475 case IRPosition::IRP_CALL_SITE_RETURNED: 4476 AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A); 4477 break; 4478 } 4479 4480 return *AA; 4481 } 4482 4483 PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) { 4484 if (!containsOpenMP(M)) 4485 return PreservedAnalyses::all(); 4486 if (DisableOpenMPOptimizations) 4487 return PreservedAnalyses::all(); 4488 4489 FunctionAnalysisManager &FAM = 4490 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 4491 KernelSet Kernels = getDeviceKernels(M); 4492 4493 auto IsCalled = [&](Function &F) { 4494 if (Kernels.contains(&F)) 4495 return true; 4496 for (const User *U : F.users()) 4497 if (!isa<BlockAddress>(U)) 4498 return true; 4499 return false; 4500 }; 4501 4502 auto EmitRemark = [&](Function &F) { 4503 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 4504 ORE.emit([&]() { 4505 OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F); 4506 return ORA << "Could not internalize function. " 4507 << "Some optimizations may not be possible. [OMP140]"; 4508 }); 4509 }; 4510 4511 // Create internal copies of each function if this is a kernel Module. This 4512 // allows iterprocedural passes to see every call edge. 4513 DenseMap<Function *, Function *> InternalizedMap; 4514 if (isOpenMPDevice(M)) { 4515 SmallPtrSet<Function *, 16> InternalizeFns; 4516 for (Function &F : M) 4517 if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) && 4518 !DisableInternalization) { 4519 if (Attributor::isInternalizable(F)) { 4520 InternalizeFns.insert(&F); 4521 } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) { 4522 EmitRemark(F); 4523 } 4524 } 4525 4526 Attributor::internalizeFunctions(InternalizeFns, InternalizedMap); 4527 } 4528 4529 // Look at every function in the Module unless it was internalized. 4530 SmallVector<Function *, 16> SCC; 4531 for (Function &F : M) 4532 if (!F.isDeclaration() && !InternalizedMap.lookup(&F)) 4533 SCC.push_back(&F); 4534 4535 if (SCC.empty()) 4536 return PreservedAnalyses::all(); 4537 4538 AnalysisGetter AG(FAM); 4539 4540 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 4541 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 4542 }; 4543 4544 BumpPtrAllocator Allocator; 4545 CallGraphUpdater CGUpdater; 4546 4547 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 4548 OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels); 4549 4550 unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32; 4551 Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false, 4552 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 4553 4554 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 4555 bool Changed = OMPOpt.run(true); 4556 4557 // Optionally inline device functions for potentially better performance. 4558 if (AlwaysInlineDeviceFunctions && isOpenMPDevice(M)) 4559 for (Function &F : M) 4560 if (!F.isDeclaration() && !Kernels.contains(&F) && 4561 !F.hasFnAttribute(Attribute::NoInline)) 4562 F.addFnAttr(Attribute::AlwaysInline); 4563 4564 if (PrintModuleAfterOptimizations) 4565 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt Module Pass:\n" << M); 4566 4567 if (Changed) 4568 return PreservedAnalyses::none(); 4569 4570 return PreservedAnalyses::all(); 4571 } 4572 4573 PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C, 4574 CGSCCAnalysisManager &AM, 4575 LazyCallGraph &CG, 4576 CGSCCUpdateResult &UR) { 4577 if (!containsOpenMP(*C.begin()->getFunction().getParent())) 4578 return PreservedAnalyses::all(); 4579 if (DisableOpenMPOptimizations) 4580 return PreservedAnalyses::all(); 4581 4582 SmallVector<Function *, 16> SCC; 4583 // If there are kernels in the module, we have to run on all SCC's. 4584 for (LazyCallGraph::Node &N : C) { 4585 Function *Fn = &N.getFunction(); 4586 SCC.push_back(Fn); 4587 } 4588 4589 if (SCC.empty()) 4590 return PreservedAnalyses::all(); 4591 4592 Module &M = *C.begin()->getFunction().getParent(); 4593 4594 KernelSet Kernels = getDeviceKernels(M); 4595 4596 FunctionAnalysisManager &FAM = 4597 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 4598 4599 AnalysisGetter AG(FAM); 4600 4601 auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & { 4602 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F); 4603 }; 4604 4605 BumpPtrAllocator Allocator; 4606 CallGraphUpdater CGUpdater; 4607 CGUpdater.initialize(CG, C, AM, UR); 4608 4609 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 4610 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator, 4611 /*CGSCC*/ Functions, Kernels); 4612 4613 unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32; 4614 Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true, 4615 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 4616 4617 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 4618 bool Changed = OMPOpt.run(false); 4619 4620 if (PrintModuleAfterOptimizations) 4621 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M); 4622 4623 if (Changed) 4624 return PreservedAnalyses::none(); 4625 4626 return PreservedAnalyses::all(); 4627 } 4628 4629 namespace { 4630 4631 struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass { 4632 CallGraphUpdater CGUpdater; 4633 static char ID; 4634 4635 OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) { 4636 initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 4637 } 4638 4639 void getAnalysisUsage(AnalysisUsage &AU) const override { 4640 CallGraphSCCPass::getAnalysisUsage(AU); 4641 } 4642 4643 bool runOnSCC(CallGraphSCC &CGSCC) override { 4644 if (!containsOpenMP(CGSCC.getCallGraph().getModule())) 4645 return false; 4646 if (DisableOpenMPOptimizations || skipSCC(CGSCC)) 4647 return false; 4648 4649 SmallVector<Function *, 16> SCC; 4650 // If there are kernels in the module, we have to run on all SCC's. 4651 for (CallGraphNode *CGN : CGSCC) { 4652 Function *Fn = CGN->getFunction(); 4653 if (!Fn || Fn->isDeclaration()) 4654 continue; 4655 SCC.push_back(Fn); 4656 } 4657 4658 if (SCC.empty()) 4659 return false; 4660 4661 Module &M = CGSCC.getCallGraph().getModule(); 4662 KernelSet Kernels = getDeviceKernels(M); 4663 4664 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 4665 CGUpdater.initialize(CG, CGSCC); 4666 4667 // Maintain a map of functions to avoid rebuilding the ORE 4668 DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap; 4669 auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & { 4670 std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F]; 4671 if (!ORE) 4672 ORE = std::make_unique<OptimizationRemarkEmitter>(F); 4673 return *ORE; 4674 }; 4675 4676 AnalysisGetter AG; 4677 SetVector<Function *> Functions(SCC.begin(), SCC.end()); 4678 BumpPtrAllocator Allocator; 4679 OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, 4680 Allocator, 4681 /*CGSCC*/ Functions, Kernels); 4682 4683 unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32; 4684 Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true, 4685 MaxFixpointIterations, OREGetter, DEBUG_TYPE); 4686 4687 OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A); 4688 bool Result = OMPOpt.run(false); 4689 4690 if (PrintModuleAfterOptimizations) 4691 LLVM_DEBUG(dbgs() << TAG << "Module after OpenMPOpt CGSCC Pass:\n" << M); 4692 4693 return Result; 4694 } 4695 4696 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 4697 }; 4698 4699 } // end anonymous namespace 4700 4701 KernelSet llvm::omp::getDeviceKernels(Module &M) { 4702 // TODO: Create a more cross-platform way of determining device kernels. 4703 NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations"); 4704 KernelSet Kernels; 4705 4706 if (!MD) 4707 return Kernels; 4708 4709 for (auto *Op : MD->operands()) { 4710 if (Op->getNumOperands() < 2) 4711 continue; 4712 MDString *KindID = dyn_cast<MDString>(Op->getOperand(1)); 4713 if (!KindID || KindID->getString() != "kernel") 4714 continue; 4715 4716 Function *KernelFn = 4717 mdconst::dyn_extract_or_null<Function>(Op->getOperand(0)); 4718 if (!KernelFn) 4719 continue; 4720 4721 ++NumOpenMPTargetRegionKernels; 4722 4723 Kernels.insert(KernelFn); 4724 } 4725 4726 return Kernels; 4727 } 4728 4729 bool llvm::omp::containsOpenMP(Module &M) { 4730 Metadata *MD = M.getModuleFlag("openmp"); 4731 if (!MD) 4732 return false; 4733 4734 return true; 4735 } 4736 4737 bool llvm::omp::isOpenMPDevice(Module &M) { 4738 Metadata *MD = M.getModuleFlag("openmp-device"); 4739 if (!MD) 4740 return false; 4741 4742 return true; 4743 } 4744 4745 char OpenMPOptCGSCCLegacyPass::ID = 0; 4746 4747 INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc", 4748 "OpenMP specific optimizations", false, false) 4749 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 4750 INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc", 4751 "OpenMP specific optimizations", false, false) 4752 4753 Pass *llvm::createOpenMPOptCGSCCLegacyPass() { 4754 return new OpenMPOptCGSCCLegacyPass(); 4755 } 4756