[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / CodeGen / CGOpenMPRuntimeGPU.h
blobc4559b3226bcf86496634a04e52b7b393c1529ed
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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
15 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H
17 #include "CGOpenMPRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/StmtOpenMP.h"
21 namespace clang {
22 namespace CodeGen {
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,
35 private:
36 /// Parallel outlined function work for workers to execute.
37 llvm::SmallVector<llvm::Function *, 16> Work;
39 struct EntryFunctionState {
40 SourceLocation Loc;
43 ExecutionMode getExecutionMode() const;
45 /// Get barrier to synchronize all threads in a block.
46 void syncCTAThreads(CodeGenFunction &CGF);
48 /// Helper for target directive initialization.
49 void emitKernelInit(CodeGenFunction &CGF, EntryFunctionState &EST,
50 bool IsSPMD);
52 /// Helper for target directive finalization.
53 void emitKernelDeinit(CodeGenFunction &CGF, EntryFunctionState &EST,
54 bool IsSPMD);
56 /// Helper for generic variables globalization prolog.
57 void emitGenericVarsProlog(CodeGenFunction &CGF, SourceLocation Loc,
58 bool WithSPMDCheck = false);
60 /// Helper for generic variables globalization epilog.
61 void emitGenericVarsEpilog(CodeGenFunction &CGF, bool WithSPMDCheck = false);
64 // Base class overrides.
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);
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);
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;
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; }
118 public:
119 explicit CGOpenMPRuntimeGPU(CodeGenModule &CGM);
120 void clear() override;
122 bool isTargetCodegen() const override { return true; };
124 /// Declare generalized virtual functions which need to be defined
125 /// by all specializations of OpenMPGPURuntime Targets like AMDGCN
126 /// and NVPTX.
128 /// Get the GPU warp size.
129 llvm::Value *getGPUWarpSize(CodeGenFunction &CGF);
131 /// Get the id of the current thread on the GPU.
132 llvm::Value *getGPUThreadID(CodeGenFunction &CGF);
134 /// Get the maximum number of threads in a block of the GPU.
135 llvm::Value *getGPUNumThreads(CodeGenFunction &CGF);
137 /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32
138 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause.
139 void emitProcBindClause(CodeGenFunction &CGF,
140 llvm::omp::ProcBindKind ProcBind,
141 SourceLocation Loc) override;
143 /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32
144 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads'
145 /// clause.
146 /// \param NumThreads An integer value of threads.
147 void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads,
148 SourceLocation Loc) override;
150 /// This function ought to emit, in the general case, a call to
151 // the openmp runtime kmpc_push_num_teams. In NVPTX backend it is not needed
152 // as these numbers are obtained through the PTX grid and block configuration.
153 /// \param NumTeams An integer expression of teams.
154 /// \param ThreadLimit An integer expression of threads.
155 void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams,
156 const Expr *ThreadLimit, SourceLocation Loc) override;
158 /// Emits inlined function for the specified OpenMP parallel
159 // directive.
160 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
161 /// kmp_int32 BoundID, struct context_vars*).
162 /// \param CGF Reference to current CodeGenFunction.
163 /// \param D OpenMP directive.
164 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
165 /// \param InnermostKind Kind of innermost directive (for simple directives it
166 /// is a directive itself, for combined - its innermost directive).
167 /// \param CodeGen Code generation sequence for the \a D directive.
168 llvm::Function *emitParallelOutlinedFunction(
169 CodeGenFunction &CGF, const OMPExecutableDirective &D,
170 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
171 const RegionCodeGenTy &CodeGen) override;
173 /// Emits inlined function for the specified OpenMP teams
174 // directive.
175 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID,
176 /// kmp_int32 BoundID, struct context_vars*).
177 /// \param CGF Reference to current CodeGenFunction.
178 /// \param D OpenMP directive.
179 /// \param ThreadIDVar Variable for thread id in the current OpenMP region.
180 /// \param InnermostKind Kind of innermost directive (for simple directives it
181 /// is a directive itself, for combined - its innermost directive).
182 /// \param CodeGen Code generation sequence for the \a D directive.
183 llvm::Function *emitTeamsOutlinedFunction(
184 CodeGenFunction &CGF, const OMPExecutableDirective &D,
185 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
186 const RegionCodeGenTy &CodeGen) override;
188 /// Emits code for teams call of the \a OutlinedFn with
189 /// variables captured in a record which address is stored in \a
190 /// CapturedStruct.
191 /// \param OutlinedFn Outlined function to be run by team masters. Type of
192 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
193 /// \param CapturedVars A pointer to the record with the references to
194 /// variables used in \a OutlinedFn function.
196 void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D,
197 SourceLocation Loc, llvm::Function *OutlinedFn,
198 ArrayRef<llvm::Value *> CapturedVars) override;
200 /// Emits code for parallel or serial call of the \a OutlinedFn with
201 /// variables captured in a record which address is stored in \a
202 /// CapturedStruct.
203 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of
204 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*).
205 /// \param CapturedVars A pointer to the record with the references to
206 /// variables used in \a OutlinedFn function.
207 /// \param IfCond Condition in the associated 'if' clause, if it was
208 /// specified, nullptr otherwise.
209 /// \param NumThreads The value corresponding to the num_threads clause, if
210 /// any,
211 /// or nullptr.
212 void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
213 llvm::Function *OutlinedFn,
214 ArrayRef<llvm::Value *> CapturedVars,
215 const Expr *IfCond, llvm::Value *NumThreads) override;
217 /// Emit an implicit/explicit barrier for OpenMP threads.
218 /// \param Kind Directive for which this implicit barrier call must be
219 /// generated. Must be OMPD_barrier for explicit barrier generation.
220 /// \param EmitChecks true if need to emit checks for cancellation barriers.
221 /// \param ForceSimpleCall true simple barrier call must be emitted, false if
222 /// runtime class decides which one to emit (simple or with cancellation
223 /// checks).
225 void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
226 OpenMPDirectiveKind Kind, bool EmitChecks = true,
227 bool ForceSimpleCall = false) override;
229 /// Emits a critical region.
230 /// \param CriticalName Name of the critical region.
231 /// \param CriticalOpGen Generator for the statement associated with the given
232 /// critical region.
233 /// \param Hint Value of the 'hint' clause (optional).
234 void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName,
235 const RegionCodeGenTy &CriticalOpGen,
236 SourceLocation Loc,
237 const Expr *Hint = nullptr) override;
239 /// Emit a code for reduction clause.
241 /// \param Privates List of private copies for original reduction arguments.
242 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations.
243 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations.
244 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS'
245 /// or 'operator binop(LHS, RHS)'.
246 /// \param Options List of options for reduction codegen:
247 /// WithNowait true if parent directive has also nowait clause, false
248 /// otherwise.
249 /// SimpleReduction Emit reduction operation only. Used for omp simd
250 /// directive on the host.
251 /// ReductionKind The kind of reduction to perform.
252 void emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
253 ArrayRef<const Expr *> Privates,
254 ArrayRef<const Expr *> LHSExprs,
255 ArrayRef<const Expr *> RHSExprs,
256 ArrayRef<const Expr *> ReductionOps,
257 ReductionOptionsTy Options) override;
259 /// Translates the native parameter of outlined function if this is required
260 /// for target.
261 /// \param FD Field decl from captured record for the parameter.
262 /// \param NativeParam Parameter itself.
263 const VarDecl *translateParameter(const FieldDecl *FD,
264 const VarDecl *NativeParam) const override;
266 /// Gets the address of the native argument basing on the address of the
267 /// target-specific parameter.
268 /// \param NativeParam Parameter itself.
269 /// \param TargetParam Corresponding target-specific parameter.
270 Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam,
271 const VarDecl *TargetParam) const override;
273 /// Emits call of the outlined function with the provided arguments,
274 /// translating these arguments to correct target-specific arguments.
275 void emitOutlinedFunctionCall(
276 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
277 ArrayRef<llvm::Value *> Args = std::nullopt) const override;
279 /// Emits OpenMP-specific function prolog.
280 /// Required for device constructs.
281 void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D) override;
283 /// Gets the OpenMP-specific address of the local variable.
284 Address getAddressOfLocalVariable(CodeGenFunction &CGF,
285 const VarDecl *VD) override;
287 /// Target codegen is specialized based on two data-sharing modes: CUDA, in
288 /// which the local variables are actually global threadlocal, and Generic, in
289 /// which the local variables are placed in global memory if they may escape
290 /// their declaration context.
291 enum DataSharingMode {
292 /// CUDA data sharing mode.
293 CUDA,
294 /// Generic data-sharing mode.
295 Generic,
298 /// Cleans up references to the objects in finished function.
300 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;
307 /// Choose a default value for the schedule clause.
308 void getDefaultScheduleAndChunk(CodeGenFunction &CGF,
309 const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind,
310 const Expr *&ChunkExpr) const override;
312 /// Adjust some parameters for the target-based directives, like addresses of
313 /// the variables captured by reference in lambdas.
314 void adjustTargetSpecificDataForLambdas(
315 CodeGenFunction &CGF, const OMPExecutableDirective &D) const override;
317 /// Perform check on requires decl to ensure that target architecture
318 /// supports unified addressing
319 void processRequiresDirective(const OMPRequiresDecl *D) override;
321 /// Checks if the variable has associated OMPAllocateDeclAttr attribute with
322 /// the predefined allocator and translates it into the corresponding address
323 /// space.
324 bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS) override;
326 private:
327 /// Track the execution mode when codegening directives within a target
328 /// region. The appropriate mode (SPMD/NON-SPMD) is set on entry to the
329 /// target region and used by containing directives such as 'parallel'
330 /// to emit optimized code.
331 ExecutionMode CurrentExecutionMode = EM_Unknown;
333 /// true if currently emitting code for target/teams/distribute region, false
334 /// - otherwise.
335 bool IsInTTDRegion = false;
337 /// Map between an outlined function and its wrapper.
338 llvm::DenseMap<llvm::Function *, llvm::Function *> WrapperFunctionsMap;
340 /// Emit function which wraps the outline parallel region
341 /// and controls the parameters which are passed to this function.
342 /// The wrapper ensures that the outlined function is called
343 /// with the correct arguments when data is shared.
344 llvm::Function *createParallelDataSharingWrapper(
345 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D);
347 /// The data for the single globalized variable.
348 struct MappedVarData {
349 /// Corresponding field in the global record.
350 llvm::Value *GlobalizedVal = nullptr;
351 /// Corresponding address.
352 Address PrivateAddr = Address::invalid();
354 /// The map of local variables to their addresses in the global memory.
355 using DeclToAddrMapTy = llvm::MapVector<const Decl *, MappedVarData>;
356 /// Set of the parameters passed by value escaping OpenMP context.
357 using EscapedParamsTy = llvm::SmallPtrSet<const Decl *, 4>;
358 struct FunctionData {
359 DeclToAddrMapTy LocalVarData;
360 EscapedParamsTy EscapedParameters;
361 llvm::SmallVector<const ValueDecl*, 4> EscapedVariableLengthDecls;
362 llvm::SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4>
363 EscapedVariableLengthDeclsAddrs;
364 std::unique_ptr<CodeGenFunction::OMPMapVars> MappedParams;
366 /// Maps the function to the list of the globalized variables with their
367 /// addresses.
368 llvm::SmallDenseMap<llvm::Function *, FunctionData> FunctionGlobalizedDecls;
369 llvm::GlobalVariable *KernelTeamsReductionPtr = nullptr;
370 /// List of the records with the list of fields for the reductions across the
371 /// teams. Used to build the intermediate buffer for the fast teams
372 /// reductions.
373 /// All the records are gathered into a union `union.type` is created.
374 llvm::SmallVector<const RecordDecl *, 4> TeamsReductions;
375 /// Pair of the Non-SPMD team and all reductions variables in this team
376 /// region.
377 std::pair<const Decl *, llvm::SmallVector<const ValueDecl *, 4>>
378 TeamAndReductions;
381 } // CodeGen namespace.
382 } // clang namespace.
384 #endif // LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIMEGPU_H