blob: 21911c96f36ad89f56a99574e1b97cf8206ce9bb [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation specialized to NVPTX
11// targets.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000016#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000017#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000018#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000019#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000020#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000021#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000022
23using namespace clang;
24using namespace CodeGen;
25
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000026namespace {
27enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000028 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000029 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000030 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000031 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000032 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000033 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000034 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000035 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000036 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
37 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000039 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000040 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000041 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000043 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000044 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000046 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
47 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
48 /// global_tid);
49 OMPRTL_NVPTX__kmpc_serialized_parallel,
50 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
51 /// global_tid);
52 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000053 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000054 /// int16_t lane_offset, int16_t warp_size);
55 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000057 /// int16_t lane_offset, int16_t warp_size);
58 OMPRTL_NVPTX__kmpc_shuffle_int64,
Alexey Bataev8e009032019-01-04 17:25:09 +000059 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000060 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
61 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
62 /// lane_offset, int16_t shortCircuit),
63 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
Alexey Bataev8e009032019-01-04 17:25:09 +000064 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2,
Alexey Bataeva1166022018-11-27 21:24:54 +000065 /// Call to __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
66 /// global_tid, kmp_critical_name *lck)
67 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple,
68 /// Call to __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc,
69 /// kmp_int32 global_tid, kmp_critical_name *lck)
70 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000072 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000073 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000074 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000075 /// Call to void __kmpc_data_sharing_init_stack_spmd();
76 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000077 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000078 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000079 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000081 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000082 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// size_t n_args);
84 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000089 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
90 /// global_tid);
91 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000092 /// Call to int8_t __kmpc_is_spmd_exec_mode();
93 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +000094 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
95 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +000096 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +000097 /// Call to void __kmpc_restore_team_static_memory(int16_t
98 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +000099 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000100 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000101 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000102 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
103 /// global_tid);
104 OMPRTL__kmpc_barrier_simple_spmd,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000105};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106
107/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
108class NVPTXActionTy final : public PrePostActionTy {
Alexey Bataev9ff80832018-04-16 20:16:21 +0000109 llvm::Value *EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000110 ArrayRef<llvm::Value *> EnterArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000111 llvm::Value *ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000112 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000113 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000114 llvm::BasicBlock *ContBlock = nullptr;
115
116public:
117 NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
118 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
119 bool Conditional = false)
120 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
121 ExitArgs(ExitArgs), Conditional(Conditional) {}
122 void Enter(CodeGenFunction &CGF) override {
123 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
124 if (Conditional) {
125 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
126 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
127 ContBlock = CGF.createBasicBlock("omp_if.end");
128 // Generate the branch (If-stmt)
129 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
130 CGF.EmitBlock(ThenBlock);
131 }
132 }
133 void Done(CodeGenFunction &CGF) {
134 // Emit the rest of blocks/branches
135 CGF.EmitBranch(ContBlock);
136 CGF.EmitBlock(ContBlock, true);
137 }
138 void Exit(CodeGenFunction &CGF) override {
139 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
140 }
141};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000142
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000143/// A class to track the execution mode when codegening directives within
144/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
145/// to the target region and used by containing directives such as 'parallel'
146/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000147class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000149 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
150 CGOpenMPRuntimeNVPTX::EM_Unknown;
151 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
152 bool SavedRuntimeMode = false;
153 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000154
155public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000156 /// Constructor for Non-SPMD mode.
157 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
158 : ExecMode(ExecMode) {
159 SavedExecMode = ExecMode;
160 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000161 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000162 /// Constructor for SPMD mode.
163 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
164 bool &RuntimeMode, bool FullRuntimeMode)
165 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
166 SavedExecMode = ExecMode;
167 SavedRuntimeMode = RuntimeMode;
168 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
169 RuntimeMode = FullRuntimeMode;
170 }
171 ~ExecutionRuntimeModesRAII() {
172 ExecMode = SavedExecMode;
173 if (RuntimeMode)
174 *RuntimeMode = SavedRuntimeMode;
175 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000176};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000177
178/// GPU Configuration: This information can be derived from cuda registers,
179/// however, providing compile time constants helps generate more efficient
180/// code. For all practical purposes this is fine because the configuration
181/// is the same for all known NVPTX architectures.
182enum MachineConfiguration : unsigned {
183 WarpSize = 32,
184 /// Number of bits required to represent a lane identifier, which is
185 /// computed as log_2(WarpSize).
186 LaneIDBits = 5,
187 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000188
189 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000190 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000191
192 /// Maximal size of the shared memory buffer.
193 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000194};
195
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000196static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
197 RefExpr = RefExpr->IgnoreParens();
198 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
199 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
200 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
201 Base = TempASE->getBase()->IgnoreParenImpCasts();
202 RefExpr = Base;
203 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
204 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
205 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
206 Base = TempOASE->getBase()->IgnoreParenImpCasts();
207 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
208 Base = TempASE->getBase()->IgnoreParenImpCasts();
209 RefExpr = Base;
210 }
211 RefExpr = RefExpr->IgnoreParenImpCasts();
212 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
213 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
214 const auto *ME = cast<MemberExpr>(RefExpr);
215 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
216}
217
Alexey Bataev2adecff2018-09-21 14:22:53 +0000218typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
219static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
220 return P1.first > P2.first;
221}
222
223static RecordDecl *buildRecordForGlobalizedVars(
224 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000225 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000226 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
227 &MappedDeclsFields) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000228 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000229 return nullptr;
230 SmallVector<VarsDataTy, 4> GlobalizedVars;
231 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000232 GlobalizedVars.emplace_back(
233 CharUnits::fromQuantity(std::max(
234 C.getDeclAlign(D).getQuantity(),
235 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
236 D);
237 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000238 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
239 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
240 stable_sort_comparator);
241 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000242 // /* globalized vars */[WarSize] align (max(decl_align,
243 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000244 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000245 // };
246 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
247 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000248 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
249 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 for (const auto &Pair : GlobalizedVars) {
251 const ValueDecl *VD = Pair.second;
252 QualType Type = VD->getType();
253 if (Type->isLValueReferenceType())
254 Type = C.getPointerType(Type.getNonReferenceType());
255 else
256 Type = Type.getNonReferenceType();
257 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000258 FieldDecl *Field;
259 if (SingleEscaped.count(VD)) {
260 Field = FieldDecl::Create(
261 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
262 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
263 /*BW=*/nullptr, /*Mutable=*/false,
264 /*InitStyle=*/ICIS_NoInit);
265 Field->setAccess(AS_public);
266 if (VD->hasAttrs()) {
267 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
268 E(VD->getAttrs().end());
269 I != E; ++I)
270 Field->addAttr(*I);
271 }
272 } else {
273 llvm::APInt ArraySize(32, WarpSize);
274 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
275 Field = FieldDecl::Create(
276 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
277 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
278 /*BW=*/nullptr, /*Mutable=*/false,
279 /*InitStyle=*/ICIS_NoInit);
280 Field->setAccess(AS_public);
281 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
282 static_cast<CharUnits::QuantityType>(
283 GlobalMemoryAlignment)));
284 Field->addAttr(AlignedAttr::CreateImplicit(
285 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
286 IntegerLiteral::Create(C, Align,
287 C.getIntTypeForBitwidth(32, /*Signed=*/0),
288 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000289 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000290 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000291 MappedDeclsFields.try_emplace(VD, Field);
292 }
293 GlobalizedRD->completeDefinition();
294 return GlobalizedRD;
295}
296
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000297/// Get the list of variables that can escape their declaration context.
298class CheckVarsEscapingDeclContext final
299 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
300 CodeGenFunction &CGF;
301 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000302 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000303 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000304 RecordDecl *GlobalizedRD = nullptr;
305 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000306 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000307 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000308
309 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000310 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000311 if (!isa<VarDecl>(VD) ||
312 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000313 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000314 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataevc99042b2018-03-15 18:10:54 +0000315 // Variables captured by value must be globalized.
316 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000317 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000318 // Check if need to capture the variable that was already captured by
319 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000320 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000321 if (!FD->hasAttrs())
322 return;
323 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
324 if (!Attr)
325 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000326 if (((Attr->getCaptureKind() != OMPC_map) &&
327 !isOpenMPPrivate(
328 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
329 ((Attr->getCaptureKind() == OMPC_map) &&
330 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000331 return;
332 }
333 if (!FD->getType()->isReferenceType()) {
334 assert(!VD->getType()->isVariablyModifiedType() &&
335 "Parameter captured by value with variably modified type");
336 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000337 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000338 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000339 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000340 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000341 }
342 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000343 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000344 VD->getType()->isReferenceType())
345 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000346 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000347 if (VD->getType()->isVariablyModifiedType())
348 EscapedVariableLengthDecls.insert(VD);
349 else
350 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000351 }
352
353 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000354 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000355 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000356 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
357 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
358 const bool SavedAllEscaped = AllEscaped;
359 AllEscaped = VD->getType()->isLValueReferenceType();
360 Visit(VarD->getInit());
361 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000362 }
363 }
364 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000365 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
366 ArrayRef<OMPClause *> Clauses,
367 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 if (!S)
369 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000370 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000371 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
372 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000373 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
374 if (IsCombinedParallelRegion) {
375 // Check if the variable is privatized in the combined construct and
376 // those private copies must be shared in the inner parallel
377 // directive.
378 IsForCombinedParallelRegion = false;
379 for (const OMPClause *C : Clauses) {
380 if (!isOpenMPPrivate(C->getClauseKind()) ||
381 C->getClauseKind() == OMPC_reduction ||
382 C->getClauseKind() == OMPC_linear ||
383 C->getClauseKind() == OMPC_private)
384 continue;
385 ArrayRef<const Expr *> Vars;
386 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
387 Vars = PC->getVarRefs();
388 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
389 Vars = PC->getVarRefs();
390 else
391 llvm_unreachable("Unexpected clause.");
392 for (const auto *E : Vars) {
393 const Decl *D =
394 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
395 if (D == VD->getCanonicalDecl()) {
396 IsForCombinedParallelRegion = true;
397 break;
398 }
399 }
400 if (IsForCombinedParallelRegion)
401 break;
402 }
403 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000404 markAsEscaped(VD);
405 if (isa<OMPCapturedExprDecl>(VD))
406 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000407 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000408 }
409 }
410 }
411
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000412 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000413 assert(!GlobalizedRD &&
414 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000415 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000416 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000417 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
418 else
419 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000420 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000421 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000422 MappedDeclsFields);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000423 }
424
425public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000426 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
427 ArrayRef<const ValueDecl *> TeamsReductions)
428 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
429 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000430 virtual ~CheckVarsEscapingDeclContext() = default;
431 void VisitDeclStmt(const DeclStmt *S) {
432 if (!S)
433 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000434 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000435 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
436 VisitValueDecl(VD);
437 }
438 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
439 if (!D)
440 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000441 if (!D->hasAssociatedStmt())
442 return;
443 if (const auto *S =
444 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
445 // Do not analyze directives that do not actually require capturing,
446 // like `omp for` or `omp simd` directives.
447 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
448 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
449 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
450 VisitStmt(S->getCapturedStmt());
451 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000452 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000453 VisitOpenMPCapturedStmt(
454 S, D->clauses(),
455 CaptureRegions.back() == OMPD_parallel &&
456 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000457 }
458 }
459 void VisitCapturedStmt(const CapturedStmt *S) {
460 if (!S)
461 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000462 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
464 const ValueDecl *VD = C.getCapturedVar();
465 markAsEscaped(VD);
466 if (isa<OMPCapturedExprDecl>(VD))
467 VisitValueDecl(VD);
468 }
469 }
470 }
471 void VisitLambdaExpr(const LambdaExpr *E) {
472 if (!E)
473 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000474 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000475 if (C.capturesVariable()) {
476 if (C.getCaptureKind() == LCK_ByRef) {
477 const ValueDecl *VD = C.getCapturedVar();
478 markAsEscaped(VD);
479 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
480 VisitValueDecl(VD);
481 }
482 }
483 }
484 }
485 void VisitBlockExpr(const BlockExpr *E) {
486 if (!E)
487 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000488 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000489 if (C.isByRef()) {
490 const VarDecl *VD = C.getVariable();
491 markAsEscaped(VD);
492 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
493 VisitValueDecl(VD);
494 }
495 }
496 }
497 void VisitCallExpr(const CallExpr *E) {
498 if (!E)
499 return;
500 for (const Expr *Arg : E->arguments()) {
501 if (!Arg)
502 continue;
503 if (Arg->isLValue()) {
504 const bool SavedAllEscaped = AllEscaped;
505 AllEscaped = true;
506 Visit(Arg);
507 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000508 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000509 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000510 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000511 }
512 Visit(E->getCallee());
513 }
514 void VisitDeclRefExpr(const DeclRefExpr *E) {
515 if (!E)
516 return;
517 const ValueDecl *VD = E->getDecl();
518 if (AllEscaped)
519 markAsEscaped(VD);
520 if (isa<OMPCapturedExprDecl>(VD))
521 VisitValueDecl(VD);
522 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
523 if (VarD->isInitCapture())
524 VisitValueDecl(VD);
525 }
526 void VisitUnaryOperator(const UnaryOperator *E) {
527 if (!E)
528 return;
529 if (E->getOpcode() == UO_AddrOf) {
530 const bool SavedAllEscaped = AllEscaped;
531 AllEscaped = true;
532 Visit(E->getSubExpr());
533 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000534 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000535 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000536 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000537 }
538 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
539 if (!E)
540 return;
541 if (E->getCastKind() == CK_ArrayToPointerDecay) {
542 const bool SavedAllEscaped = AllEscaped;
543 AllEscaped = true;
544 Visit(E->getSubExpr());
545 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000546 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000547 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000548 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000549 }
550 void VisitExpr(const Expr *E) {
551 if (!E)
552 return;
553 bool SavedAllEscaped = AllEscaped;
554 if (!E->isLValue())
555 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000556 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000557 if (Child)
558 Visit(Child);
559 AllEscaped = SavedAllEscaped;
560 }
561 void VisitStmt(const Stmt *S) {
562 if (!S)
563 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000564 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000565 if (Child)
566 Visit(Child);
567 }
568
Alexey Bataevc99042b2018-03-15 18:10:54 +0000569 /// Returns the record that handles all the escaped local variables and used
570 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000571 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000572 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000573 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000574 return GlobalizedRD;
575 }
576
Alexey Bataevc99042b2018-03-15 18:10:54 +0000577 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000578 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
579 assert(GlobalizedRD &&
580 "Record for globalized variables must be generated already.");
581 auto I = MappedDeclsFields.find(VD);
582 if (I == MappedDeclsFields.end())
583 return nullptr;
584 return I->getSecond();
585 }
586
Alexey Bataevc99042b2018-03-15 18:10:54 +0000587 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000588 ArrayRef<const ValueDecl *> getEscapedDecls() const {
589 return EscapedDecls.getArrayRef();
590 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000591
592 /// Checks if the escaped local variable is actually a parameter passed by
593 /// value.
594 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
595 return EscapedParameters;
596 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000597
598 /// Returns the list of the escaped variables with the variably modified
599 /// types.
600 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
601 return EscapedVariableLengthDecls.getArrayRef();
602 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000603};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000604} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000605
606/// Get the GPU warp size.
607static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000608 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000609 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000610 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000611 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000612}
613
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000614/// Get the id of the current thread on the GPU.
615static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000616 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000617 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000618 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000620}
621
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000622/// Get the id of the warp in the block.
623/// We assume that the warp size is 32, which is always the case
624/// on the NVPTX device, to generate more efficient code.
625static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
626 CGBuilderTy &Bld = CGF.Builder;
627 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
628}
629
630/// Get the id of the current lane in the Warp.
631/// We assume that the warp size is 32, which is always the case
632/// on the NVPTX device, to generate more efficient code.
633static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
634 CGBuilderTy &Bld = CGF.Builder;
635 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
636 "nvptx_lane_id");
637}
638
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000639/// Get the maximum number of threads in a block of the GPU.
640static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000641 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000642 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000643 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000644 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000645}
646
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000647/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000648/// For the 'generic' execution mode, the runtime encodes thread_limit in
649/// the launch parameters, always starting thread_limit+warpSize threads per
650/// CTA. The threads in the last warp are reserved for master execution.
651/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
652static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000653 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000654 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000655 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000656 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000657 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
658 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000659}
660
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000661/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000662/// The master thread id is the first thread (lane) of the last warp in the
663/// GPU block. Warp size is assumed to be some power of 2.
664/// Thread id is 0 indexed.
665/// E.g: If NumThreads is 33, master id is 32.
666/// If NumThreads is 64, master id is 32.
667/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000668static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000669 CGBuilderTy &Bld = CGF.Builder;
670 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
671
672 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000673 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000674
Alexey Bataeve290ec02018-04-06 16:03:36 +0000675 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000676 Bld.CreateNot(Mask), "master_tid");
677}
678
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000679CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000680 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000681 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
682 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000684}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000685
686void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
687 CodeGenModule &CGM) {
688 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689
690 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000691 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000692 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000693 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000694 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695}
696
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000697CGOpenMPRuntimeNVPTX::ExecutionMode
698CGOpenMPRuntimeNVPTX::getExecutionMode() const {
699 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000700}
701
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000702static CGOpenMPRuntimeNVPTX::DataSharingMode
703getDataSharingMode(CodeGenModule &CGM) {
704 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
705 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000706}
707
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000708// Checks if the expression is constant or does not have non-trivial function
709// calls.
710static bool isTrivial(ASTContext &Ctx, const Expr * E) {
711 // We can skip constant expressions.
712 // We can skip expressions with trivial calls or simple expressions.
713 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
714 !E->hasNonTrivialCall(Ctx)) &&
715 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
716}
717
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000718/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000719/// iff there is only one that is not evaluatable at the compile time.
720static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
721 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
722 const Stmt *Child = nullptr;
723 for (const Stmt *S : C->body()) {
724 if (const auto *E = dyn_cast<Expr>(S)) {
725 if (isTrivial(Ctx, E))
726 continue;
727 }
728 // Some of the statements can be ignored.
729 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
730 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
731 continue;
732 // Analyze declarations.
733 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
734 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
735 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
736 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
737 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
738 isa<UsingDirectiveDecl>(D) ||
739 isa<OMPDeclareReductionDecl>(D) ||
740 isa<OMPThreadPrivateDecl>(D))
741 return true;
742 const auto *VD = dyn_cast<VarDecl>(D);
743 if (!VD)
744 return false;
745 return VD->isConstexpr() ||
746 ((VD->getType().isTrivialType(Ctx) ||
747 VD->getType()->isReferenceType()) &&
748 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
749 }))
750 continue;
751 }
752 // Found multiple children - cannot get the one child only.
753 if (Child)
754 return Body;
755 Child = S;
756 }
757 if (Child)
758 return Child;
759 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000760 return Body;
761}
762
763/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000764/// false condition. Also, check if the number of threads is strictly specified
765/// and run those directives in non-SPMD mode.
766static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
767 const OMPExecutableDirective &D) {
768 if (D.hasClausesOfKind<OMPNumThreadsClause>())
769 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000770 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
771 OpenMPDirectiveKind NameModifier = C->getNameModifier();
772 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
773 continue;
774 const Expr *Cond = C->getCondition();
775 bool Result;
776 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
777 return true;
778 }
779 return false;
780}
781
782/// Check for inner (nested) SPMD construct, if any
783static bool hasNestedSPMDDirective(ASTContext &Ctx,
784 const OMPExecutableDirective &D) {
785 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000786 const auto *Body =
787 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000788 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000789
790 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
791 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000792 switch (D.getDirectiveKind()) {
793 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000794 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000795 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000796 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000797 if (DKind == OMPD_teams) {
798 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
799 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000800 if (!Body)
801 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000802 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000803 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
804 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000805 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000806 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000807 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000808 }
809 }
810 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000811 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000812 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000813 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000814 case OMPD_target_simd:
815 case OMPD_target_parallel:
816 case OMPD_target_parallel_for:
817 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000818 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 case OMPD_target_teams_distribute_simd:
820 case OMPD_target_teams_distribute_parallel_for:
821 case OMPD_target_teams_distribute_parallel_for_simd:
822 case OMPD_parallel:
823 case OMPD_for:
824 case OMPD_parallel_for:
825 case OMPD_parallel_sections:
826 case OMPD_for_simd:
827 case OMPD_parallel_for_simd:
828 case OMPD_cancel:
829 case OMPD_cancellation_point:
830 case OMPD_ordered:
831 case OMPD_threadprivate:
832 case OMPD_task:
833 case OMPD_simd:
834 case OMPD_sections:
835 case OMPD_section:
836 case OMPD_single:
837 case OMPD_master:
838 case OMPD_critical:
839 case OMPD_taskyield:
840 case OMPD_barrier:
841 case OMPD_taskwait:
842 case OMPD_taskgroup:
843 case OMPD_atomic:
844 case OMPD_flush:
845 case OMPD_teams:
846 case OMPD_target_data:
847 case OMPD_target_exit_data:
848 case OMPD_target_enter_data:
849 case OMPD_distribute:
850 case OMPD_distribute_simd:
851 case OMPD_distribute_parallel_for:
852 case OMPD_distribute_parallel_for_simd:
853 case OMPD_teams_distribute:
854 case OMPD_teams_distribute_simd:
855 case OMPD_teams_distribute_parallel_for:
856 case OMPD_teams_distribute_parallel_for_simd:
857 case OMPD_target_update:
858 case OMPD_declare_simd:
859 case OMPD_declare_target:
860 case OMPD_end_declare_target:
861 case OMPD_declare_reduction:
862 case OMPD_taskloop:
863 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000864 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000865 case OMPD_unknown:
866 llvm_unreachable("Unexpected directive.");
867 }
868 }
869
870 return false;
871}
872
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000873static bool supportsSPMDExecutionMode(ASTContext &Ctx,
874 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000875 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
876 switch (DirectiveKind) {
877 case OMPD_target:
878 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000879 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000880 case OMPD_target_parallel:
881 case OMPD_target_parallel_for:
882 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000883 case OMPD_target_teams_distribute_parallel_for:
884 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000885 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000886 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000887 case OMPD_target_teams_distribute:
888 case OMPD_target_teams_distribute_simd:
889 return false;
890 case OMPD_parallel:
891 case OMPD_for:
892 case OMPD_parallel_for:
893 case OMPD_parallel_sections:
894 case OMPD_for_simd:
895 case OMPD_parallel_for_simd:
896 case OMPD_cancel:
897 case OMPD_cancellation_point:
898 case OMPD_ordered:
899 case OMPD_threadprivate:
900 case OMPD_task:
901 case OMPD_simd:
902 case OMPD_sections:
903 case OMPD_section:
904 case OMPD_single:
905 case OMPD_master:
906 case OMPD_critical:
907 case OMPD_taskyield:
908 case OMPD_barrier:
909 case OMPD_taskwait:
910 case OMPD_taskgroup:
911 case OMPD_atomic:
912 case OMPD_flush:
913 case OMPD_teams:
914 case OMPD_target_data:
915 case OMPD_target_exit_data:
916 case OMPD_target_enter_data:
917 case OMPD_distribute:
918 case OMPD_distribute_simd:
919 case OMPD_distribute_parallel_for:
920 case OMPD_distribute_parallel_for_simd:
921 case OMPD_teams_distribute:
922 case OMPD_teams_distribute_simd:
923 case OMPD_teams_distribute_parallel_for:
924 case OMPD_teams_distribute_parallel_for_simd:
925 case OMPD_target_update:
926 case OMPD_declare_simd:
927 case OMPD_declare_target:
928 case OMPD_end_declare_target:
929 case OMPD_declare_reduction:
930 case OMPD_taskloop:
931 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000932 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000933 case OMPD_unknown:
934 break;
935 }
936 llvm_unreachable(
937 "Unknown programming model for OpenMP directive on NVPTX target.");
938}
939
940/// Check if the directive is loops based and has schedule clause at all or has
941/// static scheduling.
942static bool hasStaticScheduling(const OMPExecutableDirective &D) {
943 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
944 isOpenMPLoopDirective(D.getDirectiveKind()) &&
945 "Expected loop-based directive.");
946 return !D.hasClausesOfKind<OMPOrderedClause>() &&
947 (!D.hasClausesOfKind<OMPScheduleClause>() ||
948 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
949 [](const OMPScheduleClause *C) {
950 return C->getScheduleKind() == OMPC_SCHEDULE_static;
951 }));
952}
953
954/// Check for inner (nested) lightweight runtime construct, if any
955static bool hasNestedLightweightDirective(ASTContext &Ctx,
956 const OMPExecutableDirective &D) {
957 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
958 const auto *CS = D.getInnermostCapturedStmt();
959 const auto *Body =
960 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000961 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000962
963 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
964 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
965 switch (D.getDirectiveKind()) {
966 case OMPD_target:
967 if (isOpenMPParallelDirective(DKind) &&
968 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
969 hasStaticScheduling(*NestedDir))
970 return true;
971 if (DKind == OMPD_parallel) {
972 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
973 /*IgnoreCaptured=*/true);
974 if (!Body)
975 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000976 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000977 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
978 DKind = NND->getDirectiveKind();
979 if (isOpenMPWorksharingDirective(DKind) &&
980 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
981 return true;
982 }
983 } else if (DKind == OMPD_teams) {
984 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
985 /*IgnoreCaptured=*/true);
986 if (!Body)
987 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000988 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000989 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
990 DKind = NND->getDirectiveKind();
991 if (isOpenMPParallelDirective(DKind) &&
992 isOpenMPWorksharingDirective(DKind) &&
993 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
994 return true;
995 if (DKind == OMPD_parallel) {
996 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
997 /*IgnoreCaptured=*/true);
998 if (!Body)
999 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001000 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001001 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1002 DKind = NND->getDirectiveKind();
1003 if (isOpenMPWorksharingDirective(DKind) &&
1004 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1005 return true;
1006 }
1007 }
1008 }
1009 }
1010 return false;
1011 case OMPD_target_teams:
1012 if (isOpenMPParallelDirective(DKind) &&
1013 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1014 hasStaticScheduling(*NestedDir))
1015 return true;
1016 if (DKind == OMPD_parallel) {
1017 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1018 /*IgnoreCaptured=*/true);
1019 if (!Body)
1020 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001021 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001022 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1023 DKind = NND->getDirectiveKind();
1024 if (isOpenMPWorksharingDirective(DKind) &&
1025 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1026 return true;
1027 }
1028 }
1029 return false;
1030 case OMPD_target_parallel:
1031 return isOpenMPWorksharingDirective(DKind) &&
1032 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1033 case OMPD_target_teams_distribute:
1034 case OMPD_target_simd:
1035 case OMPD_target_parallel_for:
1036 case OMPD_target_parallel_for_simd:
1037 case OMPD_target_teams_distribute_simd:
1038 case OMPD_target_teams_distribute_parallel_for:
1039 case OMPD_target_teams_distribute_parallel_for_simd:
1040 case OMPD_parallel:
1041 case OMPD_for:
1042 case OMPD_parallel_for:
1043 case OMPD_parallel_sections:
1044 case OMPD_for_simd:
1045 case OMPD_parallel_for_simd:
1046 case OMPD_cancel:
1047 case OMPD_cancellation_point:
1048 case OMPD_ordered:
1049 case OMPD_threadprivate:
1050 case OMPD_task:
1051 case OMPD_simd:
1052 case OMPD_sections:
1053 case OMPD_section:
1054 case OMPD_single:
1055 case OMPD_master:
1056 case OMPD_critical:
1057 case OMPD_taskyield:
1058 case OMPD_barrier:
1059 case OMPD_taskwait:
1060 case OMPD_taskgroup:
1061 case OMPD_atomic:
1062 case OMPD_flush:
1063 case OMPD_teams:
1064 case OMPD_target_data:
1065 case OMPD_target_exit_data:
1066 case OMPD_target_enter_data:
1067 case OMPD_distribute:
1068 case OMPD_distribute_simd:
1069 case OMPD_distribute_parallel_for:
1070 case OMPD_distribute_parallel_for_simd:
1071 case OMPD_teams_distribute:
1072 case OMPD_teams_distribute_simd:
1073 case OMPD_teams_distribute_parallel_for:
1074 case OMPD_teams_distribute_parallel_for_simd:
1075 case OMPD_target_update:
1076 case OMPD_declare_simd:
1077 case OMPD_declare_target:
1078 case OMPD_end_declare_target:
1079 case OMPD_declare_reduction:
1080 case OMPD_taskloop:
1081 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001082 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001083 case OMPD_unknown:
1084 llvm_unreachable("Unexpected directive.");
1085 }
1086 }
1087
1088 return false;
1089}
1090
1091/// Checks if the construct supports lightweight runtime. It must be SPMD
1092/// construct + inner loop-based construct with static scheduling.
1093static bool supportsLightweightRuntime(ASTContext &Ctx,
1094 const OMPExecutableDirective &D) {
1095 if (!supportsSPMDExecutionMode(Ctx, D))
1096 return false;
1097 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1098 switch (DirectiveKind) {
1099 case OMPD_target:
1100 case OMPD_target_teams:
1101 case OMPD_target_parallel:
1102 return hasNestedLightweightDirective(Ctx, D);
1103 case OMPD_target_parallel_for:
1104 case OMPD_target_parallel_for_simd:
1105 case OMPD_target_teams_distribute_parallel_for:
1106 case OMPD_target_teams_distribute_parallel_for_simd:
1107 // (Last|First)-privates must be shared in parallel region.
1108 return hasStaticScheduling(D);
1109 case OMPD_target_simd:
1110 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001111 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001112 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001113 case OMPD_parallel:
1114 case OMPD_for:
1115 case OMPD_parallel_for:
1116 case OMPD_parallel_sections:
1117 case OMPD_for_simd:
1118 case OMPD_parallel_for_simd:
1119 case OMPD_cancel:
1120 case OMPD_cancellation_point:
1121 case OMPD_ordered:
1122 case OMPD_threadprivate:
1123 case OMPD_task:
1124 case OMPD_simd:
1125 case OMPD_sections:
1126 case OMPD_section:
1127 case OMPD_single:
1128 case OMPD_master:
1129 case OMPD_critical:
1130 case OMPD_taskyield:
1131 case OMPD_barrier:
1132 case OMPD_taskwait:
1133 case OMPD_taskgroup:
1134 case OMPD_atomic:
1135 case OMPD_flush:
1136 case OMPD_teams:
1137 case OMPD_target_data:
1138 case OMPD_target_exit_data:
1139 case OMPD_target_enter_data:
1140 case OMPD_distribute:
1141 case OMPD_distribute_simd:
1142 case OMPD_distribute_parallel_for:
1143 case OMPD_distribute_parallel_for_simd:
1144 case OMPD_teams_distribute:
1145 case OMPD_teams_distribute_simd:
1146 case OMPD_teams_distribute_parallel_for:
1147 case OMPD_teams_distribute_parallel_for_simd:
1148 case OMPD_target_update:
1149 case OMPD_declare_simd:
1150 case OMPD_declare_target:
1151 case OMPD_end_declare_target:
1152 case OMPD_declare_reduction:
1153 case OMPD_taskloop:
1154 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001155 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001156 case OMPD_unknown:
1157 break;
1158 }
1159 llvm_unreachable(
1160 "Unknown programming model for OpenMP directive on NVPTX target.");
1161}
1162
1163void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001164 StringRef ParentName,
1165 llvm::Function *&OutlinedFn,
1166 llvm::Constant *&OutlinedFnID,
1167 bool IsOffloadEntry,
1168 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001169 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001170 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001171 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001172 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001173 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001174
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001175 // Emit target region as a standalone region.
1176 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001177 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1178 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001179
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001181 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001183 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001185 auto &RT =
1186 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001187 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1188 // Skip target region initialization.
1189 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001190 }
1191 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001192 auto &RT =
1193 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001194 RT.clearLocThreadIdInsertPt(CGF);
1195 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001196 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001197 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001199 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001200 // Reserve place for the globalized memory.
1201 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001202 if (!KernelStaticGlobalized) {
1203 KernelStaticGlobalized = new llvm::GlobalVariable(
1204 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1205 llvm::GlobalValue::InternalLinkage,
1206 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1207 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1208 llvm::GlobalValue::NotThreadLocal,
1209 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1210 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1212 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001213 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001214
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001215 // Now change the name of the worker function to correspond to this target
1216 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001217 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001218
1219 // Create the worker function
1220 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221}
1222
1223// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001224void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 EntryFunctionState &EST,
1226 WorkerFunctionState &WST) {
1227 CGBuilderTy &Bld = CGF.Builder;
1228
1229 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1230 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1231 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1232 EST.ExitBB = CGF.createBasicBlock(".exit");
1233
Alexey Bataev9ff80832018-04-16 20:16:21 +00001234 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001235 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1236 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1237
1238 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001239 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001240 CGF.EmitBranch(EST.ExitBB);
1241
1242 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001243 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001244 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1245 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1246
1247 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001248 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001249 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001250 // First action in sequential region:
1251 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001252 // TODO: Optimize runtime initialization and pass in correct value.
1253 llvm::Value *Args[] = {getThreadLimit(CGF),
1254 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001255 CGF.EmitRuntimeCall(
1256 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001257
1258 // For data sharing, we need to initialize the stack.
1259 CGF.EmitRuntimeCall(
1260 createNVPTXRuntimeFunction(
1261 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1262
Alexey Bataevc99042b2018-03-15 18:10:54 +00001263 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001264}
1265
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001266void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001267 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001268 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001269 if (!CGF.HaveInsertPoint())
1270 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001271
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001272 emitGenericVarsEpilog(CGF);
1273
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001274 if (!EST.ExitBB)
1275 EST.ExitBB = CGF.createBasicBlock(".exit");
1276
1277 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1278 CGF.EmitBranch(TerminateBB);
1279
1280 CGF.EmitBlock(TerminateBB);
1281 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001282 // TODO: Optimize runtime initialization and pass in correct value.
1283 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001284 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001285 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001286 // Barrier to terminate worker threads.
1287 syncCTAThreads(CGF);
1288 // Master thread jumps to exit point.
1289 CGF.EmitBranch(EST.ExitBB);
1290
1291 CGF.EmitBlock(EST.ExitBB);
1292 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001293}
1294
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001295void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001296 StringRef ParentName,
1297 llvm::Function *&OutlinedFn,
1298 llvm::Constant *&OutlinedFnID,
1299 bool IsOffloadEntry,
1300 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001301 ExecutionRuntimeModesRAII ModeRAII(
1302 CurrentExecutionMode, RequiresFullRuntime,
1303 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1304 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001305 EntryFunctionState EST;
1306
1307 // Emit target region as a standalone region.
1308 class NVPTXPrePostActionTy : public PrePostActionTy {
1309 CGOpenMPRuntimeNVPTX &RT;
1310 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1311 const OMPExecutableDirective &D;
1312
1313 public:
1314 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1315 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1316 const OMPExecutableDirective &D)
1317 : RT(RT), EST(EST), D(D) {}
1318 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001319 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001320 // Skip target region initialization.
1321 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001322 }
1323 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001324 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001325 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326 }
1327 } Action(*this, EST, D);
1328 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001329 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001330 // Reserve place for the globalized memory.
1331 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001332 if (!KernelStaticGlobalized) {
1333 KernelStaticGlobalized = new llvm::GlobalVariable(
1334 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1335 llvm::GlobalValue::InternalLinkage,
1336 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1337 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1338 llvm::GlobalValue::NotThreadLocal,
1339 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1340 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001341 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1342 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001343 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344}
1345
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001346void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347 CodeGenFunction &CGF, EntryFunctionState &EST,
1348 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001349 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001350
1351 // Setup BBs in entry function.
1352 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1353 EST.ExitBB = CGF.createBasicBlock(".exit");
1354
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001355 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1356 /*RequiresOMPRuntime=*/
1357 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1358 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001359 CGF.EmitRuntimeCall(
1360 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001361
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001362 if (RequiresFullRuntime) {
1363 // For data sharing, we need to initialize the stack.
1364 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1365 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1366 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001367
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001368 CGF.EmitBranch(ExecuteBB);
1369
1370 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001371
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001372 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001373}
1374
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001375void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001376 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001377 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001378 if (!CGF.HaveInsertPoint())
1379 return;
1380
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001381 if (!EST.ExitBB)
1382 EST.ExitBB = CGF.createBasicBlock(".exit");
1383
1384 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1385 CGF.EmitBranch(OMPDeInitBB);
1386
1387 CGF.EmitBlock(OMPDeInitBB);
1388 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001389 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1390 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001391 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001392 createNVPTXRuntimeFunction(
1393 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001394 CGF.EmitBranch(EST.ExitBB);
1395
1396 CGF.EmitBlock(EST.ExitBB);
1397 EST.ExitBB = nullptr;
1398}
1399
1400// Create a unique global variable to indicate the execution mode of this target
1401// region. The execution mode is either 'generic', or 'spmd' depending on the
1402// target directive. This variable is picked up by the offload library to setup
1403// the device appropriately before kernel launch. If the execution mode is
1404// 'generic', the runtime reserves one warp for the master, otherwise, all
1405// warps participate in parallel work.
1406static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001407 bool Mode) {
1408 auto *GVMode =
1409 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1410 llvm::GlobalValue::WeakAnyLinkage,
1411 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1412 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001413 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001414}
1415
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001416void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001417 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001418
1419 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001420 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001421 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001422 emitWorkerLoop(CGF, WST);
1423 CGF.FinishFunction();
1424}
1425
1426void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1427 WorkerFunctionState &WST) {
1428 //
1429 // The workers enter this loop and wait for parallel work from the master.
1430 // When the master encounters a parallel region it sets up the work + variable
1431 // arguments, and wakes up the workers. The workers first check to see if
1432 // they are required for the parallel region, i.e., within the # of requested
1433 // parallel threads. The activated workers load the variable arguments and
1434 // execute the parallel work.
1435 //
1436
1437 CGBuilderTy &Bld = CGF.Builder;
1438
1439 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1440 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1441 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1442 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1443 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1444 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1445
1446 CGF.EmitBranch(AwaitBB);
1447
1448 // Workers wait for work from master.
1449 CGF.EmitBlock(AwaitBB);
1450 // Wait for parallel work
1451 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001452
1453 Address WorkFn =
1454 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1455 Address ExecStatus =
1456 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1457 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1458 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1459
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001460 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001461 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001462 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001463 llvm::Value *Ret = CGF.EmitRuntimeCall(
1464 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1465 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001466
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001467 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001468 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1469 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001470 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1471
1472 // Activate requested workers.
1473 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001474 llvm::Value *IsActive =
1475 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1476 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001477
1478 // Signal start of parallel region.
1479 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001480 // Skip initialization.
1481 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001482
1483 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001484 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001485 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001486 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001487
1488 llvm::Value *WorkFnMatch =
1489 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1490
1491 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1492 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1493 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1494
1495 // Execute this outlined function.
1496 CGF.EmitBlock(ExecuteFNBB);
1497
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001498 // Insert call to work function via shared wrapper. The shared
1499 // wrapper takes two arguments:
1500 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001501 // - the thread ID;
1502 emitCall(CGF, WST.Loc, W,
1503 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001504
1505 // Go to end of parallel region.
1506 CGF.EmitBranch(TerminateBB);
1507
1508 CGF.EmitBlock(CheckNextBB);
1509 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001510 // Default case: call to outlined function through pointer if the target
1511 // region makes a declare target call that may contain an orphaned parallel
1512 // directive.
1513 auto *ParallelFnTy =
1514 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
1515 /*isVarArg=*/false)
1516 ->getPointerTo();
1517 llvm::Value *WorkFnCast = Bld.CreateBitCast(WorkID, ParallelFnTy);
1518 // Insert call to work function via shared wrapper. The shared
1519 // wrapper takes two arguments:
1520 // - the parallelism level;
1521 // - the thread ID;
1522 emitCall(CGF, WST.Loc, WorkFnCast,
1523 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1524 // Go to end of parallel region.
1525 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001526
1527 // Signal end of parallel region.
1528 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001529 CGF.EmitRuntimeCall(
1530 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1531 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001532 CGF.EmitBranch(BarrierBB);
1533
1534 // All active and inactive workers wait at a barrier after parallel region.
1535 CGF.EmitBlock(BarrierBB);
1536 // Barrier after parallel region.
1537 syncCTAThreads(CGF);
1538 CGF.EmitBranch(AwaitBB);
1539
1540 // Exit target region.
1541 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001542 // Skip initialization.
1543 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001544}
1545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001546/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001547/// implementation. Specialized for the NVPTX device.
1548/// \param Function OpenMP runtime function.
1549/// \return Specified function.
1550llvm::Constant *
1551CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
1552 llvm::Constant *RTLFn = nullptr;
1553 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1554 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001555 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1556 // RequiresOMPRuntime);
1557 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001558 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1561 break;
1562 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001563 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001564 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1565 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001566 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001567 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1569 break;
1570 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001571 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1572 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001573 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001574 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001575 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001576 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1578 break;
1579 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001580 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1581 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1582 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001583 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001584 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1585 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001586 break;
1587 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001588 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1589 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001590 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001591 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001592 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001593 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1594 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1595 break;
1596 }
1597 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001598 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1599 /// int16_t IsOMPRuntimeInitialized);
1600 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001601 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001602 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001603 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1604 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1605 break;
1606 }
1607 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1608 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001609 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001610 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1611 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1612 break;
1613 }
1614 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1615 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1616 // global_tid);
1617 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001618 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001619 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1620 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1621 break;
1622 }
1623 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1624 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1625 // global_tid);
1626 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001627 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001628 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1629 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1630 break;
1631 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001632 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1633 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1634 // int16_t lane_offset, int16_t warp_size);
1635 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001636 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001637 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1638 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1639 break;
1640 }
1641 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1642 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1643 // int16_t lane_offset, int16_t warp_size);
1644 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001645 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001646 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1648 break;
1649 }
Alexey Bataev8e009032019-01-04 17:25:09 +00001650 case OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2: {
1651 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1652 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1653 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1654 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1655 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001656 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1657 CGM.Int16Ty, CGM.Int16Ty};
1658 auto *ShuffleReduceFnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1660 /*isVarArg=*/false);
1661 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1662 auto *InterWarpCopyFnTy =
1663 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1664 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001665 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1666 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001667 CGM.Int32Ty,
1668 CGM.SizeTy,
1669 CGM.VoidPtrTy,
1670 ShuffleReduceFnTy->getPointerTo(),
1671 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001672 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001673 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1674 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001675 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001676 break;
1677 }
1678 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1679 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1680 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001681 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001682 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1683 RTLFn = CGM.CreateRuntimeFunction(
1684 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1685 break;
1686 }
Alexey Bataeva1166022018-11-27 21:24:54 +00001687 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple: {
1688 // Build __kmpc_nvptx_teams_reduce_nowait_simple(ident_t *loc, kmp_int32
1689 // global_tid, kmp_critical_name *lck)
1690 llvm::Type *TypeParams[] = {
1691 getIdentTyPointerTy(), CGM.Int32Ty,
1692 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1693 auto *FnTy =
1694 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1695 RTLFn = CGM.CreateRuntimeFunction(
1696 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_simple");
1697 break;
1698 }
1699 case OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple: {
1700 // Build __kmpc_nvptx_teams_end_reduce_nowait_simple(ident_t *loc, kmp_int32
1701 // global_tid, kmp_critical_name *lck)
1702 llvm::Type *TypeParams[] = {
1703 getIdentTyPointerTy(), CGM.Int32Ty,
1704 llvm::PointerType::getUnqual(getKmpCriticalNameTy())};
1705 auto *FnTy =
1706 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1707 RTLFn = CGM.CreateRuntimeFunction(
1708 FnTy, /*Name=*/"__kmpc_nvptx_teams_end_reduce_nowait_simple");
1709 break;
1710 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001711 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1712 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001713 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001714 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1715 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1716 break;
1717 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001718 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1719 /// Build void __kmpc_data_sharing_init_stack_spmd();
1720 auto *FnTy =
1721 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001722 RTLFn =
1723 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001724 break;
1725 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001726 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1727 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001728 // int16_t UseSharedMemory);
1729 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001730 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001731 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1732 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001733 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001734 break;
1735 }
1736 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1737 // Build void __kmpc_data_sharing_pop_stack(void *a);
1738 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001739 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001740 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1741 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1742 /*Name=*/"__kmpc_data_sharing_pop_stack");
1743 break;
1744 }
1745 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1746 /// Build void __kmpc_begin_sharing_variables(void ***args,
1747 /// size_t n_args);
1748 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001749 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001750 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1752 break;
1753 }
1754 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1755 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001756 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001757 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1759 break;
1760 }
1761 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1762 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1763 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001764 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001765 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1766 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1767 break;
1768 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001769 case OMPRTL_NVPTX__kmpc_parallel_level: {
1770 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1771 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1772 auto *FnTy =
1773 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1775 break;
1776 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001777 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1778 // Build int8_t __kmpc_is_spmd_exec_mode();
1779 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1781 break;
1782 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001783 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001784 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1785 // const void *buf, size_t size, int16_t is_shared, const void **res);
1786 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1787 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001788 auto *FnTy =
1789 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1790 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1791 break;
1792 }
1793 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001794 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1795 // int16_t is_shared);
1796 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001797 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001799 RTLFn =
1800 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1801 break;
1802 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001803 case OMPRTL__kmpc_barrier: {
1804 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1805 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1806 auto *FnTy =
1807 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1808 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1809 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1810 break;
1811 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001812 case OMPRTL__kmpc_barrier_simple_spmd: {
1813 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1814 // global_tid);
1815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1816 auto *FnTy =
1817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1818 RTLFn =
1819 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
1820 cast<llvm::Function>(RTLFn)->addFnAttr(llvm::Attribute::Convergent);
1821 break;
1822 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001823 }
1824 return RTLFn;
1825}
1826
1827void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1828 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001829 uint64_t Size, int32_t,
1830 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001831 // TODO: Add support for global variables on the device after declare target
1832 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001833 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001834 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001835 llvm::Module &M = CGM.getModule();
1836 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001837
1838 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001839 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001840
1841 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001842 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843 llvm::ConstantAsMetadata::get(
1844 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1845 // Append metadata to nvvm.annotations
1846 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1847}
1848
1849void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1850 const OMPExecutableDirective &D, StringRef ParentName,
1851 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001852 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001853 if (!IsOffloadEntry) // Nothing to do.
1854 return;
1855
1856 assert(!ParentName.empty() && "Invalid target region parent name!");
1857
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001858 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001859 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001860 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001861 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001862 else
1863 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1864 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001865
1866 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001867}
1868
Alexey Bataevceeaa482018-11-21 21:04:34 +00001869namespace {
1870LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1871/// Enum for accesseing the reserved_2 field of the ident_t struct.
1872enum ModeFlagsTy : unsigned {
1873 /// Bit set to 1 when in SPMD mode.
1874 KMP_IDENT_SPMD_MODE = 0x01,
1875 /// Bit set to 1 when a simplified runtime is used.
1876 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1877 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1878};
1879
1880/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1881static const ModeFlagsTy UndefinedMode =
1882 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1883} // anonymous namespace
1884
1885unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001886 switch (getExecutionMode()) {
1887 case EM_SPMD:
1888 if (requiresFullRuntime())
1889 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1890 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1891 case EM_NonSPMD:
1892 assert(requiresFullRuntime() && "Expected full runtime.");
1893 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1894 case EM_Unknown:
1895 return UndefinedMode;
1896 }
1897 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001898}
1899
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001900CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001901 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001902 if (!CGM.getLangOpts().OpenMPIsDevice)
1903 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001904}
Carlo Bertollic6872252016-04-04 15:55:02 +00001905
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001906void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1907 OpenMPProcBindClauseKind ProcBind,
1908 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001909 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001910 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001911 return;
1912
1913 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1914}
1915
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001916void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1917 llvm::Value *NumThreads,
1918 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001919 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001920 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001921 return;
1922
1923 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1924}
1925
Carlo Bertollic6872252016-04-04 15:55:02 +00001926void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1927 const Expr *NumTeams,
1928 const Expr *ThreadLimit,
1929 SourceLocation Loc) {}
1930
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001931llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
1932 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1933 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001934 // Emit target region as a standalone region.
1935 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001936 bool &IsInParallelRegion;
1937 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938
1939 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001940 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1941 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001942 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001943 PrevIsInParallelRegion = IsInParallelRegion;
1944 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001945 }
1946 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001947 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001948 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001949 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001950 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001951 bool PrevIsInTTDRegion = IsInTTDRegion;
1952 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001953 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1954 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001955 auto *OutlinedFun =
1956 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1957 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001959 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001960 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1961 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001962 llvm::Function *WrapperFun =
1963 createParallelDataSharingWrapper(OutlinedFun, D);
1964 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1965 }
1966
1967 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001968}
1969
Alexey Bataev2adecff2018-09-21 14:22:53 +00001970/// Get list of lastprivate variables from the teams distribute ... or
1971/// teams {distribute ...} directives.
1972static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001973getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001974 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1975 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1976 "expected teams directive.");
1977 const OMPExecutableDirective *Dir = &D;
1978 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
1979 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001980 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001981 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1982 /*IgnoreCaptured=*/true))) {
1983 Dir = dyn_cast<OMPExecutableDirective>(S);
1984 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1985 Dir = nullptr;
1986 }
1987 }
1988 if (!Dir)
1989 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001990 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001991 for (const Expr *E : C->getVarRefs())
1992 Vars.push_back(getPrivateItem(E));
1993 }
1994}
1995
1996/// Get list of reduction variables from the teams ... directives.
1997static void
1998getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1999 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2000 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2001 "expected teams directive.");
2002 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2003 for (const Expr *E : C->privates())
2004 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 }
2006}
2007
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002008llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002009 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2010 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002011 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002012
Alexey Bataev2adecff2018-09-21 14:22:53 +00002013 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002014 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002015 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002016 // Globalize team reductions variable unconditionally in all modes.
2017 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002018 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002019 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2020 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002021 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 CGM.getContext(), llvm::None, LastPrivatesReductions,
2023 MappedDeclsFields);
2024 }
2025 } else if (!LastPrivatesReductions.empty()) {
2026 assert(!TeamAndReductions.first &&
2027 "Previous team declaration is not expected.");
2028 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2029 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002030 }
2031
Alexey Bataevc99042b2018-03-15 18:10:54 +00002032 // Emit target region as a standalone region.
2033 class NVPTXPrePostActionTy : public PrePostActionTy {
2034 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002035 const RecordDecl *GlobalizedRD;
2036 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2037 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002038
2039 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002040 NVPTXPrePostActionTy(
2041 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2042 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2043 &MappedDeclsFields)
2044 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2045 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002046 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002047 auto &Rt =
2048 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2049 if (GlobalizedRD) {
2050 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2051 I->getSecond().GlobalRecord = GlobalizedRD;
2052 I->getSecond().MappedParams =
2053 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2054 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2055 for (const auto &Pair : MappedDeclsFields) {
2056 assert(Pair.getFirst()->isCanonicalDecl() &&
2057 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002058 Data.insert(std::make_pair(Pair.getFirst(),
2059 MappedVarData(Pair.getSecond(),
2060 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002061 }
2062 }
2063 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002064 }
2065 void Exit(CodeGenFunction &CGF) override {
2066 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2067 .emitGenericVarsEpilog(CGF);
2068 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002069 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2070 CodeGen.setAction(Action);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002071 llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction(
2072 D, ThreadIDVar, InnermostKind, CodeGen);
2073 llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal);
2074 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002075 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002076 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002077
2078 return OutlinedFun;
2079}
2080
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002082 SourceLocation Loc,
2083 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2085 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002086 return;
2087
Alexey Bataevc99042b2018-03-15 18:10:54 +00002088 CGBuilderTy &Bld = CGF.Builder;
2089
2090 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2091 if (I == FunctionGlobalizedDecls.end())
2092 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002093 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002094 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002095 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002097 // Recover pointer to this function's global record. The runtime will
2098 // handle the specifics of the allocation of the memory.
2099 // Use actual memory size of the record including the padding
2100 // for alignment purposes.
2101 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002102 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002103 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002104 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002105 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002106
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002107 llvm::PointerType *GlobalRecPtrTy =
2108 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002109 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002110 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002111 if (!IsInTTDRegion &&
2112 (WithSPMDCheck ||
2113 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002114 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2115 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2116 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002117 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2118 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2119 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2120 llvm::Value *PL = CGF.EmitRuntimeCall(
2121 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2122 {RTLoc, ThreadID});
2123 IsTTD = Bld.CreateIsNull(PL);
2124 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002125 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2126 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2127 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2128 // There is no need to emit line number for unconditional branch.
2129 (void)ApplyDebugLocation::CreateEmpty(CGF);
2130 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002131 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2132 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002133 CGF.EmitBranch(ExitBB);
2134 // There is no need to emit line number for unconditional branch.
2135 (void)ApplyDebugLocation::CreateEmpty(CGF);
2136 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002137 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2138 if (const RecordDecl *SecGlobalizedVarsRecord =
2139 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2140 SecGlobalRecTy =
2141 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2142
2143 // Recover pointer to this function's global record. The runtime will
2144 // handle the specifics of the allocation of the memory.
2145 // Use actual memory size of the record including the padding
2146 // for alignment purposes.
2147 unsigned Alignment =
2148 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2149 unsigned GlobalRecordSize =
2150 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2151 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2152 Size = Bld.CreateSelect(
2153 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2154 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 // TODO: allow the usage of shared memory to be controlled by
2156 // the user, for now, default to global.
2157 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002158 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002159 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2160 createNVPTXRuntimeFunction(
2161 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2162 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002163 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002164 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002165 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002166 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002167 /*NumReservedValues=*/2, "_select_stack");
2168 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2169 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2170 GlobalRecCastAddr = Phi;
2171 I->getSecond().GlobalRecordAddr = Phi;
2172 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002173 } else if (IsInTTDRegion) {
2174 assert(GlobalizedRecords.back().Records.size() < 2 &&
2175 "Expected less than 2 globalized records: one for target and one "
2176 "for teams.");
2177 unsigned Offset = 0;
2178 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2179 QualType RDTy = CGM.getContext().getRecordType(RD);
2180 unsigned Alignment =
2181 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2182 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2183 Offset =
2184 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2185 }
2186 unsigned Alignment =
2187 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2188 Offset = llvm::alignTo(Offset, Alignment);
2189 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2190 ++GlobalizedRecords.back().RegionCounter;
2191 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002192 assert(KernelStaticGlobalized &&
2193 "Kernel static pointer must be initialized already.");
2194 auto *UseSharedMemory = new llvm::GlobalVariable(
2195 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2196 llvm::GlobalValue::InternalLinkage, nullptr,
2197 "_openmp_static_kernel$is_shared");
2198 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2199 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2200 /*DestWidth=*/16, /*Signed=*/0);
2201 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2202 Address(UseSharedMemory,
2203 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2204 /*Volatile=*/false, Int16Ty, Loc);
2205 auto *StaticGlobalized = new llvm::GlobalVariable(
2206 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002207 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002208 auto *RecSize = new llvm::GlobalVariable(
2209 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2210 llvm::GlobalValue::InternalLinkage, nullptr,
2211 "_openmp_static_kernel$size");
2212 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2213 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002214 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002215 CGM.getContext().getSizeType(), Loc);
2216 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2217 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002218 llvm::Value *GlobalRecordSizeArg[] = {
2219 llvm::ConstantInt::get(
2220 CGM.Int16Ty,
2221 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2222 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002223 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2224 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2225 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002226 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002227 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002228 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2229 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 }
2231 assert(KernelStaticGlobalized && "Global address must be set already.");
2232 Address FrameAddr = CGF.EmitLoadOfPointer(
2233 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2234 CGM.getContext()
2235 .getPointerType(CGM.getContext().VoidPtrTy)
2236 .castAs<PointerType>());
2237 llvm::Value *GlobalRecValue =
2238 Bld.CreateConstInBoundsGEP(FrameAddr, Offset, CharUnits::One())
2239 .getPointer();
2240 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2241 I->getSecond().IsInSPMDModeFlag = nullptr;
2242 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2243 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002244 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002245 // TODO: allow the usage of shared memory to be controlled by
2246 // the user, for now, default to global.
2247 llvm::Value *GlobalRecordSizeArg[] = {
2248 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2249 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002250 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2251 createNVPTXRuntimeFunction(
2252 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2253 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002254 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002255 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002256 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2257 I->getSecond().IsInSPMDModeFlag = nullptr;
2258 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002259 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002260 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002261
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002262 // Emit the "global alloca" which is a GEP from the global declaration
2263 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002264 LValue SecBase;
2265 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2266 if (IsTTD) {
2267 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2268 llvm::PointerType *SecGlobalRecPtrTy =
2269 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2270 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2271 Bld.CreatePointerBitCastOrAddrSpaceCast(
2272 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2273 SecGlobalRecTy);
2274 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002275 for (auto &Rec : I->getSecond().LocalVarData) {
2276 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2277 llvm::Value *ParValue;
2278 if (EscapedParam) {
2279 const auto *VD = cast<VarDecl>(Rec.first);
2280 LValue ParLVal =
2281 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2282 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2283 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002284 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2285 // Emit VarAddr basing on lane-id if required.
2286 QualType VarTy;
2287 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002288 VarTy = Rec.second.FD->getType();
2289 } else {
2290 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2291 VarAddr.getAddress().getPointer(),
2292 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002293 VarTy =
2294 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002295 VarAddr = CGF.MakeAddrLValue(
2296 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2297 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002298 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002299 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002300 if (!IsInTTDRegion &&
2301 (WithSPMDCheck ||
2302 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002303 assert(I->getSecond().IsInSPMDModeFlag &&
2304 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002305 if (IsTTD) {
2306 assert(SecIt->second.IsOnePerTeam &&
2307 "Secondary glob data must be one per team.");
2308 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2309 VarAddr.setAddress(
2310 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2311 VarAddr.getPointer()),
2312 VarAddr.getAlignment()));
2313 Rec.second.PrivateAddr = VarAddr.getAddress();
2314 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002315 Address GlobalPtr = Rec.second.PrivateAddr;
2316 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2317 Rec.second.PrivateAddr = Address(
2318 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2319 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2320 LocalAddr.getAlignment());
2321 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002322 if (EscapedParam) {
2323 const auto *VD = cast<VarDecl>(Rec.first);
2324 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2325 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2326 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002327 if (IsTTD)
2328 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002329 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002330 }
2331 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2332 // Recover pointer to this function's global record. The runtime will
2333 // handle the specifics of the allocation of the memory.
2334 // Use actual memory size of the record including the padding
2335 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002336 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002337 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2338 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2339 Size = Bld.CreateNUWAdd(
2340 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2341 llvm::Value *AlignVal =
2342 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2343 Size = Bld.CreateUDiv(Size, AlignVal);
2344 Size = Bld.CreateNUWMul(Size, AlignVal);
2345 // TODO: allow the usage of shared memory to be controlled by
2346 // the user, for now, default to global.
2347 llvm::Value *GlobalRecordSizeArg[] = {
2348 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2349 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002350 createNVPTXRuntimeFunction(
2351 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002352 GlobalRecordSizeArg);
2353 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2354 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2355 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2356 CGM.getContext().getDeclAlign(VD),
2357 AlignmentSource::Decl);
2358 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2359 Base.getAddress());
2360 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002361 }
2362 I->getSecond().MappedParams->apply(CGF);
2363}
2364
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002365void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2366 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002367 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2368 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002369 return;
2370
Alexey Bataevc99042b2018-03-15 18:10:54 +00002371 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002372 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002373 I->getSecond().MappedParams->restore(CGF);
2374 if (!CGF.HaveInsertPoint())
2375 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002376 for (llvm::Value *Addr :
2377 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2378 CGF.EmitRuntimeCall(
2379 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2380 Addr);
2381 }
2382 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002383 if (!IsInTTDRegion &&
2384 (WithSPMDCheck ||
2385 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002386 CGBuilderTy &Bld = CGF.Builder;
2387 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2388 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2389 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2390 // There is no need to emit line number for unconditional branch.
2391 (void)ApplyDebugLocation::CreateEmpty(CGF);
2392 CGF.EmitBlock(NonSPMDBB);
2393 CGF.EmitRuntimeCall(
2394 createNVPTXRuntimeFunction(
2395 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2396 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2397 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002398 } else if (IsInTTDRegion) {
2399 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2400 "region counter must be > 0.");
2401 --GlobalizedRecords.back().RegionCounter;
2402 // Emit the restore function only in the target region.
2403 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002404 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2405 /*DestWidth=*/16, /*Signed=*/0);
2406 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2407 Address(GlobalizedRecords.back().UseSharedMemory,
2408 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2409 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002410 llvm::Value *Args[] = {
2411 llvm::ConstantInt::get(
2412 CGM.Int16Ty,
2413 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2414 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002415 CGF.EmitRuntimeCall(
2416 createNVPTXRuntimeFunction(
2417 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002418 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002419 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002420 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002421 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2422 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2423 I->getSecond().GlobalRecordAddr);
2424 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002425 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002426 }
2427}
2428
Carlo Bertollic6872252016-04-04 15:55:02 +00002429void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2430 const OMPExecutableDirective &D,
2431 SourceLocation Loc,
2432 llvm::Value *OutlinedFn,
2433 ArrayRef<llvm::Value *> CapturedVars) {
2434 if (!CGF.HaveInsertPoint())
2435 return;
2436
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002437 Address ZeroAddr = CGF.CreateMemTemp(
2438 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2439 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002440 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2441 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002442 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002443 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2444 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002445 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002446}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002447
2448void CGOpenMPRuntimeNVPTX::emitParallelCall(
2449 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2450 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2451 if (!CGF.HaveInsertPoint())
2452 return;
2453
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002454 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002455 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002456 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002457 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002458}
2459
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002460void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002461 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2462 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2463 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002464
2465 // Force inline this outlined function at its call site.
2466 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2467
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002468 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2469 /*DestWidth=*/32, /*Signed=*/1),
2470 ".zero.addr");
2471 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002472 // ThreadId for serialized parallels is 0.
2473 Address ThreadIDAddr = ZeroAddr;
2474 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002475 CodeGenFunction &CGF, PrePostActionTy &Action) {
2476 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002477
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002478 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2479 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2480 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2481 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2482 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2483 };
2484 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2485 PrePostActionTy &) {
2486
2487 RegionCodeGenTy RCG(CodeGen);
2488 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2489 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2490 llvm::Value *Args[] = {RTLoc, ThreadID};
2491
2492 NVPTXActionTy Action(
2493 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2494 Args,
2495 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2496 Args);
2497 RCG.setAction(Action);
2498 RCG(CGF);
2499 };
2500
2501 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2502 PrePostActionTy &Action) {
2503 CGBuilderTy &Bld = CGF.Builder;
2504 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2505 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002506 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2507
2508 // Prepare for parallel region. Indicate the outlined function.
2509 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002510 CGF.EmitRuntimeCall(
2511 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2512 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002513
2514 // Create a private scope that will globalize the arguments
2515 // passed from the outside of the target region.
2516 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2517
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002518 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002519 if (!CapturedVars.empty()) {
2520 // Prepare for parallel region. Indicate the outlined function.
2521 Address SharedArgs =
2522 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2523 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2524
2525 llvm::Value *DataSharingArgs[] = {
2526 SharedArgsPtr,
2527 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2528 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2529 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2530 DataSharingArgs);
2531
2532 // Store variable address in a list of references to pass to workers.
2533 unsigned Idx = 0;
2534 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002535 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2536 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2537 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002538 for (llvm::Value *V : CapturedVars) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002539 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
2540 CGF.getPointerSize());
2541 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002542 if (V->getType()->isIntegerTy())
2543 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2544 else
2545 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002546 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2547 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002548 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002549 }
2550 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002551
2552 // Activate workers. This barrier is used by the master to signal
2553 // work for the workers.
2554 syncCTAThreads(CGF);
2555
2556 // OpenMP [2.5, Parallel Construct, p.49]
2557 // There is an implied barrier at the end of a parallel region. After the
2558 // end of a parallel region, only the master thread of the team resumes
2559 // execution of the enclosing task region.
2560 //
2561 // The master waits at this barrier until all workers are done.
2562 syncCTAThreads(CGF);
2563
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002564 if (!CapturedVars.empty())
2565 CGF.EmitRuntimeCall(
2566 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2567
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002568 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002569 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002570 };
2571
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002572 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2573 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002574 if (IsInParallelRegion) {
2575 SeqGen(CGF, Action);
2576 } else if (IsInTargetMasterThreadRegion) {
2577 L0ParallelGen(CGF, Action);
2578 } else {
2579 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002580 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002581 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002582 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002583 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002584 // }
2585 CGBuilderTy &Bld = CGF.Builder;
2586 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002587 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2588 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002589 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002590 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2591 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002592 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002593 // There is no need to emit line number for unconditional branch.
2594 (void)ApplyDebugLocation::CreateEmpty(CGF);
2595 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002596 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2597 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2598 llvm::Value *PL = CGF.EmitRuntimeCall(
2599 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2600 {RTLoc, ThreadID});
2601 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002602 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002603 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002604 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002605 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002606 // There is no need to emit line number for unconditional branch.
2607 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002608 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002609 L0ParallelGen(CGF, Action);
2610 CGF.EmitBranch(ExitBB);
2611 // There is no need to emit line number for unconditional branch.
2612 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002613 // Emit the continuation block for code after the if.
2614 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2615 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002616 };
2617
Alexey Bataev9ff80832018-04-16 20:16:21 +00002618 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002619 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002620 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002621 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002622 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002623 ThenRCG(CGF);
2624 }
2625}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002626
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002627void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002628 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2629 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2630 // Just call the outlined function to execute the parallel region.
2631 // OutlinedFn(&GTid, &zero, CapturedStruct);
2632 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002633 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002634
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002635 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2636 /*DestWidth=*/32, /*Signed=*/1),
2637 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002638 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002639 // ThreadId for serialized parallels is 0.
2640 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002641 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002642 &ThreadIDAddr](CodeGenFunction &CGF,
2643 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002644 Action.Enter(CGF);
2645
2646 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2647 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2648 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2649 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2650 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2651 };
2652 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2653 PrePostActionTy &) {
2654
2655 RegionCodeGenTy RCG(CodeGen);
2656 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2657 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2658 llvm::Value *Args[] = {RTLoc, ThreadID};
2659
2660 NVPTXActionTy Action(
2661 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2662 Args,
2663 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2664 Args);
2665 RCG.setAction(Action);
2666 RCG(CGF);
2667 };
2668
2669 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002670 // In the worker need to use the real thread id.
2671 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002672 RegionCodeGenTy RCG(CodeGen);
2673 RCG(CGF);
2674 } else {
2675 // If we are not in the target region, it is definitely L2 parallelism or
2676 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2677 // need to check for orphaned directives.
2678 RegionCodeGenTy RCG(SeqGen);
2679 RCG(CGF);
2680 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002681}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002682
Alexey Bataeva3924b52019-01-03 16:25:35 +00002683void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2684 // Always emit simple barriers!
2685 if (!CGF.HaveInsertPoint())
2686 return;
2687 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2688 // This function does not use parameters, so we can emit just default values.
2689 llvm::Value *Args[] = {
2690 llvm::ConstantPointerNull::get(
2691 cast<llvm::PointerType>(getIdentTyPointerTy())),
2692 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2693 CGF.EmitRuntimeCall(
2694 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2695}
2696
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002697void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2698 SourceLocation Loc,
2699 OpenMPDirectiveKind Kind, bool,
2700 bool) {
2701 // Always emit simple barriers!
2702 if (!CGF.HaveInsertPoint())
2703 return;
2704 // Build call __kmpc_cancel_barrier(loc, thread_id);
2705 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2706 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2707 getThreadID(CGF, Loc)};
2708 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2709}
2710
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002711void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2712 CodeGenFunction &CGF, StringRef CriticalName,
2713 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2714 const Expr *Hint) {
2715 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2716 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2717 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2718 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2719 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2720
2721 // Fetch team-local id of the thread.
2722 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2723
2724 // Get the width of the team.
2725 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2726
2727 // Initialize the counter variable for the loop.
2728 QualType Int32Ty =
2729 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2730 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2731 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2732 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2733 /*isInit=*/true);
2734
2735 // Block checks if loop counter exceeds upper bound.
2736 CGF.EmitBlock(LoopBB);
2737 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2738 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2739 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2740
2741 // Block tests which single thread should execute region, and which threads
2742 // should go straight to synchronisation point.
2743 CGF.EmitBlock(TestBB);
2744 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2745 llvm::Value *CmpThreadToCounter =
2746 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2747 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2748
2749 // Block emits the body of the critical region.
2750 CGF.EmitBlock(BodyBB);
2751
2752 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002753 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2754 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002755
2756 // After the body surrounded by the critical region, the single executing
2757 // thread will jump to the synchronisation point.
2758 // Block waits for all threads in current team to finish then increments the
2759 // counter variable and returns to the loop.
2760 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002761 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2762 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002763
2764 llvm::Value *IncCounterVal =
2765 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2766 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2767 CGF.EmitBranch(LoopBB);
2768
2769 // Block that is reached when all threads in the team complete the region.
2770 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2771}
2772
Alexey Bataevb2575932018-01-04 20:18:55 +00002773/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002774static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2775 QualType ValTy, QualType CastTy,
2776 SourceLocation Loc) {
2777 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2778 "Cast type must sized.");
2779 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2780 "Val type must sized.");
2781 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2782 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002783 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002784 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2785 CGF.getContext().getTypeSizeInChars(CastTy))
2786 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2787 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2788 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2789 CastTy->hasSignedIntegerRepresentation());
2790 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002791 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2792 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002793 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2794 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002795}
2796
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002797/// This function creates calls to one of two shuffle functions to copy
2798/// variables between lanes in a warp.
2799static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002801 QualType ElemType,
2802 llvm::Value *Offset,
2803 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002804 CodeGenModule &CGM = CGF.CGM;
2805 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002806 CGOpenMPRuntimeNVPTX &RT =
2807 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2808
Alexey Bataeva453f362018-03-19 17:53:56 +00002809 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2810 assert(Size.getQuantity() <= 8 &&
2811 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002812
Alexey Bataeva453f362018-03-19 17:53:56 +00002813 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002814 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2815 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2816
2817 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002818 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2819 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2820 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002821 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002822 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002823
Alexey Bataev9ff80832018-04-16 20:16:21 +00002824 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2825 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002826
Alexey Bataeva453f362018-03-19 17:53:56 +00002827 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002828}
2829
Alexey Bataev12c62902018-06-22 19:10:38 +00002830static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2831 Address DestAddr, QualType ElemType,
2832 llvm::Value *Offset, SourceLocation Loc) {
2833 CGBuilderTy &Bld = CGF.Builder;
2834
2835 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2836 // Create the loop over the big sized data.
2837 // ptr = (void*)Elem;
2838 // ptrEnd = (void*) Elem + 1;
2839 // Step = 8;
2840 // while (ptr + Step < ptrEnd)
2841 // shuffle((int64_t)*ptr);
2842 // Step = 4;
2843 // while (ptr + Step < ptrEnd)
2844 // shuffle((int32_t)*ptr);
2845 // ...
2846 Address ElemPtr = DestAddr;
2847 Address Ptr = SrcAddr;
2848 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
2849 Bld.CreateConstGEP(SrcAddr, 1, Size), CGF.VoidPtrTy);
2850 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2851 if (Size < CharUnits::fromQuantity(IntSize))
2852 continue;
2853 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2854 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2855 /*Signed=*/1);
2856 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2857 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2858 ElemPtr =
2859 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2860 if (Size.getQuantity() / IntSize > 1) {
2861 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2862 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2863 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2864 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2865 CGF.EmitBlock(PreCondBB);
2866 llvm::PHINode *PhiSrc =
2867 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2868 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2869 llvm::PHINode *PhiDest =
2870 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2871 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2872 Ptr = Address(PhiSrc, Ptr.getAlignment());
2873 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2874 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2875 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2876 Ptr.getPointer(), CGF.VoidPtrTy));
2877 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2878 ThenBB, ExitBB);
2879 CGF.EmitBlock(ThenBB);
2880 llvm::Value *Res = createRuntimeShuffleFunction(
2881 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2882 IntType, Offset, Loc);
2883 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002884 Address LocalPtr =
2885 Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2886 Address LocalElemPtr =
Alexey Bataev12c62902018-06-22 19:10:38 +00002887 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002888 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2889 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002890 CGF.EmitBranch(PreCondBB);
2891 CGF.EmitBlock(ExitBB);
2892 } else {
2893 llvm::Value *Res = createRuntimeShuffleFunction(
2894 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2895 IntType, Offset, Loc);
2896 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
2897 Ptr = Bld.CreateConstGEP(Ptr, 1, CharUnits::fromQuantity(IntSize));
2898 ElemPtr =
2899 Bld.CreateConstGEP(ElemPtr, 1, CharUnits::fromQuantity(IntSize));
2900 }
2901 Size = Size % IntSize;
2902 }
2903}
2904
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002905namespace {
2906enum CopyAction : unsigned {
2907 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2908 // the warp using shuffle instructions.
2909 RemoteLaneToThread,
2910 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2911 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002912 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2913 ThreadToScratchpad,
2914 // ScratchpadToThread: Copy from a scratchpad array in global memory
2915 // containing team-reduced data to a thread's stack.
2916 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917};
2918} // namespace
2919
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002920struct CopyOptionsTy {
2921 llvm::Value *RemoteLaneOffset;
2922 llvm::Value *ScratchpadIndex;
2923 llvm::Value *ScratchpadWidth;
2924};
2925
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002926/// Emit instructions to copy a Reduce list, which contains partially
2927/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002928static void emitReductionListCopy(
2929 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2930 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2931 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002932
Alexey Bataev9ff80832018-04-16 20:16:21 +00002933 CodeGenModule &CGM = CGF.CGM;
2934 ASTContext &C = CGM.getContext();
2935 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002936
Alexey Bataev9ff80832018-04-16 20:16:21 +00002937 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2938 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2939 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002940
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002941 // Iterates, element-by-element, through the source Reduce list and
2942 // make a copy.
2943 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002944 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002945 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002946 Address SrcElementAddr = Address::invalid();
2947 Address DestElementAddr = Address::invalid();
2948 Address DestElementPtrAddr = Address::invalid();
2949 // Should we shuffle in an element from a remote lane?
2950 bool ShuffleInElement = false;
2951 // Set to true to update the pointer in the dest Reduce list to a
2952 // newly created element.
2953 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002954 // Increment the src or dest pointer to the scratchpad, for each
2955 // new element.
2956 bool IncrScratchpadSrc = false;
2957 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958
2959 switch (Action) {
2960 case RemoteLaneToThread: {
2961 // Step 1.1: Get the address for the src element in the Reduce list.
2962 Address SrcElementPtrAddr =
2963 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002964 SrcElementAddr = CGF.EmitLoadOfPointer(
2965 SrcElementPtrAddr,
2966 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002967
2968 // Step 1.2: Create a temporary to store the element in the destination
2969 // Reduce list.
2970 DestElementPtrAddr =
2971 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
2972 DestElementAddr =
2973 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2974 ShuffleInElement = true;
2975 UpdateDestListPtr = true;
2976 break;
2977 }
2978 case ThreadCopy: {
2979 // Step 1.1: Get the address for the src element in the Reduce list.
2980 Address SrcElementPtrAddr =
2981 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002982 SrcElementAddr = CGF.EmitLoadOfPointer(
2983 SrcElementPtrAddr,
2984 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002985
2986 // Step 1.2: Get the address for dest element. The destination
2987 // element has already been created on the thread's stack.
2988 DestElementPtrAddr =
2989 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002990 DestElementAddr = CGF.EmitLoadOfPointer(
2991 DestElementPtrAddr,
2992 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002993 break;
2994 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002995 case ThreadToScratchpad: {
2996 // Step 1.1: Get the address for the src element in the Reduce list.
2997 Address SrcElementPtrAddr =
2998 Bld.CreateConstArrayGEP(SrcBase, Idx, CGF.getPointerSize());
Alexey Bataevb2575932018-01-04 20:18:55 +00002999 SrcElementAddr = CGF.EmitLoadOfPointer(
3000 SrcElementPtrAddr,
3001 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003002
3003 // Step 1.2: Get the address for dest element:
3004 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003005 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003006 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003007 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003008 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003009 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003010 ScratchPadElemAbsolutePtrVal =
3011 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003012 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3013 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003014 IncrScratchpadDest = true;
3015 break;
3016 }
3017 case ScratchpadToThread: {
3018 // Step 1.1: Get the address for the src element in the scratchpad.
3019 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003020 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003021 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003022 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003023 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003024 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003025 ScratchPadElemAbsolutePtrVal =
3026 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3027 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3028 C.getTypeAlignInChars(Private->getType()));
3029 IncrScratchpadSrc = true;
3030
3031 // Step 1.2: Create a temporary to store the element in the destination
3032 // Reduce list.
3033 DestElementPtrAddr =
3034 Bld.CreateConstArrayGEP(DestBase, Idx, CGF.getPointerSize());
3035 DestElementAddr =
3036 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3037 UpdateDestListPtr = true;
3038 break;
3039 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003040 }
3041
3042 // Regardless of src and dest of copy, we emit the load of src
3043 // element as this is required in all directions
3044 SrcElementAddr = Bld.CreateElementBitCast(
3045 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003046 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3047 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003048
3049 // Now that all active lanes have read the element in the
3050 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003051 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003052 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3053 RemoteLaneOffset, Private->getExprLoc());
3054 } else {
3055 if (Private->getType()->isScalarType()) {
3056 llvm::Value *Elem =
3057 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3058 Private->getType(), Private->getExprLoc());
3059 // Store the source element value to the dest element address.
3060 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3061 Private->getType());
3062 } else {
3063 CGF.EmitAggregateCopy(
3064 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3065 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3066 Private->getType(), AggValueSlot::DoesNotOverlap);
3067 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003068 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003069
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003070 // Step 3.1: Modify reference in dest Reduce list as needed.
3071 // Modifying the reference in Reduce list to point to the newly
3072 // created element. The element is live in the current function
3073 // scope and that of functions it invokes (i.e., reduce_function).
3074 // RemoteReduceData[i] = (void*)&RemoteElem
3075 if (UpdateDestListPtr) {
3076 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3077 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3078 DestElementPtrAddr, /*Volatile=*/false,
3079 C.VoidPtrTy);
3080 }
3081
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003082 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3083 // address of the next element in scratchpad memory, unless we're currently
3084 // processing the last one. Memory alignment is also taken care of here.
3085 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3086 llvm::Value *ScratchpadBasePtr =
3087 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003088 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3089 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003090 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003091 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003092
3093 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003094 ScratchpadBasePtr = Bld.CreateNUWSub(
3095 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3096 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003097 ScratchpadBasePtr,
3098 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003099 ScratchpadBasePtr = Bld.CreateNUWAdd(
3100 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3101 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003102 ScratchpadBasePtr,
3103 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3104
3105 if (IncrScratchpadDest)
3106 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3107 else /* IncrScratchpadSrc = true */
3108 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3109 }
3110
Alexey Bataev9ff80832018-04-16 20:16:21 +00003111 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003112 }
3113}
3114
3115/// This function emits a helper that gathers Reduce lists from the first
3116/// lane of every active warp to lanes in the first warp.
3117///
3118/// void inter_warp_copy_func(void* reduce_data, num_warps)
3119/// shared smem[warp_size];
3120/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003121/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003122/// If (I am the first lane in each warp)
3123/// Copy my local D to smem[warp_id]
3124/// sync
3125/// if (I am the first warp)
3126/// Copy smem[thread_id] to my local D
3127/// sync
3128static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3129 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003130 QualType ReductionArrayTy,
3131 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003132 ASTContext &C = CGM.getContext();
3133 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003134
3135 // ReduceList: thread local Reduce list.
3136 // At the stage of the computation when this function is called, partially
3137 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003138 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3139 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003140 // NumWarps: number of warps active in the parallel region. This could
3141 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003142 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003143 C.getIntTypeForBitwidth(32, /* Signed */ true),
3144 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145 FunctionArgList Args;
3146 Args.push_back(&ReduceListArg);
3147 Args.push_back(&NumWarpsArg);
3148
Alexey Bataev9ff80832018-04-16 20:16:21 +00003149 const CGFunctionInfo &CGFI =
3150 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003151 auto *Fn = llvm::Function::Create(
3152 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3153 "_omp_reduction_inter_warp_copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003154 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003155 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003157 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158
Alexey Bataev9ff80832018-04-16 20:16:21 +00003159 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160
3161 // This array is used as a medium to transfer, one reduce element at a time,
3162 // the data from the first lane of every warp to lanes in the first warp
3163 // in order to perform the final step of a reduction in a parallel region
3164 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3165 // for reduced latency, as well as to have a distinct copy for concurrently
3166 // executing target regions. The array is declared with common linkage so
3167 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003168 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003169 "__openmp_nvptx_data_transfer_temporary_storage";
3170 llvm::GlobalVariable *TransferMedium =
3171 M.getGlobalVariable(TransferMediumName);
3172 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003173 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003174 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3175 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003176 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177 llvm::Constant::getNullValue(Ty), TransferMediumName,
3178 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3179 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003180 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003181 }
3182
3183 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003184 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003185 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003186 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003187 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003188 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189
3190 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3191 Address LocalReduceList(
3192 Bld.CreatePointerBitCastOrAddrSpaceCast(
3193 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003194 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003195 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3196 CGF.getPointerAlign());
3197
3198 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003199 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200 //
3201 // Warp master copies reduce element to transfer medium in __shared__
3202 // memory.
3203 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003204 unsigned RealTySize =
3205 C.getTypeSizeInChars(Private->getType())
3206 .alignTo(C.getTypeAlignInChars(Private->getType()))
3207 .getQuantity();
3208 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3209 unsigned NumIters = RealTySize / TySize;
3210 if (NumIters == 0)
3211 continue;
3212 QualType CType = C.getIntTypeForBitwidth(
3213 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3214 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3215 CharUnits Align = CharUnits::fromQuantity(TySize);
3216 llvm::Value *Cnt = nullptr;
3217 Address CntAddr = Address::invalid();
3218 llvm::BasicBlock *PrecondBB = nullptr;
3219 llvm::BasicBlock *ExitBB = nullptr;
3220 if (NumIters > 1) {
3221 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3222 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3223 /*Volatile=*/false, C.IntTy);
3224 PrecondBB = CGF.createBasicBlock("precond");
3225 ExitBB = CGF.createBasicBlock("exit");
3226 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3227 // There is no need to emit line number for unconditional branch.
3228 (void)ApplyDebugLocation::CreateEmpty(CGF);
3229 CGF.EmitBlock(PrecondBB);
3230 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3231 llvm::Value *Cmp =
3232 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3233 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3234 CGF.EmitBlock(BodyBB);
3235 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003236 // kmpc_barrier.
3237 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3238 /*EmitChecks=*/false,
3239 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003240 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3241 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3242 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003243
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003244 // if (lane_id == 0)
3245 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3246 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3247 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003248
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003249 // Reduce element = LocalReduceList[i]
3250 Address ElemPtrPtrAddr =
3251 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3252 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3253 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3254 // elemptr = ((CopyType*)(elemptrptr)) + I
3255 Address ElemPtr = Address(ElemPtrPtr, Align);
3256 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3257 if (NumIters > 1) {
3258 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3259 ElemPtr.getAlignment());
3260 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003261
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003262 // Get pointer to location in transfer medium.
3263 // MediumPtr = &medium[warp_id]
3264 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3265 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3266 Address MediumPtr(MediumPtrVal, Align);
3267 // Casting to actual data type.
3268 // MediumPtr = (CopyType*)MediumPtrAddr;
3269 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003270
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003271 // elem = *elemptr
3272 //*MediumPtr = elem
3273 llvm::Value *Elem =
3274 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003275 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003277
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003278 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 CGF.EmitBlock(ElseBB);
3281 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003282
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003283 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003284
Alexey Bataevae51b962018-12-14 21:00:58 +00003285 // kmpc_barrier.
3286 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3287 /*EmitChecks=*/false,
3288 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003289
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003290 //
3291 // Warp 0 copies reduce element from transfer medium.
3292 //
3293 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3294 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3295 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003296
Alexey Bataevae51b962018-12-14 21:00:58 +00003297 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3298 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3299 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3300
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003301 // Up to 32 threads in warp 0 are active.
3302 llvm::Value *IsActiveThread =
3303 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3304 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003305
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003306 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 // SrcMediumPtr = &medium[tid]
3309 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3310 TransferMedium,
3311 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3312 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3313 // SrcMediumVal = *SrcMediumPtr;
3314 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003315
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003316 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
3317 Address TargetElemPtrPtr =
3318 Bld.CreateConstArrayGEP(LocalReduceList, Idx, CGF.getPointerSize());
3319 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3320 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3321 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3322 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3323 if (NumIters > 1) {
3324 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3325 TargetElemPtr.getAlignment());
3326 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003328 // *TargetElemPtr = SrcMediumVal;
3329 llvm::Value *SrcMediumValue =
3330 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003331 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003332 CType);
3333 Bld.CreateBr(W0MergeBB);
3334
3335 CGF.EmitBlock(W0ElseBB);
3336 Bld.CreateBr(W0MergeBB);
3337
3338 CGF.EmitBlock(W0MergeBB);
3339
3340 // While warp 0 copies values from transfer medium, all other warps must
3341 // wait.
Alexey Bataevae51b962018-12-14 21:00:58 +00003342 // kmpc_barrier.
3343 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3344 /*EmitChecks=*/false,
3345 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003346 if (NumIters > 1) {
3347 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3348 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3349 CGF.EmitBranch(PrecondBB);
3350 (void)ApplyDebugLocation::CreateEmpty(CGF);
3351 CGF.EmitBlock(ExitBB);
3352 }
3353 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003354 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003355 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003356 }
3357
3358 CGF.FinishFunction();
3359 return Fn;
3360}
3361
3362/// Emit a helper that reduces data across two OpenMP threads (lanes)
3363/// in the same warp. It uses shuffle instructions to copy over data from
3364/// a remote lane's stack. The reduction algorithm performed is specified
3365/// by the fourth parameter.
3366///
3367/// Algorithm Versions.
3368/// Full Warp Reduce (argument value 0):
3369/// This algorithm assumes that all 32 lanes are active and gathers
3370/// data from these 32 lanes, producing a single resultant value.
3371/// Contiguous Partial Warp Reduce (argument value 1):
3372/// This algorithm assumes that only a *contiguous* subset of lanes
3373/// are active. This happens for the last warp in a parallel region
3374/// when the user specified num_threads is not an integer multiple of
3375/// 32. This contiguous subset always starts with the zeroth lane.
3376/// Partial Warp Reduce (argument value 2):
3377/// This algorithm gathers data from any number of lanes at any position.
3378/// All reduced values are stored in the lowest possible lane. The set
3379/// of problems every algorithm addresses is a super set of those
3380/// addressable by algorithms with a lower version number. Overhead
3381/// increases as algorithm version increases.
3382///
3383/// Terminology
3384/// Reduce element:
3385/// Reduce element refers to the individual data field with primitive
3386/// data types to be combined and reduced across threads.
3387/// Reduce list:
3388/// Reduce list refers to a collection of local, thread-private
3389/// reduce elements.
3390/// Remote Reduce list:
3391/// Remote Reduce list refers to a collection of remote (relative to
3392/// the current thread) reduce elements.
3393///
3394/// We distinguish between three states of threads that are important to
3395/// the implementation of this function.
3396/// Alive threads:
3397/// Threads in a warp executing the SIMT instruction, as distinguished from
3398/// threads that are inactive due to divergent control flow.
3399/// Active threads:
3400/// The minimal set of threads that has to be alive upon entry to this
3401/// function. The computation is correct iff active threads are alive.
3402/// Some threads are alive but they are not active because they do not
3403/// contribute to the computation in any useful manner. Turning them off
3404/// may introduce control flow overheads without any tangible benefits.
3405/// Effective threads:
3406/// In order to comply with the argument requirements of the shuffle
3407/// function, we must keep all lanes holding data alive. But at most
3408/// half of them perform value aggregation; we refer to this half of
3409/// threads as effective. The other half is simply handing off their
3410/// data.
3411///
3412/// Procedure
3413/// Value shuffle:
3414/// In this step active threads transfer data from higher lane positions
3415/// in the warp to lower lane positions, creating Remote Reduce list.
3416/// Value aggregation:
3417/// In this step, effective threads combine their thread local Reduce list
3418/// with Remote Reduce list and store the result in the thread local
3419/// Reduce list.
3420/// Value copy:
3421/// In this step, we deal with the assumption made by algorithm 2
3422/// (i.e. contiguity assumption). When we have an odd number of lanes
3423/// active, say 2k+1, only k threads will be effective and therefore k
3424/// new values will be produced. However, the Reduce list owned by the
3425/// (2k+1)th thread is ignored in the value aggregation. Therefore
3426/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3427/// that the contiguity assumption still holds.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003428static llvm::Value *emitShuffleAndReduceFunction(
3429 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3430 QualType ReductionArrayTy, llvm::Value *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003431 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003432
3433 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003434 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3435 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003436 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003437 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3438 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003439 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003440 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3441 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003442 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003443 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3444 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445 FunctionArgList Args;
3446 Args.push_back(&ReduceListArg);
3447 Args.push_back(&LaneIDArg);
3448 Args.push_back(&RemoteLaneOffsetArg);
3449 Args.push_back(&AlgoVerArg);
3450
Alexey Bataev9ff80832018-04-16 20:16:21 +00003451 const CGFunctionInfo &CGFI =
3452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003453 auto *Fn = llvm::Function::Create(
3454 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3455 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003456 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003457 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003458 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003459 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460
Alexey Bataev9ff80832018-04-16 20:16:21 +00003461 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003462
3463 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3464 Address LocalReduceList(
3465 Bld.CreatePointerBitCastOrAddrSpaceCast(
3466 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3467 C.VoidPtrTy, SourceLocation()),
3468 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3469 CGF.getPointerAlign());
3470
3471 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3472 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3473 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3474
3475 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3476 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3477 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3478
3479 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3480 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3481 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3482
3483 // Create a local thread-private variable to host the Reduce list
3484 // from a remote lane.
3485 Address RemoteReduceList =
3486 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3487
3488 // This loop iterates through the list of reduce elements and copies,
3489 // element by element, from a remote lane in the warp to RemoteReduceList,
3490 // hosted on the thread's stack.
3491 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3492 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003493 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3494 /*ScratchpadIndex=*/nullptr,
3495 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003496
3497 // The actions to be performed on the Remote Reduce list is dependent
3498 // on the algorithm version.
3499 //
3500 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3501 // LaneId % 2 == 0 && Offset > 0):
3502 // do the reduction value aggregation
3503 //
3504 // The thread local variable Reduce list is mutated in place to host the
3505 // reduced data, which is the aggregated value produced from local and
3506 // remote lanes.
3507 //
3508 // Note that AlgoVer is expected to be a constant integer known at compile
3509 // time.
3510 // When AlgoVer==0, the first conjunction evaluates to true, making
3511 // the entire predicate true during compile time.
3512 // When AlgoVer==1, the second conjunction has only the second part to be
3513 // evaluated during runtime. Other conjunctions evaluates to false
3514 // during compile time.
3515 // When AlgoVer==2, the third conjunction has only the second part to be
3516 // evaluated during runtime. Other conjunctions evaluates to false
3517 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003518 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003519
Alexey Bataev9ff80832018-04-16 20:16:21 +00003520 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3521 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003522 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3523
Alexey Bataev9ff80832018-04-16 20:16:21 +00003524 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3525 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3526 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003527 CondAlgo2 = Bld.CreateAnd(
3528 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3529
Alexey Bataev9ff80832018-04-16 20:16:21 +00003530 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003531 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3532
3533 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3534 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3535 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3536 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3537
3538 CGF.EmitBlock(ThenBB);
3539 // reduce_function(LocalReduceList, RemoteReduceList)
3540 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3541 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3542 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3543 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003544 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3545 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003546 Bld.CreateBr(MergeBB);
3547
3548 CGF.EmitBlock(ElseBB);
3549 Bld.CreateBr(MergeBB);
3550
3551 CGF.EmitBlock(MergeBB);
3552
3553 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3554 // Reduce list.
3555 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003556 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003557 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3558
3559 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3560 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3561 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3562 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3563
3564 CGF.EmitBlock(CpyThenBB);
3565 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3566 RemoteReduceList, LocalReduceList);
3567 Bld.CreateBr(CpyMergeBB);
3568
3569 CGF.EmitBlock(CpyElseBB);
3570 Bld.CreateBr(CpyMergeBB);
3571
3572 CGF.EmitBlock(CpyMergeBB);
3573
3574 CGF.FinishFunction();
3575 return Fn;
3576}
3577
3578///
3579/// Design of OpenMP reductions on the GPU
3580///
3581/// Consider a typical OpenMP program with one or more reduction
3582/// clauses:
3583///
3584/// float foo;
3585/// double bar;
3586/// #pragma omp target teams distribute parallel for \
3587/// reduction(+:foo) reduction(*:bar)
3588/// for (int i = 0; i < N; i++) {
3589/// foo += A[i]; bar *= B[i];
3590/// }
3591///
3592/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3593/// all teams. In our OpenMP implementation on the NVPTX device an
3594/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3595/// within a team are mapped to CUDA threads within a threadblock.
3596/// Our goal is to efficiently aggregate values across all OpenMP
3597/// threads such that:
3598///
3599/// - the compiler and runtime are logically concise, and
3600/// - the reduction is performed efficiently in a hierarchical
3601/// manner as follows: within OpenMP threads in the same warp,
3602/// across warps in a threadblock, and finally across teams on
3603/// the NVPTX device.
3604///
3605/// Introduction to Decoupling
3606///
3607/// We would like to decouple the compiler and the runtime so that the
3608/// latter is ignorant of the reduction variables (number, data types)
3609/// and the reduction operators. This allows a simpler interface
3610/// and implementation while still attaining good performance.
3611///
3612/// Pseudocode for the aforementioned OpenMP program generated by the
3613/// compiler is as follows:
3614///
3615/// 1. Create private copies of reduction variables on each OpenMP
3616/// thread: 'foo_private', 'bar_private'
3617/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3618/// to it and writes the result in 'foo_private' and 'bar_private'
3619/// respectively.
3620/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3621/// and store the result on the team master:
3622///
Alexey Bataev8e009032019-01-04 17:25:09 +00003623/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003624/// reduceData, shuffleReduceFn, interWarpCpyFn)
3625///
3626/// where:
3627/// struct ReduceData {
3628/// double *foo;
3629/// double *bar;
3630/// } reduceData
3631/// reduceData.foo = &foo_private
3632/// reduceData.bar = &bar_private
3633///
3634/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3635/// auxiliary functions generated by the compiler that operate on
3636/// variables of type 'ReduceData'. They aid the runtime perform
3637/// algorithmic steps in a data agnostic manner.
3638///
3639/// 'shuffleReduceFn' is a pointer to a function that reduces data
3640/// of type 'ReduceData' across two OpenMP threads (lanes) in the
3641/// same warp. It takes the following arguments as input:
3642///
3643/// a. variable of type 'ReduceData' on the calling lane,
3644/// b. its lane_id,
3645/// c. an offset relative to the current lane_id to generate a
3646/// remote_lane_id. The remote lane contains the second
3647/// variable of type 'ReduceData' that is to be reduced.
3648/// d. an algorithm version parameter determining which reduction
3649/// algorithm to use.
3650///
3651/// 'shuffleReduceFn' retrieves data from the remote lane using
3652/// efficient GPU shuffle intrinsics and reduces, using the
3653/// algorithm specified by the 4th parameter, the two operands
3654/// element-wise. The result is written to the first operand.
3655///
3656/// Different reduction algorithms are implemented in different
3657/// runtime functions, all calling 'shuffleReduceFn' to perform
3658/// the essential reduction step. Therefore, based on the 4th
3659/// parameter, this function behaves slightly differently to
3660/// cooperate with the runtime to ensure correctness under
3661/// different circumstances.
3662///
3663/// 'InterWarpCpyFn' is a pointer to a function that transfers
3664/// reduced variables across warps. It tunnels, through CUDA
3665/// shared memory, the thread-private data of type 'ReduceData'
3666/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003667/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
3668/// The last team writes the global reduced value to memory.
3669///
3670/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
3671/// reduceData, shuffleReduceFn, interWarpCpyFn,
3672/// scratchpadCopyFn, loadAndReduceFn)
3673///
3674/// 'scratchpadCopyFn' is a helper that stores reduced
3675/// data from the team master to a scratchpad array in
3676/// global memory.
3677///
3678/// 'loadAndReduceFn' is a helper that loads data from
3679/// the scratchpad array and reduces it with the input
3680/// operand.
3681///
3682/// These compiler generated functions hide address
3683/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003684/// 5. if ret == 1:
3685/// The team master of the last team stores the reduced
3686/// result to the globals in memory.
3687/// foo += reduceData.foo; bar *= reduceData.bar
3688///
3689///
3690/// Warp Reduction Algorithms
3691///
3692/// On the warp level, we have three algorithms implemented in the
3693/// OpenMP runtime depending on the number of active lanes:
3694///
3695/// Full Warp Reduction
3696///
3697/// The reduce algorithm within a warp where all lanes are active
3698/// is implemented in the runtime as follows:
3699///
3700/// full_warp_reduce(void *reduce_data,
3701/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3702/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
3703/// ShuffleReduceFn(reduce_data, 0, offset, 0);
3704/// }
3705///
3706/// The algorithm completes in log(2, WARPSIZE) steps.
3707///
3708/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
3709/// not used therefore we save instructions by not retrieving lane_id
3710/// from the corresponding special registers. The 4th parameter, which
3711/// represents the version of the algorithm being used, is set to 0 to
3712/// signify full warp reduction.
3713///
3714/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3715///
3716/// #reduce_elem refers to an element in the local lane's data structure
3717/// #remote_elem is retrieved from a remote lane
3718/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3719/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
3720///
3721/// Contiguous Partial Warp Reduction
3722///
3723/// This reduce algorithm is used within a warp where only the first
3724/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
3725/// number of OpenMP threads in a parallel region is not a multiple of
3726/// WARPSIZE. The algorithm is implemented in the runtime as follows:
3727///
3728/// void
3729/// contiguous_partial_reduce(void *reduce_data,
3730/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
3731/// int size, int lane_id) {
3732/// int curr_size;
3733/// int offset;
3734/// curr_size = size;
3735/// mask = curr_size/2;
3736/// while (offset>0) {
3737/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
3738/// curr_size = (curr_size+1)/2;
3739/// offset = curr_size/2;
3740/// }
3741/// }
3742///
3743/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3744///
3745/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3746/// if (lane_id < offset)
3747/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3748/// else
3749/// reduce_elem = remote_elem
3750///
3751/// This algorithm assumes that the data to be reduced are located in a
3752/// contiguous subset of lanes starting from the first. When there is
3753/// an odd number of active lanes, the data in the last lane is not
3754/// aggregated with any other lane's dat but is instead copied over.
3755///
3756/// Dispersed Partial Warp Reduction
3757///
3758/// This algorithm is used within a warp when any discontiguous subset of
3759/// lanes are active. It is used to implement the reduction operation
3760/// across lanes in an OpenMP simd region or in a nested parallel region.
3761///
3762/// void
3763/// dispersed_partial_reduce(void *reduce_data,
3764/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
3765/// int size, remote_id;
3766/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
3767/// do {
3768/// remote_id = next_active_lane_id_right_after_me();
3769/// # the above function returns 0 of no active lane
3770/// # is present right after the current lane.
3771/// size = number_of_active_lanes_in_this_warp();
3772/// logical_lane_id /= 2;
3773/// ShuffleReduceFn(reduce_data, logical_lane_id,
3774/// remote_id-1-threadIdx.x, 2);
3775/// } while (logical_lane_id % 2 == 0 && size > 1);
3776/// }
3777///
3778/// There is no assumption made about the initial state of the reduction.
3779/// Any number of lanes (>=1) could be active at any position. The reduction
3780/// result is returned in the first active lane.
3781///
3782/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
3783///
3784/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
3785/// if (lane_id % 2 == 0 && offset > 0)
3786/// reduce_elem = reduce_elem REDUCE_OP remote_elem
3787/// else
3788/// reduce_elem = remote_elem
3789///
3790///
3791/// Intra-Team Reduction
3792///
3793/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00003794/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003795/// threads in a team. It first reduces within a warp using the
3796/// aforementioned algorithms. We then proceed to gather all such
3797/// reduced values at the first warp.
3798///
3799/// The runtime makes use of the function 'InterWarpCpyFn', which copies
3800/// data from each of the "warp master" (zeroth lane of each warp, where
3801/// warp-reduced data is held) to the zeroth warp. This step reduces (in
3802/// a mathematical sense) the problem of reduction across warp masters in
3803/// a block to the problem of warp reduction.
3804///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003805///
3806/// Inter-Team Reduction
3807///
3808/// Once a team has reduced its data to a single value, it is stored in
3809/// a global scratchpad array. Since each team has a distinct slot, this
3810/// can be done without locking.
3811///
3812/// The last team to write to the scratchpad array proceeds to reduce the
3813/// scratchpad array. One or more workers in the last team use the helper
3814/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
3815/// the k'th worker reduces every k'th element.
3816///
Alexey Bataev8e009032019-01-04 17:25:09 +00003817/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003818/// reduce across workers and compute a globally reduced value.
3819///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003820void CGOpenMPRuntimeNVPTX::emitReduction(
3821 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
3822 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
3823 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
3824 if (!CGF.HaveInsertPoint())
3825 return;
3826
3827 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003828#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003829 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00003830#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003831
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003832 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003833 assert(!TeamsReduction && !ParallelReduction &&
3834 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00003835 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
3836 ReductionOps, Options);
3837 return;
3838 }
3839
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003840 assert((TeamsReduction || ParallelReduction) &&
3841 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003842
Alexey Bataeva1166022018-11-27 21:24:54 +00003843 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003844 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00003845 // or
3846 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00003847 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003848 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003849
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003850 llvm::Value *Res;
3851 if (ParallelReduction) {
Alexey Bataeva1166022018-11-27 21:24:54 +00003852 ASTContext &C = CGM.getContext();
3853 // 1. Build a list of reduction variables.
3854 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3855 auto Size = RHSExprs.size();
3856 for (const Expr *E : Privates) {
3857 if (E->getType()->isVariablyModifiedType())
3858 // Reserve place for array size.
3859 ++Size;
3860 }
3861 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
3862 QualType ReductionArrayTy =
3863 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3864 /*IndexTypeQuals=*/0);
3865 Address ReductionList =
3866 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3867 auto IPriv = Privates.begin();
3868 unsigned Idx = 0;
3869 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
3870 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3871 CGF.getPointerSize());
3872 CGF.Builder.CreateStore(
3873 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3874 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
3875 Elem);
3876 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3877 // Store array size.
3878 ++Idx;
3879 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
3880 CGF.getPointerSize());
3881 llvm::Value *Size = CGF.Builder.CreateIntCast(
3882 CGF.getVLASize(
3883 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3884 .NumElts,
3885 CGF.SizeTy, /*isSigned=*/false);
3886 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3887 Elem);
3888 }
3889 }
3890
3891 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
3892 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3893 ReductionList.getPointer(), CGF.VoidPtrTy);
3894 llvm::Value *ReductionFn = emitReductionFunction(
3895 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
3896 Privates, LHSExprs, RHSExprs, ReductionOps);
3897 llvm::Value *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
3898 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
3899 llvm::Value *InterWarpCopyFn =
3900 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
3901
Alexey Bataev8e009032019-01-04 17:25:09 +00003902 llvm::Value *Args[] = {RTLoc,
3903 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003904 CGF.Builder.getInt32(RHSExprs.size()),
3905 ReductionArrayTySize,
3906 RL,
3907 ShuffleAndReduceFn,
3908 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003909
Alexey Bataev8e009032019-01-04 17:25:09 +00003910 Res = CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
3911 OMPRTL_NVPTX__kmpc_parallel_reduce_nowait_v2),
3912 Args);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003913 } else {
3914 assert(TeamsReduction && "expected teams reduction.");
Alexey Bataeva1166022018-11-27 21:24:54 +00003915 std::string Name = getName({"reduction"});
3916 llvm::Value *Lock = getCriticalRegionLock(Name);
3917 llvm::Value *Args[] = {RTLoc, ThreadId, Lock};
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003918 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00003919 createNVPTXRuntimeFunction(
3920 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_simple),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003921 Args);
3922 }
3923
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003924 // 5. Build if (res == 1)
3925 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
3926 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
3927 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
3928 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
3929 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003930
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003931 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003932 // thread in each team.
3933 // __kmpc_end_reduce{_nowait}(<gtid>);
3934 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003935 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003936
3937 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003938 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003939 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
3940 auto IPriv = Privates.begin();
3941 auto ILHS = LHSExprs.begin();
3942 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00003943 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003944 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
3945 cast<DeclRefExpr>(*IRHS));
3946 ++IPriv;
3947 ++ILHS;
3948 ++IRHS;
3949 }
3950 };
Alexey Bataeva1166022018-11-27 21:24:54 +00003951 if (ParallelReduction) {
3952 llvm::Value *EndArgs[] = {ThreadId};
3953 RegionCodeGenTy RCG(CodeGen);
3954 NVPTXActionTy Action(
3955 nullptr, llvm::None,
3956 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
3957 EndArgs);
3958 RCG.setAction(Action);
3959 RCG(CGF);
3960 } else {
3961 assert(TeamsReduction && "expected teams reduction.");
3962 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
3963 std::string Name = getName({"reduction"});
3964 llvm::Value *Lock = getCriticalRegionLock(Name);
3965 llvm::Value *EndArgs[] = {RTLoc, ThreadId, Lock};
3966 RegionCodeGenTy RCG(CodeGen);
3967 NVPTXActionTy Action(
3968 nullptr, llvm::None,
3969 createNVPTXRuntimeFunction(
3970 OMPRTL_NVPTX__kmpc_nvptx_teams_end_reduce_nowait_simple),
3971 EndArgs);
3972 RCG.setAction(Action);
3973 RCG(CGF);
3974 }
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003975 // There is no need to emit line number for unconditional branch.
3976 (void)ApplyDebugLocation::CreateEmpty(CGF);
3977 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003978}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003979
3980const VarDecl *
3981CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
3982 const VarDecl *NativeParam) const {
3983 if (!NativeParam->getType()->isReferenceType())
3984 return NativeParam;
3985 QualType ArgType = NativeParam->getType();
3986 QualifierCollector QC;
3987 const Type *NonQualTy = QC.strip(ArgType);
3988 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
3989 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
3990 if (Attr->getCaptureKind() == OMPC_map) {
3991 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
3992 LangAS::opencl_global);
3993 }
3994 }
3995 ArgType = CGM.getContext().getPointerType(PointeeTy);
3996 QC.addRestrict();
3997 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00003998 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00003999 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004000 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004001 return ImplicitParamDecl::Create(
4002 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4003 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004004 return ParmVarDecl::Create(
4005 CGM.getContext(),
4006 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004007 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004008 NativeParam->getIdentifier(), ArgType,
4009 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004010}
4011
4012Address
4013CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4014 const VarDecl *NativeParam,
4015 const VarDecl *TargetParam) const {
4016 assert(NativeParam != TargetParam &&
4017 NativeParam->getType()->isReferenceType() &&
4018 "Native arg must not be the same as target arg.");
4019 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4020 QualType NativeParamType = NativeParam->getType();
4021 QualifierCollector QC;
4022 const Type *NonQualTy = QC.strip(NativeParamType);
4023 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4024 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004025 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004026 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004027 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004028 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004029 // First cast to generic.
4030 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4031 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4032 /*AddrSpace=*/0));
4033 // Cast from generic to native address space.
4034 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4035 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4036 NativePointeeAddrSpace));
4037 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4038 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004039 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004040 return NativeParamAddr;
4041}
4042
4043void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
Alexey Bataev3c595a62017-08-14 15:01:03 +00004044 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004045 ArrayRef<llvm::Value *> Args) const {
4046 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004047 TargetArgs.reserve(Args.size());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004048 auto *FnType =
4049 cast<llvm::FunctionType>(OutlinedFn->getType()->getPointerElementType());
4050 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004051 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4052 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4053 break;
4054 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004055 llvm::Type *TargetType = FnType->getParamType(I);
4056 llvm::Value *NativeArg = Args[I];
4057 if (!TargetType->isPointerTy()) {
4058 TargetArgs.emplace_back(NativeArg);
4059 continue;
4060 }
4061 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004062 NativeArg,
4063 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004064 TargetArgs.emplace_back(
4065 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4066 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004067 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004068}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004069
4070/// Emit function which wraps the outline parallel region
4071/// and controls the arguments which are passed to this function.
4072/// The wrapper ensures that the outlined function is called
4073/// with the correct arguments when data is shared.
4074llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4075 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4076 ASTContext &Ctx = CGM.getContext();
4077 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4078
4079 // Create a function that takes as argument the source thread.
4080 FunctionArgList WrapperArgs;
4081 QualType Int16QTy =
4082 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4083 QualType Int32QTy =
4084 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004086 /*Id=*/nullptr, Int16QTy,
4087 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004088 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004089 /*Id=*/nullptr, Int32QTy,
4090 ImplicitParamDecl::Other);
4091 WrapperArgs.emplace_back(&ParallelLevelArg);
4092 WrapperArgs.emplace_back(&WrapperArg);
4093
Alexey Bataev9ff80832018-04-16 20:16:21 +00004094 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004095 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4096
4097 auto *Fn = llvm::Function::Create(
4098 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004099 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004100 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004101 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004102 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004103
4104 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4105 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004106 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004107
4108 const auto *RD = CS.getCapturedRecordDecl();
4109 auto CurField = RD->field_begin();
4110
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004111 Address ZeroAddr = CGF.CreateMemTemp(
4112 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4113 /*Name*/ ".zero.addr");
4114 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004115 // Get the array of arguments.
4116 SmallVector<llvm::Value *, 8> Args;
4117
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004118 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4119 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004120
4121 CGBuilderTy &Bld = CGF.Builder;
4122 auto CI = CS.capture_begin();
4123
4124 // Use global memory for data sharing.
4125 // Handle passing of global args to workers.
4126 Address GlobalArgs =
4127 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4128 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4129 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4130 CGF.EmitRuntimeCall(
4131 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4132 DataSharingArgs);
4133
4134 // Retrieve the shared variables from the list of references returned
4135 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004136 Address SharedArgListAddress = Address::invalid();
4137 if (CS.capture_size() > 0 ||
4138 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4139 SharedArgListAddress = CGF.EmitLoadOfPointer(
4140 GlobalArgs, CGF.getContext()
4141 .getPointerType(CGF.getContext().getPointerType(
4142 CGF.getContext().VoidPtrTy))
4143 .castAs<PointerType>());
4144 }
4145 unsigned Idx = 0;
4146 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4147 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4148 CGF.getPointerSize());
4149 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4150 Src, CGF.SizeTy->getPointerTo());
4151 llvm::Value *LB = CGF.EmitLoadOfScalar(
4152 TypedAddress,
4153 /*Volatile=*/false,
4154 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4155 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4156 Args.emplace_back(LB);
4157 ++Idx;
4158 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx,
4159 CGF.getPointerSize());
4160 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4161 Src, CGF.SizeTy->getPointerTo());
4162 llvm::Value *UB = CGF.EmitLoadOfScalar(
4163 TypedAddress,
4164 /*Volatile=*/false,
4165 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4166 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4167 Args.emplace_back(UB);
4168 ++Idx;
4169 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004170 if (CS.capture_size() > 0) {
4171 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004172 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4173 QualType ElemTy = CurField->getType();
Alexey Bataev17314212018-03-20 15:41:05 +00004174 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx,
4175 CGF.getPointerSize());
4176 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004177 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4178 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4179 /*Volatile=*/false,
4180 CGFContext.getPointerType(ElemTy),
4181 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004182 if (CI->capturesVariableByCopy() &&
4183 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004184 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4185 CI->getLocation());
4186 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004187 Args.emplace_back(Arg);
4188 }
4189 }
4190
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004191 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004192 CGF.FinishFunction();
4193 return Fn;
4194}
4195
4196void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4197 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004198 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4199 return;
4200
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004201 assert(D && "Expected function or captured|block decl.");
4202 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4203 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004204 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4205 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004206 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004207 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004208 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4209 Body = FD->getBody();
4210 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4211 Body = BD->getBody();
4212 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4213 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004214 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004215 if (NeedToDelayGlobalization &&
4216 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4217 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004218 }
4219 if (!Body)
4220 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004221 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004222 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004223 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004224 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004225 TeamAndReductions.first = nullptr;
4226 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004227 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4228 VarChecker.getEscapedVariableLengthDecls();
4229 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004230 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004231 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4232 I->getSecond().MappedParams =
4233 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4234 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4235 I->getSecond().EscapedParameters.insert(
4236 VarChecker.getEscapedParameters().begin(),
4237 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004238 I->getSecond().EscapedVariableLengthDecls.append(
4239 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004240 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004241 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004242 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004243 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004244 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004245 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004246 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004247 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004248 VarChecker.Visit(Body);
4249 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004250 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004251 I->getSecond().SecondaryLocalVarData.emplace();
4252 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4253 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4254 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4255 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004256 Data.insert(
4257 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004258 }
4259 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004260 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004261 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004262 struct GlobalizationScope final : EHScopeStack::Cleanup {
4263 GlobalizationScope() = default;
4264
4265 void Emit(CodeGenFunction &CGF, Flags flags) override {
4266 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004267 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004268 }
4269 };
4270 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004271 }
4272}
4273
4274Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4275 const VarDecl *VD) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004276 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4277 return Address::invalid();
4278
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004279 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004280 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4281 if (I == FunctionGlobalizedDecls.end())
4282 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004283 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004284 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004285 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004286 if (VD->hasAttrs()) {
4287 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4288 E(VD->attr_end());
4289 IT != E; ++IT) {
4290 auto VDI = I->getSecond().LocalVarData.find(
4291 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4292 ->getCanonicalDecl());
4293 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004294 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004295 }
4296 }
4297 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004298}
4299
4300void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004301 FunctionGlobalizedDecls.erase(CGF.CurFn);
4302 CGOpenMPRuntime::functionFinished(CGF);
4303}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004304
4305void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4306 CodeGenFunction &CGF, const OMPLoopDirective &S,
4307 OpenMPDistScheduleClauseKind &ScheduleKind,
4308 llvm::Value *&Chunk) const {
4309 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4310 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4311 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4312 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4313 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004314 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004315 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004316 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4317 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004318}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004319
4320void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4321 CodeGenFunction &CGF, const OMPLoopDirective &S,
4322 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004323 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004324 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004325 // Chunk size is 1 in this case.
4326 llvm::APInt ChunkSize(32, 1);
4327 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4328 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4329 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004330}
Alexey Bataev60705422018-10-30 15:50:12 +00004331
4332void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4333 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4334 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4335 " Expected target-based directive.");
4336 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4337 for (const CapturedStmt::Capture &C : CS->captures()) {
4338 // Capture variables captured by reference in lambdas for target-based
4339 // directives.
4340 if (!C.capturesVariable())
4341 continue;
4342 const VarDecl *VD = C.getCapturedVar();
4343 const auto *RD = VD->getType()
4344 .getCanonicalType()
4345 .getNonReferenceType()
4346 ->getAsCXXRecordDecl();
4347 if (!RD || !RD->isLambda())
4348 continue;
4349 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4350 LValue VDLVal;
4351 if (VD->getType().getCanonicalType()->isReferenceType())
4352 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4353 else
4354 VDLVal = CGF.MakeAddrLValue(
4355 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4356 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4357 FieldDecl *ThisCapture = nullptr;
4358 RD->getCaptureFields(Captures, ThisCapture);
4359 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4360 LValue ThisLVal =
4361 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4362 llvm::Value *CXXThis = CGF.LoadCXXThis();
4363 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4364 }
4365 for (const LambdaCapture &LC : RD->captures()) {
4366 if (LC.getCaptureKind() != LCK_ByRef)
4367 continue;
4368 const VarDecl *VD = LC.getCapturedVar();
4369 if (!CS->capturesVariable(VD))
4370 continue;
4371 auto It = Captures.find(VD);
4372 assert(It != Captures.end() && "Found lambda capture without field.");
4373 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4374 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4375 if (VD->getType().getCanonicalType()->isReferenceType())
4376 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4377 VD->getType().getCanonicalType())
4378 .getAddress();
4379 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4380 }
4381 }
4382}
4383
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004384// Get current CudaArch and ignore any unknown values
4385static CudaArch getCudaArch(CodeGenModule &CGM) {
4386 if (!CGM.getTarget().hasFeature("ptx"))
4387 return CudaArch::UNKNOWN;
4388 llvm::StringMap<bool> Features;
4389 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4390 CGM.getTarget().getTargetOpts().CPU,
4391 CGM.getTarget().getTargetOpts().Features);
4392 for (const auto &Feature : Features) {
4393 if (Feature.getValue()) {
4394 CudaArch Arch = StringToCudaArch(Feature.getKey());
4395 if (Arch != CudaArch::UNKNOWN)
4396 return Arch;
4397 }
4398 }
4399 return CudaArch::UNKNOWN;
4400}
4401
4402/// Check to see if target architecture supports unified addressing which is
4403/// a restriction for OpenMP requires clause "unified_shared_memory".
4404void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4405 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4406 for (const OMPClause *Clause : D->clauselists()) {
4407 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4408 switch (getCudaArch(CGM)) {
4409 case CudaArch::SM_20:
4410 case CudaArch::SM_21:
4411 case CudaArch::SM_30:
4412 case CudaArch::SM_32:
4413 case CudaArch::SM_35:
4414 case CudaArch::SM_37:
4415 case CudaArch::SM_50:
4416 case CudaArch::SM_52:
4417 case CudaArch::SM_53:
4418 case CudaArch::SM_60:
4419 case CudaArch::SM_61:
4420 case CudaArch::SM_62:
4421 CGM.Error(Clause->getBeginLoc(),
4422 "Target architecture does not support unified addressing");
4423 return;
4424 case CudaArch::SM_70:
4425 case CudaArch::SM_72:
4426 case CudaArch::SM_75:
4427 case CudaArch::GFX600:
4428 case CudaArch::GFX601:
4429 case CudaArch::GFX700:
4430 case CudaArch::GFX701:
4431 case CudaArch::GFX702:
4432 case CudaArch::GFX703:
4433 case CudaArch::GFX704:
4434 case CudaArch::GFX801:
4435 case CudaArch::GFX802:
4436 case CudaArch::GFX803:
4437 case CudaArch::GFX810:
4438 case CudaArch::GFX900:
4439 case CudaArch::GFX902:
4440 case CudaArch::GFX904:
4441 case CudaArch::GFX906:
4442 case CudaArch::GFX909:
4443 case CudaArch::UNKNOWN:
4444 break;
4445 case CudaArch::LAST:
4446 llvm_unreachable("Unexpected Cuda arch.");
4447 }
4448 }
4449 }
4450}
4451
Alexey Bataeve4090182018-11-02 14:54:07 +00004452/// Get number of SMs and number of blocks per SM.
4453static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4454 std::pair<unsigned, unsigned> Data;
4455 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4456 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4457 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4458 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4459 if (Data.first && Data.second)
4460 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004461 switch (getCudaArch(CGM)) {
4462 case CudaArch::SM_20:
4463 case CudaArch::SM_21:
4464 case CudaArch::SM_30:
4465 case CudaArch::SM_32:
4466 case CudaArch::SM_35:
4467 case CudaArch::SM_37:
4468 case CudaArch::SM_50:
4469 case CudaArch::SM_52:
4470 case CudaArch::SM_53:
4471 return {16, 16};
4472 case CudaArch::SM_60:
4473 case CudaArch::SM_61:
4474 case CudaArch::SM_62:
4475 return {56, 32};
4476 case CudaArch::SM_70:
4477 case CudaArch::SM_72:
4478 case CudaArch::SM_75:
4479 return {84, 32};
4480 case CudaArch::GFX600:
4481 case CudaArch::GFX601:
4482 case CudaArch::GFX700:
4483 case CudaArch::GFX701:
4484 case CudaArch::GFX702:
4485 case CudaArch::GFX703:
4486 case CudaArch::GFX704:
4487 case CudaArch::GFX801:
4488 case CudaArch::GFX802:
4489 case CudaArch::GFX803:
4490 case CudaArch::GFX810:
4491 case CudaArch::GFX900:
4492 case CudaArch::GFX902:
4493 case CudaArch::GFX904:
4494 case CudaArch::GFX906:
4495 case CudaArch::GFX909:
4496 case CudaArch::UNKNOWN:
4497 break;
4498 case CudaArch::LAST:
4499 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004500 }
4501 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4502}
4503
4504void CGOpenMPRuntimeNVPTX::clear() {
4505 if (!GlobalizedRecords.empty()) {
4506 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004507 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4508 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004509 RecordDecl *StaticRD = C.buildImplicitRecord(
4510 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4511 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004512 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4513 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4514 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004515 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4516 if (Records.Records.empty())
4517 continue;
4518 unsigned Size = 0;
4519 unsigned RecAlignment = 0;
4520 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004521 QualType RDTy = C.getRecordType(RD);
4522 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004523 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004524 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004525 Size =
4526 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4527 }
4528 Size = llvm::alignTo(Size, RecAlignment);
4529 llvm::APInt ArySize(/*numBits=*/64, Size);
4530 QualType SubTy = C.getConstantArrayType(
4531 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004532 const bool UseSharedMemory = Size <= SharedMemorySize;
4533 auto *Field =
4534 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4535 SourceLocation(), SourceLocation(), nullptr, SubTy,
4536 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4537 /*BW=*/nullptr, /*Mutable=*/false,
4538 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004539 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004540 if (UseSharedMemory) {
4541 SharedStaticRD->addDecl(Field);
4542 SharedRecs.push_back(&Records);
4543 } else {
4544 StaticRD->addDecl(Field);
4545 GlobalRecs.push_back(&Records);
4546 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004547 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004548 Records.UseSharedMemory->setInitializer(
4549 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
4550 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00004551 // Allocate SharedMemorySize buffer for the shared memory.
4552 // FIXME: nvlink does not handle weak linkage correctly (object with the
4553 // different size are reported as erroneous).
4554 // Restore this code as sson as nvlink is fixed.
4555 if (!SharedStaticRD->field_empty()) {
4556 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
4557 QualType SubTy = C.getConstantArrayType(
4558 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
4559 auto *Field = FieldDecl::Create(
4560 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
4561 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4562 /*BW=*/nullptr, /*Mutable=*/false,
4563 /*InitStyle=*/ICIS_NoInit);
4564 Field->setAccess(AS_public);
4565 SharedStaticRD->addDecl(Field);
4566 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004567 SharedStaticRD->completeDefinition();
4568 if (!SharedStaticRD->field_empty()) {
4569 QualType StaticTy = C.getRecordType(SharedStaticRD);
4570 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
4571 auto *GV = new llvm::GlobalVariable(
4572 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004573 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004574 llvm::Constant::getNullValue(LLVMStaticTy),
4575 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
4576 llvm::GlobalValue::NotThreadLocal,
4577 C.getTargetAddressSpace(LangAS::cuda_shared));
4578 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4579 GV, CGM.VoidPtrTy);
4580 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
4581 Rec->Buffer->replaceAllUsesWith(Replacement);
4582 Rec->Buffer->eraseFromParent();
4583 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004584 }
4585 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004586 if (!StaticRD->field_empty()) {
4587 QualType StaticTy = C.getRecordType(StaticRD);
4588 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
4589 llvm::APInt Size1(32, SMsBlockPerSM.second);
4590 QualType Arr1Ty =
4591 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
4592 /*IndexTypeQuals=*/0);
4593 llvm::APInt Size2(32, SMsBlockPerSM.first);
4594 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
4595 /*IndexTypeQuals=*/0);
4596 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
4597 auto *GV = new llvm::GlobalVariable(
4598 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004599 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004600 llvm::Constant::getNullValue(LLVMArr2Ty),
4601 "_openmp_static_glob_rd_$_");
4602 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
4603 GV, CGM.VoidPtrTy);
4604 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
4605 Rec->Buffer->replaceAllUsesWith(Replacement);
4606 Rec->Buffer->eraseFromParent();
4607 }
4608 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004609 }
4610 CGOpenMPRuntime::clear();
4611}