blob: ca1e9311b6b4f0543326ea911689918c3086573a [file] [log] [blame]
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Samuel Antao45bfe4c2016-02-08 15:59:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation specialized to NVPTX
10// targets.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGOpenMPRuntimeNVPTX.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000015#include "CodeGenFunction.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000016#include "clang/AST/DeclOpenMP.h"
Carlo Bertollic6872252016-04-04 15:55:02 +000017#include "clang/AST/StmtOpenMP.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000018#include "clang/AST/StmtVisitor.h"
Alexey Bataeve4090182018-11-02 14:54:07 +000019#include "clang/Basic/Cuda.h"
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000020#include "llvm/ADT/SmallPtrSet.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000021
22using namespace clang;
23using namespace CodeGen;
24
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000025namespace {
26enum OpenMPRTLFunctionNVPTX {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000027 /// Call to void __kmpc_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000028 /// int16_t RequiresOMPRuntime);
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +000029 OMPRTL_NVPTX__kmpc_kernel_init,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030 /// Call to void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +000031 OMPRTL_NVPTX__kmpc_kernel_deinit,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000032 /// Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +000033 /// int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +000034 OMPRTL_NVPTX__kmpc_spmd_kernel_init,
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +000035 /// Call to void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
36 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037 /// Call to void __kmpc_kernel_prepare_parallel(void
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000038 /// *outlined_function, int16_t
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +000039 /// IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000040 OMPRTL_NVPTX__kmpc_kernel_prepare_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000041 /// Call to bool __kmpc_kernel_parallel(void **outlined_function,
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +000042 /// int16_t IsOMPRuntimeInitialized);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000043 OMPRTL_NVPTX__kmpc_kernel_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044 /// Call to void __kmpc_kernel_end_parallel();
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +000045 OMPRTL_NVPTX__kmpc_kernel_end_parallel,
46 /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
47 /// global_tid);
48 OMPRTL_NVPTX__kmpc_serialized_parallel,
49 /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
50 /// global_tid);
51 OMPRTL_NVPTX__kmpc_end_serialized_parallel,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 /// Call to int32_t __kmpc_shuffle_int32(int32_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000053 /// int16_t lane_offset, int16_t warp_size);
54 OMPRTL_NVPTX__kmpc_shuffle_int32,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055 /// Call to int64_t __kmpc_shuffle_int64(int64_t element,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000056 /// int16_t lane_offset, int16_t warp_size);
57 OMPRTL_NVPTX__kmpc_shuffle_int64,
Alexey Bataev8e009032019-01-04 17:25:09 +000058 /// Call to __kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc, kmp_int32
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +000059 /// global_tid, kmp_int32 num_vars, size_t reduce_size, void* reduce_data,
60 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
61 /// lane_offset, int16_t shortCircuit),
62 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num));
Alexey Bataev8061acd2019-02-20 16:36:22 +000063 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2,
64 /// Call to __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
65 /// global_tid, void *global_buffer, int32_t num_of_records, void*
66 /// reduce_data,
67 /// void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
68 /// lane_offset, int16_t shortCircuit),
69 /// void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
70 /// (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
71 /// void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
72 /// void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
73 /// int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
74 /// *buffer, int idx, void *reduce_data));
75 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// Call to __kmpc_nvptx_end_reduce_nowait(int32_t global_tid);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000077 OMPRTL_NVPTX__kmpc_end_reduce_nowait,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000078 /// Call to void __kmpc_data_sharing_init_stack();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000079 OMPRTL_NVPTX__kmpc_data_sharing_init_stack,
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +000080 /// Call to void __kmpc_data_sharing_init_stack_spmd();
81 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd,
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000082 /// Call to void* __kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000083 /// int16_t UseSharedMemory);
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +000084 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Call to void __kmpc_data_sharing_pop_stack(void *a);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000086 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000087 /// Call to void __kmpc_begin_sharing_variables(void ***args,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000088 /// size_t n_args);
89 OMPRTL_NVPTX__kmpc_begin_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Call to void __kmpc_end_sharing_variables();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000091 OMPRTL_NVPTX__kmpc_end_sharing_variables,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000092 /// Call to void __kmpc_get_shared_variables(void ***GlobalArgs)
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +000093 OMPRTL_NVPTX__kmpc_get_shared_variables,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +000094 /// Call to uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32
95 /// global_tid);
96 OMPRTL_NVPTX__kmpc_parallel_level,
Alexey Bataev673110d2018-05-16 13:36:30 +000097 /// Call to int8_t __kmpc_is_spmd_exec_mode();
98 OMPRTL_NVPTX__kmpc_is_spmd_exec_mode,
Alexey Bataev8e009032019-01-04 17:25:09 +000099 /// Call to void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
100 /// const void *buf, size_t size, int16_t is_shared, const void **res);
Alexey Bataeve4090182018-11-02 14:54:07 +0000101 OMPRTL_NVPTX__kmpc_get_team_static_memory,
Alexey Bataev8e009032019-01-04 17:25:09 +0000102 /// Call to void __kmpc_restore_team_static_memory(int16_t
103 /// isSPMDExecutionMode, int16_t is_shared);
Alexey Bataeve4090182018-11-02 14:54:07 +0000104 OMPRTL_NVPTX__kmpc_restore_team_static_memory,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000105 /// Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataevc3028ca2018-12-04 15:03:25 +0000106 OMPRTL__kmpc_barrier,
Alexey Bataeva3924b52019-01-03 16:25:35 +0000107 /// Call to void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
108 /// global_tid);
109 OMPRTL__kmpc_barrier_simple_spmd,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000110};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000111
112/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
113class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000114 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000116 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000118 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000119 llvm::BasicBlock *ContBlock = nullptr;
120
121public:
James Y Knight9871db02019-02-05 16:42:33 +0000122 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
123 ArrayRef<llvm::Value *> EnterArgs,
124 llvm::FunctionCallee ExitCallee,
125 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000126 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
127 ExitArgs(ExitArgs), Conditional(Conditional) {}
128 void Enter(CodeGenFunction &CGF) override {
129 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
130 if (Conditional) {
131 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
132 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
133 ContBlock = CGF.createBasicBlock("omp_if.end");
134 // Generate the branch (If-stmt)
135 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
136 CGF.EmitBlock(ThenBlock);
137 }
138 }
139 void Done(CodeGenFunction &CGF) {
140 // Emit the rest of blocks/branches
141 CGF.EmitBranch(ContBlock);
142 CGF.EmitBlock(ContBlock, true);
143 }
144 void Exit(CodeGenFunction &CGF) override {
145 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
146 }
147};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000148
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000149/// A class to track the execution mode when codegening directives within
150/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
151/// to the target region and used by containing directives such as 'parallel'
152/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000153class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000154private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000155 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
156 CGOpenMPRuntimeNVPTX::EM_Unknown;
157 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
158 bool SavedRuntimeMode = false;
159 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000160
161public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000162 /// Constructor for Non-SPMD mode.
163 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
164 : ExecMode(ExecMode) {
165 SavedExecMode = ExecMode;
166 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000167 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000168 /// Constructor for SPMD mode.
169 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
170 bool &RuntimeMode, bool FullRuntimeMode)
171 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
172 SavedExecMode = ExecMode;
173 SavedRuntimeMode = RuntimeMode;
174 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
175 RuntimeMode = FullRuntimeMode;
176 }
177 ~ExecutionRuntimeModesRAII() {
178 ExecMode = SavedExecMode;
179 if (RuntimeMode)
180 *RuntimeMode = SavedRuntimeMode;
181 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000182};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000183
184/// GPU Configuration: This information can be derived from cuda registers,
185/// however, providing compile time constants helps generate more efficient
186/// code. For all practical purposes this is fine because the configuration
187/// is the same for all known NVPTX architectures.
188enum MachineConfiguration : unsigned {
189 WarpSize = 32,
190 /// Number of bits required to represent a lane identifier, which is
191 /// computed as log_2(WarpSize).
192 LaneIDBits = 5,
193 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000194
195 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000196 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000197
198 /// Maximal size of the shared memory buffer.
199 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000200};
201
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000202static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
203 RefExpr = RefExpr->IgnoreParens();
204 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
205 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
206 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
207 Base = TempASE->getBase()->IgnoreParenImpCasts();
208 RefExpr = Base;
209 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
210 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
211 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
212 Base = TempOASE->getBase()->IgnoreParenImpCasts();
213 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
214 Base = TempASE->getBase()->IgnoreParenImpCasts();
215 RefExpr = Base;
216 }
217 RefExpr = RefExpr->IgnoreParenImpCasts();
218 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
219 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
220 const auto *ME = cast<MemberExpr>(RefExpr);
221 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
222}
223
Alexey Bataev2adecff2018-09-21 14:22:53 +0000224
225static RecordDecl *buildRecordForGlobalizedVars(
226 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000227 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000228 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000229 &MappedDeclsFields, int BufSize) {
Fangrui Song899d1392019-04-24 14:43:05 +0000230 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 return nullptr;
233 SmallVector<VarsDataTy, 4> GlobalizedVars;
234 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 GlobalizedVars.emplace_back(
236 CharUnits::fromQuantity(std::max(
237 C.getDeclAlign(D).getQuantity(),
238 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
239 D);
240 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000241 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
Fangrui Song899d1392019-04-24 14:43:05 +0000242 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
243 return L.first > R.first;
244 });
245
Alexey Bataev2adecff2018-09-21 14:22:53 +0000246 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000247 // /* globalized vars */[WarSize] align (max(decl_align,
248 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000249 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 // };
251 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
252 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
254 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000255 for (const auto &Pair : GlobalizedVars) {
256 const ValueDecl *VD = Pair.second;
257 QualType Type = VD->getType();
258 if (Type->isLValueReferenceType())
259 Type = C.getPointerType(Type.getNonReferenceType());
260 else
261 Type = Type.getNonReferenceType();
262 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000263 FieldDecl *Field;
264 if (SingleEscaped.count(VD)) {
265 Field = FieldDecl::Create(
266 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
267 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
268 /*BW=*/nullptr, /*Mutable=*/false,
269 /*InitStyle=*/ICIS_NoInit);
270 Field->setAccess(AS_public);
271 if (VD->hasAttrs()) {
272 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
273 E(VD->getAttrs().end());
274 I != E; ++I)
275 Field->addAttr(*I);
276 }
277 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000278 llvm::APInt ArraySize(32, BufSize);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000279 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
280 Field = FieldDecl::Create(
281 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
282 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
283 /*BW=*/nullptr, /*Mutable=*/false,
284 /*InitStyle=*/ICIS_NoInit);
285 Field->setAccess(AS_public);
286 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
287 static_cast<CharUnits::QuantityType>(
288 GlobalMemoryAlignment)));
289 Field->addAttr(AlignedAttr::CreateImplicit(
290 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
291 IntegerLiteral::Create(C, Align,
292 C.getIntTypeForBitwidth(32, /*Signed=*/0),
293 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000294 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000295 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000296 MappedDeclsFields.try_emplace(VD, Field);
297 }
298 GlobalizedRD->completeDefinition();
299 return GlobalizedRD;
300}
301
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000302/// Get the list of variables that can escape their declaration context.
303class CheckVarsEscapingDeclContext final
304 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
305 CodeGenFunction &CGF;
306 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000307 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000308 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000309 RecordDecl *GlobalizedRD = nullptr;
310 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000311 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000312 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000313
314 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000315 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000316 if (!isa<VarDecl>(VD) ||
317 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000318 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000319 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000320 // Use user-specified allocation.
321 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
322 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000323 // Variables captured by value must be globalized.
324 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000325 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000326 // Check if need to capture the variable that was already captured by
327 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000328 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000329 if (!FD->hasAttrs())
330 return;
331 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
332 if (!Attr)
333 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000334 if (((Attr->getCaptureKind() != OMPC_map) &&
335 !isOpenMPPrivate(
336 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
337 ((Attr->getCaptureKind() == OMPC_map) &&
338 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000339 return;
340 }
341 if (!FD->getType()->isReferenceType()) {
342 assert(!VD->getType()->isVariablyModifiedType() &&
343 "Parameter captured by value with variably modified type");
344 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000345 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000346 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000347 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000348 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000349 }
350 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000351 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000352 VD->getType()->isReferenceType())
353 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000354 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000355 if (VD->getType()->isVariablyModifiedType())
356 EscapedVariableLengthDecls.insert(VD);
357 else
358 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000359 }
360
361 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000362 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000363 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000364 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
365 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
366 const bool SavedAllEscaped = AllEscaped;
367 AllEscaped = VD->getType()->isLValueReferenceType();
368 Visit(VarD->getInit());
369 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000370 }
371 }
372 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000373 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
374 ArrayRef<OMPClause *> Clauses,
375 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000376 if (!S)
377 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000378 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000379 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
380 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000381 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
382 if (IsCombinedParallelRegion) {
383 // Check if the variable is privatized in the combined construct and
384 // those private copies must be shared in the inner parallel
385 // directive.
386 IsForCombinedParallelRegion = false;
387 for (const OMPClause *C : Clauses) {
388 if (!isOpenMPPrivate(C->getClauseKind()) ||
389 C->getClauseKind() == OMPC_reduction ||
390 C->getClauseKind() == OMPC_linear ||
391 C->getClauseKind() == OMPC_private)
392 continue;
393 ArrayRef<const Expr *> Vars;
394 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
395 Vars = PC->getVarRefs();
396 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
397 Vars = PC->getVarRefs();
398 else
399 llvm_unreachable("Unexpected clause.");
400 for (const auto *E : Vars) {
401 const Decl *D =
402 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
403 if (D == VD->getCanonicalDecl()) {
404 IsForCombinedParallelRegion = true;
405 break;
406 }
407 }
408 if (IsForCombinedParallelRegion)
409 break;
410 }
411 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000412 markAsEscaped(VD);
413 if (isa<OMPCapturedExprDecl>(VD))
414 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000415 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000416 }
417 }
418 }
419
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000420 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000421 assert(!GlobalizedRD &&
422 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000423 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000424 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000425 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
426 else
427 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000428 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000429 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000430 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000431 }
432
433public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000434 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
435 ArrayRef<const ValueDecl *> TeamsReductions)
436 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
437 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000438 virtual ~CheckVarsEscapingDeclContext() = default;
439 void VisitDeclStmt(const DeclStmt *S) {
440 if (!S)
441 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000442 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000443 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
444 VisitValueDecl(VD);
445 }
446 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
447 if (!D)
448 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000449 if (!D->hasAssociatedStmt())
450 return;
451 if (const auto *S =
452 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
453 // Do not analyze directives that do not actually require capturing,
454 // like `omp for` or `omp simd` directives.
455 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
456 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
457 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
458 VisitStmt(S->getCapturedStmt());
459 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000460 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000461 VisitOpenMPCapturedStmt(
462 S, D->clauses(),
463 CaptureRegions.back() == OMPD_parallel &&
464 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000465 }
466 }
467 void VisitCapturedStmt(const CapturedStmt *S) {
468 if (!S)
469 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000470 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
472 const ValueDecl *VD = C.getCapturedVar();
473 markAsEscaped(VD);
474 if (isa<OMPCapturedExprDecl>(VD))
475 VisitValueDecl(VD);
476 }
477 }
478 }
479 void VisitLambdaExpr(const LambdaExpr *E) {
480 if (!E)
481 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000482 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000483 if (C.capturesVariable()) {
484 if (C.getCaptureKind() == LCK_ByRef) {
485 const ValueDecl *VD = C.getCapturedVar();
486 markAsEscaped(VD);
487 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
488 VisitValueDecl(VD);
489 }
490 }
491 }
492 }
493 void VisitBlockExpr(const BlockExpr *E) {
494 if (!E)
495 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000496 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000497 if (C.isByRef()) {
498 const VarDecl *VD = C.getVariable();
499 markAsEscaped(VD);
500 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
501 VisitValueDecl(VD);
502 }
503 }
504 }
505 void VisitCallExpr(const CallExpr *E) {
506 if (!E)
507 return;
508 for (const Expr *Arg : E->arguments()) {
509 if (!Arg)
510 continue;
511 if (Arg->isLValue()) {
512 const bool SavedAllEscaped = AllEscaped;
513 AllEscaped = true;
514 Visit(Arg);
515 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000516 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000517 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000518 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000519 }
520 Visit(E->getCallee());
521 }
522 void VisitDeclRefExpr(const DeclRefExpr *E) {
523 if (!E)
524 return;
525 const ValueDecl *VD = E->getDecl();
526 if (AllEscaped)
527 markAsEscaped(VD);
528 if (isa<OMPCapturedExprDecl>(VD))
529 VisitValueDecl(VD);
530 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
531 if (VarD->isInitCapture())
532 VisitValueDecl(VD);
533 }
534 void VisitUnaryOperator(const UnaryOperator *E) {
535 if (!E)
536 return;
537 if (E->getOpcode() == UO_AddrOf) {
538 const bool SavedAllEscaped = AllEscaped;
539 AllEscaped = true;
540 Visit(E->getSubExpr());
541 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000542 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000543 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000544 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000545 }
546 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
547 if (!E)
548 return;
549 if (E->getCastKind() == CK_ArrayToPointerDecay) {
550 const bool SavedAllEscaped = AllEscaped;
551 AllEscaped = true;
552 Visit(E->getSubExpr());
553 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000554 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000555 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000556 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000557 }
558 void VisitExpr(const Expr *E) {
559 if (!E)
560 return;
561 bool SavedAllEscaped = AllEscaped;
562 if (!E->isLValue())
563 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000564 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000565 if (Child)
566 Visit(Child);
567 AllEscaped = SavedAllEscaped;
568 }
569 void VisitStmt(const Stmt *S) {
570 if (!S)
571 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000572 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000573 if (Child)
574 Visit(Child);
575 }
576
Alexey Bataevc99042b2018-03-15 18:10:54 +0000577 /// Returns the record that handles all the escaped local variables and used
578 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000579 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000580 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000581 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000582 return GlobalizedRD;
583 }
584
Alexey Bataevc99042b2018-03-15 18:10:54 +0000585 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000586 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
587 assert(GlobalizedRD &&
588 "Record for globalized variables must be generated already.");
589 auto I = MappedDeclsFields.find(VD);
590 if (I == MappedDeclsFields.end())
591 return nullptr;
592 return I->getSecond();
593 }
594
Alexey Bataevc99042b2018-03-15 18:10:54 +0000595 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000596 ArrayRef<const ValueDecl *> getEscapedDecls() const {
597 return EscapedDecls.getArrayRef();
598 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000599
600 /// Checks if the escaped local variable is actually a parameter passed by
601 /// value.
602 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
603 return EscapedParameters;
604 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000605
606 /// Returns the list of the escaped variables with the variably modified
607 /// types.
608 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
609 return EscapedVariableLengthDecls.getArrayRef();
610 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000611};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000612} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000613
614/// Get the GPU warp size.
615static llvm::Value *getNVPTXWarpSize(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_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000619 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000620}
621
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000622/// Get the id of the current thread on the GPU.
623static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000624 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000625 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000626 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000627 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000628}
629
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000630/// Get the id of the warp in the block.
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 *getNVPTXWarpID(CodeGenFunction &CGF) {
634 CGBuilderTy &Bld = CGF.Builder;
635 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
636}
637
638/// Get the id of the current lane in the Warp.
639/// We assume that the warp size is 32, which is always the case
640/// on the NVPTX device, to generate more efficient code.
641static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
642 CGBuilderTy &Bld = CGF.Builder;
643 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
644 "nvptx_lane_id");
645}
646
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000647/// Get the maximum number of threads in a block of the GPU.
648static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000649 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000650 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000651 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000652 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000653}
654
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000655/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000656/// For the 'generic' execution mode, the runtime encodes thread_limit in
657/// the launch parameters, always starting thread_limit+warpSize threads per
658/// CTA. The threads in the last warp are reserved for master execution.
659/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
660static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000661 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000662 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000663 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000664 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000665 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
666 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000667}
668
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000669/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000670/// The master thread id is the first thread (lane) of the last warp in the
671/// GPU block. Warp size is assumed to be some power of 2.
672/// Thread id is 0 indexed.
673/// E.g: If NumThreads is 33, master id is 32.
674/// If NumThreads is 64, master id is 32.
675/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000676static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000677 CGBuilderTy &Bld = CGF.Builder;
678 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
679
680 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000681 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682
Alexey Bataeve290ec02018-04-06 16:03:36 +0000683 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000684 Bld.CreateNot(Mask), "master_tid");
685}
686
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000687CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000688 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000689 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
690 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000692}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000693
694void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
695 CodeGenModule &CGM) {
696 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000697
698 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000699 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000700 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000701 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000702 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703}
704
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000705CGOpenMPRuntimeNVPTX::ExecutionMode
706CGOpenMPRuntimeNVPTX::getExecutionMode() const {
707 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000708}
709
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000710static CGOpenMPRuntimeNVPTX::DataSharingMode
711getDataSharingMode(CodeGenModule &CGM) {
712 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
713 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000714}
715
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000716/// Check for inner (nested) SPMD construct, if any
717static bool hasNestedSPMDDirective(ASTContext &Ctx,
718 const OMPExecutableDirective &D) {
719 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000720 const auto *Body =
721 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000722 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000723
Alexey Bataev5c427362019-04-10 19:11:33 +0000724 if (const auto *NestedDir =
725 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000726 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727 switch (D.getDirectiveKind()) {
728 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000729 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000730 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000731 if (DKind == OMPD_teams) {
732 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
733 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000734 if (!Body)
735 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000736 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
737 if (const auto *NND =
738 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000739 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000740 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000741 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000742 }
743 }
744 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000745 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000746 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000747 case OMPD_target_simd:
748 case OMPD_target_parallel:
749 case OMPD_target_parallel_for:
750 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000751 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000752 case OMPD_target_teams_distribute_simd:
753 case OMPD_target_teams_distribute_parallel_for:
754 case OMPD_target_teams_distribute_parallel_for_simd:
755 case OMPD_parallel:
756 case OMPD_for:
757 case OMPD_parallel_for:
758 case OMPD_parallel_sections:
759 case OMPD_for_simd:
760 case OMPD_parallel_for_simd:
761 case OMPD_cancel:
762 case OMPD_cancellation_point:
763 case OMPD_ordered:
764 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000765 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000766 case OMPD_task:
767 case OMPD_simd:
768 case OMPD_sections:
769 case OMPD_section:
770 case OMPD_single:
771 case OMPD_master:
772 case OMPD_critical:
773 case OMPD_taskyield:
774 case OMPD_barrier:
775 case OMPD_taskwait:
776 case OMPD_taskgroup:
777 case OMPD_atomic:
778 case OMPD_flush:
779 case OMPD_teams:
780 case OMPD_target_data:
781 case OMPD_target_exit_data:
782 case OMPD_target_enter_data:
783 case OMPD_distribute:
784 case OMPD_distribute_simd:
785 case OMPD_distribute_parallel_for:
786 case OMPD_distribute_parallel_for_simd:
787 case OMPD_teams_distribute:
788 case OMPD_teams_distribute_simd:
789 case OMPD_teams_distribute_parallel_for:
790 case OMPD_teams_distribute_parallel_for_simd:
791 case OMPD_target_update:
792 case OMPD_declare_simd:
793 case OMPD_declare_target:
794 case OMPD_end_declare_target:
795 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000796 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000797 case OMPD_taskloop:
798 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000799 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000800 case OMPD_unknown:
801 llvm_unreachable("Unexpected directive.");
802 }
803 }
804
805 return false;
806}
807
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000808static bool supportsSPMDExecutionMode(ASTContext &Ctx,
809 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000810 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
811 switch (DirectiveKind) {
812 case OMPD_target:
813 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000815 case OMPD_target_parallel:
816 case OMPD_target_parallel_for:
817 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 case OMPD_target_teams_distribute_parallel_for:
819 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000820 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000821 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000822 return true;
823 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000824 return false;
825 case OMPD_parallel:
826 case OMPD_for:
827 case OMPD_parallel_for:
828 case OMPD_parallel_sections:
829 case OMPD_for_simd:
830 case OMPD_parallel_for_simd:
831 case OMPD_cancel:
832 case OMPD_cancellation_point:
833 case OMPD_ordered:
834 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000835 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000836 case OMPD_task:
837 case OMPD_simd:
838 case OMPD_sections:
839 case OMPD_section:
840 case OMPD_single:
841 case OMPD_master:
842 case OMPD_critical:
843 case OMPD_taskyield:
844 case OMPD_barrier:
845 case OMPD_taskwait:
846 case OMPD_taskgroup:
847 case OMPD_atomic:
848 case OMPD_flush:
849 case OMPD_teams:
850 case OMPD_target_data:
851 case OMPD_target_exit_data:
852 case OMPD_target_enter_data:
853 case OMPD_distribute:
854 case OMPD_distribute_simd:
855 case OMPD_distribute_parallel_for:
856 case OMPD_distribute_parallel_for_simd:
857 case OMPD_teams_distribute:
858 case OMPD_teams_distribute_simd:
859 case OMPD_teams_distribute_parallel_for:
860 case OMPD_teams_distribute_parallel_for_simd:
861 case OMPD_target_update:
862 case OMPD_declare_simd:
863 case OMPD_declare_target:
864 case OMPD_end_declare_target:
865 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000866 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000867 case OMPD_taskloop:
868 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000869 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000870 case OMPD_unknown:
871 break;
872 }
873 llvm_unreachable(
874 "Unknown programming model for OpenMP directive on NVPTX target.");
875}
876
877/// Check if the directive is loops based and has schedule clause at all or has
878/// static scheduling.
879static bool hasStaticScheduling(const OMPExecutableDirective &D) {
880 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
881 isOpenMPLoopDirective(D.getDirectiveKind()) &&
882 "Expected loop-based directive.");
883 return !D.hasClausesOfKind<OMPOrderedClause>() &&
884 (!D.hasClausesOfKind<OMPScheduleClause>() ||
885 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
886 [](const OMPScheduleClause *C) {
887 return C->getScheduleKind() == OMPC_SCHEDULE_static;
888 }));
889}
890
891/// Check for inner (nested) lightweight runtime construct, if any
892static bool hasNestedLightweightDirective(ASTContext &Ctx,
893 const OMPExecutableDirective &D) {
894 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
895 const auto *CS = D.getInnermostCapturedStmt();
896 const auto *Body =
897 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000898 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000899
Alexey Bataev5c427362019-04-10 19:11:33 +0000900 if (const auto *NestedDir =
901 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000902 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
903 switch (D.getDirectiveKind()) {
904 case OMPD_target:
905 if (isOpenMPParallelDirective(DKind) &&
906 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
907 hasStaticScheduling(*NestedDir))
908 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000909 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
910 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000911 if (DKind == OMPD_parallel) {
912 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
913 /*IgnoreCaptured=*/true);
914 if (!Body)
915 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000916 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
917 if (const auto *NND =
918 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000919 DKind = NND->getDirectiveKind();
920 if (isOpenMPWorksharingDirective(DKind) &&
921 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
922 return true;
923 }
924 } else if (DKind == OMPD_teams) {
925 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
926 /*IgnoreCaptured=*/true);
927 if (!Body)
928 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000929 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
930 if (const auto *NND =
931 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000932 DKind = NND->getDirectiveKind();
933 if (isOpenMPParallelDirective(DKind) &&
934 isOpenMPWorksharingDirective(DKind) &&
935 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
936 return true;
937 if (DKind == OMPD_parallel) {
938 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
939 /*IgnoreCaptured=*/true);
940 if (!Body)
941 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000942 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
943 if (const auto *NND =
944 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000945 DKind = NND->getDirectiveKind();
946 if (isOpenMPWorksharingDirective(DKind) &&
947 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
948 return true;
949 }
950 }
951 }
952 }
953 return false;
954 case OMPD_target_teams:
955 if (isOpenMPParallelDirective(DKind) &&
956 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
957 hasStaticScheduling(*NestedDir))
958 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000959 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
960 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000961 if (DKind == OMPD_parallel) {
962 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
963 /*IgnoreCaptured=*/true);
964 if (!Body)
965 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000966 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
967 if (const auto *NND =
968 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000969 DKind = NND->getDirectiveKind();
970 if (isOpenMPWorksharingDirective(DKind) &&
971 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
972 return true;
973 }
974 }
975 return false;
976 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000977 if (DKind == OMPD_simd)
978 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000979 return isOpenMPWorksharingDirective(DKind) &&
980 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
981 case OMPD_target_teams_distribute:
982 case OMPD_target_simd:
983 case OMPD_target_parallel_for:
984 case OMPD_target_parallel_for_simd:
985 case OMPD_target_teams_distribute_simd:
986 case OMPD_target_teams_distribute_parallel_for:
987 case OMPD_target_teams_distribute_parallel_for_simd:
988 case OMPD_parallel:
989 case OMPD_for:
990 case OMPD_parallel_for:
991 case OMPD_parallel_sections:
992 case OMPD_for_simd:
993 case OMPD_parallel_for_simd:
994 case OMPD_cancel:
995 case OMPD_cancellation_point:
996 case OMPD_ordered:
997 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000998 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000999 case OMPD_task:
1000 case OMPD_simd:
1001 case OMPD_sections:
1002 case OMPD_section:
1003 case OMPD_single:
1004 case OMPD_master:
1005 case OMPD_critical:
1006 case OMPD_taskyield:
1007 case OMPD_barrier:
1008 case OMPD_taskwait:
1009 case OMPD_taskgroup:
1010 case OMPD_atomic:
1011 case OMPD_flush:
1012 case OMPD_teams:
1013 case OMPD_target_data:
1014 case OMPD_target_exit_data:
1015 case OMPD_target_enter_data:
1016 case OMPD_distribute:
1017 case OMPD_distribute_simd:
1018 case OMPD_distribute_parallel_for:
1019 case OMPD_distribute_parallel_for_simd:
1020 case OMPD_teams_distribute:
1021 case OMPD_teams_distribute_simd:
1022 case OMPD_teams_distribute_parallel_for:
1023 case OMPD_teams_distribute_parallel_for_simd:
1024 case OMPD_target_update:
1025 case OMPD_declare_simd:
1026 case OMPD_declare_target:
1027 case OMPD_end_declare_target:
1028 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001029 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001030 case OMPD_taskloop:
1031 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001032 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001033 case OMPD_unknown:
1034 llvm_unreachable("Unexpected directive.");
1035 }
1036 }
1037
1038 return false;
1039}
1040
1041/// Checks if the construct supports lightweight runtime. It must be SPMD
1042/// construct + inner loop-based construct with static scheduling.
1043static bool supportsLightweightRuntime(ASTContext &Ctx,
1044 const OMPExecutableDirective &D) {
1045 if (!supportsSPMDExecutionMode(Ctx, D))
1046 return false;
1047 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1048 switch (DirectiveKind) {
1049 case OMPD_target:
1050 case OMPD_target_teams:
1051 case OMPD_target_parallel:
1052 return hasNestedLightweightDirective(Ctx, D);
1053 case OMPD_target_parallel_for:
1054 case OMPD_target_parallel_for_simd:
1055 case OMPD_target_teams_distribute_parallel_for:
1056 case OMPD_target_teams_distribute_parallel_for_simd:
1057 // (Last|First)-privates must be shared in parallel region.
1058 return hasStaticScheduling(D);
1059 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001060 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001061 return true;
1062 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001063 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001064 case OMPD_parallel:
1065 case OMPD_for:
1066 case OMPD_parallel_for:
1067 case OMPD_parallel_sections:
1068 case OMPD_for_simd:
1069 case OMPD_parallel_for_simd:
1070 case OMPD_cancel:
1071 case OMPD_cancellation_point:
1072 case OMPD_ordered:
1073 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001074 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001075 case OMPD_task:
1076 case OMPD_simd:
1077 case OMPD_sections:
1078 case OMPD_section:
1079 case OMPD_single:
1080 case OMPD_master:
1081 case OMPD_critical:
1082 case OMPD_taskyield:
1083 case OMPD_barrier:
1084 case OMPD_taskwait:
1085 case OMPD_taskgroup:
1086 case OMPD_atomic:
1087 case OMPD_flush:
1088 case OMPD_teams:
1089 case OMPD_target_data:
1090 case OMPD_target_exit_data:
1091 case OMPD_target_enter_data:
1092 case OMPD_distribute:
1093 case OMPD_distribute_simd:
1094 case OMPD_distribute_parallel_for:
1095 case OMPD_distribute_parallel_for_simd:
1096 case OMPD_teams_distribute:
1097 case OMPD_teams_distribute_simd:
1098 case OMPD_teams_distribute_parallel_for:
1099 case OMPD_teams_distribute_parallel_for_simd:
1100 case OMPD_target_update:
1101 case OMPD_declare_simd:
1102 case OMPD_declare_target:
1103 case OMPD_end_declare_target:
1104 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001105 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001106 case OMPD_taskloop:
1107 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001108 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001109 case OMPD_unknown:
1110 break;
1111 }
1112 llvm_unreachable(
1113 "Unknown programming model for OpenMP directive on NVPTX target.");
1114}
1115
1116void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001117 StringRef ParentName,
1118 llvm::Function *&OutlinedFn,
1119 llvm::Constant *&OutlinedFnID,
1120 bool IsOffloadEntry,
1121 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001122 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001123 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001124 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001125 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001126 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001127
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001128 // Emit target region as a standalone region.
1129 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001130 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1131 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001132
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001134 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001135 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001136 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001137 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001138 auto &RT =
1139 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001140 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1141 // Skip target region initialization.
1142 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001143 }
1144 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001145 auto &RT =
1146 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001147 RT.clearLocThreadIdInsertPt(CGF);
1148 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001149 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001150 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001152 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001153 // Reserve place for the globalized memory.
1154 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001155 if (!KernelStaticGlobalized) {
1156 KernelStaticGlobalized = new llvm::GlobalVariable(
1157 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1158 llvm::GlobalValue::InternalLinkage,
1159 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1160 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1161 llvm::GlobalValue::NotThreadLocal,
1162 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1163 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001164 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1165 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001166 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168 // Now change the name of the worker function to correspond to this target
1169 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001170 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001171
1172 // Create the worker function
1173 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174}
1175
1176// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001177void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 EntryFunctionState &EST,
1179 WorkerFunctionState &WST) {
1180 CGBuilderTy &Bld = CGF.Builder;
1181
1182 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1183 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1184 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1185 EST.ExitBB = CGF.createBasicBlock(".exit");
1186
Alexey Bataev9ff80832018-04-16 20:16:21 +00001187 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001188 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1189 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1190
1191 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001192 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193 CGF.EmitBranch(EST.ExitBB);
1194
1195 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001196 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1198 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1199
1200 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001201 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001202 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 // First action in sequential region:
1204 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001205 // TODO: Optimize runtime initialization and pass in correct value.
1206 llvm::Value *Args[] = {getThreadLimit(CGF),
1207 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001208 CGF.EmitRuntimeCall(
1209 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001210
1211 // For data sharing, we need to initialize the stack.
1212 CGF.EmitRuntimeCall(
1213 createNVPTXRuntimeFunction(
1214 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1215
Alexey Bataevc99042b2018-03-15 18:10:54 +00001216 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217}
1218
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001219void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001220 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001221 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001222 if (!CGF.HaveInsertPoint())
1223 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001224
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001225 emitGenericVarsEpilog(CGF);
1226
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227 if (!EST.ExitBB)
1228 EST.ExitBB = CGF.createBasicBlock(".exit");
1229
1230 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1231 CGF.EmitBranch(TerminateBB);
1232
1233 CGF.EmitBlock(TerminateBB);
1234 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001235 // TODO: Optimize runtime initialization and pass in correct value.
1236 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001237 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001238 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001239 // Barrier to terminate worker threads.
1240 syncCTAThreads(CGF);
1241 // Master thread jumps to exit point.
1242 CGF.EmitBranch(EST.ExitBB);
1243
1244 CGF.EmitBlock(EST.ExitBB);
1245 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001246}
1247
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001248void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001249 StringRef ParentName,
1250 llvm::Function *&OutlinedFn,
1251 llvm::Constant *&OutlinedFnID,
1252 bool IsOffloadEntry,
1253 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001254 ExecutionRuntimeModesRAII ModeRAII(
1255 CurrentExecutionMode, RequiresFullRuntime,
1256 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1257 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001258 EntryFunctionState EST;
1259
1260 // Emit target region as a standalone region.
1261 class NVPTXPrePostActionTy : public PrePostActionTy {
1262 CGOpenMPRuntimeNVPTX &RT;
1263 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1264 const OMPExecutableDirective &D;
1265
1266 public:
1267 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1268 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1269 const OMPExecutableDirective &D)
1270 : RT(RT), EST(EST), D(D) {}
1271 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001272 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001273 // Skip target region initialization.
1274 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001275 }
1276 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001277 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001278 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001279 }
1280 } Action(*this, EST, D);
1281 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001282 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001283 // Reserve place for the globalized memory.
1284 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001285 if (!KernelStaticGlobalized) {
1286 KernelStaticGlobalized = new llvm::GlobalVariable(
1287 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1288 llvm::GlobalValue::InternalLinkage,
1289 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1290 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1291 llvm::GlobalValue::NotThreadLocal,
1292 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1293 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001294 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1295 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001296 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001297}
1298
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001299void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001300 CodeGenFunction &CGF, EntryFunctionState &EST,
1301 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001302 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001303
1304 // Setup BBs in entry function.
1305 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1306 EST.ExitBB = CGF.createBasicBlock(".exit");
1307
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001308 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1309 /*RequiresOMPRuntime=*/
1310 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1311 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001312 CGF.EmitRuntimeCall(
1313 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001314
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001315 if (RequiresFullRuntime) {
1316 // For data sharing, we need to initialize the stack.
1317 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1318 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1319 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001320
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001321 CGF.EmitBranch(ExecuteBB);
1322
1323 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001324
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001325 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326}
1327
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001328void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001329 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001330 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001331 if (!CGF.HaveInsertPoint())
1332 return;
1333
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001334 if (!EST.ExitBB)
1335 EST.ExitBB = CGF.createBasicBlock(".exit");
1336
1337 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1338 CGF.EmitBranch(OMPDeInitBB);
1339
1340 CGF.EmitBlock(OMPDeInitBB);
1341 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001342 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1343 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001345 createNVPTXRuntimeFunction(
1346 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347 CGF.EmitBranch(EST.ExitBB);
1348
1349 CGF.EmitBlock(EST.ExitBB);
1350 EST.ExitBB = nullptr;
1351}
1352
1353// Create a unique global variable to indicate the execution mode of this target
1354// region. The execution mode is either 'generic', or 'spmd' depending on the
1355// target directive. This variable is picked up by the offload library to setup
1356// the device appropriately before kernel launch. If the execution mode is
1357// 'generic', the runtime reserves one warp for the master, otherwise, all
1358// warps participate in parallel work.
1359static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001360 bool Mode) {
1361 auto *GVMode =
1362 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1363 llvm::GlobalValue::WeakAnyLinkage,
1364 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1365 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001366 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001367}
1368
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001369void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001370 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001371
1372 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001373 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001374 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001375 emitWorkerLoop(CGF, WST);
1376 CGF.FinishFunction();
1377}
1378
1379void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1380 WorkerFunctionState &WST) {
1381 //
1382 // The workers enter this loop and wait for parallel work from the master.
1383 // When the master encounters a parallel region it sets up the work + variable
1384 // arguments, and wakes up the workers. The workers first check to see if
1385 // they are required for the parallel region, i.e., within the # of requested
1386 // parallel threads. The activated workers load the variable arguments and
1387 // execute the parallel work.
1388 //
1389
1390 CGBuilderTy &Bld = CGF.Builder;
1391
1392 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1393 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1394 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1395 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1396 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1397 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1398
1399 CGF.EmitBranch(AwaitBB);
1400
1401 // Workers wait for work from master.
1402 CGF.EmitBlock(AwaitBB);
1403 // Wait for parallel work
1404 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001405
1406 Address WorkFn =
1407 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1408 Address ExecStatus =
1409 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1410 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1411 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1412
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001413 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001414 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001415 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001416 llvm::Value *Ret = CGF.EmitRuntimeCall(
1417 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1418 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001419
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001420 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001421 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1422 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001423 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1424
1425 // Activate requested workers.
1426 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001427 llvm::Value *IsActive =
1428 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1429 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001430
1431 // Signal start of parallel region.
1432 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001433 // Skip initialization.
1434 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001435
1436 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001437 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001438 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001439 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001440
1441 llvm::Value *WorkFnMatch =
1442 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1443
1444 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1445 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1446 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1447
1448 // Execute this outlined function.
1449 CGF.EmitBlock(ExecuteFNBB);
1450
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001451 // Insert call to work function via shared wrapper. The shared
1452 // wrapper takes two arguments:
1453 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001454 // - the thread ID;
1455 emitCall(CGF, WST.Loc, W,
1456 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001457
1458 // Go to end of parallel region.
1459 CGF.EmitBranch(TerminateBB);
1460
1461 CGF.EmitBlock(CheckNextBB);
1462 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001463 // Default case: call to outlined function through pointer if the target
1464 // region makes a declare target call that may contain an orphaned parallel
1465 // directive.
1466 auto *ParallelFnTy =
1467 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001468 /*isVarArg=*/false);
1469 llvm::Value *WorkFnCast =
1470 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001471 // Insert call to work function via shared wrapper. The shared
1472 // wrapper takes two arguments:
1473 // - the parallelism level;
1474 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001475 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001476 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1477 // Go to end of parallel region.
1478 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001479
1480 // Signal end of parallel region.
1481 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001482 CGF.EmitRuntimeCall(
1483 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1484 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001485 CGF.EmitBranch(BarrierBB);
1486
1487 // All active and inactive workers wait at a barrier after parallel region.
1488 CGF.EmitBlock(BarrierBB);
1489 // Barrier after parallel region.
1490 syncCTAThreads(CGF);
1491 CGF.EmitBranch(AwaitBB);
1492
1493 // Exit target region.
1494 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001495 // Skip initialization.
1496 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001497}
1498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001499/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001500/// implementation. Specialized for the NVPTX device.
1501/// \param Function OpenMP runtime function.
1502/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001503llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001504CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001505 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001506 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1507 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001508 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1509 // RequiresOMPRuntime);
1510 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001511 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001512 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1513 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1514 break;
1515 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001516 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001517 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1518 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001519 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001520 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1522 break;
1523 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001524 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1525 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001526 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001527 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001528 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001529 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1530 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1531 break;
1532 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001533 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1534 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1535 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001536 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001537 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1538 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001539 break;
1540 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001541 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1542 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001543 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001544 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001545 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001546 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1547 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1548 break;
1549 }
1550 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001551 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1552 /// int16_t IsOMPRuntimeInitialized);
1553 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001554 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001555 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001556 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1558 break;
1559 }
1560 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1561 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001562 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001563 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1565 break;
1566 }
1567 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1568 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1569 // global_tid);
1570 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001571 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001572 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1573 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1574 break;
1575 }
1576 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1577 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1578 // global_tid);
1579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001580 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1583 break;
1584 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001585 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1586 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1587 // int16_t lane_offset, int16_t warp_size);
1588 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1592 break;
1593 }
1594 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1595 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1596 // int16_t lane_offset, int16_t warp_size);
1597 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001598 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001599 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1601 break;
1602 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001603 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001604 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1605 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1606 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1607 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1608 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001609 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1610 CGM.Int16Ty, CGM.Int16Ty};
1611 auto *ShuffleReduceFnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1613 /*isVarArg=*/false);
1614 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1615 auto *InterWarpCopyFnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1617 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1619 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001620 CGM.Int32Ty,
1621 CGM.SizeTy,
1622 CGM.VoidPtrTy,
1623 ShuffleReduceFnTy->getPointerTo(),
1624 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001625 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001626 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1627 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001628 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001629 break;
1630 }
1631 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1632 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1633 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001634 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1636 RTLFn = CGM.CreateRuntimeFunction(
1637 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1638 break;
1639 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001640 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1641 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1642 // global_tid, void *global_buffer, int32_t num_of_records, void*
1643 // reduce_data,
1644 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1645 // lane_offset, int16_t shortCircuit),
1646 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1647 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1648 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1649 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1650 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1651 // *buffer, int idx, void *reduce_data));
1652 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1653 CGM.Int16Ty, CGM.Int16Ty};
1654 auto *ShuffleReduceFnTy =
1655 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1656 /*isVarArg=*/false);
1657 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1658 auto *InterWarpCopyFnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1660 /*isVarArg=*/false);
1661 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1662 CGM.VoidPtrTy};
1663 auto *GlobalListFnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1665 /*isVarArg=*/false);
1666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1667 CGM.Int32Ty,
1668 CGM.VoidPtrTy,
1669 CGM.Int32Ty,
1670 CGM.VoidPtrTy,
1671 ShuffleReduceFnTy->getPointerTo(),
1672 InterWarpCopyFnTy->getPointerTo(),
1673 GlobalListFnTy->getPointerTo(),
1674 GlobalListFnTy->getPointerTo(),
1675 GlobalListFnTy->getPointerTo(),
1676 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001677 auto *FnTy =
1678 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1679 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001680 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001681 break;
1682 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001683 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1684 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001685 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001686 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1688 break;
1689 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001690 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1691 /// Build void __kmpc_data_sharing_init_stack_spmd();
1692 auto *FnTy =
1693 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001694 RTLFn =
1695 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001696 break;
1697 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001698 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1699 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001700 // int16_t UseSharedMemory);
1701 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001702 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001703 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1704 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001705 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001706 break;
1707 }
1708 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1709 // Build void __kmpc_data_sharing_pop_stack(void *a);
1710 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001711 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001712 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1713 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1714 /*Name=*/"__kmpc_data_sharing_pop_stack");
1715 break;
1716 }
1717 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1718 /// Build void __kmpc_begin_sharing_variables(void ***args,
1719 /// size_t n_args);
1720 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001721 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001722 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1723 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1724 break;
1725 }
1726 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1727 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001728 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001729 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1730 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1731 break;
1732 }
1733 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1734 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1735 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001736 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001737 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1738 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1739 break;
1740 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001741 case OMPRTL_NVPTX__kmpc_parallel_level: {
1742 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1743 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1744 auto *FnTy =
1745 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1746 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1747 break;
1748 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001749 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1750 // Build int8_t __kmpc_is_spmd_exec_mode();
1751 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1753 break;
1754 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001755 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001756 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1757 // const void *buf, size_t size, int16_t is_shared, const void **res);
1758 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1759 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001760 auto *FnTy =
1761 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1763 break;
1764 }
1765 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001766 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1767 // int16_t is_shared);
1768 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001769 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001770 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001771 RTLFn =
1772 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1773 break;
1774 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001775 case OMPRTL__kmpc_barrier: {
1776 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1777 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1778 auto *FnTy =
1779 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001781 cast<llvm::Function>(RTLFn.getCallee())
1782 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001783 break;
1784 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001785 case OMPRTL__kmpc_barrier_simple_spmd: {
1786 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1787 // global_tid);
1788 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1789 auto *FnTy =
1790 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1791 RTLFn =
1792 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001793 cast<llvm::Function>(RTLFn.getCallee())
1794 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001795 break;
1796 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001797 }
1798 return RTLFn;
1799}
1800
1801void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1802 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001803 uint64_t Size, int32_t,
1804 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001805 // TODO: Add support for global variables on the device after declare target
1806 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001807 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001808 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001809 llvm::Module &M = CGM.getModule();
1810 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001811
1812 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001813 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001814
1815 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001816 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001817 llvm::ConstantAsMetadata::get(
1818 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1819 // Append metadata to nvvm.annotations
1820 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1821}
1822
1823void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1824 const OMPExecutableDirective &D, StringRef ParentName,
1825 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001826 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001827 if (!IsOffloadEntry) // Nothing to do.
1828 return;
1829
1830 assert(!ParentName.empty() && "Invalid target region parent name!");
1831
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001832 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001833 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001834 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001835 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001836 else
1837 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1838 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001839
1840 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001841}
1842
Alexey Bataevceeaa482018-11-21 21:04:34 +00001843namespace {
1844LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1845/// Enum for accesseing the reserved_2 field of the ident_t struct.
1846enum ModeFlagsTy : unsigned {
1847 /// Bit set to 1 when in SPMD mode.
1848 KMP_IDENT_SPMD_MODE = 0x01,
1849 /// Bit set to 1 when a simplified runtime is used.
1850 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1851 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1852};
1853
1854/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1855static const ModeFlagsTy UndefinedMode =
1856 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1857} // anonymous namespace
1858
1859unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001860 switch (getExecutionMode()) {
1861 case EM_SPMD:
1862 if (requiresFullRuntime())
1863 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1864 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1865 case EM_NonSPMD:
1866 assert(requiresFullRuntime() && "Expected full runtime.");
1867 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1868 case EM_Unknown:
1869 return UndefinedMode;
1870 }
1871 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001872}
1873
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001874CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001875 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001876 if (!CGM.getLangOpts().OpenMPIsDevice)
1877 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001878}
Carlo Bertollic6872252016-04-04 15:55:02 +00001879
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001880void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1881 OpenMPProcBindClauseKind ProcBind,
1882 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001883 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001884 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001885 return;
1886
1887 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1888}
1889
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001890void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1891 llvm::Value *NumThreads,
1892 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001893 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001894 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001895 return;
1896
1897 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1898}
1899
Carlo Bertollic6872252016-04-04 15:55:02 +00001900void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1901 const Expr *NumTeams,
1902 const Expr *ThreadLimit,
1903 SourceLocation Loc) {}
1904
James Y Knight9871db02019-02-05 16:42:33 +00001905llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001906 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1907 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001908 // Emit target region as a standalone region.
1909 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001910 bool &IsInParallelRegion;
1911 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001912
1913 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001914 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1915 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001916 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001917 PrevIsInParallelRegion = IsInParallelRegion;
1918 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001919 }
1920 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001921 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001922 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001923 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001924 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001925 bool PrevIsInTTDRegion = IsInTTDRegion;
1926 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001927 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1928 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001929 auto *OutlinedFun =
1930 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1931 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001932 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001933 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001934 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1935 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001936 llvm::Function *WrapperFun =
1937 createParallelDataSharingWrapper(OutlinedFun, D);
1938 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1939 }
1940
1941 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001942}
1943
Alexey Bataev2adecff2018-09-21 14:22:53 +00001944/// Get list of lastprivate variables from the teams distribute ... or
1945/// teams {distribute ...} directives.
1946static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001947getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001948 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1949 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1950 "expected teams directive.");
1951 const OMPExecutableDirective *Dir = &D;
1952 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001953 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001954 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001955 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1956 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001957 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001958 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1959 Dir = nullptr;
1960 }
1961 }
1962 if (!Dir)
1963 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001964 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001965 for (const Expr *E : C->getVarRefs())
1966 Vars.push_back(getPrivateItem(E));
1967 }
1968}
1969
1970/// Get list of reduction variables from the teams ... directives.
1971static void
1972getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1973 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1974 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1975 "expected teams directive.");
1976 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1977 for (const Expr *E : C->privates())
1978 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001979 }
1980}
1981
James Y Knight9871db02019-02-05 16:42:33 +00001982llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001983 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1984 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001985 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001986
Alexey Bataev2adecff2018-09-21 14:22:53 +00001987 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001988 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001989 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001990 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00001991 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1992 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001993 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001994 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1995 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001996 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001997 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00001998 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001999 }
2000 } else if (!LastPrivatesReductions.empty()) {
2001 assert(!TeamAndReductions.first &&
2002 "Previous team declaration is not expected.");
2003 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2004 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 }
2006
Alexey Bataevc99042b2018-03-15 18:10:54 +00002007 // Emit target region as a standalone region.
2008 class NVPTXPrePostActionTy : public PrePostActionTy {
2009 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002010 const RecordDecl *GlobalizedRD;
2011 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2012 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002013
2014 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002015 NVPTXPrePostActionTy(
2016 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2017 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2018 &MappedDeclsFields)
2019 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2020 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002021 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002022 auto &Rt =
2023 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2024 if (GlobalizedRD) {
2025 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2026 I->getSecond().GlobalRecord = GlobalizedRD;
2027 I->getSecond().MappedParams =
2028 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2029 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2030 for (const auto &Pair : MappedDeclsFields) {
2031 assert(Pair.getFirst()->isCanonicalDecl() &&
2032 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002033 Data.insert(std::make_pair(Pair.getFirst(),
2034 MappedVarData(Pair.getSecond(),
2035 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002036 }
2037 }
2038 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002039 }
2040 void Exit(CodeGenFunction &CGF) override {
2041 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2042 .emitGenericVarsEpilog(CGF);
2043 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002044 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2045 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002046 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002047 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002048 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002049 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002050 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002051
2052 return OutlinedFun;
2053}
2054
Alexey Bataevc99042b2018-03-15 18:10:54 +00002055void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002056 SourceLocation Loc,
2057 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002058 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2059 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002060 return;
2061
Alexey Bataevc99042b2018-03-15 18:10:54 +00002062 CGBuilderTy &Bld = CGF.Builder;
2063
2064 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2065 if (I == FunctionGlobalizedDecls.end())
2066 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002067 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002068 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002069 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002070
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002071 // Recover pointer to this function's global record. The runtime will
2072 // handle the specifics of the allocation of the memory.
2073 // Use actual memory size of the record including the padding
2074 // for alignment purposes.
2075 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002076 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002077 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002078 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002079 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002080
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002081 llvm::PointerType *GlobalRecPtrTy =
2082 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002083 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002084 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002085 if (!IsInTTDRegion &&
2086 (WithSPMDCheck ||
2087 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002088 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2089 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2090 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002091 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2092 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2093 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2094 llvm::Value *PL = CGF.EmitRuntimeCall(
2095 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2096 {RTLoc, ThreadID});
2097 IsTTD = Bld.CreateIsNull(PL);
2098 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002099 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2100 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2101 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2102 // There is no need to emit line number for unconditional branch.
2103 (void)ApplyDebugLocation::CreateEmpty(CGF);
2104 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002105 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2106 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002107 CGF.EmitBranch(ExitBB);
2108 // There is no need to emit line number for unconditional branch.
2109 (void)ApplyDebugLocation::CreateEmpty(CGF);
2110 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002111 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2112 if (const RecordDecl *SecGlobalizedVarsRecord =
2113 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2114 SecGlobalRecTy =
2115 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2116
2117 // Recover pointer to this function's global record. The runtime will
2118 // handle the specifics of the allocation of the memory.
2119 // Use actual memory size of the record including the padding
2120 // for alignment purposes.
2121 unsigned Alignment =
2122 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2123 unsigned GlobalRecordSize =
2124 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2125 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2126 Size = Bld.CreateSelect(
2127 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2128 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002129 // TODO: allow the usage of shared memory to be controlled by
2130 // the user, for now, default to global.
2131 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002132 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002133 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2134 createNVPTXRuntimeFunction(
2135 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2136 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002137 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002138 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002139 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002140 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002141 /*NumReservedValues=*/2, "_select_stack");
2142 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2143 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2144 GlobalRecCastAddr = Phi;
2145 I->getSecond().GlobalRecordAddr = Phi;
2146 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002147 } else if (IsInTTDRegion) {
2148 assert(GlobalizedRecords.back().Records.size() < 2 &&
2149 "Expected less than 2 globalized records: one for target and one "
2150 "for teams.");
2151 unsigned Offset = 0;
2152 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2153 QualType RDTy = CGM.getContext().getRecordType(RD);
2154 unsigned Alignment =
2155 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2156 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2157 Offset =
2158 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2159 }
2160 unsigned Alignment =
2161 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2162 Offset = llvm::alignTo(Offset, Alignment);
2163 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2164 ++GlobalizedRecords.back().RegionCounter;
2165 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002166 assert(KernelStaticGlobalized &&
2167 "Kernel static pointer must be initialized already.");
2168 auto *UseSharedMemory = new llvm::GlobalVariable(
2169 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2170 llvm::GlobalValue::InternalLinkage, nullptr,
2171 "_openmp_static_kernel$is_shared");
2172 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2173 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2174 /*DestWidth=*/16, /*Signed=*/0);
2175 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2176 Address(UseSharedMemory,
2177 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2178 /*Volatile=*/false, Int16Ty, Loc);
2179 auto *StaticGlobalized = new llvm::GlobalVariable(
2180 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002181 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002182 auto *RecSize = new llvm::GlobalVariable(
2183 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2184 llvm::GlobalValue::InternalLinkage, nullptr,
2185 "_openmp_static_kernel$size");
2186 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2187 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002188 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002189 CGM.getContext().getSizeType(), Loc);
2190 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2191 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002192 llvm::Value *GlobalRecordSizeArg[] = {
2193 llvm::ConstantInt::get(
2194 CGM.Int16Ty,
2195 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2196 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002197 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2198 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2199 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002200 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002201 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002202 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2203 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002204 }
2205 assert(KernelStaticGlobalized && "Global address must be set already.");
2206 Address FrameAddr = CGF.EmitLoadOfPointer(
2207 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2208 CGM.getContext()
2209 .getPointerType(CGM.getContext().VoidPtrTy)
2210 .castAs<PointerType>());
2211 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002212 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002213 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2214 I->getSecond().IsInSPMDModeFlag = nullptr;
2215 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2216 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002217 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002218 // TODO: allow the usage of shared memory to be controlled by
2219 // the user, for now, default to global.
2220 llvm::Value *GlobalRecordSizeArg[] = {
2221 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2222 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002223 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2224 createNVPTXRuntimeFunction(
2225 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2226 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002227 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002228 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002229 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2230 I->getSecond().IsInSPMDModeFlag = nullptr;
2231 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002232 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002233 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002234
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002235 // Emit the "global alloca" which is a GEP from the global declaration
2236 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002237 LValue SecBase;
2238 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2239 if (IsTTD) {
2240 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2241 llvm::PointerType *SecGlobalRecPtrTy =
2242 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2243 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2244 Bld.CreatePointerBitCastOrAddrSpaceCast(
2245 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2246 SecGlobalRecTy);
2247 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002248 for (auto &Rec : I->getSecond().LocalVarData) {
2249 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2250 llvm::Value *ParValue;
2251 if (EscapedParam) {
2252 const auto *VD = cast<VarDecl>(Rec.first);
2253 LValue ParLVal =
2254 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2255 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2256 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002257 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2258 // Emit VarAddr basing on lane-id if required.
2259 QualType VarTy;
2260 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002261 VarTy = Rec.second.FD->getType();
2262 } else {
2263 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2264 VarAddr.getAddress().getPointer(),
2265 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002266 VarTy =
2267 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002268 VarAddr = CGF.MakeAddrLValue(
2269 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2270 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002271 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002272 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002273 if (!IsInTTDRegion &&
2274 (WithSPMDCheck ||
2275 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002276 assert(I->getSecond().IsInSPMDModeFlag &&
2277 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002278 if (IsTTD) {
2279 assert(SecIt->second.IsOnePerTeam &&
2280 "Secondary glob data must be one per team.");
2281 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2282 VarAddr.setAddress(
2283 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2284 VarAddr.getPointer()),
2285 VarAddr.getAlignment()));
2286 Rec.second.PrivateAddr = VarAddr.getAddress();
2287 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002288 Address GlobalPtr = Rec.second.PrivateAddr;
2289 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2290 Rec.second.PrivateAddr = Address(
2291 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2292 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2293 LocalAddr.getAlignment());
2294 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002295 if (EscapedParam) {
2296 const auto *VD = cast<VarDecl>(Rec.first);
2297 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2298 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2299 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002300 if (IsTTD)
2301 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002302 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002303 }
2304 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2305 // Recover pointer to this function's global record. The runtime will
2306 // handle the specifics of the allocation of the memory.
2307 // Use actual memory size of the record including the padding
2308 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002309 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002310 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2311 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2312 Size = Bld.CreateNUWAdd(
2313 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2314 llvm::Value *AlignVal =
2315 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2316 Size = Bld.CreateUDiv(Size, AlignVal);
2317 Size = Bld.CreateNUWMul(Size, AlignVal);
2318 // TODO: allow the usage of shared memory to be controlled by
2319 // the user, for now, default to global.
2320 llvm::Value *GlobalRecordSizeArg[] = {
2321 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2322 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002323 createNVPTXRuntimeFunction(
2324 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002325 GlobalRecordSizeArg);
2326 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2327 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2328 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2329 CGM.getContext().getDeclAlign(VD),
2330 AlignmentSource::Decl);
2331 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2332 Base.getAddress());
2333 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002334 }
2335 I->getSecond().MappedParams->apply(CGF);
2336}
2337
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002338void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2339 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002340 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2341 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002342 return;
2343
Alexey Bataevc99042b2018-03-15 18:10:54 +00002344 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002345 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002346 I->getSecond().MappedParams->restore(CGF);
2347 if (!CGF.HaveInsertPoint())
2348 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002349 for (llvm::Value *Addr :
2350 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2351 CGF.EmitRuntimeCall(
2352 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2353 Addr);
2354 }
2355 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002356 if (!IsInTTDRegion &&
2357 (WithSPMDCheck ||
2358 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002359 CGBuilderTy &Bld = CGF.Builder;
2360 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2361 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2362 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2363 // There is no need to emit line number for unconditional branch.
2364 (void)ApplyDebugLocation::CreateEmpty(CGF);
2365 CGF.EmitBlock(NonSPMDBB);
2366 CGF.EmitRuntimeCall(
2367 createNVPTXRuntimeFunction(
2368 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2369 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2370 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002371 } else if (IsInTTDRegion) {
2372 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2373 "region counter must be > 0.");
2374 --GlobalizedRecords.back().RegionCounter;
2375 // Emit the restore function only in the target region.
2376 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002377 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2378 /*DestWidth=*/16, /*Signed=*/0);
2379 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2380 Address(GlobalizedRecords.back().UseSharedMemory,
2381 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2382 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002383 llvm::Value *Args[] = {
2384 llvm::ConstantInt::get(
2385 CGM.Int16Ty,
2386 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2387 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002388 CGF.EmitRuntimeCall(
2389 createNVPTXRuntimeFunction(
2390 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002391 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002392 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002393 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002394 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2395 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2396 I->getSecond().GlobalRecordAddr);
2397 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002398 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002399 }
2400}
2401
Carlo Bertollic6872252016-04-04 15:55:02 +00002402void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2403 const OMPExecutableDirective &D,
2404 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002405 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002406 ArrayRef<llvm::Value *> CapturedVars) {
2407 if (!CGF.HaveInsertPoint())
2408 return;
2409
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002410 Address ZeroAddr = CGF.CreateMemTemp(
2411 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2412 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002413 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2414 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002415 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002416 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2417 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002418 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002419}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002420
2421void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002422 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002423 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2424 if (!CGF.HaveInsertPoint())
2425 return;
2426
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002427 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002428 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002429 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002430 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002431}
2432
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002433void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002434 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2435 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2436 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002437
2438 // Force inline this outlined function at its call site.
2439 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2440
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002441 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2442 /*DestWidth=*/32, /*Signed=*/1),
2443 ".zero.addr");
2444 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002445 // ThreadId for serialized parallels is 0.
2446 Address ThreadIDAddr = ZeroAddr;
2447 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002448 CodeGenFunction &CGF, PrePostActionTy &Action) {
2449 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002450
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002451 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2452 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2453 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2454 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2455 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2456 };
2457 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2458 PrePostActionTy &) {
2459
2460 RegionCodeGenTy RCG(CodeGen);
2461 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2462 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2463 llvm::Value *Args[] = {RTLoc, ThreadID};
2464
2465 NVPTXActionTy Action(
2466 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2467 Args,
2468 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2469 Args);
2470 RCG.setAction(Action);
2471 RCG(CGF);
2472 };
2473
2474 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2475 PrePostActionTy &Action) {
2476 CGBuilderTy &Bld = CGF.Builder;
2477 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2478 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002479 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2480
2481 // Prepare for parallel region. Indicate the outlined function.
2482 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002483 CGF.EmitRuntimeCall(
2484 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2485 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002486
2487 // Create a private scope that will globalize the arguments
2488 // passed from the outside of the target region.
2489 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2490
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002491 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002492 if (!CapturedVars.empty()) {
2493 // Prepare for parallel region. Indicate the outlined function.
2494 Address SharedArgs =
2495 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2496 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2497
2498 llvm::Value *DataSharingArgs[] = {
2499 SharedArgsPtr,
2500 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2501 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2502 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2503 DataSharingArgs);
2504
2505 // Store variable address in a list of references to pass to workers.
2506 unsigned Idx = 0;
2507 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002508 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2509 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2510 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002511 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002512 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002513 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002514 if (V->getType()->isIntegerTy())
2515 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2516 else
2517 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002518 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2519 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002520 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002521 }
2522 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002523
2524 // Activate workers. This barrier is used by the master to signal
2525 // work for the workers.
2526 syncCTAThreads(CGF);
2527
2528 // OpenMP [2.5, Parallel Construct, p.49]
2529 // There is an implied barrier at the end of a parallel region. After the
2530 // end of a parallel region, only the master thread of the team resumes
2531 // execution of the enclosing task region.
2532 //
2533 // The master waits at this barrier until all workers are done.
2534 syncCTAThreads(CGF);
2535
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002536 if (!CapturedVars.empty())
2537 CGF.EmitRuntimeCall(
2538 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2539
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002540 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002541 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002542 };
2543
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002544 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2545 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002546 if (IsInParallelRegion) {
2547 SeqGen(CGF, Action);
2548 } else if (IsInTargetMasterThreadRegion) {
2549 L0ParallelGen(CGF, Action);
2550 } else {
2551 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002552 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002553 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002554 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002555 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002556 // }
2557 CGBuilderTy &Bld = CGF.Builder;
2558 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002559 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2560 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002561 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002562 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2563 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002564 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002565 // There is no need to emit line number for unconditional branch.
2566 (void)ApplyDebugLocation::CreateEmpty(CGF);
2567 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002568 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2569 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2570 llvm::Value *PL = CGF.EmitRuntimeCall(
2571 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2572 {RTLoc, ThreadID});
2573 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002574 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002575 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002576 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002577 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002578 // There is no need to emit line number for unconditional branch.
2579 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002580 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002581 L0ParallelGen(CGF, Action);
2582 CGF.EmitBranch(ExitBB);
2583 // There is no need to emit line number for unconditional branch.
2584 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002585 // Emit the continuation block for code after the if.
2586 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2587 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002588 };
2589
Alexey Bataev9ff80832018-04-16 20:16:21 +00002590 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002591 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002592 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002593 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002594 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002595 ThenRCG(CGF);
2596 }
2597}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002598
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002599void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002600 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002601 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2602 // Just call the outlined function to execute the parallel region.
2603 // OutlinedFn(&GTid, &zero, CapturedStruct);
2604 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002605 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002606
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002607 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2608 /*DestWidth=*/32, /*Signed=*/1),
2609 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002610 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002611 // ThreadId for serialized parallels is 0.
2612 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002613 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002614 &ThreadIDAddr](CodeGenFunction &CGF,
2615 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002616 Action.Enter(CGF);
2617
2618 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2619 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2620 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2621 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2622 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2623 };
2624 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2625 PrePostActionTy &) {
2626
2627 RegionCodeGenTy RCG(CodeGen);
2628 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2629 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2630 llvm::Value *Args[] = {RTLoc, ThreadID};
2631
2632 NVPTXActionTy Action(
2633 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2634 Args,
2635 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2636 Args);
2637 RCG.setAction(Action);
2638 RCG(CGF);
2639 };
2640
2641 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002642 // In the worker need to use the real thread id.
2643 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002644 RegionCodeGenTy RCG(CodeGen);
2645 RCG(CGF);
2646 } else {
2647 // If we are not in the target region, it is definitely L2 parallelism or
2648 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2649 // need to check for orphaned directives.
2650 RegionCodeGenTy RCG(SeqGen);
2651 RCG(CGF);
2652 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002653}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002654
Alexey Bataeva3924b52019-01-03 16:25:35 +00002655void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2656 // Always emit simple barriers!
2657 if (!CGF.HaveInsertPoint())
2658 return;
2659 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2660 // This function does not use parameters, so we can emit just default values.
2661 llvm::Value *Args[] = {
2662 llvm::ConstantPointerNull::get(
2663 cast<llvm::PointerType>(getIdentTyPointerTy())),
2664 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2665 CGF.EmitRuntimeCall(
2666 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2667}
2668
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002669void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2670 SourceLocation Loc,
2671 OpenMPDirectiveKind Kind, bool,
2672 bool) {
2673 // Always emit simple barriers!
2674 if (!CGF.HaveInsertPoint())
2675 return;
2676 // Build call __kmpc_cancel_barrier(loc, thread_id);
2677 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2678 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2679 getThreadID(CGF, Loc)};
2680 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2681}
2682
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002683void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2684 CodeGenFunction &CGF, StringRef CriticalName,
2685 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2686 const Expr *Hint) {
2687 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2688 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2689 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2690 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2691 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2692
2693 // Fetch team-local id of the thread.
2694 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2695
2696 // Get the width of the team.
2697 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2698
2699 // Initialize the counter variable for the loop.
2700 QualType Int32Ty =
2701 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2702 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2703 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2704 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2705 /*isInit=*/true);
2706
2707 // Block checks if loop counter exceeds upper bound.
2708 CGF.EmitBlock(LoopBB);
2709 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2710 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2711 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2712
2713 // Block tests which single thread should execute region, and which threads
2714 // should go straight to synchronisation point.
2715 CGF.EmitBlock(TestBB);
2716 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2717 llvm::Value *CmpThreadToCounter =
2718 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2719 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2720
2721 // Block emits the body of the critical region.
2722 CGF.EmitBlock(BodyBB);
2723
2724 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002725 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2726 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002727
2728 // After the body surrounded by the critical region, the single executing
2729 // thread will jump to the synchronisation point.
2730 // Block waits for all threads in current team to finish then increments the
2731 // counter variable and returns to the loop.
2732 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002733 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2734 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002735
2736 llvm::Value *IncCounterVal =
2737 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2738 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2739 CGF.EmitBranch(LoopBB);
2740
2741 // Block that is reached when all threads in the team complete the region.
2742 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2743}
2744
Alexey Bataevb2575932018-01-04 20:18:55 +00002745/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002746static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2747 QualType ValTy, QualType CastTy,
2748 SourceLocation Loc) {
2749 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2750 "Cast type must sized.");
2751 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2752 "Val type must sized.");
2753 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2754 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002755 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002756 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2757 CGF.getContext().getTypeSizeInChars(CastTy))
2758 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2759 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2760 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2761 CastTy->hasSignedIntegerRepresentation());
2762 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002763 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2764 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002765 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2766 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002767}
2768
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002769/// This function creates calls to one of two shuffle functions to copy
2770/// variables between lanes in a warp.
2771static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002772 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002773 QualType ElemType,
2774 llvm::Value *Offset,
2775 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002776 CodeGenModule &CGM = CGF.CGM;
2777 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002778 CGOpenMPRuntimeNVPTX &RT =
2779 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2780
Alexey Bataeva453f362018-03-19 17:53:56 +00002781 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2782 assert(Size.getQuantity() <= 8 &&
2783 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002784
Alexey Bataeva453f362018-03-19 17:53:56 +00002785 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002786 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2787 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2788
2789 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002790 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2791 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2792 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002793 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002794 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002795
Alexey Bataev9ff80832018-04-16 20:16:21 +00002796 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2797 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002798
Alexey Bataeva453f362018-03-19 17:53:56 +00002799 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800}
2801
Alexey Bataev12c62902018-06-22 19:10:38 +00002802static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2803 Address DestAddr, QualType ElemType,
2804 llvm::Value *Offset, SourceLocation Loc) {
2805 CGBuilderTy &Bld = CGF.Builder;
2806
2807 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2808 // Create the loop over the big sized data.
2809 // ptr = (void*)Elem;
2810 // ptrEnd = (void*) Elem + 1;
2811 // Step = 8;
2812 // while (ptr + Step < ptrEnd)
2813 // shuffle((int64_t)*ptr);
2814 // Step = 4;
2815 // while (ptr + Step < ptrEnd)
2816 // shuffle((int32_t)*ptr);
2817 // ...
2818 Address ElemPtr = DestAddr;
2819 Address Ptr = SrcAddr;
2820 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002821 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002822 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2823 if (Size < CharUnits::fromQuantity(IntSize))
2824 continue;
2825 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2826 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2827 /*Signed=*/1);
2828 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2829 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2830 ElemPtr =
2831 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2832 if (Size.getQuantity() / IntSize > 1) {
2833 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2834 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2835 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2836 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2837 CGF.EmitBlock(PreCondBB);
2838 llvm::PHINode *PhiSrc =
2839 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2840 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2841 llvm::PHINode *PhiDest =
2842 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2843 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2844 Ptr = Address(PhiSrc, Ptr.getAlignment());
2845 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2846 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2847 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2848 Ptr.getPointer(), CGF.VoidPtrTy));
2849 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2850 ThenBB, ExitBB);
2851 CGF.EmitBlock(ThenBB);
2852 llvm::Value *Res = createRuntimeShuffleFunction(
2853 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2854 IntType, Offset, Loc);
2855 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002856 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2857 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002858 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2859 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002860 CGF.EmitBranch(PreCondBB);
2861 CGF.EmitBlock(ExitBB);
2862 } else {
2863 llvm::Value *Res = createRuntimeShuffleFunction(
2864 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2865 IntType, Offset, Loc);
2866 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002867 Ptr = Bld.CreateConstGEP(Ptr, 1);
2868 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002869 }
2870 Size = Size % IntSize;
2871 }
2872}
2873
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002874namespace {
2875enum CopyAction : unsigned {
2876 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2877 // the warp using shuffle instructions.
2878 RemoteLaneToThread,
2879 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2880 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002881 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2882 ThreadToScratchpad,
2883 // ScratchpadToThread: Copy from a scratchpad array in global memory
2884 // containing team-reduced data to a thread's stack.
2885 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002886};
2887} // namespace
2888
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002889struct CopyOptionsTy {
2890 llvm::Value *RemoteLaneOffset;
2891 llvm::Value *ScratchpadIndex;
2892 llvm::Value *ScratchpadWidth;
2893};
2894
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002895/// Emit instructions to copy a Reduce list, which contains partially
2896/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002897static void emitReductionListCopy(
2898 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2899 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2900 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002901
Alexey Bataev9ff80832018-04-16 20:16:21 +00002902 CodeGenModule &CGM = CGF.CGM;
2903 ASTContext &C = CGM.getContext();
2904 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002905
Alexey Bataev9ff80832018-04-16 20:16:21 +00002906 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2907 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2908 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002909
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002910 // Iterates, element-by-element, through the source Reduce list and
2911 // make a copy.
2912 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002913 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002914 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002915 Address SrcElementAddr = Address::invalid();
2916 Address DestElementAddr = Address::invalid();
2917 Address DestElementPtrAddr = Address::invalid();
2918 // Should we shuffle in an element from a remote lane?
2919 bool ShuffleInElement = false;
2920 // Set to true to update the pointer in the dest Reduce list to a
2921 // newly created element.
2922 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002923 // Increment the src or dest pointer to the scratchpad, for each
2924 // new element.
2925 bool IncrScratchpadSrc = false;
2926 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002927
2928 switch (Action) {
2929 case RemoteLaneToThread: {
2930 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002931 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002932 SrcElementAddr = CGF.EmitLoadOfPointer(
2933 SrcElementPtrAddr,
2934 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002935
2936 // Step 1.2: Create a temporary to store the element in the destination
2937 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002938 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002939 DestElementAddr =
2940 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2941 ShuffleInElement = true;
2942 UpdateDestListPtr = true;
2943 break;
2944 }
2945 case ThreadCopy: {
2946 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002947 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002948 SrcElementAddr = CGF.EmitLoadOfPointer(
2949 SrcElementPtrAddr,
2950 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002951
2952 // Step 1.2: Get the address for dest element. The destination
2953 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002954 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002955 DestElementAddr = CGF.EmitLoadOfPointer(
2956 DestElementPtrAddr,
2957 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958 break;
2959 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002960 case ThreadToScratchpad: {
2961 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002962 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002963 SrcElementAddr = CGF.EmitLoadOfPointer(
2964 SrcElementPtrAddr,
2965 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002966
2967 // Step 1.2: Get the address for dest element:
2968 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002969 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002970 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002971 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002972 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002973 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002974 ScratchPadElemAbsolutePtrVal =
2975 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002976 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2977 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002978 IncrScratchpadDest = true;
2979 break;
2980 }
2981 case ScratchpadToThread: {
2982 // Step 1.1: Get the address for the src element in the scratchpad.
2983 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002984 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002985 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002986 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002987 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002988 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002989 ScratchPadElemAbsolutePtrVal =
2990 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2991 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2992 C.getTypeAlignInChars(Private->getType()));
2993 IncrScratchpadSrc = true;
2994
2995 // Step 1.2: Create a temporary to store the element in the destination
2996 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002997 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002998 DestElementAddr =
2999 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3000 UpdateDestListPtr = true;
3001 break;
3002 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003003 }
3004
3005 // Regardless of src and dest of copy, we emit the load of src
3006 // element as this is required in all directions
3007 SrcElementAddr = Bld.CreateElementBitCast(
3008 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003009 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3010 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003011
3012 // Now that all active lanes have read the element in the
3013 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003014 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003015 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3016 RemoteLaneOffset, Private->getExprLoc());
3017 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003018 switch (CGF.getEvaluationKind(Private->getType())) {
3019 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003020 llvm::Value *Elem =
3021 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3022 Private->getType(), Private->getExprLoc());
3023 // Store the source element value to the dest element address.
3024 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3025 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003026 break;
3027 }
3028 case TEK_Complex: {
3029 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3030 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3031 Private->getExprLoc());
3032 CGF.EmitStoreOfComplex(
3033 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3034 /*isInit=*/false);
3035 break;
3036 }
3037 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003038 CGF.EmitAggregateCopy(
3039 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3040 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3041 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003042 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003043 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003044 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003045
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003046 // Step 3.1: Modify reference in dest Reduce list as needed.
3047 // Modifying the reference in Reduce list to point to the newly
3048 // created element. The element is live in the current function
3049 // scope and that of functions it invokes (i.e., reduce_function).
3050 // RemoteReduceData[i] = (void*)&RemoteElem
3051 if (UpdateDestListPtr) {
3052 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3053 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3054 DestElementPtrAddr, /*Volatile=*/false,
3055 C.VoidPtrTy);
3056 }
3057
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003058 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3059 // address of the next element in scratchpad memory, unless we're currently
3060 // processing the last one. Memory alignment is also taken care of here.
3061 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3062 llvm::Value *ScratchpadBasePtr =
3063 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003064 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3065 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003066 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003067 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003068
3069 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003070 ScratchpadBasePtr = Bld.CreateNUWSub(
3071 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3072 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003073 ScratchpadBasePtr,
3074 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003075 ScratchpadBasePtr = Bld.CreateNUWAdd(
3076 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3077 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003078 ScratchpadBasePtr,
3079 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3080
3081 if (IncrScratchpadDest)
3082 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3083 else /* IncrScratchpadSrc = true */
3084 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3085 }
3086
Alexey Bataev9ff80832018-04-16 20:16:21 +00003087 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003088 }
3089}
3090
3091/// This function emits a helper that gathers Reduce lists from the first
3092/// lane of every active warp to lanes in the first warp.
3093///
3094/// void inter_warp_copy_func(void* reduce_data, num_warps)
3095/// shared smem[warp_size];
3096/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003097/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003098/// If (I am the first lane in each warp)
3099/// Copy my local D to smem[warp_id]
3100/// sync
3101/// if (I am the first warp)
3102/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3104 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003105 QualType ReductionArrayTy,
3106 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003107 ASTContext &C = CGM.getContext();
3108 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109
3110 // ReduceList: thread local Reduce list.
3111 // At the stage of the computation when this function is called, partially
3112 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003113 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3114 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003115 // NumWarps: number of warps active in the parallel region. This could
3116 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003117 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003118 C.getIntTypeForBitwidth(32, /* Signed */ true),
3119 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003120 FunctionArgList Args;
3121 Args.push_back(&ReduceListArg);
3122 Args.push_back(&NumWarpsArg);
3123
Alexey Bataev9ff80832018-04-16 20:16:21 +00003124 const CGFunctionInfo &CGFI =
3125 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003126 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3127 llvm::GlobalValue::InternalLinkage,
3128 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003129 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003130 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003132 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003133
Alexey Bataev9ff80832018-04-16 20:16:21 +00003134 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003135
3136 // This array is used as a medium to transfer, one reduce element at a time,
3137 // the data from the first lane of every warp to lanes in the first warp
3138 // in order to perform the final step of a reduction in a parallel region
3139 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3140 // for reduced latency, as well as to have a distinct copy for concurrently
3141 // executing target regions. The array is declared with common linkage so
3142 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003143 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003144 "__openmp_nvptx_data_transfer_temporary_storage";
3145 llvm::GlobalVariable *TransferMedium =
3146 M.getGlobalVariable(TransferMediumName);
3147 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003148 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3150 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003151 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003152 llvm::Constant::getNullValue(Ty), TransferMediumName,
3153 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3154 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003155 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156 }
3157
3158 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003159 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003161 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003162 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003163 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164
3165 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3166 Address LocalReduceList(
3167 Bld.CreatePointerBitCastOrAddrSpaceCast(
3168 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003169 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3171 CGF.getPointerAlign());
3172
3173 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003174 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003175 //
3176 // Warp master copies reduce element to transfer medium in __shared__
3177 // memory.
3178 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003179 unsigned RealTySize =
3180 C.getTypeSizeInChars(Private->getType())
3181 .alignTo(C.getTypeAlignInChars(Private->getType()))
3182 .getQuantity();
3183 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3184 unsigned NumIters = RealTySize / TySize;
3185 if (NumIters == 0)
3186 continue;
3187 QualType CType = C.getIntTypeForBitwidth(
3188 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3189 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3190 CharUnits Align = CharUnits::fromQuantity(TySize);
3191 llvm::Value *Cnt = nullptr;
3192 Address CntAddr = Address::invalid();
3193 llvm::BasicBlock *PrecondBB = nullptr;
3194 llvm::BasicBlock *ExitBB = nullptr;
3195 if (NumIters > 1) {
3196 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3197 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3198 /*Volatile=*/false, C.IntTy);
3199 PrecondBB = CGF.createBasicBlock("precond");
3200 ExitBB = CGF.createBasicBlock("exit");
3201 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3202 // There is no need to emit line number for unconditional branch.
3203 (void)ApplyDebugLocation::CreateEmpty(CGF);
3204 CGF.EmitBlock(PrecondBB);
3205 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3206 llvm::Value *Cmp =
3207 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3208 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3209 CGF.EmitBlock(BodyBB);
3210 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003211 // kmpc_barrier.
3212 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3213 /*EmitChecks=*/false,
3214 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003215 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3216 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3217 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003218
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003219 // if (lane_id == 0)
3220 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3221 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3222 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003224 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003225 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003226 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3227 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3228 // elemptr = ((CopyType*)(elemptrptr)) + I
3229 Address ElemPtr = Address(ElemPtrPtr, Align);
3230 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3231 if (NumIters > 1) {
3232 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3233 ElemPtr.getAlignment());
3234 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003235
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003236 // Get pointer to location in transfer medium.
3237 // MediumPtr = &medium[warp_id]
3238 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3239 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3240 Address MediumPtr(MediumPtrVal, Align);
3241 // Casting to actual data type.
3242 // MediumPtr = (CopyType*)MediumPtrAddr;
3243 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003244
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003245 // elem = *elemptr
3246 //*MediumPtr = elem
3247 llvm::Value *Elem =
3248 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003249 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003250 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003251
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003252 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003253
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003254 CGF.EmitBlock(ElseBB);
3255 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003256
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003257 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003258
Alexey Bataevae51b962018-12-14 21:00:58 +00003259 // kmpc_barrier.
3260 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3261 /*EmitChecks=*/false,
3262 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003263
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003264 //
3265 // Warp 0 copies reduce element from transfer medium.
3266 //
3267 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3268 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3269 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003270
Alexey Bataevae51b962018-12-14 21:00:58 +00003271 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3272 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3273 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3274
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003275 // Up to 32 threads in warp 0 are active.
3276 llvm::Value *IsActiveThread =
3277 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3278 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 // SrcMediumPtr = &medium[tid]
3283 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3284 TransferMedium,
3285 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3286 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3287 // SrcMediumVal = *SrcMediumPtr;
3288 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003289
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003290 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003291 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003292 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3293 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3294 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3295 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3296 if (NumIters > 1) {
3297 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3298 TargetElemPtr.getAlignment());
3299 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003300
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003301 // *TargetElemPtr = SrcMediumVal;
3302 llvm::Value *SrcMediumValue =
3303 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003304 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003305 CType);
3306 Bld.CreateBr(W0MergeBB);
3307
3308 CGF.EmitBlock(W0ElseBB);
3309 Bld.CreateBr(W0MergeBB);
3310
3311 CGF.EmitBlock(W0MergeBB);
3312
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003313 if (NumIters > 1) {
3314 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3315 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3316 CGF.EmitBranch(PrecondBB);
3317 (void)ApplyDebugLocation::CreateEmpty(CGF);
3318 CGF.EmitBlock(ExitBB);
3319 }
3320 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003321 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003322 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003323 }
3324
3325 CGF.FinishFunction();
3326 return Fn;
3327}
3328
3329/// Emit a helper that reduces data across two OpenMP threads (lanes)
3330/// in the same warp. It uses shuffle instructions to copy over data from
3331/// a remote lane's stack. The reduction algorithm performed is specified
3332/// by the fourth parameter.
3333///
3334/// Algorithm Versions.
3335/// Full Warp Reduce (argument value 0):
3336/// This algorithm assumes that all 32 lanes are active and gathers
3337/// data from these 32 lanes, producing a single resultant value.
3338/// Contiguous Partial Warp Reduce (argument value 1):
3339/// This algorithm assumes that only a *contiguous* subset of lanes
3340/// are active. This happens for the last warp in a parallel region
3341/// when the user specified num_threads is not an integer multiple of
3342/// 32. This contiguous subset always starts with the zeroth lane.
3343/// Partial Warp Reduce (argument value 2):
3344/// This algorithm gathers data from any number of lanes at any position.
3345/// All reduced values are stored in the lowest possible lane. The set
3346/// of problems every algorithm addresses is a super set of those
3347/// addressable by algorithms with a lower version number. Overhead
3348/// increases as algorithm version increases.
3349///
3350/// Terminology
3351/// Reduce element:
3352/// Reduce element refers to the individual data field with primitive
3353/// data types to be combined and reduced across threads.
3354/// Reduce list:
3355/// Reduce list refers to a collection of local, thread-private
3356/// reduce elements.
3357/// Remote Reduce list:
3358/// Remote Reduce list refers to a collection of remote (relative to
3359/// the current thread) reduce elements.
3360///
3361/// We distinguish between three states of threads that are important to
3362/// the implementation of this function.
3363/// Alive threads:
3364/// Threads in a warp executing the SIMT instruction, as distinguished from
3365/// threads that are inactive due to divergent control flow.
3366/// Active threads:
3367/// The minimal set of threads that has to be alive upon entry to this
3368/// function. The computation is correct iff active threads are alive.
3369/// Some threads are alive but they are not active because they do not
3370/// contribute to the computation in any useful manner. Turning them off
3371/// may introduce control flow overheads without any tangible benefits.
3372/// Effective threads:
3373/// In order to comply with the argument requirements of the shuffle
3374/// function, we must keep all lanes holding data alive. But at most
3375/// half of them perform value aggregation; we refer to this half of
3376/// threads as effective. The other half is simply handing off their
3377/// data.
3378///
3379/// Procedure
3380/// Value shuffle:
3381/// In this step active threads transfer data from higher lane positions
3382/// in the warp to lower lane positions, creating Remote Reduce list.
3383/// Value aggregation:
3384/// In this step, effective threads combine their thread local Reduce list
3385/// with Remote Reduce list and store the result in the thread local
3386/// Reduce list.
3387/// Value copy:
3388/// In this step, we deal with the assumption made by algorithm 2
3389/// (i.e. contiguity assumption). When we have an odd number of lanes
3390/// active, say 2k+1, only k threads will be effective and therefore k
3391/// new values will be produced. However, the Reduce list owned by the
3392/// (2k+1)th thread is ignored in the value aggregation. Therefore
3393/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3394/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003395static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003396 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003397 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003398 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003399
3400 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003401 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3402 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003403 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003404 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3405 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003406 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003407 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3408 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003409 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003410 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3411 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003412 FunctionArgList Args;
3413 Args.push_back(&ReduceListArg);
3414 Args.push_back(&LaneIDArg);
3415 Args.push_back(&RemoteLaneOffsetArg);
3416 Args.push_back(&AlgoVerArg);
3417
Alexey Bataev9ff80832018-04-16 20:16:21 +00003418 const CGFunctionInfo &CGFI =
3419 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003420 auto *Fn = llvm::Function::Create(
3421 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3422 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003423 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003424 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003425 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003426 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003427
Alexey Bataev9ff80832018-04-16 20:16:21 +00003428 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003429
3430 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3431 Address LocalReduceList(
3432 Bld.CreatePointerBitCastOrAddrSpaceCast(
3433 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3434 C.VoidPtrTy, SourceLocation()),
3435 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3436 CGF.getPointerAlign());
3437
3438 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3439 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3440 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3441
3442 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3443 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3444 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3445
3446 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3447 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3448 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3449
3450 // Create a local thread-private variable to host the Reduce list
3451 // from a remote lane.
3452 Address RemoteReduceList =
3453 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3454
3455 // This loop iterates through the list of reduce elements and copies,
3456 // element by element, from a remote lane in the warp to RemoteReduceList,
3457 // hosted on the thread's stack.
3458 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3459 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003460 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3461 /*ScratchpadIndex=*/nullptr,
3462 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003463
3464 // The actions to be performed on the Remote Reduce list is dependent
3465 // on the algorithm version.
3466 //
3467 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3468 // LaneId % 2 == 0 && Offset > 0):
3469 // do the reduction value aggregation
3470 //
3471 // The thread local variable Reduce list is mutated in place to host the
3472 // reduced data, which is the aggregated value produced from local and
3473 // remote lanes.
3474 //
3475 // Note that AlgoVer is expected to be a constant integer known at compile
3476 // time.
3477 // When AlgoVer==0, the first conjunction evaluates to true, making
3478 // the entire predicate true during compile time.
3479 // When AlgoVer==1, the second conjunction has only the second part to be
3480 // evaluated during runtime. Other conjunctions evaluates to false
3481 // during compile time.
3482 // When AlgoVer==2, the third conjunction has only the second part to be
3483 // evaluated during runtime. Other conjunctions evaluates to false
3484 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003485 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003486
Alexey Bataev9ff80832018-04-16 20:16:21 +00003487 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3488 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003489 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3490
Alexey Bataev9ff80832018-04-16 20:16:21 +00003491 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3492 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3493 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003494 CondAlgo2 = Bld.CreateAnd(
3495 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3496
Alexey Bataev9ff80832018-04-16 20:16:21 +00003497 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003498 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3499
3500 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3501 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3502 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3503 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3504
3505 CGF.EmitBlock(ThenBB);
3506 // reduce_function(LocalReduceList, RemoteReduceList)
3507 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3508 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3509 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3510 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003511 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3512 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003513 Bld.CreateBr(MergeBB);
3514
3515 CGF.EmitBlock(ElseBB);
3516 Bld.CreateBr(MergeBB);
3517
3518 CGF.EmitBlock(MergeBB);
3519
3520 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3521 // Reduce list.
3522 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003523 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003524 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3525
3526 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3527 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3528 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3529 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3530
3531 CGF.EmitBlock(CpyThenBB);
3532 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3533 RemoteReduceList, LocalReduceList);
3534 Bld.CreateBr(CpyMergeBB);
3535
3536 CGF.EmitBlock(CpyElseBB);
3537 Bld.CreateBr(CpyMergeBB);
3538
3539 CGF.EmitBlock(CpyMergeBB);
3540
3541 CGF.FinishFunction();
3542 return Fn;
3543}
3544
Alexey Bataev8061acd2019-02-20 16:36:22 +00003545/// This function emits a helper that copies all the reduction variables from
3546/// the team into the provided global buffer for the reduction variables.
3547///
3548/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3549/// For all data entries D in reduce_data:
3550/// Copy local D to buffer.D[Idx]
3551static llvm::Value *emitListToGlobalCopyFunction(
3552 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3553 QualType ReductionArrayTy, SourceLocation Loc,
3554 const RecordDecl *TeamReductionRec,
3555 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3556 &VarFieldMap) {
3557 ASTContext &C = CGM.getContext();
3558
3559 // Buffer: global reduction buffer.
3560 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3561 C.VoidPtrTy, ImplicitParamDecl::Other);
3562 // Idx: index of the buffer.
3563 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3564 ImplicitParamDecl::Other);
3565 // ReduceList: thread local Reduce list.
3566 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3567 C.VoidPtrTy, ImplicitParamDecl::Other);
3568 FunctionArgList Args;
3569 Args.push_back(&BufferArg);
3570 Args.push_back(&IdxArg);
3571 Args.push_back(&ReduceListArg);
3572
3573 const CGFunctionInfo &CGFI =
3574 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3575 auto *Fn = llvm::Function::Create(
3576 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3577 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3578 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3579 Fn->setDoesNotRecurse();
3580 CodeGenFunction CGF(CGM);
3581 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3582
3583 CGBuilderTy &Bld = CGF.Builder;
3584
3585 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3586 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3587 Address LocalReduceList(
3588 Bld.CreatePointerBitCastOrAddrSpaceCast(
3589 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3590 C.VoidPtrTy, Loc),
3591 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3592 CGF.getPointerAlign());
3593 QualType StaticTy = C.getRecordType(TeamReductionRec);
3594 llvm::Type *LLVMReductionsBufferTy =
3595 CGM.getTypes().ConvertTypeForMem(StaticTy);
3596 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3597 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3598 LLVMReductionsBufferTy->getPointerTo());
3599 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3600 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3601 /*Volatile=*/false, C.IntTy,
3602 Loc)};
3603 unsigned Idx = 0;
3604 for (const Expr *Private : Privates) {
3605 // Reduce element = LocalReduceList[i]
3606 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3607 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3608 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3609 // elemptr = ((CopyType*)(elemptrptr)) + I
3610 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3611 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3612 Address ElemPtr =
3613 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3614 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3615 // Global = Buffer.VD[Idx];
3616 const FieldDecl *FD = VarFieldMap.lookup(VD);
3617 LValue GlobLVal = CGF.EmitLValueForField(
3618 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3619 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3620 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3621 switch (CGF.getEvaluationKind(Private->getType())) {
3622 case TEK_Scalar: {
3623 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3624 Private->getType(), Loc);
3625 CGF.EmitStoreOfScalar(V, GlobLVal);
3626 break;
3627 }
3628 case TEK_Complex: {
3629 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3630 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3631 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3632 break;
3633 }
3634 case TEK_Aggregate:
3635 CGF.EmitAggregateCopy(GlobLVal,
3636 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3637 Private->getType(), AggValueSlot::DoesNotOverlap);
3638 break;
3639 }
3640 ++Idx;
3641 }
3642
3643 CGF.FinishFunction();
3644 return Fn;
3645}
3646
3647/// This function emits a helper that reduces all the reduction variables from
3648/// the team into the provided global buffer for the reduction variables.
3649///
3650/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3651/// void *GlobPtrs[];
3652/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3653/// ...
3654/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3655/// reduce_function(GlobPtrs, reduce_data);
3656static llvm::Value *emitListToGlobalReduceFunction(
3657 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3658 QualType ReductionArrayTy, SourceLocation Loc,
3659 const RecordDecl *TeamReductionRec,
3660 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3661 &VarFieldMap,
3662 llvm::Function *ReduceFn) {
3663 ASTContext &C = CGM.getContext();
3664
3665 // Buffer: global reduction buffer.
3666 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3667 C.VoidPtrTy, ImplicitParamDecl::Other);
3668 // Idx: index of the buffer.
3669 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3670 ImplicitParamDecl::Other);
3671 // ReduceList: thread local Reduce list.
3672 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3673 C.VoidPtrTy, ImplicitParamDecl::Other);
3674 FunctionArgList Args;
3675 Args.push_back(&BufferArg);
3676 Args.push_back(&IdxArg);
3677 Args.push_back(&ReduceListArg);
3678
3679 const CGFunctionInfo &CGFI =
3680 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3681 auto *Fn = llvm::Function::Create(
3682 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3683 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3684 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3685 Fn->setDoesNotRecurse();
3686 CodeGenFunction CGF(CGM);
3687 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3688
3689 CGBuilderTy &Bld = CGF.Builder;
3690
3691 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3692 QualType StaticTy = C.getRecordType(TeamReductionRec);
3693 llvm::Type *LLVMReductionsBufferTy =
3694 CGM.getTypes().ConvertTypeForMem(StaticTy);
3695 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3696 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3697 LLVMReductionsBufferTy->getPointerTo());
3698
3699 // 1. Build a list of reduction variables.
3700 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3701 Address ReductionList =
3702 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3703 auto IPriv = Privates.begin();
3704 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3705 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3706 /*Volatile=*/false, C.IntTy,
3707 Loc)};
3708 unsigned Idx = 0;
3709 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3710 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3711 // Global = Buffer.VD[Idx];
3712 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3713 const FieldDecl *FD = VarFieldMap.lookup(VD);
3714 LValue GlobLVal = CGF.EmitLValueForField(
3715 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3716 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3717 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3718 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3719 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3720 // Store array size.
3721 ++Idx;
3722 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3723 llvm::Value *Size = CGF.Builder.CreateIntCast(
3724 CGF.getVLASize(
3725 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3726 .NumElts,
3727 CGF.SizeTy, /*isSigned=*/false);
3728 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3729 Elem);
3730 }
3731 }
3732
3733 // Call reduce_function(GlobalReduceList, ReduceList)
3734 llvm::Value *GlobalReduceList =
3735 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3736 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3737 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3738 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3739 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3740 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3741 CGF.FinishFunction();
3742 return Fn;
3743}
3744
3745/// This function emits a helper that copies all the reduction variables from
3746/// the team into the provided global buffer for the reduction variables.
3747///
3748/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3749/// For all data entries D in reduce_data:
3750/// Copy buffer.D[Idx] to local D;
3751static llvm::Value *emitGlobalToListCopyFunction(
3752 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3753 QualType ReductionArrayTy, SourceLocation Loc,
3754 const RecordDecl *TeamReductionRec,
3755 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3756 &VarFieldMap) {
3757 ASTContext &C = CGM.getContext();
3758
3759 // Buffer: global reduction buffer.
3760 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3761 C.VoidPtrTy, ImplicitParamDecl::Other);
3762 // Idx: index of the buffer.
3763 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3764 ImplicitParamDecl::Other);
3765 // ReduceList: thread local Reduce list.
3766 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3767 C.VoidPtrTy, ImplicitParamDecl::Other);
3768 FunctionArgList Args;
3769 Args.push_back(&BufferArg);
3770 Args.push_back(&IdxArg);
3771 Args.push_back(&ReduceListArg);
3772
3773 const CGFunctionInfo &CGFI =
3774 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3775 auto *Fn = llvm::Function::Create(
3776 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3777 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3778 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3779 Fn->setDoesNotRecurse();
3780 CodeGenFunction CGF(CGM);
3781 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3782
3783 CGBuilderTy &Bld = CGF.Builder;
3784
3785 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3786 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3787 Address LocalReduceList(
3788 Bld.CreatePointerBitCastOrAddrSpaceCast(
3789 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3790 C.VoidPtrTy, Loc),
3791 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3792 CGF.getPointerAlign());
3793 QualType StaticTy = C.getRecordType(TeamReductionRec);
3794 llvm::Type *LLVMReductionsBufferTy =
3795 CGM.getTypes().ConvertTypeForMem(StaticTy);
3796 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3797 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3798 LLVMReductionsBufferTy->getPointerTo());
3799
3800 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3801 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3802 /*Volatile=*/false, C.IntTy,
3803 Loc)};
3804 unsigned Idx = 0;
3805 for (const Expr *Private : Privates) {
3806 // Reduce element = LocalReduceList[i]
3807 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3808 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3809 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3810 // elemptr = ((CopyType*)(elemptrptr)) + I
3811 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3812 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3813 Address ElemPtr =
3814 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3815 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3816 // Global = Buffer.VD[Idx];
3817 const FieldDecl *FD = VarFieldMap.lookup(VD);
3818 LValue GlobLVal = CGF.EmitLValueForField(
3819 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3820 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3821 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3822 switch (CGF.getEvaluationKind(Private->getType())) {
3823 case TEK_Scalar: {
3824 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3825 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3826 break;
3827 }
3828 case TEK_Complex: {
3829 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3830 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3831 /*isInit=*/false);
3832 break;
3833 }
3834 case TEK_Aggregate:
3835 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3836 GlobLVal, Private->getType(),
3837 AggValueSlot::DoesNotOverlap);
3838 break;
3839 }
3840 ++Idx;
3841 }
3842
3843 CGF.FinishFunction();
3844 return Fn;
3845}
3846
3847/// This function emits a helper that reduces all the reduction variables from
3848/// the team into the provided global buffer for the reduction variables.
3849///
3850/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3851/// void *GlobPtrs[];
3852/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3853/// ...
3854/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3855/// reduce_function(reduce_data, GlobPtrs);
3856static llvm::Value *emitGlobalToListReduceFunction(
3857 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3858 QualType ReductionArrayTy, SourceLocation Loc,
3859 const RecordDecl *TeamReductionRec,
3860 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3861 &VarFieldMap,
3862 llvm::Function *ReduceFn) {
3863 ASTContext &C = CGM.getContext();
3864
3865 // Buffer: global reduction buffer.
3866 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3867 C.VoidPtrTy, ImplicitParamDecl::Other);
3868 // Idx: index of the buffer.
3869 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3870 ImplicitParamDecl::Other);
3871 // ReduceList: thread local Reduce list.
3872 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3873 C.VoidPtrTy, ImplicitParamDecl::Other);
3874 FunctionArgList Args;
3875 Args.push_back(&BufferArg);
3876 Args.push_back(&IdxArg);
3877 Args.push_back(&ReduceListArg);
3878
3879 const CGFunctionInfo &CGFI =
3880 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3881 auto *Fn = llvm::Function::Create(
3882 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3883 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3884 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3885 Fn->setDoesNotRecurse();
3886 CodeGenFunction CGF(CGM);
3887 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3888
3889 CGBuilderTy &Bld = CGF.Builder;
3890
3891 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3892 QualType StaticTy = C.getRecordType(TeamReductionRec);
3893 llvm::Type *LLVMReductionsBufferTy =
3894 CGM.getTypes().ConvertTypeForMem(StaticTy);
3895 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3896 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3897 LLVMReductionsBufferTy->getPointerTo());
3898
3899 // 1. Build a list of reduction variables.
3900 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3901 Address ReductionList =
3902 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3903 auto IPriv = Privates.begin();
3904 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3905 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3906 /*Volatile=*/false, C.IntTy,
3907 Loc)};
3908 unsigned Idx = 0;
3909 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3910 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3911 // Global = Buffer.VD[Idx];
3912 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3913 const FieldDecl *FD = VarFieldMap.lookup(VD);
3914 LValue GlobLVal = CGF.EmitLValueForField(
3915 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3916 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3917 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3918 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3919 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3920 // Store array size.
3921 ++Idx;
3922 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3923 llvm::Value *Size = CGF.Builder.CreateIntCast(
3924 CGF.getVLASize(
3925 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3926 .NumElts,
3927 CGF.SizeTy, /*isSigned=*/false);
3928 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3929 Elem);
3930 }
3931 }
3932
3933 // Call reduce_function(ReduceList, GlobalReduceList)
3934 llvm::Value *GlobalReduceList =
3935 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3936 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3937 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3938 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3939 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3940 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3941 CGF.FinishFunction();
3942 return Fn;
3943}
3944
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003945///
3946/// Design of OpenMP reductions on the GPU
3947///
3948/// Consider a typical OpenMP program with one or more reduction
3949/// clauses:
3950///
3951/// float foo;
3952/// double bar;
3953/// #pragma omp target teams distribute parallel for \
3954/// reduction(+:foo) reduction(*:bar)
3955/// for (int i = 0; i < N; i++) {
3956/// foo += A[i]; bar *= B[i];
3957/// }
3958///
3959/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3960/// all teams. In our OpenMP implementation on the NVPTX device an
3961/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3962/// within a team are mapped to CUDA threads within a threadblock.
3963/// Our goal is to efficiently aggregate values across all OpenMP
3964/// threads such that:
3965///
3966/// - the compiler and runtime are logically concise, and
3967/// - the reduction is performed efficiently in a hierarchical
3968/// manner as follows: within OpenMP threads in the same warp,
3969/// across warps in a threadblock, and finally across teams on
3970/// the NVPTX device.
3971///
3972/// Introduction to Decoupling
3973///
3974/// We would like to decouple the compiler and the runtime so that the
3975/// latter is ignorant of the reduction variables (number, data types)
3976/// and the reduction operators. This allows a simpler interface
3977/// and implementation while still attaining good performance.
3978///
3979/// Pseudocode for the aforementioned OpenMP program generated by the
3980/// compiler is as follows:
3981///
3982/// 1. Create private copies of reduction variables on each OpenMP
3983/// thread: 'foo_private', 'bar_private'
3984/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3985/// to it and writes the result in 'foo_private' and 'bar_private'
3986/// respectively.
3987/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3988/// and store the result on the team master:
3989///
Alexey Bataev8e009032019-01-04 17:25:09 +00003990/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003991/// reduceData, shuffleReduceFn, interWarpCpyFn)
3992///
3993/// where:
3994/// struct ReduceData {
3995/// double *foo;
3996/// double *bar;
3997/// } reduceData
3998/// reduceData.foo = &foo_private
3999/// reduceData.bar = &bar_private
4000///
4001/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4002/// auxiliary functions generated by the compiler that operate on
4003/// variables of type 'ReduceData'. They aid the runtime perform
4004/// algorithmic steps in a data agnostic manner.
4005///
4006/// 'shuffleReduceFn' is a pointer to a function that reduces data
4007/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4008/// same warp. It takes the following arguments as input:
4009///
4010/// a. variable of type 'ReduceData' on the calling lane,
4011/// b. its lane_id,
4012/// c. an offset relative to the current lane_id to generate a
4013/// remote_lane_id. The remote lane contains the second
4014/// variable of type 'ReduceData' that is to be reduced.
4015/// d. an algorithm version parameter determining which reduction
4016/// algorithm to use.
4017///
4018/// 'shuffleReduceFn' retrieves data from the remote lane using
4019/// efficient GPU shuffle intrinsics and reduces, using the
4020/// algorithm specified by the 4th parameter, the two operands
4021/// element-wise. The result is written to the first operand.
4022///
4023/// Different reduction algorithms are implemented in different
4024/// runtime functions, all calling 'shuffleReduceFn' to perform
4025/// the essential reduction step. Therefore, based on the 4th
4026/// parameter, this function behaves slightly differently to
4027/// cooperate with the runtime to ensure correctness under
4028/// different circumstances.
4029///
4030/// 'InterWarpCpyFn' is a pointer to a function that transfers
4031/// reduced variables across warps. It tunnels, through CUDA
4032/// shared memory, the thread-private data of type 'ReduceData'
4033/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004034/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4035/// The last team writes the global reduced value to memory.
4036///
4037/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4038/// reduceData, shuffleReduceFn, interWarpCpyFn,
4039/// scratchpadCopyFn, loadAndReduceFn)
4040///
4041/// 'scratchpadCopyFn' is a helper that stores reduced
4042/// data from the team master to a scratchpad array in
4043/// global memory.
4044///
4045/// 'loadAndReduceFn' is a helper that loads data from
4046/// the scratchpad array and reduces it with the input
4047/// operand.
4048///
4049/// These compiler generated functions hide address
4050/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004051/// 5. if ret == 1:
4052/// The team master of the last team stores the reduced
4053/// result to the globals in memory.
4054/// foo += reduceData.foo; bar *= reduceData.bar
4055///
4056///
4057/// Warp Reduction Algorithms
4058///
4059/// On the warp level, we have three algorithms implemented in the
4060/// OpenMP runtime depending on the number of active lanes:
4061///
4062/// Full Warp Reduction
4063///
4064/// The reduce algorithm within a warp where all lanes are active
4065/// is implemented in the runtime as follows:
4066///
4067/// full_warp_reduce(void *reduce_data,
4068/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4069/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4070/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4071/// }
4072///
4073/// The algorithm completes in log(2, WARPSIZE) steps.
4074///
4075/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4076/// not used therefore we save instructions by not retrieving lane_id
4077/// from the corresponding special registers. The 4th parameter, which
4078/// represents the version of the algorithm being used, is set to 0 to
4079/// signify full warp reduction.
4080///
4081/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4082///
4083/// #reduce_elem refers to an element in the local lane's data structure
4084/// #remote_elem is retrieved from a remote lane
4085/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4086/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4087///
4088/// Contiguous Partial Warp Reduction
4089///
4090/// This reduce algorithm is used within a warp where only the first
4091/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4092/// number of OpenMP threads in a parallel region is not a multiple of
4093/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4094///
4095/// void
4096/// contiguous_partial_reduce(void *reduce_data,
4097/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4098/// int size, int lane_id) {
4099/// int curr_size;
4100/// int offset;
4101/// curr_size = size;
4102/// mask = curr_size/2;
4103/// while (offset>0) {
4104/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4105/// curr_size = (curr_size+1)/2;
4106/// offset = curr_size/2;
4107/// }
4108/// }
4109///
4110/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4111///
4112/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4113/// if (lane_id < offset)
4114/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4115/// else
4116/// reduce_elem = remote_elem
4117///
4118/// This algorithm assumes that the data to be reduced are located in a
4119/// contiguous subset of lanes starting from the first. When there is
4120/// an odd number of active lanes, the data in the last lane is not
4121/// aggregated with any other lane's dat but is instead copied over.
4122///
4123/// Dispersed Partial Warp Reduction
4124///
4125/// This algorithm is used within a warp when any discontiguous subset of
4126/// lanes are active. It is used to implement the reduction operation
4127/// across lanes in an OpenMP simd region or in a nested parallel region.
4128///
4129/// void
4130/// dispersed_partial_reduce(void *reduce_data,
4131/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4132/// int size, remote_id;
4133/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4134/// do {
4135/// remote_id = next_active_lane_id_right_after_me();
4136/// # the above function returns 0 of no active lane
4137/// # is present right after the current lane.
4138/// size = number_of_active_lanes_in_this_warp();
4139/// logical_lane_id /= 2;
4140/// ShuffleReduceFn(reduce_data, logical_lane_id,
4141/// remote_id-1-threadIdx.x, 2);
4142/// } while (logical_lane_id % 2 == 0 && size > 1);
4143/// }
4144///
4145/// There is no assumption made about the initial state of the reduction.
4146/// Any number of lanes (>=1) could be active at any position. The reduction
4147/// result is returned in the first active lane.
4148///
4149/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4150///
4151/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4152/// if (lane_id % 2 == 0 && offset > 0)
4153/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4154/// else
4155/// reduce_elem = remote_elem
4156///
4157///
4158/// Intra-Team Reduction
4159///
4160/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004161/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004162/// threads in a team. It first reduces within a warp using the
4163/// aforementioned algorithms. We then proceed to gather all such
4164/// reduced values at the first warp.
4165///
4166/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4167/// data from each of the "warp master" (zeroth lane of each warp, where
4168/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4169/// a mathematical sense) the problem of reduction across warp masters in
4170/// a block to the problem of warp reduction.
4171///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004172///
4173/// Inter-Team Reduction
4174///
4175/// Once a team has reduced its data to a single value, it is stored in
4176/// a global scratchpad array. Since each team has a distinct slot, this
4177/// can be done without locking.
4178///
4179/// The last team to write to the scratchpad array proceeds to reduce the
4180/// scratchpad array. One or more workers in the last team use the helper
4181/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4182/// the k'th worker reduces every k'th element.
4183///
Alexey Bataev8e009032019-01-04 17:25:09 +00004184/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004185/// reduce across workers and compute a globally reduced value.
4186///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004187void CGOpenMPRuntimeNVPTX::emitReduction(
4188 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4189 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4190 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4191 if (!CGF.HaveInsertPoint())
4192 return;
4193
4194 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004195#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004196 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004197#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004198
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004199 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004200 assert(!TeamsReduction && !ParallelReduction &&
4201 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004202 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4203 ReductionOps, Options);
4204 return;
4205 }
4206
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004207 assert((TeamsReduction || ParallelReduction) &&
4208 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004209
Alexey Bataeva1166022018-11-27 21:24:54 +00004210 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004211 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004212 // or
4213 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004214 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004215 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004216
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004217 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004218 ASTContext &C = CGM.getContext();
4219 // 1. Build a list of reduction variables.
4220 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4221 auto Size = RHSExprs.size();
4222 for (const Expr *E : Privates) {
4223 if (E->getType()->isVariablyModifiedType())
4224 // Reserve place for array size.
4225 ++Size;
4226 }
4227 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4228 QualType ReductionArrayTy =
4229 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4230 /*IndexTypeQuals=*/0);
4231 Address ReductionList =
4232 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4233 auto IPriv = Privates.begin();
4234 unsigned Idx = 0;
4235 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4236 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4237 CGF.Builder.CreateStore(
4238 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4239 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4240 Elem);
4241 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4242 // Store array size.
4243 ++Idx;
4244 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4245 llvm::Value *Size = CGF.Builder.CreateIntCast(
4246 CGF.getVLASize(
4247 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4248 .NumElts,
4249 CGF.SizeTy, /*isSigned=*/false);
4250 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4251 Elem);
4252 }
4253 }
4254
4255 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4256 ReductionList.getPointer(), CGF.VoidPtrTy);
4257 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004258 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4259 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004260 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4261 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4262 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4263 llvm::Value *InterWarpCopyFn =
4264 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4265
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004266 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004267 llvm::Value *Args[] = {RTLoc,
4268 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004269 CGF.Builder.getInt32(RHSExprs.size()),
4270 ReductionArrayTySize,
4271 RL,
4272 ShuffleAndReduceFn,
4273 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004274
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004275 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004276 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004277 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4278 Args);
4279 } else {
4280 assert(TeamsReduction && "expected teams reduction.");
4281 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4282 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4283 int Cnt = 0;
4284 for (const Expr *DRE : Privates) {
4285 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4286 ++Cnt;
4287 }
4288 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4289 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4290 C.getLangOpts().OpenMPCUDAReductionBufNum);
4291 TeamsReductions.push_back(TeamReductionRec);
4292 if (!KernelTeamsReductionPtr) {
4293 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4294 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4295 llvm::GlobalValue::InternalLinkage, nullptr,
4296 "_openmp_teams_reductions_buffer_$_$ptr");
4297 }
4298 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4299 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4300 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4301 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4302 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4303 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4304 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4305 ReductionFn);
4306 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4307 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4308 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4309 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4310 ReductionFn);
4311
4312 llvm::Value *Args[] = {
4313 RTLoc,
4314 ThreadId,
4315 GlobalBufferPtr,
4316 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4317 RL,
4318 ShuffleAndReduceFn,
4319 InterWarpCopyFn,
4320 GlobalToBufferCpyFn,
4321 GlobalToBufferRedFn,
4322 BufferToGlobalCpyFn,
4323 BufferToGlobalRedFn};
4324
4325 Res = CGF.EmitRuntimeCall(
4326 createNVPTXRuntimeFunction(
4327 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004328 Args);
4329 }
4330
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004331 // 5. Build if (res == 1)
4332 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4333 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4334 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4335 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4336 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004337
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004338 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004339 // thread in each team.
4340 // __kmpc_end_reduce{_nowait}(<gtid>);
4341 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004342 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004343
4344 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004345 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004346 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4347 auto IPriv = Privates.begin();
4348 auto ILHS = LHSExprs.begin();
4349 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004350 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004351 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4352 cast<DeclRefExpr>(*IRHS));
4353 ++IPriv;
4354 ++ILHS;
4355 ++IRHS;
4356 }
4357 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004358 llvm::Value *EndArgs[] = {ThreadId};
4359 RegionCodeGenTy RCG(CodeGen);
4360 NVPTXActionTy Action(
4361 nullptr, llvm::None,
4362 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4363 EndArgs);
4364 RCG.setAction(Action);
4365 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004366 // There is no need to emit line number for unconditional branch.
4367 (void)ApplyDebugLocation::CreateEmpty(CGF);
4368 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004369}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004370
4371const VarDecl *
4372CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4373 const VarDecl *NativeParam) const {
4374 if (!NativeParam->getType()->isReferenceType())
4375 return NativeParam;
4376 QualType ArgType = NativeParam->getType();
4377 QualifierCollector QC;
4378 const Type *NonQualTy = QC.strip(ArgType);
4379 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4380 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4381 if (Attr->getCaptureKind() == OMPC_map) {
4382 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4383 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004384 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4385 PointeeTy.isConstant(CGM.getContext())) {
4386 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4387 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004388 }
4389 }
4390 ArgType = CGM.getContext().getPointerType(PointeeTy);
4391 QC.addRestrict();
4392 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004393 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004394 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004395 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004396 return ImplicitParamDecl::Create(
4397 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4398 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004399 return ParmVarDecl::Create(
4400 CGM.getContext(),
4401 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004402 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004403 NativeParam->getIdentifier(), ArgType,
4404 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004405}
4406
4407Address
4408CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4409 const VarDecl *NativeParam,
4410 const VarDecl *TargetParam) const {
4411 assert(NativeParam != TargetParam &&
4412 NativeParam->getType()->isReferenceType() &&
4413 "Native arg must not be the same as target arg.");
4414 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4415 QualType NativeParamType = NativeParam->getType();
4416 QualifierCollector QC;
4417 const Type *NonQualTy = QC.strip(NativeParamType);
4418 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4419 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004420 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004421 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004422 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004423 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004424 // First cast to generic.
4425 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4426 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4427 /*AddrSpace=*/0));
4428 // Cast from generic to native address space.
4429 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4430 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4431 NativePointeeAddrSpace));
4432 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4433 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004434 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004435 return NativeParamAddr;
4436}
4437
4438void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004439 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004440 ArrayRef<llvm::Value *> Args) const {
4441 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004442 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004443 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004444 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004445 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4446 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4447 break;
4448 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004449 llvm::Type *TargetType = FnType->getParamType(I);
4450 llvm::Value *NativeArg = Args[I];
4451 if (!TargetType->isPointerTy()) {
4452 TargetArgs.emplace_back(NativeArg);
4453 continue;
4454 }
4455 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004456 NativeArg,
4457 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004458 TargetArgs.emplace_back(
4459 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4460 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004461 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004462}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004463
4464/// Emit function which wraps the outline parallel region
4465/// and controls the arguments which are passed to this function.
4466/// The wrapper ensures that the outlined function is called
4467/// with the correct arguments when data is shared.
4468llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4469 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4470 ASTContext &Ctx = CGM.getContext();
4471 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4472
4473 // Create a function that takes as argument the source thread.
4474 FunctionArgList WrapperArgs;
4475 QualType Int16QTy =
4476 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4477 QualType Int32QTy =
4478 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004479 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004480 /*Id=*/nullptr, Int16QTy,
4481 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004482 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004483 /*Id=*/nullptr, Int32QTy,
4484 ImplicitParamDecl::Other);
4485 WrapperArgs.emplace_back(&ParallelLevelArg);
4486 WrapperArgs.emplace_back(&WrapperArg);
4487
Alexey Bataev9ff80832018-04-16 20:16:21 +00004488 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004489 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4490
4491 auto *Fn = llvm::Function::Create(
4492 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004493 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004494 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004495 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004496 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004497
4498 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4499 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004500 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004501
4502 const auto *RD = CS.getCapturedRecordDecl();
4503 auto CurField = RD->field_begin();
4504
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004505 Address ZeroAddr = CGF.CreateMemTemp(
4506 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4507 /*Name*/ ".zero.addr");
4508 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004509 // Get the array of arguments.
4510 SmallVector<llvm::Value *, 8> Args;
4511
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004512 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4513 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004514
4515 CGBuilderTy &Bld = CGF.Builder;
4516 auto CI = CS.capture_begin();
4517
4518 // Use global memory for data sharing.
4519 // Handle passing of global args to workers.
4520 Address GlobalArgs =
4521 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4522 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4523 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4524 CGF.EmitRuntimeCall(
4525 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4526 DataSharingArgs);
4527
4528 // Retrieve the shared variables from the list of references returned
4529 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004530 Address SharedArgListAddress = Address::invalid();
4531 if (CS.capture_size() > 0 ||
4532 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4533 SharedArgListAddress = CGF.EmitLoadOfPointer(
4534 GlobalArgs, CGF.getContext()
4535 .getPointerType(CGF.getContext().getPointerType(
4536 CGF.getContext().VoidPtrTy))
4537 .castAs<PointerType>());
4538 }
4539 unsigned Idx = 0;
4540 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004541 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004542 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4543 Src, CGF.SizeTy->getPointerTo());
4544 llvm::Value *LB = CGF.EmitLoadOfScalar(
4545 TypedAddress,
4546 /*Volatile=*/false,
4547 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4548 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4549 Args.emplace_back(LB);
4550 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004551 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004552 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4553 Src, CGF.SizeTy->getPointerTo());
4554 llvm::Value *UB = CGF.EmitLoadOfScalar(
4555 TypedAddress,
4556 /*Volatile=*/false,
4557 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4558 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4559 Args.emplace_back(UB);
4560 ++Idx;
4561 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562 if (CS.capture_size() > 0) {
4563 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004564 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4565 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004566 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004567 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004568 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4569 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4570 /*Volatile=*/false,
4571 CGFContext.getPointerType(ElemTy),
4572 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004573 if (CI->capturesVariableByCopy() &&
4574 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004575 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4576 CI->getLocation());
4577 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004578 Args.emplace_back(Arg);
4579 }
4580 }
4581
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004582 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004583 CGF.FinishFunction();
4584 return Fn;
4585}
4586
4587void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4588 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004589 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4590 return;
4591
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004592 assert(D && "Expected function or captured|block decl.");
4593 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4594 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004595 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4596 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004597 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004598 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004599 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4600 Body = FD->getBody();
4601 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4602 Body = BD->getBody();
4603 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4604 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004605 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004606 if (NeedToDelayGlobalization &&
4607 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4608 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004609 }
4610 if (!Body)
4611 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004612 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004613 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004614 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004615 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004616 TeamAndReductions.first = nullptr;
4617 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004618 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4619 VarChecker.getEscapedVariableLengthDecls();
4620 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004621 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004622 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4623 I->getSecond().MappedParams =
4624 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4625 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4626 I->getSecond().EscapedParameters.insert(
4627 VarChecker.getEscapedParameters().begin(),
4628 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004629 I->getSecond().EscapedVariableLengthDecls.append(
4630 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004631 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004632 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004633 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004634 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004635 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004636 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004637 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004638 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004639 VarChecker.Visit(Body);
4640 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004641 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004642 I->getSecond().SecondaryLocalVarData.emplace();
4643 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4644 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4645 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4646 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004647 Data.insert(
4648 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004649 }
4650 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004651 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004652 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004653 struct GlobalizationScope final : EHScopeStack::Cleanup {
4654 GlobalizationScope() = default;
4655
4656 void Emit(CodeGenFunction &CGF, Flags flags) override {
4657 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004658 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004659 }
4660 };
4661 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004662 }
4663}
4664
4665Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4666 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004667 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4668 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4669 switch (A->getAllocatorType()) {
4670 // Use the default allocator here as by default local vars are
4671 // threadlocal.
4672 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4673 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004674 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4675 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004676 // Follow the user decision - use default allocation.
4677 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004678 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004679 // TODO: implement aupport for user-defined allocators.
4680 return Address::invalid();
4681 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4682 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4683 auto *GV = new llvm::GlobalVariable(
4684 CGM.getModule(), VarTy, /*isConstant=*/false,
4685 llvm::GlobalValue::InternalLinkage,
4686 llvm::Constant::getNullValue(VarTy), VD->getName(),
4687 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4688 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4689 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4690 GV->setAlignment(Align.getQuantity());
4691 return Address(GV, Align);
4692 }
4693 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4694 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4695 auto *GV = new llvm::GlobalVariable(
4696 CGM.getModule(), VarTy, /*isConstant=*/false,
4697 llvm::GlobalValue::InternalLinkage,
4698 llvm::Constant::getNullValue(VarTy), VD->getName(),
4699 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4700 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4701 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4702 GV->setAlignment(Align.getQuantity());
4703 return Address(GV, Align);
4704 }
4705 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4706 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4707 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4708 auto *GV = new llvm::GlobalVariable(
4709 CGM.getModule(), VarTy, /*isConstant=*/false,
4710 llvm::GlobalValue::InternalLinkage,
4711 llvm::Constant::getNullValue(VarTy), VD->getName());
4712 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4713 GV->setAlignment(Align.getQuantity());
4714 return Address(GV, Align);
4715 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004716 }
4717 }
4718
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004719 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4720 return Address::invalid();
4721
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004722 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004723 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4724 if (I == FunctionGlobalizedDecls.end())
4725 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004726 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004727 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004728 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004729 if (VD->hasAttrs()) {
4730 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4731 E(VD->attr_end());
4732 IT != E; ++IT) {
4733 auto VDI = I->getSecond().LocalVarData.find(
4734 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4735 ->getCanonicalDecl());
4736 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004737 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004738 }
4739 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004740
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004741 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004742}
4743
4744void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004745 FunctionGlobalizedDecls.erase(CGF.CurFn);
4746 CGOpenMPRuntime::functionFinished(CGF);
4747}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004748
4749void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4750 CodeGenFunction &CGF, const OMPLoopDirective &S,
4751 OpenMPDistScheduleClauseKind &ScheduleKind,
4752 llvm::Value *&Chunk) const {
4753 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4754 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4755 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4756 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4757 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004758 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004759 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004760 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4761 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004762}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004763
4764void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4765 CodeGenFunction &CGF, const OMPLoopDirective &S,
4766 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004767 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004768 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004769 // Chunk size is 1 in this case.
4770 llvm::APInt ChunkSize(32, 1);
4771 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4772 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4773 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004774}
Alexey Bataev60705422018-10-30 15:50:12 +00004775
4776void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4777 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4778 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4779 " Expected target-based directive.");
4780 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4781 for (const CapturedStmt::Capture &C : CS->captures()) {
4782 // Capture variables captured by reference in lambdas for target-based
4783 // directives.
4784 if (!C.capturesVariable())
4785 continue;
4786 const VarDecl *VD = C.getCapturedVar();
4787 const auto *RD = VD->getType()
4788 .getCanonicalType()
4789 .getNonReferenceType()
4790 ->getAsCXXRecordDecl();
4791 if (!RD || !RD->isLambda())
4792 continue;
4793 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4794 LValue VDLVal;
4795 if (VD->getType().getCanonicalType()->isReferenceType())
4796 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4797 else
4798 VDLVal = CGF.MakeAddrLValue(
4799 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4800 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4801 FieldDecl *ThisCapture = nullptr;
4802 RD->getCaptureFields(Captures, ThisCapture);
4803 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4804 LValue ThisLVal =
4805 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4806 llvm::Value *CXXThis = CGF.LoadCXXThis();
4807 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4808 }
4809 for (const LambdaCapture &LC : RD->captures()) {
4810 if (LC.getCaptureKind() != LCK_ByRef)
4811 continue;
4812 const VarDecl *VD = LC.getCapturedVar();
4813 if (!CS->capturesVariable(VD))
4814 continue;
4815 auto It = Captures.find(VD);
4816 assert(It != Captures.end() && "Found lambda capture without field.");
4817 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4818 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4819 if (VD->getType().getCanonicalType()->isReferenceType())
4820 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4821 VD->getType().getCanonicalType())
4822 .getAddress();
4823 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4824 }
4825 }
4826}
4827
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004828unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4829 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4830}
4831
Alexey Bataevc5687252019-03-21 19:35:27 +00004832bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4833 LangAS &AS) {
4834 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4835 return false;
4836 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4837 switch(A->getAllocatorType()) {
4838 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4839 // Not supported, fallback to the default mem space.
4840 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4841 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4842 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4843 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4844 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4845 AS = LangAS::Default;
4846 return true;
4847 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4848 AS = LangAS::cuda_constant;
4849 return true;
4850 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4851 AS = LangAS::cuda_shared;
4852 return true;
4853 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4854 llvm_unreachable("Expected predefined allocator for the variables with the "
4855 "static storage.");
4856 }
4857 return false;
4858}
4859
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004860// Get current CudaArch and ignore any unknown values
4861static CudaArch getCudaArch(CodeGenModule &CGM) {
4862 if (!CGM.getTarget().hasFeature("ptx"))
4863 return CudaArch::UNKNOWN;
4864 llvm::StringMap<bool> Features;
4865 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4866 CGM.getTarget().getTargetOpts().CPU,
4867 CGM.getTarget().getTargetOpts().Features);
4868 for (const auto &Feature : Features) {
4869 if (Feature.getValue()) {
4870 CudaArch Arch = StringToCudaArch(Feature.getKey());
4871 if (Arch != CudaArch::UNKNOWN)
4872 return Arch;
4873 }
4874 }
4875 return CudaArch::UNKNOWN;
4876}
4877
4878/// Check to see if target architecture supports unified addressing which is
4879/// a restriction for OpenMP requires clause "unified_shared_memory".
4880void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004881 const OMPRequiresDecl *D) const {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004882 for (const OMPClause *Clause : D->clauselists()) {
4883 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4884 switch (getCudaArch(CGM)) {
4885 case CudaArch::SM_20:
4886 case CudaArch::SM_21:
4887 case CudaArch::SM_30:
4888 case CudaArch::SM_32:
4889 case CudaArch::SM_35:
4890 case CudaArch::SM_37:
4891 case CudaArch::SM_50:
4892 case CudaArch::SM_52:
4893 case CudaArch::SM_53:
4894 case CudaArch::SM_60:
4895 case CudaArch::SM_61:
4896 case CudaArch::SM_62:
4897 CGM.Error(Clause->getBeginLoc(),
4898 "Target architecture does not support unified addressing");
4899 return;
4900 case CudaArch::SM_70:
4901 case CudaArch::SM_72:
4902 case CudaArch::SM_75:
4903 case CudaArch::GFX600:
4904 case CudaArch::GFX601:
4905 case CudaArch::GFX700:
4906 case CudaArch::GFX701:
4907 case CudaArch::GFX702:
4908 case CudaArch::GFX703:
4909 case CudaArch::GFX704:
4910 case CudaArch::GFX801:
4911 case CudaArch::GFX802:
4912 case CudaArch::GFX803:
4913 case CudaArch::GFX810:
4914 case CudaArch::GFX900:
4915 case CudaArch::GFX902:
4916 case CudaArch::GFX904:
4917 case CudaArch::GFX906:
4918 case CudaArch::GFX909:
4919 case CudaArch::UNKNOWN:
4920 break;
4921 case CudaArch::LAST:
4922 llvm_unreachable("Unexpected Cuda arch.");
4923 }
4924 }
4925 }
4926}
4927
Alexey Bataeve4090182018-11-02 14:54:07 +00004928/// Get number of SMs and number of blocks per SM.
4929static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4930 std::pair<unsigned, unsigned> Data;
4931 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4932 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4933 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4934 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4935 if (Data.first && Data.second)
4936 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004937 switch (getCudaArch(CGM)) {
4938 case CudaArch::SM_20:
4939 case CudaArch::SM_21:
4940 case CudaArch::SM_30:
4941 case CudaArch::SM_32:
4942 case CudaArch::SM_35:
4943 case CudaArch::SM_37:
4944 case CudaArch::SM_50:
4945 case CudaArch::SM_52:
4946 case CudaArch::SM_53:
4947 return {16, 16};
4948 case CudaArch::SM_60:
4949 case CudaArch::SM_61:
4950 case CudaArch::SM_62:
4951 return {56, 32};
4952 case CudaArch::SM_70:
4953 case CudaArch::SM_72:
4954 case CudaArch::SM_75:
4955 return {84, 32};
4956 case CudaArch::GFX600:
4957 case CudaArch::GFX601:
4958 case CudaArch::GFX700:
4959 case CudaArch::GFX701:
4960 case CudaArch::GFX702:
4961 case CudaArch::GFX703:
4962 case CudaArch::GFX704:
4963 case CudaArch::GFX801:
4964 case CudaArch::GFX802:
4965 case CudaArch::GFX803:
4966 case CudaArch::GFX810:
4967 case CudaArch::GFX900:
4968 case CudaArch::GFX902:
4969 case CudaArch::GFX904:
4970 case CudaArch::GFX906:
4971 case CudaArch::GFX909:
4972 case CudaArch::UNKNOWN:
4973 break;
4974 case CudaArch::LAST:
4975 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004976 }
4977 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4978}
4979
4980void CGOpenMPRuntimeNVPTX::clear() {
4981 if (!GlobalizedRecords.empty()) {
4982 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004983 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4984 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004985 RecordDecl *StaticRD = C.buildImplicitRecord(
4986 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4987 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004988 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4989 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4990 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004991 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4992 if (Records.Records.empty())
4993 continue;
4994 unsigned Size = 0;
4995 unsigned RecAlignment = 0;
4996 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004997 QualType RDTy = C.getRecordType(RD);
4998 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004999 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005000 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005001 Size =
5002 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5003 }
5004 Size = llvm::alignTo(Size, RecAlignment);
5005 llvm::APInt ArySize(/*numBits=*/64, Size);
5006 QualType SubTy = C.getConstantArrayType(
5007 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005008 const bool UseSharedMemory = Size <= SharedMemorySize;
5009 auto *Field =
5010 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5011 SourceLocation(), SourceLocation(), nullptr, SubTy,
5012 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5013 /*BW=*/nullptr, /*Mutable=*/false,
5014 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005015 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005016 if (UseSharedMemory) {
5017 SharedStaticRD->addDecl(Field);
5018 SharedRecs.push_back(&Records);
5019 } else {
5020 StaticRD->addDecl(Field);
5021 GlobalRecs.push_back(&Records);
5022 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005023 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005024 Records.UseSharedMemory->setInitializer(
5025 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5026 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005027 // Allocate SharedMemorySize buffer for the shared memory.
5028 // FIXME: nvlink does not handle weak linkage correctly (object with the
5029 // different size are reported as erroneous).
5030 // Restore this code as sson as nvlink is fixed.
5031 if (!SharedStaticRD->field_empty()) {
5032 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5033 QualType SubTy = C.getConstantArrayType(
5034 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5035 auto *Field = FieldDecl::Create(
5036 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5037 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5038 /*BW=*/nullptr, /*Mutable=*/false,
5039 /*InitStyle=*/ICIS_NoInit);
5040 Field->setAccess(AS_public);
5041 SharedStaticRD->addDecl(Field);
5042 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005043 SharedStaticRD->completeDefinition();
5044 if (!SharedStaticRD->field_empty()) {
5045 QualType StaticTy = C.getRecordType(SharedStaticRD);
5046 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5047 auto *GV = new llvm::GlobalVariable(
5048 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005049 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005050 llvm::Constant::getNullValue(LLVMStaticTy),
5051 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5052 llvm::GlobalValue::NotThreadLocal,
5053 C.getTargetAddressSpace(LangAS::cuda_shared));
5054 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5055 GV, CGM.VoidPtrTy);
5056 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5057 Rec->Buffer->replaceAllUsesWith(Replacement);
5058 Rec->Buffer->eraseFromParent();
5059 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005060 }
5061 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005062 if (!StaticRD->field_empty()) {
5063 QualType StaticTy = C.getRecordType(StaticRD);
5064 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5065 llvm::APInt Size1(32, SMsBlockPerSM.second);
5066 QualType Arr1Ty =
5067 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5068 /*IndexTypeQuals=*/0);
5069 llvm::APInt Size2(32, SMsBlockPerSM.first);
5070 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5071 /*IndexTypeQuals=*/0);
5072 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005073 // FIXME: nvlink does not handle weak linkage correctly (object with the
5074 // different size are reported as erroneous).
5075 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005076 auto *GV = new llvm::GlobalVariable(
5077 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005078 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005079 llvm::Constant::getNullValue(LLVMArr2Ty),
5080 "_openmp_static_glob_rd_$_");
5081 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5082 GV, CGM.VoidPtrTy);
5083 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5084 Rec->Buffer->replaceAllUsesWith(Replacement);
5085 Rec->Buffer->eraseFromParent();
5086 }
5087 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005088 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005089 if (!TeamsReductions.empty()) {
5090 ASTContext &C = CGM.getContext();
5091 RecordDecl *StaticRD = C.buildImplicitRecord(
5092 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5093 StaticRD->startDefinition();
5094 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5095 QualType RecTy = C.getRecordType(TeamReductionRec);
5096 auto *Field = FieldDecl::Create(
5097 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5098 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5099 /*BW=*/nullptr, /*Mutable=*/false,
5100 /*InitStyle=*/ICIS_NoInit);
5101 Field->setAccess(AS_public);
5102 StaticRD->addDecl(Field);
5103 }
5104 StaticRD->completeDefinition();
5105 QualType StaticTy = C.getRecordType(StaticRD);
5106 llvm::Type *LLVMReductionsBufferTy =
5107 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005108 // FIXME: nvlink does not handle weak linkage correctly (object with the
5109 // different size are reported as erroneous).
5110 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005111 auto *GV = new llvm::GlobalVariable(
5112 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005113 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005114 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5115 "_openmp_teams_reductions_buffer_$_");
5116 KernelTeamsReductionPtr->setInitializer(
5117 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5118 CGM.VoidPtrTy));
5119 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005120 CGOpenMPRuntime::clear();
5121}