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