CGOpenMPRuntimeGPU.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. //===------ CGOpenMPRuntimeGPU.h - Interface to OpenMP GPU Runtimes ------===//
  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. // This provides a generalized class for OpenMP runtime code generation
  10. // specialized by GPU targets NVPTX and AMDGCN.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
  15. #include "CGOpenMPRuntime.h"
  16. #include "CodeGenFunction.h"
  17. #include "clang/AST/StmtOpenMP.h"
  18. namespace clang {
  19. namespace CodeGen {
  20. class CGOpenMPRuntimeGPU : public CGOpenMPRuntime {
  21. public:
  22. /// Defines the execution mode.
  23. enum ExecutionMode {
  24. /// SPMD execution mode (all threads are worker threads).
  25. EM_SPMD,
  26. /// Non-SPMD execution mode (1 master thread, others are workers).
  27. EM_NonSPMD,
  28. /// Unknown execution mode (orphaned directive).
  29. EM_Unknown,
  30. };
  31. private:
  32. /// Parallel outlined function work for workers to execute.
  33. llvm::SmallVector<llvm::Function *, 16> Work;
  34. struct EntryFunctionState {
  35. SourceLocation Loc;
  36. };
  37. ExecutionMode getExecutionMode() const;
  38. /// Get barrier to synchronize all threads in a block.
  39. void syncCTAThreads(CodeGenFunction &CGF);
  40. /// Helper for target directive initialization.
  41. void emitKernelInit(CodeGenFunction &CGF, EntryFunctionState &EST,
  42. bool IsSPMD);
  43. /// Helper for target directive finalization.
  44. void emitKernelDeinit(CodeGenFunction &CGF, EntryFunctionState &EST,
  45. bool IsSPMD);
  46. /// Helper for generic variables globalization prolog.
  47. void emitGenericVarsProlog(CodeGenFunction &CGF, SourceLocation Loc,
  48. bool WithSPMDCheck = false);
  49. /// Helper for generic variables globalization epilog.
  50. void emitGenericVarsEpilog(CodeGenFunction &CGF, bool WithSPMDCheck = false);
  51. //
  52. // Base class overrides.
  53. //
  54. /// Emit outlined function specialized for the Fork-Join
  55. /// programming model for applicable target directives on the NVPTX device.
  56. /// \param D Directive to emit.
  57. /// \param ParentName Name of the function that encloses the target region.
  58. /// \param OutlinedFn Outlined function value to be defined by this call.
  59. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  60. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  61. /// An outlined function may not be an entry if, e.g. the if clause always
  62. /// evaluates to false.
  63. void emitNonSPMDKernel(const OMPExecutableDirective &D, StringRef ParentName,
  64. llvm::Function *&OutlinedFn,
  65. llvm::Constant *&OutlinedFnID, bool IsOffloadEntry,
  66. const RegionCodeGenTy &CodeGen);
  67. /// Emit outlined function specialized for the Single Program
  68. /// Multiple Data programming model for applicable target directives on the
  69. /// NVPTX device.
  70. /// \param D Directive to emit.
  71. /// \param ParentName Name of the function that encloses the target region.
  72. /// \param OutlinedFn Outlined function value to be defined by this call.
  73. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  74. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  75. /// \param CodeGen Object containing the target statements.
  76. /// An outlined function may not be an entry if, e.g. the if clause always
  77. /// evaluates to false.
  78. void emitSPMDKernel(const OMPExecutableDirective &D, StringRef ParentName,
  79. llvm::Function *&OutlinedFn,
  80. llvm::Constant *&OutlinedFnID, bool IsOffloadEntry,
  81. const RegionCodeGenTy &CodeGen);
  82. /// Emit outlined function for 'target' directive on the NVPTX
  83. /// device.
  84. /// \param D Directive to emit.
  85. /// \param ParentName Name of the function that encloses the target region.
  86. /// \param OutlinedFn Outlined function value to be defined by this call.
  87. /// \param OutlinedFnID Outlined function ID value to be defined by this call.
  88. /// \param IsOffloadEntry True if the outlined function is an offload entry.
  89. /// An outlined function may not be an entry if, e.g. the if clause always
  90. /// evaluates to false.
  91. void emitTargetOutlinedFunction(const OMPExecutableDirective &D,
  92. StringRef ParentName,
  93. llvm::Function *&OutlinedFn,
  94. llvm::Constant *&OutlinedFnID,
  95. bool IsOffloadEntry,
  96. const RegionCodeGenTy &CodeGen) override;
  97. /// Emits code for parallel or serial call of the \a OutlinedFn with
  98. /// variables captured in a record which address is stored in \a
  99. /// CapturedStruct.
  100. /// This call is for the Non-SPMD Execution Mode.
  101. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  102. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  103. /// \param CapturedVars A pointer to the record with the references to
  104. /// variables used in \a OutlinedFn function.
  105. /// \param IfCond Condition in the associated 'if' clause, if it was
  106. /// specified, nullptr otherwise.
  107. void emitNonSPMDParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  108. llvm::Value *OutlinedFn,
  109. ArrayRef<llvm::Value *> CapturedVars,
  110. const Expr *IfCond);
  111. /// Emits code for parallel or serial call of the \a OutlinedFn with
  112. /// variables captured in a record which address is stored in \a
  113. /// CapturedStruct.
  114. /// This call is for a parallel directive within an SPMD target directive.
  115. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  116. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  117. /// \param CapturedVars A pointer to the record with the references to
  118. /// variables used in \a OutlinedFn function.
  119. /// \param IfCond Condition in the associated 'if' clause, if it was
  120. /// specified, nullptr otherwise.
  121. ///
  122. void emitSPMDParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  123. llvm::Function *OutlinedFn,
  124. ArrayRef<llvm::Value *> CapturedVars,
  125. const Expr *IfCond);
  126. protected:
  127. /// Get the function name of an outlined region.
  128. // The name can be customized depending on the target.
  129. //
  130. StringRef getOutlinedHelperName() const override {
  131. return "__omp_outlined__";
  132. }
  133. /// Check if the default location must be constant.
  134. /// Constant for NVPTX for better optimization.
  135. bool isDefaultLocationConstant() const override { return true; }
  136. public:
  137. explicit CGOpenMPRuntimeGPU(CodeGenModule &CGM);
  138. void clear() override;
  139. bool isTargetCodegen() const override { return true; };
  140. /// Declare generalized virtual functions which need to be defined
  141. /// by all specializations of OpenMPGPURuntime Targets like AMDGCN
  142. /// and NVPTX.
  143. /// Get the GPU warp size.
  144. llvm::Value *getGPUWarpSize(CodeGenFunction &CGF);
  145. /// Get the id of the current thread on the GPU.
  146. llvm::Value *getGPUThreadID(CodeGenFunction &CGF);
  147. /// Get the maximum number of threads in a block of the GPU.
  148. llvm::Value *getGPUNumThreads(CodeGenFunction &CGF);
  149. /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
  150. /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
  151. void emitProcBindClause(CodeGenFunction &CGF,
  152. llvm::omp::ProcBindKind ProcBind,
  153. SourceLocation Loc) override;
  154. /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
  155. /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
  156. /// clause.
  157. /// \param NumThreads An integer value of threads.
  158. void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads,
  159. SourceLocation Loc) override;
  160. /// This function ought to emit, in the general case, a call to
  161. // the openmp runtime kmpc_push_num_teams. In NVPTX backend it is not needed
  162. // as these numbers are obtained through the PTX grid and block configuration.
  163. /// \param NumTeams An integer expression of teams.
  164. /// \param ThreadLimit An integer expression of threads.
  165. void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
  166. const Expr *ThreadLimit, SourceLocation Loc) override;
  167. /// Emits inlined function for the specified OpenMP parallel
  168. // directive.
  169. /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
  170. /// kmp_int32 BoundID, struct context_vars*).
  171. /// \param D OpenMP directive.
  172. /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
  173. /// \param InnermostKind Kind of innermost directive (for simple directives it
  174. /// is a directive itself, for combined - its innermost directive).
  175. /// \param CodeGen Code generation sequence for the \a D directive.
  176. llvm::Function *
  177. emitParallelOutlinedFunction(const OMPExecutableDirective &D,
  178. const VarDecl *ThreadIDVar,
  179. OpenMPDirectiveKind InnermostKind,
  180. const RegionCodeGenTy &CodeGen) override;
  181. /// Emits inlined function for the specified OpenMP teams
  182. // directive.
  183. /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
  184. /// kmp_int32 BoundID, struct context_vars*).
  185. /// \param D OpenMP directive.
  186. /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
  187. /// \param InnermostKind Kind of innermost directive (for simple directives it
  188. /// is a directive itself, for combined - its innermost directive).
  189. /// \param CodeGen Code generation sequence for the \a D directive.
  190. llvm::Function *
  191. emitTeamsOutlinedFunction(const OMPExecutableDirective &D,
  192. const VarDecl *ThreadIDVar,
  193. OpenMPDirectiveKind InnermostKind,
  194. const RegionCodeGenTy &CodeGen) override;
  195. /// Emits code for teams call of the \a OutlinedFn with
  196. /// variables captured in a record which address is stored in \a
  197. /// CapturedStruct.
  198. /// \param OutlinedFn Outlined function to be run by team masters. Type of
  199. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  200. /// \param CapturedVars A pointer to the record with the references to
  201. /// variables used in \a OutlinedFn function.
  202. ///
  203. void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,
  204. SourceLocation Loc, llvm::Function *OutlinedFn,
  205. ArrayRef<llvm::Value *> CapturedVars) override;
  206. /// Emits code for parallel or serial call of the \a OutlinedFn with
  207. /// variables captured in a record which address is stored in \a
  208. /// CapturedStruct.
  209. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
  210. /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
  211. /// \param CapturedVars A pointer to the record with the references to
  212. /// variables used in \a OutlinedFn function.
  213. /// \param IfCond Condition in the associated 'if' clause, if it was
  214. /// specified, nullptr otherwise.
  215. /// \param NumThreads The value corresponding to the num_threads clause, if
  216. /// any,
  217. /// or nullptr.
  218. void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
  219. llvm::Function *OutlinedFn,
  220. ArrayRef<llvm::Value *> CapturedVars,
  221. const Expr *IfCond, llvm::Value *NumThreads) override;
  222. /// Emit an implicit/explicit barrier for OpenMP threads.
  223. /// \param Kind Directive for which this implicit barrier call must be
  224. /// generated. Must be OMPD_barrier for explicit barrier generation.
  225. /// \param EmitChecks true if need to emit checks for cancellation barriers.
  226. /// \param ForceSimpleCall true simple barrier call must be emitted, false if
  227. /// runtime class decides which one to emit (simple or with cancellation
  228. /// checks).
  229. ///
  230. void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
  231. OpenMPDirectiveKind Kind, bool EmitChecks = true,
  232. bool ForceSimpleCall = false) override;
  233. /// Emits a critical region.
  234. /// \param CriticalName Name of the critical region.
  235. /// \param CriticalOpGen Generator for the statement associated with the given
  236. /// critical region.
  237. /// \param Hint Value of the 'hint' clause (optional).
  238. void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
  239. const RegionCodeGenTy &CriticalOpGen,
  240. SourceLocation Loc,
  241. const Expr *Hint = nullptr) override;
  242. /// Emit a code for reduction clause.
  243. ///
  244. /// \param Privates List of private copies for original reduction arguments.
  245. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
  246. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
  247. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
  248. /// or 'operator binop(LHS, RHS)'.
  249. /// \param Options List of options for reduction codegen:
  250. /// WithNowait true if parent directive has also nowait clause, false
  251. /// otherwise.
  252. /// SimpleReduction Emit reduction operation only. Used for omp simd
  253. /// directive on the host.
  254. /// ReductionKind The kind of reduction to perform.
  255. void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
  256. ArrayRef<const Expr *> Privates,
  257. ArrayRef<const Expr *> LHSExprs,
  258. ArrayRef<const Expr *> RHSExprs,
  259. ArrayRef<const Expr *> ReductionOps,
  260. ReductionOptionsTy Options) override;
  261. /// Returns specified OpenMP runtime function for the current OpenMP
  262. /// implementation. Specialized for the NVPTX device.
  263. /// \param Function OpenMP runtime function.
  264. /// \return Specified function.
  265. llvm::FunctionCallee createNVPTXRuntimeFunction(unsigned Function);
  266. /// Translates the native parameter of outlined function if this is required
  267. /// for target.
  268. /// \param FD Field decl from captured record for the parameter.
  269. /// \param NativeParam Parameter itself.
  270. const VarDecl *translateParameter(const FieldDecl *FD,
  271. const VarDecl *NativeParam) const override;
  272. /// Gets the address of the native argument basing on the address of the
  273. /// target-specific parameter.
  274. /// \param NativeParam Parameter itself.
  275. /// \param TargetParam Corresponding target-specific parameter.
  276. Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,
  277. const VarDecl *TargetParam) const override;
  278. /// Emits call of the outlined function with the provided arguments,
  279. /// translating these arguments to correct target-specific arguments.
  280. void emitOutlinedFunctionCall(
  281. CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
  282. ArrayRef<llvm::Value *> Args = std::nullopt) const override;
  283. /// Emits OpenMP-specific function prolog.
  284. /// Required for device constructs.
  285. void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) override;
  286. /// Gets the OpenMP-specific address of the local variable.
  287. Address getAddressOfLocalVariable(CodeGenFunction &CGF,
  288. const VarDecl *VD) override;
  289. /// Target codegen is specialized based on two data-sharing modes: CUDA, in
  290. /// which the local variables are actually global threadlocal, and Generic, in
  291. /// which the local variables are placed in global memory if they may escape
  292. /// their declaration context.
  293. enum DataSharingMode {
  294. /// CUDA data sharing mode.
  295. CUDA,
  296. /// Generic data-sharing mode.
  297. Generic,
  298. };
  299. /// Cleans up references to the objects in finished function.
  300. ///
  301. void functionFinished(CodeGenFunction &CGF) override;
  302. /// Choose a default value for the dist_schedule clause.
  303. void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF,
  304. const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind,
  305. llvm::Value *&Chunk) const override;
  306. /// Choose a default value for the schedule clause.
  307. void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
  308. const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
  309. const Expr *&ChunkExpr) const override;
  310. /// Adjust some parameters for the target-based directives, like addresses of
  311. /// the variables captured by reference in lambdas.
  312. void adjustTargetSpecificDataForLambdas(
  313. CodeGenFunction &CGF, const OMPExecutableDirective &D) const override;
  314. /// Perform check on requires decl to ensure that target architecture
  315. /// supports unified addressing
  316. void processRequiresDirective(const OMPRequiresDecl *D) override;
  317. /// Checks if the variable has associated OMPAllocateDeclAttr attribute with
  318. /// the predefined allocator and translates it into the corresponding address
  319. /// space.
  320. bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS) override;
  321. private:
  322. /// Track the execution mode when codegening directives within a target
  323. /// region. The appropriate mode (SPMD/NON-SPMD) is set on entry to the
  324. /// target region and used by containing directives such as 'parallel'
  325. /// to emit optimized code.
  326. ExecutionMode CurrentExecutionMode = EM_Unknown;
  327. /// true if currently emitting code for target/teams/distribute region, false
  328. /// - otherwise.
  329. bool IsInTTDRegion = false;
  330. /// Map between an outlined function and its wrapper.
  331. llvm::DenseMap<llvm::Function *, llvm::Function *> WrapperFunctionsMap;
  332. /// Emit function which wraps the outline parallel region
  333. /// and controls the parameters which are passed to this function.
  334. /// The wrapper ensures that the outlined function is called
  335. /// with the correct arguments when data is shared.
  336. llvm::Function *createParallelDataSharingWrapper(
  337. llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D);
  338. /// The data for the single globalized variable.
  339. struct MappedVarData {
  340. /// Corresponding field in the global record.
  341. llvm::Value *GlobalizedVal = nullptr;
  342. /// Corresponding address.
  343. Address PrivateAddr = Address::invalid();
  344. };
  345. /// The map of local variables to their addresses in the global memory.
  346. using DeclToAddrMapTy = llvm::MapVector<const Decl *, MappedVarData>;
  347. /// Set of the parameters passed by value escaping OpenMP context.
  348. using EscapedParamsTy = llvm::SmallPtrSet<const Decl *, 4>;
  349. struct FunctionData {
  350. DeclToAddrMapTy LocalVarData;
  351. EscapedParamsTy EscapedParameters;
  352. llvm::SmallVector<const ValueDecl*, 4> EscapedVariableLengthDecls;
  353. llvm::SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4>
  354. EscapedVariableLengthDeclsAddrs;
  355. std::unique_ptr<CodeGenFunction::OMPMapVars> MappedParams;
  356. };
  357. /// Maps the function to the list of the globalized variables with their
  358. /// addresses.
  359. llvm::SmallDenseMap<llvm::Function *, FunctionData> FunctionGlobalizedDecls;
  360. llvm::GlobalVariable *KernelTeamsReductionPtr = nullptr;
  361. /// List of the records with the list of fields for the reductions across the
  362. /// teams. Used to build the intermediate buffer for the fast teams
  363. /// reductions.
  364. /// All the records are gathered into a union `union.type` is created.
  365. llvm::SmallVector<const RecordDecl *, 4> TeamsReductions;
  366. /// Pair of the Non-SPMD team and all reductions variables in this team
  367. /// region.
  368. std::pair<const Decl *, llvm::SmallVector<const ValueDecl *, 4>>
  369. TeamAndReductions;
  370. };
  371. } // CodeGen namespace.
  372. } // clang namespace.
  373. #endif // LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H