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