blob: 5a8f50bf316aa167da2ad557e8e96dbe83dd8052 [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 +0000224typedef std::pair<CharUnits /*Align*/, const ValueDecl *> VarsDataTy;
225static bool stable_sort_comparator(const VarsDataTy P1, const VarsDataTy P2) {
226 return P1.first > P2.first;
227}
228
229static RecordDecl *buildRecordForGlobalizedVars(
230 ASTContext &C, ArrayRef<const ValueDecl *> EscapedDecls,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000231 ArrayRef<const ValueDecl *> EscapedDeclsForTeams,
Alexey Bataev2adecff2018-09-21 14:22:53 +0000232 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
Alexey Bataev8061acd2019-02-20 16:36:22 +0000233 &MappedDeclsFields, int BufSize) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000234 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000235 return nullptr;
236 SmallVector<VarsDataTy, 4> GlobalizedVars;
237 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000238 GlobalizedVars.emplace_back(
239 CharUnits::fromQuantity(std::max(
240 C.getDeclAlign(D).getQuantity(),
241 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
242 D);
243 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000244 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
245 std::stable_sort(GlobalizedVars.begin(), GlobalizedVars.end(),
246 stable_sort_comparator);
247 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000248 // /* globalized vars */[WarSize] align (max(decl_align,
249 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000250 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000251 // };
252 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
253 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000254 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
255 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000256 for (const auto &Pair : GlobalizedVars) {
257 const ValueDecl *VD = Pair.second;
258 QualType Type = VD->getType();
259 if (Type->isLValueReferenceType())
260 Type = C.getPointerType(Type.getNonReferenceType());
261 else
262 Type = Type.getNonReferenceType();
263 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000264 FieldDecl *Field;
265 if (SingleEscaped.count(VD)) {
266 Field = FieldDecl::Create(
267 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
268 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
269 /*BW=*/nullptr, /*Mutable=*/false,
270 /*InitStyle=*/ICIS_NoInit);
271 Field->setAccess(AS_public);
272 if (VD->hasAttrs()) {
273 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
274 E(VD->getAttrs().end());
275 I != E; ++I)
276 Field->addAttr(*I);
277 }
278 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000279 llvm::APInt ArraySize(32, BufSize);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000280 Type = C.getConstantArrayType(Type, ArraySize, ArrayType::Normal, 0);
281 Field = FieldDecl::Create(
282 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
283 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
284 /*BW=*/nullptr, /*Mutable=*/false,
285 /*InitStyle=*/ICIS_NoInit);
286 Field->setAccess(AS_public);
287 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
288 static_cast<CharUnits::QuantityType>(
289 GlobalMemoryAlignment)));
290 Field->addAttr(AlignedAttr::CreateImplicit(
291 C, AlignedAttr::GNU_aligned, /*IsAlignmentExpr=*/true,
292 IntegerLiteral::Create(C, Align,
293 C.getIntTypeForBitwidth(32, /*Signed=*/0),
294 SourceLocation())));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000295 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000296 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000297 MappedDeclsFields.try_emplace(VD, Field);
298 }
299 GlobalizedRD->completeDefinition();
300 return GlobalizedRD;
301}
302
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000303/// Get the list of variables that can escape their declaration context.
304class CheckVarsEscapingDeclContext final
305 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
306 CodeGenFunction &CGF;
307 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000308 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000309 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000310 RecordDecl *GlobalizedRD = nullptr;
311 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000312 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000313 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000314
315 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000316 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000317 if (!isa<VarDecl>(VD) ||
318 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000319 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000320 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000321 // Use user-specified allocation.
322 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
323 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000324 // Variables captured by value must be globalized.
325 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000326 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000327 // Check if need to capture the variable that was already captured by
328 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000329 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000330 if (!FD->hasAttrs())
331 return;
332 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
333 if (!Attr)
334 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000335 if (((Attr->getCaptureKind() != OMPC_map) &&
336 !isOpenMPPrivate(
337 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
338 ((Attr->getCaptureKind() == OMPC_map) &&
339 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000340 return;
341 }
342 if (!FD->getType()->isReferenceType()) {
343 assert(!VD->getType()->isVariablyModifiedType() &&
344 "Parameter captured by value with variably modified type");
345 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000346 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000347 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000348 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000349 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000350 }
351 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000352 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000353 VD->getType()->isReferenceType())
354 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000355 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000356 if (VD->getType()->isVariablyModifiedType())
357 EscapedVariableLengthDecls.insert(VD);
358 else
359 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000360 }
361
362 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000363 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000364 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000365 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
366 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
367 const bool SavedAllEscaped = AllEscaped;
368 AllEscaped = VD->getType()->isLValueReferenceType();
369 Visit(VarD->getInit());
370 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000371 }
372 }
373 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000374 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
375 ArrayRef<OMPClause *> Clauses,
376 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000377 if (!S)
378 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000379 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000380 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
381 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000382 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
383 if (IsCombinedParallelRegion) {
384 // Check if the variable is privatized in the combined construct and
385 // those private copies must be shared in the inner parallel
386 // directive.
387 IsForCombinedParallelRegion = false;
388 for (const OMPClause *C : Clauses) {
389 if (!isOpenMPPrivate(C->getClauseKind()) ||
390 C->getClauseKind() == OMPC_reduction ||
391 C->getClauseKind() == OMPC_linear ||
392 C->getClauseKind() == OMPC_private)
393 continue;
394 ArrayRef<const Expr *> Vars;
395 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
396 Vars = PC->getVarRefs();
397 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
398 Vars = PC->getVarRefs();
399 else
400 llvm_unreachable("Unexpected clause.");
401 for (const auto *E : Vars) {
402 const Decl *D =
403 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
404 if (D == VD->getCanonicalDecl()) {
405 IsForCombinedParallelRegion = true;
406 break;
407 }
408 }
409 if (IsForCombinedParallelRegion)
410 break;
411 }
412 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000413 markAsEscaped(VD);
414 if (isa<OMPCapturedExprDecl>(VD))
415 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000416 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000417 }
418 }
419 }
420
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000421 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 assert(!GlobalizedRD &&
423 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000424 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000425 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000426 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
427 else
428 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000429 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000430 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000431 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000432 }
433
434public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000435 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
436 ArrayRef<const ValueDecl *> TeamsReductions)
437 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
438 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000439 virtual ~CheckVarsEscapingDeclContext() = default;
440 void VisitDeclStmt(const DeclStmt *S) {
441 if (!S)
442 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000443 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000444 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
445 VisitValueDecl(VD);
446 }
447 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
448 if (!D)
449 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000450 if (!D->hasAssociatedStmt())
451 return;
452 if (const auto *S =
453 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
454 // Do not analyze directives that do not actually require capturing,
455 // like `omp for` or `omp simd` directives.
456 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
457 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
458 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
459 VisitStmt(S->getCapturedStmt());
460 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000461 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000462 VisitOpenMPCapturedStmt(
463 S, D->clauses(),
464 CaptureRegions.back() == OMPD_parallel &&
465 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000466 }
467 }
468 void VisitCapturedStmt(const CapturedStmt *S) {
469 if (!S)
470 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000471 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000472 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
473 const ValueDecl *VD = C.getCapturedVar();
474 markAsEscaped(VD);
475 if (isa<OMPCapturedExprDecl>(VD))
476 VisitValueDecl(VD);
477 }
478 }
479 }
480 void VisitLambdaExpr(const LambdaExpr *E) {
481 if (!E)
482 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000483 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000484 if (C.capturesVariable()) {
485 if (C.getCaptureKind() == LCK_ByRef) {
486 const ValueDecl *VD = C.getCapturedVar();
487 markAsEscaped(VD);
488 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
489 VisitValueDecl(VD);
490 }
491 }
492 }
493 }
494 void VisitBlockExpr(const BlockExpr *E) {
495 if (!E)
496 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000497 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000498 if (C.isByRef()) {
499 const VarDecl *VD = C.getVariable();
500 markAsEscaped(VD);
501 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
502 VisitValueDecl(VD);
503 }
504 }
505 }
506 void VisitCallExpr(const CallExpr *E) {
507 if (!E)
508 return;
509 for (const Expr *Arg : E->arguments()) {
510 if (!Arg)
511 continue;
512 if (Arg->isLValue()) {
513 const bool SavedAllEscaped = AllEscaped;
514 AllEscaped = true;
515 Visit(Arg);
516 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000517 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000518 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000519 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000520 }
521 Visit(E->getCallee());
522 }
523 void VisitDeclRefExpr(const DeclRefExpr *E) {
524 if (!E)
525 return;
526 const ValueDecl *VD = E->getDecl();
527 if (AllEscaped)
528 markAsEscaped(VD);
529 if (isa<OMPCapturedExprDecl>(VD))
530 VisitValueDecl(VD);
531 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
532 if (VarD->isInitCapture())
533 VisitValueDecl(VD);
534 }
535 void VisitUnaryOperator(const UnaryOperator *E) {
536 if (!E)
537 return;
538 if (E->getOpcode() == UO_AddrOf) {
539 const bool SavedAllEscaped = AllEscaped;
540 AllEscaped = true;
541 Visit(E->getSubExpr());
542 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000543 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000544 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000545 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000546 }
547 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
548 if (!E)
549 return;
550 if (E->getCastKind() == CK_ArrayToPointerDecay) {
551 const bool SavedAllEscaped = AllEscaped;
552 AllEscaped = true;
553 Visit(E->getSubExpr());
554 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000555 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000556 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000557 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000558 }
559 void VisitExpr(const Expr *E) {
560 if (!E)
561 return;
562 bool SavedAllEscaped = AllEscaped;
563 if (!E->isLValue())
564 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000565 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000566 if (Child)
567 Visit(Child);
568 AllEscaped = SavedAllEscaped;
569 }
570 void VisitStmt(const Stmt *S) {
571 if (!S)
572 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000573 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000574 if (Child)
575 Visit(Child);
576 }
577
Alexey Bataevc99042b2018-03-15 18:10:54 +0000578 /// Returns the record that handles all the escaped local variables and used
579 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000580 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000581 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000582 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000583 return GlobalizedRD;
584 }
585
Alexey Bataevc99042b2018-03-15 18:10:54 +0000586 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000587 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
588 assert(GlobalizedRD &&
589 "Record for globalized variables must be generated already.");
590 auto I = MappedDeclsFields.find(VD);
591 if (I == MappedDeclsFields.end())
592 return nullptr;
593 return I->getSecond();
594 }
595
Alexey Bataevc99042b2018-03-15 18:10:54 +0000596 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000597 ArrayRef<const ValueDecl *> getEscapedDecls() const {
598 return EscapedDecls.getArrayRef();
599 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000600
601 /// Checks if the escaped local variable is actually a parameter passed by
602 /// value.
603 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
604 return EscapedParameters;
605 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000606
607 /// Returns the list of the escaped variables with the variably modified
608 /// types.
609 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
610 return EscapedVariableLengthDecls.getArrayRef();
611 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000612};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000613} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000614
615/// Get the GPU warp size.
616static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000619 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000620 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000621}
622
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000623/// Get the id of the current thread on the GPU.
624static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000625 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000627 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000628 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000629}
630
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000631/// Get the id of the warp in the block.
632/// We assume that the warp size is 32, which is always the case
633/// on the NVPTX device, to generate more efficient code.
634static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
635 CGBuilderTy &Bld = CGF.Builder;
636 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
637}
638
639/// Get the id of the current lane in the Warp.
640/// We assume that the warp size is 32, which is always the case
641/// on the NVPTX device, to generate more efficient code.
642static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
643 CGBuilderTy &Bld = CGF.Builder;
644 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
645 "nvptx_lane_id");
646}
647
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000648/// Get the maximum number of threads in a block of the GPU.
649static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000650 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000651 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000652 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000653 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000654}
655
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000656/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000657/// For the 'generic' execution mode, the runtime encodes thread_limit in
658/// the launch parameters, always starting thread_limit+warpSize threads per
659/// CTA. The threads in the last warp are reserved for master execution.
660/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
661static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000662 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000663 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000664 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000665 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000666 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
667 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000668}
669
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000670/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000671/// The master thread id is the first thread (lane) of the last warp in the
672/// GPU block. Warp size is assumed to be some power of 2.
673/// Thread id is 0 indexed.
674/// E.g: If NumThreads is 33, master id is 32.
675/// If NumThreads is 64, master id is 32.
676/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000677static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000678 CGBuilderTy &Bld = CGF.Builder;
679 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
680
681 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000682 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683
Alexey Bataeve290ec02018-04-06 16:03:36 +0000684 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000685 Bld.CreateNot(Mask), "master_tid");
686}
687
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000688CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000689 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000690 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
691 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000692 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000693}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000694
695void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
696 CodeGenModule &CGM) {
697 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000698
699 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000700 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000701 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000702 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000703 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000704}
705
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000706CGOpenMPRuntimeNVPTX::ExecutionMode
707CGOpenMPRuntimeNVPTX::getExecutionMode() const {
708 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000709}
710
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000711static CGOpenMPRuntimeNVPTX::DataSharingMode
712getDataSharingMode(CodeGenModule &CGM) {
713 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
714 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000715}
716
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000717/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000718/// false condition. Also, check if the number of threads is strictly specified
719/// and run those directives in non-SPMD mode.
720static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
721 const OMPExecutableDirective &D) {
722 if (D.hasClausesOfKind<OMPNumThreadsClause>())
723 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000724 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
725 OpenMPDirectiveKind NameModifier = C->getNameModifier();
726 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
727 continue;
728 const Expr *Cond = C->getCondition();
729 bool Result;
730 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
731 return true;
732 }
733 return false;
734}
735
736/// Check for inner (nested) SPMD construct, if any
737static bool hasNestedSPMDDirective(ASTContext &Ctx,
738 const OMPExecutableDirective &D) {
739 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000740 const auto *Body =
741 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000742 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000743
Alexey Bataev5c427362019-04-10 19:11:33 +0000744 if (const auto *NestedDir =
745 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000746 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000747 switch (D.getDirectiveKind()) {
748 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000749 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000750 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000751 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000752 if (DKind == OMPD_teams) {
753 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
754 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000755 if (!Body)
756 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000757 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
758 if (const auto *NND =
759 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000760 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000761 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000762 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000763 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000764 }
765 }
766 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000767 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000768 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000769 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000770 case OMPD_target_simd:
771 case OMPD_target_parallel:
772 case OMPD_target_parallel_for:
773 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000774 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000775 case OMPD_target_teams_distribute_simd:
776 case OMPD_target_teams_distribute_parallel_for:
777 case OMPD_target_teams_distribute_parallel_for_simd:
778 case OMPD_parallel:
779 case OMPD_for:
780 case OMPD_parallel_for:
781 case OMPD_parallel_sections:
782 case OMPD_for_simd:
783 case OMPD_parallel_for_simd:
784 case OMPD_cancel:
785 case OMPD_cancellation_point:
786 case OMPD_ordered:
787 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000788 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000789 case OMPD_task:
790 case OMPD_simd:
791 case OMPD_sections:
792 case OMPD_section:
793 case OMPD_single:
794 case OMPD_master:
795 case OMPD_critical:
796 case OMPD_taskyield:
797 case OMPD_barrier:
798 case OMPD_taskwait:
799 case OMPD_taskgroup:
800 case OMPD_atomic:
801 case OMPD_flush:
802 case OMPD_teams:
803 case OMPD_target_data:
804 case OMPD_target_exit_data:
805 case OMPD_target_enter_data:
806 case OMPD_distribute:
807 case OMPD_distribute_simd:
808 case OMPD_distribute_parallel_for:
809 case OMPD_distribute_parallel_for_simd:
810 case OMPD_teams_distribute:
811 case OMPD_teams_distribute_simd:
812 case OMPD_teams_distribute_parallel_for:
813 case OMPD_teams_distribute_parallel_for_simd:
814 case OMPD_target_update:
815 case OMPD_declare_simd:
816 case OMPD_declare_target:
817 case OMPD_end_declare_target:
818 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000819 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000820 case OMPD_taskloop:
821 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000822 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000823 case OMPD_unknown:
824 llvm_unreachable("Unexpected directive.");
825 }
826 }
827
828 return false;
829}
830
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000831static bool supportsSPMDExecutionMode(ASTContext &Ctx,
832 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000833 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
834 switch (DirectiveKind) {
835 case OMPD_target:
836 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000837 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000838 case OMPD_target_parallel:
839 case OMPD_target_parallel_for:
840 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000841 case OMPD_target_teams_distribute_parallel_for:
842 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000843 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000844 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000845 case OMPD_target_teams_distribute:
846 case OMPD_target_teams_distribute_simd:
847 return false;
848 case OMPD_parallel:
849 case OMPD_for:
850 case OMPD_parallel_for:
851 case OMPD_parallel_sections:
852 case OMPD_for_simd:
853 case OMPD_parallel_for_simd:
854 case OMPD_cancel:
855 case OMPD_cancellation_point:
856 case OMPD_ordered:
857 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000858 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000859 case OMPD_task:
860 case OMPD_simd:
861 case OMPD_sections:
862 case OMPD_section:
863 case OMPD_single:
864 case OMPD_master:
865 case OMPD_critical:
866 case OMPD_taskyield:
867 case OMPD_barrier:
868 case OMPD_taskwait:
869 case OMPD_taskgroup:
870 case OMPD_atomic:
871 case OMPD_flush:
872 case OMPD_teams:
873 case OMPD_target_data:
874 case OMPD_target_exit_data:
875 case OMPD_target_enter_data:
876 case OMPD_distribute:
877 case OMPD_distribute_simd:
878 case OMPD_distribute_parallel_for:
879 case OMPD_distribute_parallel_for_simd:
880 case OMPD_teams_distribute:
881 case OMPD_teams_distribute_simd:
882 case OMPD_teams_distribute_parallel_for:
883 case OMPD_teams_distribute_parallel_for_simd:
884 case OMPD_target_update:
885 case OMPD_declare_simd:
886 case OMPD_declare_target:
887 case OMPD_end_declare_target:
888 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000889 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000890 case OMPD_taskloop:
891 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000892 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000893 case OMPD_unknown:
894 break;
895 }
896 llvm_unreachable(
897 "Unknown programming model for OpenMP directive on NVPTX target.");
898}
899
900/// Check if the directive is loops based and has schedule clause at all or has
901/// static scheduling.
902static bool hasStaticScheduling(const OMPExecutableDirective &D) {
903 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
904 isOpenMPLoopDirective(D.getDirectiveKind()) &&
905 "Expected loop-based directive.");
906 return !D.hasClausesOfKind<OMPOrderedClause>() &&
907 (!D.hasClausesOfKind<OMPScheduleClause>() ||
908 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
909 [](const OMPScheduleClause *C) {
910 return C->getScheduleKind() == OMPC_SCHEDULE_static;
911 }));
912}
913
914/// Check for inner (nested) lightweight runtime construct, if any
915static bool hasNestedLightweightDirective(ASTContext &Ctx,
916 const OMPExecutableDirective &D) {
917 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
918 const auto *CS = D.getInnermostCapturedStmt();
919 const auto *Body =
920 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000921 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000922
Alexey Bataev5c427362019-04-10 19:11:33 +0000923 if (const auto *NestedDir =
924 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000925 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
926 switch (D.getDirectiveKind()) {
927 case OMPD_target:
928 if (isOpenMPParallelDirective(DKind) &&
929 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
930 hasStaticScheduling(*NestedDir))
931 return true;
932 if (DKind == OMPD_parallel) {
933 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
934 /*IgnoreCaptured=*/true);
935 if (!Body)
936 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000937 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
938 if (const auto *NND =
939 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000940 DKind = NND->getDirectiveKind();
941 if (isOpenMPWorksharingDirective(DKind) &&
942 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
943 return true;
944 }
945 } else if (DKind == OMPD_teams) {
946 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
947 /*IgnoreCaptured=*/true);
948 if (!Body)
949 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000950 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
951 if (const auto *NND =
952 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000953 DKind = NND->getDirectiveKind();
954 if (isOpenMPParallelDirective(DKind) &&
955 isOpenMPWorksharingDirective(DKind) &&
956 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
957 return true;
958 if (DKind == OMPD_parallel) {
959 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
960 /*IgnoreCaptured=*/true);
961 if (!Body)
962 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000963 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
964 if (const auto *NND =
965 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000966 DKind = NND->getDirectiveKind();
967 if (isOpenMPWorksharingDirective(DKind) &&
968 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
969 return true;
970 }
971 }
972 }
973 }
974 return false;
975 case OMPD_target_teams:
976 if (isOpenMPParallelDirective(DKind) &&
977 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
978 hasStaticScheduling(*NestedDir))
979 return true;
980 if (DKind == OMPD_parallel) {
981 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
982 /*IgnoreCaptured=*/true);
983 if (!Body)
984 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000985 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
986 if (const auto *NND =
987 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000988 DKind = NND->getDirectiveKind();
989 if (isOpenMPWorksharingDirective(DKind) &&
990 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
991 return true;
992 }
993 }
994 return false;
995 case OMPD_target_parallel:
996 return isOpenMPWorksharingDirective(DKind) &&
997 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
998 case OMPD_target_teams_distribute:
999 case OMPD_target_simd:
1000 case OMPD_target_parallel_for:
1001 case OMPD_target_parallel_for_simd:
1002 case OMPD_target_teams_distribute_simd:
1003 case OMPD_target_teams_distribute_parallel_for:
1004 case OMPD_target_teams_distribute_parallel_for_simd:
1005 case OMPD_parallel:
1006 case OMPD_for:
1007 case OMPD_parallel_for:
1008 case OMPD_parallel_sections:
1009 case OMPD_for_simd:
1010 case OMPD_parallel_for_simd:
1011 case OMPD_cancel:
1012 case OMPD_cancellation_point:
1013 case OMPD_ordered:
1014 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001015 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001016 case OMPD_task:
1017 case OMPD_simd:
1018 case OMPD_sections:
1019 case OMPD_section:
1020 case OMPD_single:
1021 case OMPD_master:
1022 case OMPD_critical:
1023 case OMPD_taskyield:
1024 case OMPD_barrier:
1025 case OMPD_taskwait:
1026 case OMPD_taskgroup:
1027 case OMPD_atomic:
1028 case OMPD_flush:
1029 case OMPD_teams:
1030 case OMPD_target_data:
1031 case OMPD_target_exit_data:
1032 case OMPD_target_enter_data:
1033 case OMPD_distribute:
1034 case OMPD_distribute_simd:
1035 case OMPD_distribute_parallel_for:
1036 case OMPD_distribute_parallel_for_simd:
1037 case OMPD_teams_distribute:
1038 case OMPD_teams_distribute_simd:
1039 case OMPD_teams_distribute_parallel_for:
1040 case OMPD_teams_distribute_parallel_for_simd:
1041 case OMPD_target_update:
1042 case OMPD_declare_simd:
1043 case OMPD_declare_target:
1044 case OMPD_end_declare_target:
1045 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001046 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001047 case OMPD_taskloop:
1048 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001049 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001050 case OMPD_unknown:
1051 llvm_unreachable("Unexpected directive.");
1052 }
1053 }
1054
1055 return false;
1056}
1057
1058/// Checks if the construct supports lightweight runtime. It must be SPMD
1059/// construct + inner loop-based construct with static scheduling.
1060static bool supportsLightweightRuntime(ASTContext &Ctx,
1061 const OMPExecutableDirective &D) {
1062 if (!supportsSPMDExecutionMode(Ctx, D))
1063 return false;
1064 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1065 switch (DirectiveKind) {
1066 case OMPD_target:
1067 case OMPD_target_teams:
1068 case OMPD_target_parallel:
1069 return hasNestedLightweightDirective(Ctx, D);
1070 case OMPD_target_parallel_for:
1071 case OMPD_target_parallel_for_simd:
1072 case OMPD_target_teams_distribute_parallel_for:
1073 case OMPD_target_teams_distribute_parallel_for_simd:
1074 // (Last|First)-privates must be shared in parallel region.
1075 return hasStaticScheduling(D);
1076 case OMPD_target_simd:
1077 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001078 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001079 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001080 case OMPD_parallel:
1081 case OMPD_for:
1082 case OMPD_parallel_for:
1083 case OMPD_parallel_sections:
1084 case OMPD_for_simd:
1085 case OMPD_parallel_for_simd:
1086 case OMPD_cancel:
1087 case OMPD_cancellation_point:
1088 case OMPD_ordered:
1089 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001090 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001091 case OMPD_task:
1092 case OMPD_simd:
1093 case OMPD_sections:
1094 case OMPD_section:
1095 case OMPD_single:
1096 case OMPD_master:
1097 case OMPD_critical:
1098 case OMPD_taskyield:
1099 case OMPD_barrier:
1100 case OMPD_taskwait:
1101 case OMPD_taskgroup:
1102 case OMPD_atomic:
1103 case OMPD_flush:
1104 case OMPD_teams:
1105 case OMPD_target_data:
1106 case OMPD_target_exit_data:
1107 case OMPD_target_enter_data:
1108 case OMPD_distribute:
1109 case OMPD_distribute_simd:
1110 case OMPD_distribute_parallel_for:
1111 case OMPD_distribute_parallel_for_simd:
1112 case OMPD_teams_distribute:
1113 case OMPD_teams_distribute_simd:
1114 case OMPD_teams_distribute_parallel_for:
1115 case OMPD_teams_distribute_parallel_for_simd:
1116 case OMPD_target_update:
1117 case OMPD_declare_simd:
1118 case OMPD_declare_target:
1119 case OMPD_end_declare_target:
1120 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001121 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001122 case OMPD_taskloop:
1123 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001124 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001125 case OMPD_unknown:
1126 break;
1127 }
1128 llvm_unreachable(
1129 "Unknown programming model for OpenMP directive on NVPTX target.");
1130}
1131
1132void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 StringRef ParentName,
1134 llvm::Function *&OutlinedFn,
1135 llvm::Constant *&OutlinedFnID,
1136 bool IsOffloadEntry,
1137 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001138 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001139 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001140 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001141 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001142 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001143
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001144 // Emit target region as a standalone region.
1145 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001146 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1147 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001148
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001149 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001150 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001152 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001153 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001154 auto &RT =
1155 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001156 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1157 // Skip target region initialization.
1158 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001159 }
1160 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001161 auto &RT =
1162 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001163 RT.clearLocThreadIdInsertPt(CGF);
1164 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001165 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001166 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001168 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001169 // Reserve place for the globalized memory.
1170 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001171 if (!KernelStaticGlobalized) {
1172 KernelStaticGlobalized = new llvm::GlobalVariable(
1173 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1174 llvm::GlobalValue::InternalLinkage,
1175 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1176 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1177 llvm::GlobalValue::NotThreadLocal,
1178 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1179 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1181 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001182 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001183
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184 // Now change the name of the worker function to correspond to this target
1185 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001186 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001187
1188 // Create the worker function
1189 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001190}
1191
1192// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001193void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 EntryFunctionState &EST,
1195 WorkerFunctionState &WST) {
1196 CGBuilderTy &Bld = CGF.Builder;
1197
1198 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1199 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1200 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1201 EST.ExitBB = CGF.createBasicBlock(".exit");
1202
Alexey Bataev9ff80832018-04-16 20:16:21 +00001203 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1205 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1206
1207 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001208 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 CGF.EmitBranch(EST.ExitBB);
1210
1211 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001212 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1214 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1215
1216 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001217 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001218 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 // First action in sequential region:
1220 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001221 // TODO: Optimize runtime initialization and pass in correct value.
1222 llvm::Value *Args[] = {getThreadLimit(CGF),
1223 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001224 CGF.EmitRuntimeCall(
1225 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001226
1227 // For data sharing, we need to initialize the stack.
1228 CGF.EmitRuntimeCall(
1229 createNVPTXRuntimeFunction(
1230 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1231
Alexey Bataevc99042b2018-03-15 18:10:54 +00001232 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001233}
1234
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001235void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001236 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001237 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001238 if (!CGF.HaveInsertPoint())
1239 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001240
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001241 emitGenericVarsEpilog(CGF);
1242
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243 if (!EST.ExitBB)
1244 EST.ExitBB = CGF.createBasicBlock(".exit");
1245
1246 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1247 CGF.EmitBranch(TerminateBB);
1248
1249 CGF.EmitBlock(TerminateBB);
1250 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001251 // TODO: Optimize runtime initialization and pass in correct value.
1252 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001253 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001254 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001255 // Barrier to terminate worker threads.
1256 syncCTAThreads(CGF);
1257 // Master thread jumps to exit point.
1258 CGF.EmitBranch(EST.ExitBB);
1259
1260 CGF.EmitBlock(EST.ExitBB);
1261 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001262}
1263
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001264void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001265 StringRef ParentName,
1266 llvm::Function *&OutlinedFn,
1267 llvm::Constant *&OutlinedFnID,
1268 bool IsOffloadEntry,
1269 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001270 ExecutionRuntimeModesRAII ModeRAII(
1271 CurrentExecutionMode, RequiresFullRuntime,
1272 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1273 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001274 EntryFunctionState EST;
1275
1276 // Emit target region as a standalone region.
1277 class NVPTXPrePostActionTy : public PrePostActionTy {
1278 CGOpenMPRuntimeNVPTX &RT;
1279 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1280 const OMPExecutableDirective &D;
1281
1282 public:
1283 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1284 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1285 const OMPExecutableDirective &D)
1286 : RT(RT), EST(EST), D(D) {}
1287 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001288 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001289 // Skip target region initialization.
1290 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001291 }
1292 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001293 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001294 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001295 }
1296 } Action(*this, EST, D);
1297 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001298 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001299 // Reserve place for the globalized memory.
1300 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001301 if (!KernelStaticGlobalized) {
1302 KernelStaticGlobalized = new llvm::GlobalVariable(
1303 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1304 llvm::GlobalValue::InternalLinkage,
1305 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1306 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1307 llvm::GlobalValue::NotThreadLocal,
1308 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1309 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001310 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1311 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001312 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001313}
1314
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001315void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001316 CodeGenFunction &CGF, EntryFunctionState &EST,
1317 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001318 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001319
1320 // Setup BBs in entry function.
1321 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1322 EST.ExitBB = CGF.createBasicBlock(".exit");
1323
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001324 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1325 /*RequiresOMPRuntime=*/
1326 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1327 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001328 CGF.EmitRuntimeCall(
1329 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001330
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001331 if (RequiresFullRuntime) {
1332 // For data sharing, we need to initialize the stack.
1333 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1334 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1335 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001336
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001337 CGF.EmitBranch(ExecuteBB);
1338
1339 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001340
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001341 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001342}
1343
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001344void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001345 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001346 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001347 if (!CGF.HaveInsertPoint())
1348 return;
1349
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001350 if (!EST.ExitBB)
1351 EST.ExitBB = CGF.createBasicBlock(".exit");
1352
1353 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1354 CGF.EmitBranch(OMPDeInitBB);
1355
1356 CGF.EmitBlock(OMPDeInitBB);
1357 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001358 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1359 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001360 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001361 createNVPTXRuntimeFunction(
1362 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001363 CGF.EmitBranch(EST.ExitBB);
1364
1365 CGF.EmitBlock(EST.ExitBB);
1366 EST.ExitBB = nullptr;
1367}
1368
1369// Create a unique global variable to indicate the execution mode of this target
1370// region. The execution mode is either 'generic', or 'spmd' depending on the
1371// target directive. This variable is picked up by the offload library to setup
1372// the device appropriately before kernel launch. If the execution mode is
1373// 'generic', the runtime reserves one warp for the master, otherwise, all
1374// warps participate in parallel work.
1375static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001376 bool Mode) {
1377 auto *GVMode =
1378 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1379 llvm::GlobalValue::WeakAnyLinkage,
1380 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1381 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001382 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001383}
1384
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001385void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001386 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001387
1388 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001389 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001390 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001391 emitWorkerLoop(CGF, WST);
1392 CGF.FinishFunction();
1393}
1394
1395void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1396 WorkerFunctionState &WST) {
1397 //
1398 // The workers enter this loop and wait for parallel work from the master.
1399 // When the master encounters a parallel region it sets up the work + variable
1400 // arguments, and wakes up the workers. The workers first check to see if
1401 // they are required for the parallel region, i.e., within the # of requested
1402 // parallel threads. The activated workers load the variable arguments and
1403 // execute the parallel work.
1404 //
1405
1406 CGBuilderTy &Bld = CGF.Builder;
1407
1408 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1409 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1410 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1411 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1412 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1413 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1414
1415 CGF.EmitBranch(AwaitBB);
1416
1417 // Workers wait for work from master.
1418 CGF.EmitBlock(AwaitBB);
1419 // Wait for parallel work
1420 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001421
1422 Address WorkFn =
1423 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1424 Address ExecStatus =
1425 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1426 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1427 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1428
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001429 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001430 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001431 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001432 llvm::Value *Ret = CGF.EmitRuntimeCall(
1433 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1434 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001435
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001436 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001437 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1438 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001439 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1440
1441 // Activate requested workers.
1442 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001443 llvm::Value *IsActive =
1444 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1445 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001446
1447 // Signal start of parallel region.
1448 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001449 // Skip initialization.
1450 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001451
1452 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001453 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001454 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001455 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001456
1457 llvm::Value *WorkFnMatch =
1458 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1459
1460 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1461 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1462 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1463
1464 // Execute this outlined function.
1465 CGF.EmitBlock(ExecuteFNBB);
1466
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001467 // Insert call to work function via shared wrapper. The shared
1468 // wrapper takes two arguments:
1469 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001470 // - the thread ID;
1471 emitCall(CGF, WST.Loc, W,
1472 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001473
1474 // Go to end of parallel region.
1475 CGF.EmitBranch(TerminateBB);
1476
1477 CGF.EmitBlock(CheckNextBB);
1478 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001479 // Default case: call to outlined function through pointer if the target
1480 // region makes a declare target call that may contain an orphaned parallel
1481 // directive.
1482 auto *ParallelFnTy =
1483 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001484 /*isVarArg=*/false);
1485 llvm::Value *WorkFnCast =
1486 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001487 // Insert call to work function via shared wrapper. The shared
1488 // wrapper takes two arguments:
1489 // - the parallelism level;
1490 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001491 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001492 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1493 // Go to end of parallel region.
1494 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001495
1496 // Signal end of parallel region.
1497 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001498 CGF.EmitRuntimeCall(
1499 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1500 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001501 CGF.EmitBranch(BarrierBB);
1502
1503 // All active and inactive workers wait at a barrier after parallel region.
1504 CGF.EmitBlock(BarrierBB);
1505 // Barrier after parallel region.
1506 syncCTAThreads(CGF);
1507 CGF.EmitBranch(AwaitBB);
1508
1509 // Exit target region.
1510 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001511 // Skip initialization.
1512 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001513}
1514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001515/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001516/// implementation. Specialized for the NVPTX device.
1517/// \param Function OpenMP runtime function.
1518/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001519llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001520CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001521 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001522 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1523 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001524 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1525 // RequiresOMPRuntime);
1526 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001527 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001528 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1529 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1530 break;
1531 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001532 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001533 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1534 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001535 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001536 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001537 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1538 break;
1539 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001540 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1541 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001542 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001543 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001544 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001545 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1546 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1547 break;
1548 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001549 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1550 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1551 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001552 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001553 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1554 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001555 break;
1556 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001557 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1558 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001559 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001560 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001561 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001562 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1563 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1564 break;
1565 }
1566 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001567 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1568 /// int16_t IsOMPRuntimeInitialized);
1569 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001570 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001571 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001572 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1573 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1574 break;
1575 }
1576 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1577 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001578 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001579 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1580 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1581 break;
1582 }
1583 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1584 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1585 // global_tid);
1586 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001587 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1590 break;
1591 }
1592 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1593 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1594 // global_tid);
1595 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001596 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001597 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1599 break;
1600 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001601 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1602 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1603 // int16_t lane_offset, int16_t warp_size);
1604 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001605 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1608 break;
1609 }
1610 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1611 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1612 // int16_t lane_offset, int16_t warp_size);
1613 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001614 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001615 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1616 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1617 break;
1618 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001619 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001620 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1621 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1622 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1623 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1624 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001625 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1626 CGM.Int16Ty, CGM.Int16Ty};
1627 auto *ShuffleReduceFnTy =
1628 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1629 /*isVarArg=*/false);
1630 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1631 auto *InterWarpCopyFnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1633 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001634 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1635 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001636 CGM.Int32Ty,
1637 CGM.SizeTy,
1638 CGM.VoidPtrTy,
1639 ShuffleReduceFnTy->getPointerTo(),
1640 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001641 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001642 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1643 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001644 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001645 break;
1646 }
1647 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1648 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1649 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001650 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1652 RTLFn = CGM.CreateRuntimeFunction(
1653 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1654 break;
1655 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001656 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1657 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1658 // global_tid, void *global_buffer, int32_t num_of_records, void*
1659 // reduce_data,
1660 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1661 // lane_offset, int16_t shortCircuit),
1662 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1663 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1664 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1665 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1666 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1667 // *buffer, int idx, void *reduce_data));
1668 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1669 CGM.Int16Ty, CGM.Int16Ty};
1670 auto *ShuffleReduceFnTy =
1671 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1672 /*isVarArg=*/false);
1673 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1674 auto *InterWarpCopyFnTy =
1675 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1676 /*isVarArg=*/false);
1677 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1678 CGM.VoidPtrTy};
1679 auto *GlobalListFnTy =
1680 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1681 /*isVarArg=*/false);
1682 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1683 CGM.Int32Ty,
1684 CGM.VoidPtrTy,
1685 CGM.Int32Ty,
1686 CGM.VoidPtrTy,
1687 ShuffleReduceFnTy->getPointerTo(),
1688 InterWarpCopyFnTy->getPointerTo(),
1689 GlobalListFnTy->getPointerTo(),
1690 GlobalListFnTy->getPointerTo(),
1691 GlobalListFnTy->getPointerTo(),
1692 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001693 auto *FnTy =
1694 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1695 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001696 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001697 break;
1698 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001699 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1700 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001701 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001702 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1703 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1704 break;
1705 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001706 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1707 /// Build void __kmpc_data_sharing_init_stack_spmd();
1708 auto *FnTy =
1709 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001710 RTLFn =
1711 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001712 break;
1713 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001714 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1715 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001716 // int16_t UseSharedMemory);
1717 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001718 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001719 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1720 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001721 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001722 break;
1723 }
1724 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1725 // Build void __kmpc_data_sharing_pop_stack(void *a);
1726 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001727 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001728 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1730 /*Name=*/"__kmpc_data_sharing_pop_stack");
1731 break;
1732 }
1733 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1734 /// Build void __kmpc_begin_sharing_variables(void ***args,
1735 /// size_t n_args);
1736 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001737 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1740 break;
1741 }
1742 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1743 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001744 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001745 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1746 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1747 break;
1748 }
1749 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1750 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1751 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001752 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001753 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1754 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1755 break;
1756 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001757 case OMPRTL_NVPTX__kmpc_parallel_level: {
1758 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1759 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1760 auto *FnTy =
1761 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1763 break;
1764 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001765 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1766 // Build int8_t __kmpc_is_spmd_exec_mode();
1767 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1769 break;
1770 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001771 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001772 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1773 // const void *buf, size_t size, int16_t is_shared, const void **res);
1774 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1775 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001776 auto *FnTy =
1777 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1778 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1779 break;
1780 }
1781 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001782 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1783 // int16_t is_shared);
1784 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001785 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001787 RTLFn =
1788 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1789 break;
1790 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001791 case OMPRTL__kmpc_barrier: {
1792 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1793 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1794 auto *FnTy =
1795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1796 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001797 cast<llvm::Function>(RTLFn.getCallee())
1798 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001799 break;
1800 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001801 case OMPRTL__kmpc_barrier_simple_spmd: {
1802 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1803 // global_tid);
1804 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1805 auto *FnTy =
1806 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1807 RTLFn =
1808 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001809 cast<llvm::Function>(RTLFn.getCallee())
1810 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001811 break;
1812 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001813 }
1814 return RTLFn;
1815}
1816
1817void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1818 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001819 uint64_t Size, int32_t,
1820 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001821 // TODO: Add support for global variables on the device after declare target
1822 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001823 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001824 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001825 llvm::Module &M = CGM.getModule();
1826 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001827
1828 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001829 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001830
1831 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001832 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001833 llvm::ConstantAsMetadata::get(
1834 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1835 // Append metadata to nvvm.annotations
1836 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1837}
1838
1839void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1840 const OMPExecutableDirective &D, StringRef ParentName,
1841 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001842 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843 if (!IsOffloadEntry) // Nothing to do.
1844 return;
1845
1846 assert(!ParentName.empty() && "Invalid target region parent name!");
1847
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001848 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001849 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001850 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001851 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001852 else
1853 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1854 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001855
1856 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001857}
1858
Alexey Bataevceeaa482018-11-21 21:04:34 +00001859namespace {
1860LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1861/// Enum for accesseing the reserved_2 field of the ident_t struct.
1862enum ModeFlagsTy : unsigned {
1863 /// Bit set to 1 when in SPMD mode.
1864 KMP_IDENT_SPMD_MODE = 0x01,
1865 /// Bit set to 1 when a simplified runtime is used.
1866 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1867 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1868};
1869
1870/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1871static const ModeFlagsTy UndefinedMode =
1872 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1873} // anonymous namespace
1874
1875unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001876 switch (getExecutionMode()) {
1877 case EM_SPMD:
1878 if (requiresFullRuntime())
1879 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1880 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1881 case EM_NonSPMD:
1882 assert(requiresFullRuntime() && "Expected full runtime.");
1883 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1884 case EM_Unknown:
1885 return UndefinedMode;
1886 }
1887 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001888}
1889
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001890CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001891 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001892 if (!CGM.getLangOpts().OpenMPIsDevice)
1893 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001894}
Carlo Bertollic6872252016-04-04 15:55:02 +00001895
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001896void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1897 OpenMPProcBindClauseKind ProcBind,
1898 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001899 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001900 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001901 return;
1902
1903 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1904}
1905
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001906void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1907 llvm::Value *NumThreads,
1908 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001909 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001910 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001911 return;
1912
1913 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1914}
1915
Carlo Bertollic6872252016-04-04 15:55:02 +00001916void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1917 const Expr *NumTeams,
1918 const Expr *ThreadLimit,
1919 SourceLocation Loc) {}
1920
James Y Knight9871db02019-02-05 16:42:33 +00001921llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001922 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1923 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001924 // Emit target region as a standalone region.
1925 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001926 bool &IsInParallelRegion;
1927 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001928
1929 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001930 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1931 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001932 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001933 PrevIsInParallelRegion = IsInParallelRegion;
1934 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001935 }
1936 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001937 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001938 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001939 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001940 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001941 bool PrevIsInTTDRegion = IsInTTDRegion;
1942 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001943 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1944 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001945 auto *OutlinedFun =
1946 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1947 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001948 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001949 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001950 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1951 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001952 llvm::Function *WrapperFun =
1953 createParallelDataSharingWrapper(OutlinedFun, D);
1954 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1955 }
1956
1957 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001958}
1959
Alexey Bataev2adecff2018-09-21 14:22:53 +00001960/// Get list of lastprivate variables from the teams distribute ... or
1961/// teams {distribute ...} directives.
1962static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001963getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001964 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1965 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1966 "expected teams directive.");
1967 const OMPExecutableDirective *Dir = &D;
1968 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001969 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001970 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001971 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1972 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001973 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001974 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1975 Dir = nullptr;
1976 }
1977 }
1978 if (!Dir)
1979 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001980 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001981 for (const Expr *E : C->getVarRefs())
1982 Vars.push_back(getPrivateItem(E));
1983 }
1984}
1985
1986/// Get list of reduction variables from the teams ... directives.
1987static void
1988getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1989 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1990 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1991 "expected teams directive.");
1992 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1993 for (const Expr *E : C->privates())
1994 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001995 }
1996}
1997
James Y Knight9871db02019-02-05 16:42:33 +00001998llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001999 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2000 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002001 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002002
Alexey Bataev2adecff2018-09-21 14:22:53 +00002003 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002004 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002006 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002007 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2008 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002009 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002010 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2011 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002012 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002013 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002014 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002015 }
2016 } else if (!LastPrivatesReductions.empty()) {
2017 assert(!TeamAndReductions.first &&
2018 "Previous team declaration is not expected.");
2019 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2020 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002021 }
2022
Alexey Bataevc99042b2018-03-15 18:10:54 +00002023 // Emit target region as a standalone region.
2024 class NVPTXPrePostActionTy : public PrePostActionTy {
2025 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002026 const RecordDecl *GlobalizedRD;
2027 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2028 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002029
2030 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002031 NVPTXPrePostActionTy(
2032 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2033 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2034 &MappedDeclsFields)
2035 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2036 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002037 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002038 auto &Rt =
2039 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2040 if (GlobalizedRD) {
2041 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2042 I->getSecond().GlobalRecord = GlobalizedRD;
2043 I->getSecond().MappedParams =
2044 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2045 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2046 for (const auto &Pair : MappedDeclsFields) {
2047 assert(Pair.getFirst()->isCanonicalDecl() &&
2048 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002049 Data.insert(std::make_pair(Pair.getFirst(),
2050 MappedVarData(Pair.getSecond(),
2051 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002052 }
2053 }
2054 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002055 }
2056 void Exit(CodeGenFunction &CGF) override {
2057 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2058 .emitGenericVarsEpilog(CGF);
2059 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002060 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2061 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002062 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002063 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002064 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002065 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002066 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002067
2068 return OutlinedFun;
2069}
2070
Alexey Bataevc99042b2018-03-15 18:10:54 +00002071void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002072 SourceLocation Loc,
2073 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002074 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2075 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002076 return;
2077
Alexey Bataevc99042b2018-03-15 18:10:54 +00002078 CGBuilderTy &Bld = CGF.Builder;
2079
2080 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2081 if (I == FunctionGlobalizedDecls.end())
2082 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002083 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002084 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002085 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002086
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002087 // Recover pointer to this function's global record. The runtime will
2088 // handle the specifics of the allocation of the memory.
2089 // Use actual memory size of the record including the padding
2090 // for alignment purposes.
2091 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002092 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002093 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002094 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002095 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002096
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002097 llvm::PointerType *GlobalRecPtrTy =
2098 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002099 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002100 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002101 if (!IsInTTDRegion &&
2102 (WithSPMDCheck ||
2103 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002104 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2105 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2106 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002107 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2108 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2109 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2110 llvm::Value *PL = CGF.EmitRuntimeCall(
2111 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2112 {RTLoc, ThreadID});
2113 IsTTD = Bld.CreateIsNull(PL);
2114 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002115 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2116 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2117 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2118 // There is no need to emit line number for unconditional branch.
2119 (void)ApplyDebugLocation::CreateEmpty(CGF);
2120 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002121 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2122 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002123 CGF.EmitBranch(ExitBB);
2124 // There is no need to emit line number for unconditional branch.
2125 (void)ApplyDebugLocation::CreateEmpty(CGF);
2126 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002127 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2128 if (const RecordDecl *SecGlobalizedVarsRecord =
2129 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2130 SecGlobalRecTy =
2131 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2132
2133 // Recover pointer to this function's global record. The runtime will
2134 // handle the specifics of the allocation of the memory.
2135 // Use actual memory size of the record including the padding
2136 // for alignment purposes.
2137 unsigned Alignment =
2138 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2139 unsigned GlobalRecordSize =
2140 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2141 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2142 Size = Bld.CreateSelect(
2143 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2144 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002145 // TODO: allow the usage of shared memory to be controlled by
2146 // the user, for now, default to global.
2147 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002148 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002149 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2150 createNVPTXRuntimeFunction(
2151 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2152 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002153 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002154 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002156 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002157 /*NumReservedValues=*/2, "_select_stack");
2158 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2159 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2160 GlobalRecCastAddr = Phi;
2161 I->getSecond().GlobalRecordAddr = Phi;
2162 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002163 } else if (IsInTTDRegion) {
2164 assert(GlobalizedRecords.back().Records.size() < 2 &&
2165 "Expected less than 2 globalized records: one for target and one "
2166 "for teams.");
2167 unsigned Offset = 0;
2168 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2169 QualType RDTy = CGM.getContext().getRecordType(RD);
2170 unsigned Alignment =
2171 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2172 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2173 Offset =
2174 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2175 }
2176 unsigned Alignment =
2177 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2178 Offset = llvm::alignTo(Offset, Alignment);
2179 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2180 ++GlobalizedRecords.back().RegionCounter;
2181 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002182 assert(KernelStaticGlobalized &&
2183 "Kernel static pointer must be initialized already.");
2184 auto *UseSharedMemory = new llvm::GlobalVariable(
2185 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2186 llvm::GlobalValue::InternalLinkage, nullptr,
2187 "_openmp_static_kernel$is_shared");
2188 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2189 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2190 /*DestWidth=*/16, /*Signed=*/0);
2191 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2192 Address(UseSharedMemory,
2193 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2194 /*Volatile=*/false, Int16Ty, Loc);
2195 auto *StaticGlobalized = new llvm::GlobalVariable(
2196 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002197 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002198 auto *RecSize = new llvm::GlobalVariable(
2199 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2200 llvm::GlobalValue::InternalLinkage, nullptr,
2201 "_openmp_static_kernel$size");
2202 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2203 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002204 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002205 CGM.getContext().getSizeType(), Loc);
2206 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2207 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002208 llvm::Value *GlobalRecordSizeArg[] = {
2209 llvm::ConstantInt::get(
2210 CGM.Int16Ty,
2211 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2212 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002213 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2214 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2215 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002216 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002217 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002218 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2219 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002220 }
2221 assert(KernelStaticGlobalized && "Global address must be set already.");
2222 Address FrameAddr = CGF.EmitLoadOfPointer(
2223 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2224 CGM.getContext()
2225 .getPointerType(CGM.getContext().VoidPtrTy)
2226 .castAs<PointerType>());
2227 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002228 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002229 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2230 I->getSecond().IsInSPMDModeFlag = nullptr;
2231 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2232 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002233 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002234 // TODO: allow the usage of shared memory to be controlled by
2235 // the user, for now, default to global.
2236 llvm::Value *GlobalRecordSizeArg[] = {
2237 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2238 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002239 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2240 createNVPTXRuntimeFunction(
2241 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2242 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002243 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002244 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002245 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2246 I->getSecond().IsInSPMDModeFlag = nullptr;
2247 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002248 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002249 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002250
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002251 // Emit the "global alloca" which is a GEP from the global declaration
2252 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002253 LValue SecBase;
2254 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2255 if (IsTTD) {
2256 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2257 llvm::PointerType *SecGlobalRecPtrTy =
2258 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2259 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2260 Bld.CreatePointerBitCastOrAddrSpaceCast(
2261 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2262 SecGlobalRecTy);
2263 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002264 for (auto &Rec : I->getSecond().LocalVarData) {
2265 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2266 llvm::Value *ParValue;
2267 if (EscapedParam) {
2268 const auto *VD = cast<VarDecl>(Rec.first);
2269 LValue ParLVal =
2270 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2271 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2272 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002273 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2274 // Emit VarAddr basing on lane-id if required.
2275 QualType VarTy;
2276 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002277 VarTy = Rec.second.FD->getType();
2278 } else {
2279 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2280 VarAddr.getAddress().getPointer(),
2281 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002282 VarTy =
2283 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002284 VarAddr = CGF.MakeAddrLValue(
2285 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2286 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002287 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002288 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002289 if (!IsInTTDRegion &&
2290 (WithSPMDCheck ||
2291 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002292 assert(I->getSecond().IsInSPMDModeFlag &&
2293 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002294 if (IsTTD) {
2295 assert(SecIt->second.IsOnePerTeam &&
2296 "Secondary glob data must be one per team.");
2297 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2298 VarAddr.setAddress(
2299 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2300 VarAddr.getPointer()),
2301 VarAddr.getAlignment()));
2302 Rec.second.PrivateAddr = VarAddr.getAddress();
2303 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002304 Address GlobalPtr = Rec.second.PrivateAddr;
2305 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2306 Rec.second.PrivateAddr = Address(
2307 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2308 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2309 LocalAddr.getAlignment());
2310 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002311 if (EscapedParam) {
2312 const auto *VD = cast<VarDecl>(Rec.first);
2313 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2314 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2315 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002316 if (IsTTD)
2317 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002318 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002319 }
2320 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2321 // Recover pointer to this function's global record. The runtime will
2322 // handle the specifics of the allocation of the memory.
2323 // Use actual memory size of the record including the padding
2324 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002325 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002326 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2327 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2328 Size = Bld.CreateNUWAdd(
2329 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2330 llvm::Value *AlignVal =
2331 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2332 Size = Bld.CreateUDiv(Size, AlignVal);
2333 Size = Bld.CreateNUWMul(Size, AlignVal);
2334 // TODO: allow the usage of shared memory to be controlled by
2335 // the user, for now, default to global.
2336 llvm::Value *GlobalRecordSizeArg[] = {
2337 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2338 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002339 createNVPTXRuntimeFunction(
2340 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002341 GlobalRecordSizeArg);
2342 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2343 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2344 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2345 CGM.getContext().getDeclAlign(VD),
2346 AlignmentSource::Decl);
2347 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2348 Base.getAddress());
2349 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002350 }
2351 I->getSecond().MappedParams->apply(CGF);
2352}
2353
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002354void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2355 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002356 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2357 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002358 return;
2359
Alexey Bataevc99042b2018-03-15 18:10:54 +00002360 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002361 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002362 I->getSecond().MappedParams->restore(CGF);
2363 if (!CGF.HaveInsertPoint())
2364 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002365 for (llvm::Value *Addr :
2366 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2367 CGF.EmitRuntimeCall(
2368 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2369 Addr);
2370 }
2371 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002372 if (!IsInTTDRegion &&
2373 (WithSPMDCheck ||
2374 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002375 CGBuilderTy &Bld = CGF.Builder;
2376 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2377 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2378 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2379 // There is no need to emit line number for unconditional branch.
2380 (void)ApplyDebugLocation::CreateEmpty(CGF);
2381 CGF.EmitBlock(NonSPMDBB);
2382 CGF.EmitRuntimeCall(
2383 createNVPTXRuntimeFunction(
2384 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2385 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2386 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002387 } else if (IsInTTDRegion) {
2388 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2389 "region counter must be > 0.");
2390 --GlobalizedRecords.back().RegionCounter;
2391 // Emit the restore function only in the target region.
2392 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002393 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2394 /*DestWidth=*/16, /*Signed=*/0);
2395 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2396 Address(GlobalizedRecords.back().UseSharedMemory,
2397 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2398 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002399 llvm::Value *Args[] = {
2400 llvm::ConstantInt::get(
2401 CGM.Int16Ty,
2402 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2403 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002404 CGF.EmitRuntimeCall(
2405 createNVPTXRuntimeFunction(
2406 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002407 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002408 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002409 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002410 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2411 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2412 I->getSecond().GlobalRecordAddr);
2413 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002414 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002415 }
2416}
2417
Carlo Bertollic6872252016-04-04 15:55:02 +00002418void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2419 const OMPExecutableDirective &D,
2420 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002421 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002422 ArrayRef<llvm::Value *> CapturedVars) {
2423 if (!CGF.HaveInsertPoint())
2424 return;
2425
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002426 Address ZeroAddr = CGF.CreateMemTemp(
2427 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2428 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002429 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2430 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002431 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002432 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2433 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002434 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002435}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002436
2437void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002438 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002439 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2440 if (!CGF.HaveInsertPoint())
2441 return;
2442
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002443 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002444 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002445 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002446 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002447}
2448
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002449void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002450 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2451 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2452 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002453
2454 // Force inline this outlined function at its call site.
2455 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2456
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002457 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2458 /*DestWidth=*/32, /*Signed=*/1),
2459 ".zero.addr");
2460 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002461 // ThreadId for serialized parallels is 0.
2462 Address ThreadIDAddr = ZeroAddr;
2463 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002464 CodeGenFunction &CGF, PrePostActionTy &Action) {
2465 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002466
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002467 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2468 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2469 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2470 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2471 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2472 };
2473 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2474 PrePostActionTy &) {
2475
2476 RegionCodeGenTy RCG(CodeGen);
2477 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2478 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2479 llvm::Value *Args[] = {RTLoc, ThreadID};
2480
2481 NVPTXActionTy Action(
2482 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2483 Args,
2484 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2485 Args);
2486 RCG.setAction(Action);
2487 RCG(CGF);
2488 };
2489
2490 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2491 PrePostActionTy &Action) {
2492 CGBuilderTy &Bld = CGF.Builder;
2493 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2494 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002495 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2496
2497 // Prepare for parallel region. Indicate the outlined function.
2498 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002499 CGF.EmitRuntimeCall(
2500 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2501 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002502
2503 // Create a private scope that will globalize the arguments
2504 // passed from the outside of the target region.
2505 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2506
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002507 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002508 if (!CapturedVars.empty()) {
2509 // Prepare for parallel region. Indicate the outlined function.
2510 Address SharedArgs =
2511 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2512 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2513
2514 llvm::Value *DataSharingArgs[] = {
2515 SharedArgsPtr,
2516 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2517 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2518 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2519 DataSharingArgs);
2520
2521 // Store variable address in a list of references to pass to workers.
2522 unsigned Idx = 0;
2523 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002524 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2525 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2526 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002527 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002528 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002529 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002530 if (V->getType()->isIntegerTy())
2531 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2532 else
2533 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002534 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2535 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002536 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002537 }
2538 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002539
2540 // Activate workers. This barrier is used by the master to signal
2541 // work for the workers.
2542 syncCTAThreads(CGF);
2543
2544 // OpenMP [2.5, Parallel Construct, p.49]
2545 // There is an implied barrier at the end of a parallel region. After the
2546 // end of a parallel region, only the master thread of the team resumes
2547 // execution of the enclosing task region.
2548 //
2549 // The master waits at this barrier until all workers are done.
2550 syncCTAThreads(CGF);
2551
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002552 if (!CapturedVars.empty())
2553 CGF.EmitRuntimeCall(
2554 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2555
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002556 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002557 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002558 };
2559
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002560 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2561 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002562 if (IsInParallelRegion) {
2563 SeqGen(CGF, Action);
2564 } else if (IsInTargetMasterThreadRegion) {
2565 L0ParallelGen(CGF, Action);
2566 } else {
2567 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002568 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002569 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002570 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002571 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002572 // }
2573 CGBuilderTy &Bld = CGF.Builder;
2574 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002575 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2576 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002577 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002578 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2579 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002580 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002581 // There is no need to emit line number for unconditional branch.
2582 (void)ApplyDebugLocation::CreateEmpty(CGF);
2583 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002584 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2585 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2586 llvm::Value *PL = CGF.EmitRuntimeCall(
2587 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2588 {RTLoc, ThreadID});
2589 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002590 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002591 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002592 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002593 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002594 // There is no need to emit line number for unconditional branch.
2595 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002596 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002597 L0ParallelGen(CGF, Action);
2598 CGF.EmitBranch(ExitBB);
2599 // There is no need to emit line number for unconditional branch.
2600 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002601 // Emit the continuation block for code after the if.
2602 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2603 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002604 };
2605
Alexey Bataev9ff80832018-04-16 20:16:21 +00002606 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002607 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002608 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002609 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002610 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002611 ThenRCG(CGF);
2612 }
2613}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002614
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002615void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002616 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002617 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2618 // Just call the outlined function to execute the parallel region.
2619 // OutlinedFn(&GTid, &zero, CapturedStruct);
2620 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002621 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002622
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002623 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2624 /*DestWidth=*/32, /*Signed=*/1),
2625 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002626 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002627 // ThreadId for serialized parallels is 0.
2628 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002629 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002630 &ThreadIDAddr](CodeGenFunction &CGF,
2631 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002632 Action.Enter(CGF);
2633
2634 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2635 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2636 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2637 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2638 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2639 };
2640 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2641 PrePostActionTy &) {
2642
2643 RegionCodeGenTy RCG(CodeGen);
2644 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2645 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2646 llvm::Value *Args[] = {RTLoc, ThreadID};
2647
2648 NVPTXActionTy Action(
2649 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2650 Args,
2651 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2652 Args);
2653 RCG.setAction(Action);
2654 RCG(CGF);
2655 };
2656
2657 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002658 // In the worker need to use the real thread id.
2659 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002660 RegionCodeGenTy RCG(CodeGen);
2661 RCG(CGF);
2662 } else {
2663 // If we are not in the target region, it is definitely L2 parallelism or
2664 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2665 // need to check for orphaned directives.
2666 RegionCodeGenTy RCG(SeqGen);
2667 RCG(CGF);
2668 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002669}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002670
Alexey Bataeva3924b52019-01-03 16:25:35 +00002671void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2672 // Always emit simple barriers!
2673 if (!CGF.HaveInsertPoint())
2674 return;
2675 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2676 // This function does not use parameters, so we can emit just default values.
2677 llvm::Value *Args[] = {
2678 llvm::ConstantPointerNull::get(
2679 cast<llvm::PointerType>(getIdentTyPointerTy())),
2680 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2681 CGF.EmitRuntimeCall(
2682 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2683}
2684
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002685void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2686 SourceLocation Loc,
2687 OpenMPDirectiveKind Kind, bool,
2688 bool) {
2689 // Always emit simple barriers!
2690 if (!CGF.HaveInsertPoint())
2691 return;
2692 // Build call __kmpc_cancel_barrier(loc, thread_id);
2693 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2694 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2695 getThreadID(CGF, Loc)};
2696 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2697}
2698
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002699void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2700 CodeGenFunction &CGF, StringRef CriticalName,
2701 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2702 const Expr *Hint) {
2703 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2704 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2705 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2706 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2707 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2708
2709 // Fetch team-local id of the thread.
2710 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2711
2712 // Get the width of the team.
2713 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2714
2715 // Initialize the counter variable for the loop.
2716 QualType Int32Ty =
2717 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2718 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2719 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2720 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2721 /*isInit=*/true);
2722
2723 // Block checks if loop counter exceeds upper bound.
2724 CGF.EmitBlock(LoopBB);
2725 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2726 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2727 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2728
2729 // Block tests which single thread should execute region, and which threads
2730 // should go straight to synchronisation point.
2731 CGF.EmitBlock(TestBB);
2732 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2733 llvm::Value *CmpThreadToCounter =
2734 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2735 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2736
2737 // Block emits the body of the critical region.
2738 CGF.EmitBlock(BodyBB);
2739
2740 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002741 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2742 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002743
2744 // After the body surrounded by the critical region, the single executing
2745 // thread will jump to the synchronisation point.
2746 // Block waits for all threads in current team to finish then increments the
2747 // counter variable and returns to the loop.
2748 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002749 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2750 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002751
2752 llvm::Value *IncCounterVal =
2753 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2754 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2755 CGF.EmitBranch(LoopBB);
2756
2757 // Block that is reached when all threads in the team complete the region.
2758 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2759}
2760
Alexey Bataevb2575932018-01-04 20:18:55 +00002761/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002762static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2763 QualType ValTy, QualType CastTy,
2764 SourceLocation Loc) {
2765 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2766 "Cast type must sized.");
2767 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2768 "Val type must sized.");
2769 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2770 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002771 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002772 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2773 CGF.getContext().getTypeSizeInChars(CastTy))
2774 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2775 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2776 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2777 CastTy->hasSignedIntegerRepresentation());
2778 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002779 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2780 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002781 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2782 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002783}
2784
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002785/// This function creates calls to one of two shuffle functions to copy
2786/// variables between lanes in a warp.
2787static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002788 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002789 QualType ElemType,
2790 llvm::Value *Offset,
2791 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002792 CodeGenModule &CGM = CGF.CGM;
2793 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002794 CGOpenMPRuntimeNVPTX &RT =
2795 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2796
Alexey Bataeva453f362018-03-19 17:53:56 +00002797 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2798 assert(Size.getQuantity() <= 8 &&
2799 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002800
Alexey Bataeva453f362018-03-19 17:53:56 +00002801 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002802 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2803 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2804
2805 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002806 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2807 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2808 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002809 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002810 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002811
Alexey Bataev9ff80832018-04-16 20:16:21 +00002812 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2813 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002814
Alexey Bataeva453f362018-03-19 17:53:56 +00002815 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002816}
2817
Alexey Bataev12c62902018-06-22 19:10:38 +00002818static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2819 Address DestAddr, QualType ElemType,
2820 llvm::Value *Offset, SourceLocation Loc) {
2821 CGBuilderTy &Bld = CGF.Builder;
2822
2823 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2824 // Create the loop over the big sized data.
2825 // ptr = (void*)Elem;
2826 // ptrEnd = (void*) Elem + 1;
2827 // Step = 8;
2828 // while (ptr + Step < ptrEnd)
2829 // shuffle((int64_t)*ptr);
2830 // Step = 4;
2831 // while (ptr + Step < ptrEnd)
2832 // shuffle((int32_t)*ptr);
2833 // ...
2834 Address ElemPtr = DestAddr;
2835 Address Ptr = SrcAddr;
2836 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002837 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002838 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2839 if (Size < CharUnits::fromQuantity(IntSize))
2840 continue;
2841 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2842 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2843 /*Signed=*/1);
2844 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2845 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2846 ElemPtr =
2847 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2848 if (Size.getQuantity() / IntSize > 1) {
2849 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2850 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2851 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2852 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2853 CGF.EmitBlock(PreCondBB);
2854 llvm::PHINode *PhiSrc =
2855 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2856 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2857 llvm::PHINode *PhiDest =
2858 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2859 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2860 Ptr = Address(PhiSrc, Ptr.getAlignment());
2861 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2862 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2863 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2864 Ptr.getPointer(), CGF.VoidPtrTy));
2865 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2866 ThenBB, ExitBB);
2867 CGF.EmitBlock(ThenBB);
2868 llvm::Value *Res = createRuntimeShuffleFunction(
2869 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2870 IntType, Offset, Loc);
2871 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002872 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2873 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002874 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2875 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002876 CGF.EmitBranch(PreCondBB);
2877 CGF.EmitBlock(ExitBB);
2878 } else {
2879 llvm::Value *Res = createRuntimeShuffleFunction(
2880 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2881 IntType, Offset, Loc);
2882 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002883 Ptr = Bld.CreateConstGEP(Ptr, 1);
2884 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002885 }
2886 Size = Size % IntSize;
2887 }
2888}
2889
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002890namespace {
2891enum CopyAction : unsigned {
2892 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2893 // the warp using shuffle instructions.
2894 RemoteLaneToThread,
2895 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2896 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002897 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2898 ThreadToScratchpad,
2899 // ScratchpadToThread: Copy from a scratchpad array in global memory
2900 // containing team-reduced data to a thread's stack.
2901 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002902};
2903} // namespace
2904
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002905struct CopyOptionsTy {
2906 llvm::Value *RemoteLaneOffset;
2907 llvm::Value *ScratchpadIndex;
2908 llvm::Value *ScratchpadWidth;
2909};
2910
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002911/// Emit instructions to copy a Reduce list, which contains partially
2912/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002913static void emitReductionListCopy(
2914 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2915 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2916 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002917
Alexey Bataev9ff80832018-04-16 20:16:21 +00002918 CodeGenModule &CGM = CGF.CGM;
2919 ASTContext &C = CGM.getContext();
2920 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002921
Alexey Bataev9ff80832018-04-16 20:16:21 +00002922 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2923 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2924 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002925
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002926 // Iterates, element-by-element, through the source Reduce list and
2927 // make a copy.
2928 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002929 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002930 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002931 Address SrcElementAddr = Address::invalid();
2932 Address DestElementAddr = Address::invalid();
2933 Address DestElementPtrAddr = Address::invalid();
2934 // Should we shuffle in an element from a remote lane?
2935 bool ShuffleInElement = false;
2936 // Set to true to update the pointer in the dest Reduce list to a
2937 // newly created element.
2938 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002939 // Increment the src or dest pointer to the scratchpad, for each
2940 // new element.
2941 bool IncrScratchpadSrc = false;
2942 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002943
2944 switch (Action) {
2945 case RemoteLaneToThread: {
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: Create a temporary to store the element in the destination
2953 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002954 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002955 DestElementAddr =
2956 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2957 ShuffleInElement = true;
2958 UpdateDestListPtr = true;
2959 break;
2960 }
2961 case ThreadCopy: {
2962 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002963 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002964 SrcElementAddr = CGF.EmitLoadOfPointer(
2965 SrcElementPtrAddr,
2966 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002967
2968 // Step 1.2: Get the address for dest element. The destination
2969 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002970 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002971 DestElementAddr = CGF.EmitLoadOfPointer(
2972 DestElementPtrAddr,
2973 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002974 break;
2975 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002976 case ThreadToScratchpad: {
2977 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002978 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002979 SrcElementAddr = CGF.EmitLoadOfPointer(
2980 SrcElementPtrAddr,
2981 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002982
2983 // Step 1.2: Get the address for dest element:
2984 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002985 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002986 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002987 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002988 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002989 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002990 ScratchPadElemAbsolutePtrVal =
2991 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002992 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2993 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002994 IncrScratchpadDest = true;
2995 break;
2996 }
2997 case ScratchpadToThread: {
2998 // Step 1.1: Get the address for the src element in the scratchpad.
2999 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003000 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003001 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003002 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003003 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003004 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003005 ScratchPadElemAbsolutePtrVal =
3006 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3007 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3008 C.getTypeAlignInChars(Private->getType()));
3009 IncrScratchpadSrc = true;
3010
3011 // Step 1.2: Create a temporary to store the element in the destination
3012 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003013 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003014 DestElementAddr =
3015 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3016 UpdateDestListPtr = true;
3017 break;
3018 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003019 }
3020
3021 // Regardless of src and dest of copy, we emit the load of src
3022 // element as this is required in all directions
3023 SrcElementAddr = Bld.CreateElementBitCast(
3024 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003025 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3026 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003027
3028 // Now that all active lanes have read the element in the
3029 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003030 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003031 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3032 RemoteLaneOffset, Private->getExprLoc());
3033 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003034 switch (CGF.getEvaluationKind(Private->getType())) {
3035 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003036 llvm::Value *Elem =
3037 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3038 Private->getType(), Private->getExprLoc());
3039 // Store the source element value to the dest element address.
3040 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3041 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003042 break;
3043 }
3044 case TEK_Complex: {
3045 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3046 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3047 Private->getExprLoc());
3048 CGF.EmitStoreOfComplex(
3049 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3050 /*isInit=*/false);
3051 break;
3052 }
3053 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003054 CGF.EmitAggregateCopy(
3055 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3056 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3057 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003058 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003059 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003060 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003061
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003062 // Step 3.1: Modify reference in dest Reduce list as needed.
3063 // Modifying the reference in Reduce list to point to the newly
3064 // created element. The element is live in the current function
3065 // scope and that of functions it invokes (i.e., reduce_function).
3066 // RemoteReduceData[i] = (void*)&RemoteElem
3067 if (UpdateDestListPtr) {
3068 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3069 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3070 DestElementPtrAddr, /*Volatile=*/false,
3071 C.VoidPtrTy);
3072 }
3073
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003074 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3075 // address of the next element in scratchpad memory, unless we're currently
3076 // processing the last one. Memory alignment is also taken care of here.
3077 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3078 llvm::Value *ScratchpadBasePtr =
3079 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003080 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3081 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003082 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003083 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003084
3085 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003086 ScratchpadBasePtr = Bld.CreateNUWSub(
3087 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3088 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003089 ScratchpadBasePtr,
3090 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003091 ScratchpadBasePtr = Bld.CreateNUWAdd(
3092 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3093 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003094 ScratchpadBasePtr,
3095 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3096
3097 if (IncrScratchpadDest)
3098 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3099 else /* IncrScratchpadSrc = true */
3100 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3101 }
3102
Alexey Bataev9ff80832018-04-16 20:16:21 +00003103 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003104 }
3105}
3106
3107/// This function emits a helper that gathers Reduce lists from the first
3108/// lane of every active warp to lanes in the first warp.
3109///
3110/// void inter_warp_copy_func(void* reduce_data, num_warps)
3111/// shared smem[warp_size];
3112/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003113/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003114/// If (I am the first lane in each warp)
3115/// Copy my local D to smem[warp_id]
3116/// sync
3117/// if (I am the first warp)
3118/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003119static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3120 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003121 QualType ReductionArrayTy,
3122 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003123 ASTContext &C = CGM.getContext();
3124 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003125
3126 // ReduceList: thread local Reduce list.
3127 // At the stage of the computation when this function is called, partially
3128 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003129 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3130 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003131 // NumWarps: number of warps active in the parallel region. This could
3132 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003133 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003134 C.getIntTypeForBitwidth(32, /* Signed */ true),
3135 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003136 FunctionArgList Args;
3137 Args.push_back(&ReduceListArg);
3138 Args.push_back(&NumWarpsArg);
3139
Alexey Bataev9ff80832018-04-16 20:16:21 +00003140 const CGFunctionInfo &CGFI =
3141 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003142 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3143 llvm::GlobalValue::InternalLinkage,
3144 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003145 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003146 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003147 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003148 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149
Alexey Bataev9ff80832018-04-16 20:16:21 +00003150 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003151
3152 // This array is used as a medium to transfer, one reduce element at a time,
3153 // the data from the first lane of every warp to lanes in the first warp
3154 // in order to perform the final step of a reduction in a parallel region
3155 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3156 // for reduced latency, as well as to have a distinct copy for concurrently
3157 // executing target regions. The array is declared with common linkage so
3158 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003159 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160 "__openmp_nvptx_data_transfer_temporary_storage";
3161 llvm::GlobalVariable *TransferMedium =
3162 M.getGlobalVariable(TransferMediumName);
3163 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003164 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003165 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3166 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003167 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003168 llvm::Constant::getNullValue(Ty), TransferMediumName,
3169 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3170 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003171 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172 }
3173
3174 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003177 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003179 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003180
3181 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3182 Address LocalReduceList(
3183 Bld.CreatePointerBitCastOrAddrSpaceCast(
3184 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003185 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003186 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3187 CGF.getPointerAlign());
3188
3189 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003190 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003191 //
3192 // Warp master copies reduce element to transfer medium in __shared__
3193 // memory.
3194 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003195 unsigned RealTySize =
3196 C.getTypeSizeInChars(Private->getType())
3197 .alignTo(C.getTypeAlignInChars(Private->getType()))
3198 .getQuantity();
3199 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3200 unsigned NumIters = RealTySize / TySize;
3201 if (NumIters == 0)
3202 continue;
3203 QualType CType = C.getIntTypeForBitwidth(
3204 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3205 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3206 CharUnits Align = CharUnits::fromQuantity(TySize);
3207 llvm::Value *Cnt = nullptr;
3208 Address CntAddr = Address::invalid();
3209 llvm::BasicBlock *PrecondBB = nullptr;
3210 llvm::BasicBlock *ExitBB = nullptr;
3211 if (NumIters > 1) {
3212 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3213 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3214 /*Volatile=*/false, C.IntTy);
3215 PrecondBB = CGF.createBasicBlock("precond");
3216 ExitBB = CGF.createBasicBlock("exit");
3217 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3218 // There is no need to emit line number for unconditional branch.
3219 (void)ApplyDebugLocation::CreateEmpty(CGF);
3220 CGF.EmitBlock(PrecondBB);
3221 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3222 llvm::Value *Cmp =
3223 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3224 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3225 CGF.EmitBlock(BodyBB);
3226 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003227 // kmpc_barrier.
3228 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3229 /*EmitChecks=*/false,
3230 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003231 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3232 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3233 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003234
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003235 // if (lane_id == 0)
3236 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3237 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3238 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003239
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003240 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003241 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3243 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3244 // elemptr = ((CopyType*)(elemptrptr)) + I
3245 Address ElemPtr = Address(ElemPtrPtr, Align);
3246 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3247 if (NumIters > 1) {
3248 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3249 ElemPtr.getAlignment());
3250 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003251
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003252 // Get pointer to location in transfer medium.
3253 // MediumPtr = &medium[warp_id]
3254 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3255 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3256 Address MediumPtr(MediumPtrVal, Align);
3257 // Casting to actual data type.
3258 // MediumPtr = (CopyType*)MediumPtrAddr;
3259 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003260
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003261 // elem = *elemptr
3262 //*MediumPtr = elem
3263 llvm::Value *Elem =
3264 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003265 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003266 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003267
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003268 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003269
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003270 CGF.EmitBlock(ElseBB);
3271 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003272
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003273 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataevae51b962018-12-14 21:00:58 +00003275 // kmpc_barrier.
3276 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3277 /*EmitChecks=*/false,
3278 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003279
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003280 //
3281 // Warp 0 copies reduce element from transfer medium.
3282 //
3283 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3284 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3285 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevae51b962018-12-14 21:00:58 +00003287 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3288 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3289 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3290
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003291 // Up to 32 threads in warp 0 are active.
3292 llvm::Value *IsActiveThread =
3293 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3294 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003295
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003296 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003297
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003298 // SrcMediumPtr = &medium[tid]
3299 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3300 TransferMedium,
3301 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3302 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3303 // SrcMediumVal = *SrcMediumPtr;
3304 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003305
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003306 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003307 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3309 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3310 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3311 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3312 if (NumIters > 1) {
3313 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3314 TargetElemPtr.getAlignment());
3315 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003316
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003317 // *TargetElemPtr = SrcMediumVal;
3318 llvm::Value *SrcMediumValue =
3319 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003320 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003321 CType);
3322 Bld.CreateBr(W0MergeBB);
3323
3324 CGF.EmitBlock(W0ElseBB);
3325 Bld.CreateBr(W0MergeBB);
3326
3327 CGF.EmitBlock(W0MergeBB);
3328
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003329 if (NumIters > 1) {
3330 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3331 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3332 CGF.EmitBranch(PrecondBB);
3333 (void)ApplyDebugLocation::CreateEmpty(CGF);
3334 CGF.EmitBlock(ExitBB);
3335 }
3336 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003337 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003338 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003339 }
3340
3341 CGF.FinishFunction();
3342 return Fn;
3343}
3344
3345/// Emit a helper that reduces data across two OpenMP threads (lanes)
3346/// in the same warp. It uses shuffle instructions to copy over data from
3347/// a remote lane's stack. The reduction algorithm performed is specified
3348/// by the fourth parameter.
3349///
3350/// Algorithm Versions.
3351/// Full Warp Reduce (argument value 0):
3352/// This algorithm assumes that all 32 lanes are active and gathers
3353/// data from these 32 lanes, producing a single resultant value.
3354/// Contiguous Partial Warp Reduce (argument value 1):
3355/// This algorithm assumes that only a *contiguous* subset of lanes
3356/// are active. This happens for the last warp in a parallel region
3357/// when the user specified num_threads is not an integer multiple of
3358/// 32. This contiguous subset always starts with the zeroth lane.
3359/// Partial Warp Reduce (argument value 2):
3360/// This algorithm gathers data from any number of lanes at any position.
3361/// All reduced values are stored in the lowest possible lane. The set
3362/// of problems every algorithm addresses is a super set of those
3363/// addressable by algorithms with a lower version number. Overhead
3364/// increases as algorithm version increases.
3365///
3366/// Terminology
3367/// Reduce element:
3368/// Reduce element refers to the individual data field with primitive
3369/// data types to be combined and reduced across threads.
3370/// Reduce list:
3371/// Reduce list refers to a collection of local, thread-private
3372/// reduce elements.
3373/// Remote Reduce list:
3374/// Remote Reduce list refers to a collection of remote (relative to
3375/// the current thread) reduce elements.
3376///
3377/// We distinguish between three states of threads that are important to
3378/// the implementation of this function.
3379/// Alive threads:
3380/// Threads in a warp executing the SIMT instruction, as distinguished from
3381/// threads that are inactive due to divergent control flow.
3382/// Active threads:
3383/// The minimal set of threads that has to be alive upon entry to this
3384/// function. The computation is correct iff active threads are alive.
3385/// Some threads are alive but they are not active because they do not
3386/// contribute to the computation in any useful manner. Turning them off
3387/// may introduce control flow overheads without any tangible benefits.
3388/// Effective threads:
3389/// In order to comply with the argument requirements of the shuffle
3390/// function, we must keep all lanes holding data alive. But at most
3391/// half of them perform value aggregation; we refer to this half of
3392/// threads as effective. The other half is simply handing off their
3393/// data.
3394///
3395/// Procedure
3396/// Value shuffle:
3397/// In this step active threads transfer data from higher lane positions
3398/// in the warp to lower lane positions, creating Remote Reduce list.
3399/// Value aggregation:
3400/// In this step, effective threads combine their thread local Reduce list
3401/// with Remote Reduce list and store the result in the thread local
3402/// Reduce list.
3403/// Value copy:
3404/// In this step, we deal with the assumption made by algorithm 2
3405/// (i.e. contiguity assumption). When we have an odd number of lanes
3406/// active, say 2k+1, only k threads will be effective and therefore k
3407/// new values will be produced. However, the Reduce list owned by the
3408/// (2k+1)th thread is ignored in the value aggregation. Therefore
3409/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3410/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003411static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003412 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003413 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003414 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003415
3416 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003417 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3418 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003419 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003420 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3421 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003422 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003423 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3424 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003425 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003426 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3427 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428 FunctionArgList Args;
3429 Args.push_back(&ReduceListArg);
3430 Args.push_back(&LaneIDArg);
3431 Args.push_back(&RemoteLaneOffsetArg);
3432 Args.push_back(&AlgoVerArg);
3433
Alexey Bataev9ff80832018-04-16 20:16:21 +00003434 const CGFunctionInfo &CGFI =
3435 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003436 auto *Fn = llvm::Function::Create(
3437 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3438 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003439 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003440 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003441 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003442 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003443
Alexey Bataev9ff80832018-04-16 20:16:21 +00003444 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003445
3446 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3447 Address LocalReduceList(
3448 Bld.CreatePointerBitCastOrAddrSpaceCast(
3449 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3450 C.VoidPtrTy, SourceLocation()),
3451 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3452 CGF.getPointerAlign());
3453
3454 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3455 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3456 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3457
3458 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3459 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3460 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3461
3462 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3463 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3464 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3465
3466 // Create a local thread-private variable to host the Reduce list
3467 // from a remote lane.
3468 Address RemoteReduceList =
3469 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3470
3471 // This loop iterates through the list of reduce elements and copies,
3472 // element by element, from a remote lane in the warp to RemoteReduceList,
3473 // hosted on the thread's stack.
3474 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3475 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003476 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3477 /*ScratchpadIndex=*/nullptr,
3478 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003479
3480 // The actions to be performed on the Remote Reduce list is dependent
3481 // on the algorithm version.
3482 //
3483 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3484 // LaneId % 2 == 0 && Offset > 0):
3485 // do the reduction value aggregation
3486 //
3487 // The thread local variable Reduce list is mutated in place to host the
3488 // reduced data, which is the aggregated value produced from local and
3489 // remote lanes.
3490 //
3491 // Note that AlgoVer is expected to be a constant integer known at compile
3492 // time.
3493 // When AlgoVer==0, the first conjunction evaluates to true, making
3494 // the entire predicate true during compile time.
3495 // When AlgoVer==1, the second conjunction has only the second part to be
3496 // evaluated during runtime. Other conjunctions evaluates to false
3497 // during compile time.
3498 // When AlgoVer==2, the third conjunction has only the second part to be
3499 // evaluated during runtime. Other conjunctions evaluates to false
3500 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003501 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3504 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003505 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3506
Alexey Bataev9ff80832018-04-16 20:16:21 +00003507 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3508 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3509 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003510 CondAlgo2 = Bld.CreateAnd(
3511 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3512
Alexey Bataev9ff80832018-04-16 20:16:21 +00003513 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003514 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3515
3516 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3517 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3518 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3519 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3520
3521 CGF.EmitBlock(ThenBB);
3522 // reduce_function(LocalReduceList, RemoteReduceList)
3523 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3524 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3525 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3526 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003527 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3528 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003529 Bld.CreateBr(MergeBB);
3530
3531 CGF.EmitBlock(ElseBB);
3532 Bld.CreateBr(MergeBB);
3533
3534 CGF.EmitBlock(MergeBB);
3535
3536 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3537 // Reduce list.
3538 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003539 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003540 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3541
3542 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3543 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3544 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3545 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3546
3547 CGF.EmitBlock(CpyThenBB);
3548 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3549 RemoteReduceList, LocalReduceList);
3550 Bld.CreateBr(CpyMergeBB);
3551
3552 CGF.EmitBlock(CpyElseBB);
3553 Bld.CreateBr(CpyMergeBB);
3554
3555 CGF.EmitBlock(CpyMergeBB);
3556
3557 CGF.FinishFunction();
3558 return Fn;
3559}
3560
Alexey Bataev8061acd2019-02-20 16:36:22 +00003561/// This function emits a helper that copies all the reduction variables from
3562/// the team into the provided global buffer for the reduction variables.
3563///
3564/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3565/// For all data entries D in reduce_data:
3566/// Copy local D to buffer.D[Idx]
3567static llvm::Value *emitListToGlobalCopyFunction(
3568 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3569 QualType ReductionArrayTy, SourceLocation Loc,
3570 const RecordDecl *TeamReductionRec,
3571 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3572 &VarFieldMap) {
3573 ASTContext &C = CGM.getContext();
3574
3575 // Buffer: global reduction buffer.
3576 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3577 C.VoidPtrTy, ImplicitParamDecl::Other);
3578 // Idx: index of the buffer.
3579 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3580 ImplicitParamDecl::Other);
3581 // ReduceList: thread local Reduce list.
3582 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3583 C.VoidPtrTy, ImplicitParamDecl::Other);
3584 FunctionArgList Args;
3585 Args.push_back(&BufferArg);
3586 Args.push_back(&IdxArg);
3587 Args.push_back(&ReduceListArg);
3588
3589 const CGFunctionInfo &CGFI =
3590 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3591 auto *Fn = llvm::Function::Create(
3592 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3593 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3594 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3595 Fn->setDoesNotRecurse();
3596 CodeGenFunction CGF(CGM);
3597 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3598
3599 CGBuilderTy &Bld = CGF.Builder;
3600
3601 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3602 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3603 Address LocalReduceList(
3604 Bld.CreatePointerBitCastOrAddrSpaceCast(
3605 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3606 C.VoidPtrTy, Loc),
3607 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3608 CGF.getPointerAlign());
3609 QualType StaticTy = C.getRecordType(TeamReductionRec);
3610 llvm::Type *LLVMReductionsBufferTy =
3611 CGM.getTypes().ConvertTypeForMem(StaticTy);
3612 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3613 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3614 LLVMReductionsBufferTy->getPointerTo());
3615 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3616 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3617 /*Volatile=*/false, C.IntTy,
3618 Loc)};
3619 unsigned Idx = 0;
3620 for (const Expr *Private : Privates) {
3621 // Reduce element = LocalReduceList[i]
3622 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3623 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3624 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3625 // elemptr = ((CopyType*)(elemptrptr)) + I
3626 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3627 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3628 Address ElemPtr =
3629 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3630 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3631 // Global = Buffer.VD[Idx];
3632 const FieldDecl *FD = VarFieldMap.lookup(VD);
3633 LValue GlobLVal = CGF.EmitLValueForField(
3634 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3635 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3636 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3637 switch (CGF.getEvaluationKind(Private->getType())) {
3638 case TEK_Scalar: {
3639 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3640 Private->getType(), Loc);
3641 CGF.EmitStoreOfScalar(V, GlobLVal);
3642 break;
3643 }
3644 case TEK_Complex: {
3645 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3646 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3647 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3648 break;
3649 }
3650 case TEK_Aggregate:
3651 CGF.EmitAggregateCopy(GlobLVal,
3652 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3653 Private->getType(), AggValueSlot::DoesNotOverlap);
3654 break;
3655 }
3656 ++Idx;
3657 }
3658
3659 CGF.FinishFunction();
3660 return Fn;
3661}
3662
3663/// This function emits a helper that reduces all the reduction variables from
3664/// the team into the provided global buffer for the reduction variables.
3665///
3666/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3667/// void *GlobPtrs[];
3668/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3669/// ...
3670/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3671/// reduce_function(GlobPtrs, reduce_data);
3672static llvm::Value *emitListToGlobalReduceFunction(
3673 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3674 QualType ReductionArrayTy, SourceLocation Loc,
3675 const RecordDecl *TeamReductionRec,
3676 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3677 &VarFieldMap,
3678 llvm::Function *ReduceFn) {
3679 ASTContext &C = CGM.getContext();
3680
3681 // Buffer: global reduction buffer.
3682 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3683 C.VoidPtrTy, ImplicitParamDecl::Other);
3684 // Idx: index of the buffer.
3685 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3686 ImplicitParamDecl::Other);
3687 // ReduceList: thread local Reduce list.
3688 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3689 C.VoidPtrTy, ImplicitParamDecl::Other);
3690 FunctionArgList Args;
3691 Args.push_back(&BufferArg);
3692 Args.push_back(&IdxArg);
3693 Args.push_back(&ReduceListArg);
3694
3695 const CGFunctionInfo &CGFI =
3696 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3697 auto *Fn = llvm::Function::Create(
3698 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3699 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3700 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3701 Fn->setDoesNotRecurse();
3702 CodeGenFunction CGF(CGM);
3703 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3704
3705 CGBuilderTy &Bld = CGF.Builder;
3706
3707 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3708 QualType StaticTy = C.getRecordType(TeamReductionRec);
3709 llvm::Type *LLVMReductionsBufferTy =
3710 CGM.getTypes().ConvertTypeForMem(StaticTy);
3711 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3712 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3713 LLVMReductionsBufferTy->getPointerTo());
3714
3715 // 1. Build a list of reduction variables.
3716 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3717 Address ReductionList =
3718 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3719 auto IPriv = Privates.begin();
3720 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3721 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3722 /*Volatile=*/false, C.IntTy,
3723 Loc)};
3724 unsigned Idx = 0;
3725 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3726 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3727 // Global = Buffer.VD[Idx];
3728 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3729 const FieldDecl *FD = VarFieldMap.lookup(VD);
3730 LValue GlobLVal = CGF.EmitLValueForField(
3731 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3732 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3733 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3734 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3735 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3736 // Store array size.
3737 ++Idx;
3738 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3739 llvm::Value *Size = CGF.Builder.CreateIntCast(
3740 CGF.getVLASize(
3741 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3742 .NumElts,
3743 CGF.SizeTy, /*isSigned=*/false);
3744 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3745 Elem);
3746 }
3747 }
3748
3749 // Call reduce_function(GlobalReduceList, ReduceList)
3750 llvm::Value *GlobalReduceList =
3751 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3752 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3753 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3754 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3755 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3756 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3757 CGF.FinishFunction();
3758 return Fn;
3759}
3760
3761/// This function emits a helper that copies all the reduction variables from
3762/// the team into the provided global buffer for the reduction variables.
3763///
3764/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3765/// For all data entries D in reduce_data:
3766/// Copy buffer.D[Idx] to local D;
3767static llvm::Value *emitGlobalToListCopyFunction(
3768 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3769 QualType ReductionArrayTy, SourceLocation Loc,
3770 const RecordDecl *TeamReductionRec,
3771 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3772 &VarFieldMap) {
3773 ASTContext &C = CGM.getContext();
3774
3775 // Buffer: global reduction buffer.
3776 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3777 C.VoidPtrTy, ImplicitParamDecl::Other);
3778 // Idx: index of the buffer.
3779 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3780 ImplicitParamDecl::Other);
3781 // ReduceList: thread local Reduce list.
3782 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3783 C.VoidPtrTy, ImplicitParamDecl::Other);
3784 FunctionArgList Args;
3785 Args.push_back(&BufferArg);
3786 Args.push_back(&IdxArg);
3787 Args.push_back(&ReduceListArg);
3788
3789 const CGFunctionInfo &CGFI =
3790 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3791 auto *Fn = llvm::Function::Create(
3792 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3793 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3794 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3795 Fn->setDoesNotRecurse();
3796 CodeGenFunction CGF(CGM);
3797 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3798
3799 CGBuilderTy &Bld = CGF.Builder;
3800
3801 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3802 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3803 Address LocalReduceList(
3804 Bld.CreatePointerBitCastOrAddrSpaceCast(
3805 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3806 C.VoidPtrTy, Loc),
3807 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3808 CGF.getPointerAlign());
3809 QualType StaticTy = C.getRecordType(TeamReductionRec);
3810 llvm::Type *LLVMReductionsBufferTy =
3811 CGM.getTypes().ConvertTypeForMem(StaticTy);
3812 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3813 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3814 LLVMReductionsBufferTy->getPointerTo());
3815
3816 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3817 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3818 /*Volatile=*/false, C.IntTy,
3819 Loc)};
3820 unsigned Idx = 0;
3821 for (const Expr *Private : Privates) {
3822 // Reduce element = LocalReduceList[i]
3823 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3824 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3825 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3826 // elemptr = ((CopyType*)(elemptrptr)) + I
3827 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3828 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3829 Address ElemPtr =
3830 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3831 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3832 // Global = Buffer.VD[Idx];
3833 const FieldDecl *FD = VarFieldMap.lookup(VD);
3834 LValue GlobLVal = CGF.EmitLValueForField(
3835 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3836 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3837 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3838 switch (CGF.getEvaluationKind(Private->getType())) {
3839 case TEK_Scalar: {
3840 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3841 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3842 break;
3843 }
3844 case TEK_Complex: {
3845 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3846 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3847 /*isInit=*/false);
3848 break;
3849 }
3850 case TEK_Aggregate:
3851 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3852 GlobLVal, Private->getType(),
3853 AggValueSlot::DoesNotOverlap);
3854 break;
3855 }
3856 ++Idx;
3857 }
3858
3859 CGF.FinishFunction();
3860 return Fn;
3861}
3862
3863/// This function emits a helper that reduces all the reduction variables from
3864/// the team into the provided global buffer for the reduction variables.
3865///
3866/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3867/// void *GlobPtrs[];
3868/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3869/// ...
3870/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3871/// reduce_function(reduce_data, GlobPtrs);
3872static llvm::Value *emitGlobalToListReduceFunction(
3873 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3874 QualType ReductionArrayTy, SourceLocation Loc,
3875 const RecordDecl *TeamReductionRec,
3876 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3877 &VarFieldMap,
3878 llvm::Function *ReduceFn) {
3879 ASTContext &C = CGM.getContext();
3880
3881 // Buffer: global reduction buffer.
3882 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3883 C.VoidPtrTy, ImplicitParamDecl::Other);
3884 // Idx: index of the buffer.
3885 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3886 ImplicitParamDecl::Other);
3887 // ReduceList: thread local Reduce list.
3888 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3889 C.VoidPtrTy, ImplicitParamDecl::Other);
3890 FunctionArgList Args;
3891 Args.push_back(&BufferArg);
3892 Args.push_back(&IdxArg);
3893 Args.push_back(&ReduceListArg);
3894
3895 const CGFunctionInfo &CGFI =
3896 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3897 auto *Fn = llvm::Function::Create(
3898 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3899 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3900 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3901 Fn->setDoesNotRecurse();
3902 CodeGenFunction CGF(CGM);
3903 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3904
3905 CGBuilderTy &Bld = CGF.Builder;
3906
3907 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3908 QualType StaticTy = C.getRecordType(TeamReductionRec);
3909 llvm::Type *LLVMReductionsBufferTy =
3910 CGM.getTypes().ConvertTypeForMem(StaticTy);
3911 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3912 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3913 LLVMReductionsBufferTy->getPointerTo());
3914
3915 // 1. Build a list of reduction variables.
3916 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3917 Address ReductionList =
3918 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3919 auto IPriv = Privates.begin();
3920 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3921 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3922 /*Volatile=*/false, C.IntTy,
3923 Loc)};
3924 unsigned Idx = 0;
3925 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3926 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3927 // Global = Buffer.VD[Idx];
3928 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3929 const FieldDecl *FD = VarFieldMap.lookup(VD);
3930 LValue GlobLVal = CGF.EmitLValueForField(
3931 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3932 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3933 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3934 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3935 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3936 // Store array size.
3937 ++Idx;
3938 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3939 llvm::Value *Size = CGF.Builder.CreateIntCast(
3940 CGF.getVLASize(
3941 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3942 .NumElts,
3943 CGF.SizeTy, /*isSigned=*/false);
3944 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3945 Elem);
3946 }
3947 }
3948
3949 // Call reduce_function(ReduceList, GlobalReduceList)
3950 llvm::Value *GlobalReduceList =
3951 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3952 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3953 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3954 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3955 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3956 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3957 CGF.FinishFunction();
3958 return Fn;
3959}
3960
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003961///
3962/// Design of OpenMP reductions on the GPU
3963///
3964/// Consider a typical OpenMP program with one or more reduction
3965/// clauses:
3966///
3967/// float foo;
3968/// double bar;
3969/// #pragma omp target teams distribute parallel for \
3970/// reduction(+:foo) reduction(*:bar)
3971/// for (int i = 0; i < N; i++) {
3972/// foo += A[i]; bar *= B[i];
3973/// }
3974///
3975/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3976/// all teams. In our OpenMP implementation on the NVPTX device an
3977/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3978/// within a team are mapped to CUDA threads within a threadblock.
3979/// Our goal is to efficiently aggregate values across all OpenMP
3980/// threads such that:
3981///
3982/// - the compiler and runtime are logically concise, and
3983/// - the reduction is performed efficiently in a hierarchical
3984/// manner as follows: within OpenMP threads in the same warp,
3985/// across warps in a threadblock, and finally across teams on
3986/// the NVPTX device.
3987///
3988/// Introduction to Decoupling
3989///
3990/// We would like to decouple the compiler and the runtime so that the
3991/// latter is ignorant of the reduction variables (number, data types)
3992/// and the reduction operators. This allows a simpler interface
3993/// and implementation while still attaining good performance.
3994///
3995/// Pseudocode for the aforementioned OpenMP program generated by the
3996/// compiler is as follows:
3997///
3998/// 1. Create private copies of reduction variables on each OpenMP
3999/// thread: 'foo_private', 'bar_private'
4000/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4001/// to it and writes the result in 'foo_private' and 'bar_private'
4002/// respectively.
4003/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4004/// and store the result on the team master:
4005///
Alexey Bataev8e009032019-01-04 17:25:09 +00004006/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004007/// reduceData, shuffleReduceFn, interWarpCpyFn)
4008///
4009/// where:
4010/// struct ReduceData {
4011/// double *foo;
4012/// double *bar;
4013/// } reduceData
4014/// reduceData.foo = &foo_private
4015/// reduceData.bar = &bar_private
4016///
4017/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4018/// auxiliary functions generated by the compiler that operate on
4019/// variables of type 'ReduceData'. They aid the runtime perform
4020/// algorithmic steps in a data agnostic manner.
4021///
4022/// 'shuffleReduceFn' is a pointer to a function that reduces data
4023/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4024/// same warp. It takes the following arguments as input:
4025///
4026/// a. variable of type 'ReduceData' on the calling lane,
4027/// b. its lane_id,
4028/// c. an offset relative to the current lane_id to generate a
4029/// remote_lane_id. The remote lane contains the second
4030/// variable of type 'ReduceData' that is to be reduced.
4031/// d. an algorithm version parameter determining which reduction
4032/// algorithm to use.
4033///
4034/// 'shuffleReduceFn' retrieves data from the remote lane using
4035/// efficient GPU shuffle intrinsics and reduces, using the
4036/// algorithm specified by the 4th parameter, the two operands
4037/// element-wise. The result is written to the first operand.
4038///
4039/// Different reduction algorithms are implemented in different
4040/// runtime functions, all calling 'shuffleReduceFn' to perform
4041/// the essential reduction step. Therefore, based on the 4th
4042/// parameter, this function behaves slightly differently to
4043/// cooperate with the runtime to ensure correctness under
4044/// different circumstances.
4045///
4046/// 'InterWarpCpyFn' is a pointer to a function that transfers
4047/// reduced variables across warps. It tunnels, through CUDA
4048/// shared memory, the thread-private data of type 'ReduceData'
4049/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004050/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4051/// The last team writes the global reduced value to memory.
4052///
4053/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4054/// reduceData, shuffleReduceFn, interWarpCpyFn,
4055/// scratchpadCopyFn, loadAndReduceFn)
4056///
4057/// 'scratchpadCopyFn' is a helper that stores reduced
4058/// data from the team master to a scratchpad array in
4059/// global memory.
4060///
4061/// 'loadAndReduceFn' is a helper that loads data from
4062/// the scratchpad array and reduces it with the input
4063/// operand.
4064///
4065/// These compiler generated functions hide address
4066/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004067/// 5. if ret == 1:
4068/// The team master of the last team stores the reduced
4069/// result to the globals in memory.
4070/// foo += reduceData.foo; bar *= reduceData.bar
4071///
4072///
4073/// Warp Reduction Algorithms
4074///
4075/// On the warp level, we have three algorithms implemented in the
4076/// OpenMP runtime depending on the number of active lanes:
4077///
4078/// Full Warp Reduction
4079///
4080/// The reduce algorithm within a warp where all lanes are active
4081/// is implemented in the runtime as follows:
4082///
4083/// full_warp_reduce(void *reduce_data,
4084/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4085/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4086/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4087/// }
4088///
4089/// The algorithm completes in log(2, WARPSIZE) steps.
4090///
4091/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4092/// not used therefore we save instructions by not retrieving lane_id
4093/// from the corresponding special registers. The 4th parameter, which
4094/// represents the version of the algorithm being used, is set to 0 to
4095/// signify full warp reduction.
4096///
4097/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4098///
4099/// #reduce_elem refers to an element in the local lane's data structure
4100/// #remote_elem is retrieved from a remote lane
4101/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4102/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4103///
4104/// Contiguous Partial Warp Reduction
4105///
4106/// This reduce algorithm is used within a warp where only the first
4107/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4108/// number of OpenMP threads in a parallel region is not a multiple of
4109/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4110///
4111/// void
4112/// contiguous_partial_reduce(void *reduce_data,
4113/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4114/// int size, int lane_id) {
4115/// int curr_size;
4116/// int offset;
4117/// curr_size = size;
4118/// mask = curr_size/2;
4119/// while (offset>0) {
4120/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4121/// curr_size = (curr_size+1)/2;
4122/// offset = curr_size/2;
4123/// }
4124/// }
4125///
4126/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4127///
4128/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4129/// if (lane_id < offset)
4130/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4131/// else
4132/// reduce_elem = remote_elem
4133///
4134/// This algorithm assumes that the data to be reduced are located in a
4135/// contiguous subset of lanes starting from the first. When there is
4136/// an odd number of active lanes, the data in the last lane is not
4137/// aggregated with any other lane's dat but is instead copied over.
4138///
4139/// Dispersed Partial Warp Reduction
4140///
4141/// This algorithm is used within a warp when any discontiguous subset of
4142/// lanes are active. It is used to implement the reduction operation
4143/// across lanes in an OpenMP simd region or in a nested parallel region.
4144///
4145/// void
4146/// dispersed_partial_reduce(void *reduce_data,
4147/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4148/// int size, remote_id;
4149/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4150/// do {
4151/// remote_id = next_active_lane_id_right_after_me();
4152/// # the above function returns 0 of no active lane
4153/// # is present right after the current lane.
4154/// size = number_of_active_lanes_in_this_warp();
4155/// logical_lane_id /= 2;
4156/// ShuffleReduceFn(reduce_data, logical_lane_id,
4157/// remote_id-1-threadIdx.x, 2);
4158/// } while (logical_lane_id % 2 == 0 && size > 1);
4159/// }
4160///
4161/// There is no assumption made about the initial state of the reduction.
4162/// Any number of lanes (>=1) could be active at any position. The reduction
4163/// result is returned in the first active lane.
4164///
4165/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4166///
4167/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4168/// if (lane_id % 2 == 0 && offset > 0)
4169/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4170/// else
4171/// reduce_elem = remote_elem
4172///
4173///
4174/// Intra-Team Reduction
4175///
4176/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004177/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004178/// threads in a team. It first reduces within a warp using the
4179/// aforementioned algorithms. We then proceed to gather all such
4180/// reduced values at the first warp.
4181///
4182/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4183/// data from each of the "warp master" (zeroth lane of each warp, where
4184/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4185/// a mathematical sense) the problem of reduction across warp masters in
4186/// a block to the problem of warp reduction.
4187///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004188///
4189/// Inter-Team Reduction
4190///
4191/// Once a team has reduced its data to a single value, it is stored in
4192/// a global scratchpad array. Since each team has a distinct slot, this
4193/// can be done without locking.
4194///
4195/// The last team to write to the scratchpad array proceeds to reduce the
4196/// scratchpad array. One or more workers in the last team use the helper
4197/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4198/// the k'th worker reduces every k'th element.
4199///
Alexey Bataev8e009032019-01-04 17:25:09 +00004200/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004201/// reduce across workers and compute a globally reduced value.
4202///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004203void CGOpenMPRuntimeNVPTX::emitReduction(
4204 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4205 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4206 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4207 if (!CGF.HaveInsertPoint())
4208 return;
4209
4210 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004211#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004212 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004213#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004214
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004215 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004216 assert(!TeamsReduction && !ParallelReduction &&
4217 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004218 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4219 ReductionOps, Options);
4220 return;
4221 }
4222
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004223 assert((TeamsReduction || ParallelReduction) &&
4224 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004225
Alexey Bataeva1166022018-11-27 21:24:54 +00004226 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004227 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004228 // or
4229 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004230 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004231 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004232
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004233 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004234 ASTContext &C = CGM.getContext();
4235 // 1. Build a list of reduction variables.
4236 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4237 auto Size = RHSExprs.size();
4238 for (const Expr *E : Privates) {
4239 if (E->getType()->isVariablyModifiedType())
4240 // Reserve place for array size.
4241 ++Size;
4242 }
4243 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4244 QualType ReductionArrayTy =
4245 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4246 /*IndexTypeQuals=*/0);
4247 Address ReductionList =
4248 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4249 auto IPriv = Privates.begin();
4250 unsigned Idx = 0;
4251 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4252 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4253 CGF.Builder.CreateStore(
4254 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4255 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4256 Elem);
4257 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4258 // Store array size.
4259 ++Idx;
4260 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4261 llvm::Value *Size = CGF.Builder.CreateIntCast(
4262 CGF.getVLASize(
4263 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4264 .NumElts,
4265 CGF.SizeTy, /*isSigned=*/false);
4266 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4267 Elem);
4268 }
4269 }
4270
4271 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4272 ReductionList.getPointer(), CGF.VoidPtrTy);
4273 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004274 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4275 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004276 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4277 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4278 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4279 llvm::Value *InterWarpCopyFn =
4280 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004282 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004283 llvm::Value *Args[] = {RTLoc,
4284 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004285 CGF.Builder.getInt32(RHSExprs.size()),
4286 ReductionArrayTySize,
4287 RL,
4288 ShuffleAndReduceFn,
4289 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004290
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004291 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004292 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004293 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4294 Args);
4295 } else {
4296 assert(TeamsReduction && "expected teams reduction.");
4297 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4298 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4299 int Cnt = 0;
4300 for (const Expr *DRE : Privates) {
4301 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4302 ++Cnt;
4303 }
4304 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4305 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4306 C.getLangOpts().OpenMPCUDAReductionBufNum);
4307 TeamsReductions.push_back(TeamReductionRec);
4308 if (!KernelTeamsReductionPtr) {
4309 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4310 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4311 llvm::GlobalValue::InternalLinkage, nullptr,
4312 "_openmp_teams_reductions_buffer_$_$ptr");
4313 }
4314 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4315 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4316 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4317 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4318 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4319 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4320 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4321 ReductionFn);
4322 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4323 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4324 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4325 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4326 ReductionFn);
4327
4328 llvm::Value *Args[] = {
4329 RTLoc,
4330 ThreadId,
4331 GlobalBufferPtr,
4332 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4333 RL,
4334 ShuffleAndReduceFn,
4335 InterWarpCopyFn,
4336 GlobalToBufferCpyFn,
4337 GlobalToBufferRedFn,
4338 BufferToGlobalCpyFn,
4339 BufferToGlobalRedFn};
4340
4341 Res = CGF.EmitRuntimeCall(
4342 createNVPTXRuntimeFunction(
4343 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004344 Args);
4345 }
4346
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004347 // 5. Build if (res == 1)
4348 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4349 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4350 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4351 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4352 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004353
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004354 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004355 // thread in each team.
4356 // __kmpc_end_reduce{_nowait}(<gtid>);
4357 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004358 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004359
4360 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004361 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004362 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4363 auto IPriv = Privates.begin();
4364 auto ILHS = LHSExprs.begin();
4365 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004366 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004367 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4368 cast<DeclRefExpr>(*IRHS));
4369 ++IPriv;
4370 ++ILHS;
4371 ++IRHS;
4372 }
4373 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004374 llvm::Value *EndArgs[] = {ThreadId};
4375 RegionCodeGenTy RCG(CodeGen);
4376 NVPTXActionTy Action(
4377 nullptr, llvm::None,
4378 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4379 EndArgs);
4380 RCG.setAction(Action);
4381 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004382 // There is no need to emit line number for unconditional branch.
4383 (void)ApplyDebugLocation::CreateEmpty(CGF);
4384 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004385}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004386
4387const VarDecl *
4388CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4389 const VarDecl *NativeParam) const {
4390 if (!NativeParam->getType()->isReferenceType())
4391 return NativeParam;
4392 QualType ArgType = NativeParam->getType();
4393 QualifierCollector QC;
4394 const Type *NonQualTy = QC.strip(ArgType);
4395 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4396 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4397 if (Attr->getCaptureKind() == OMPC_map) {
4398 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4399 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004400 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4401 PointeeTy.isConstant(CGM.getContext())) {
4402 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4403 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004404 }
4405 }
4406 ArgType = CGM.getContext().getPointerType(PointeeTy);
4407 QC.addRestrict();
4408 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004409 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004410 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004411 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004412 return ImplicitParamDecl::Create(
4413 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4414 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004415 return ParmVarDecl::Create(
4416 CGM.getContext(),
4417 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004418 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004419 NativeParam->getIdentifier(), ArgType,
4420 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004421}
4422
4423Address
4424CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4425 const VarDecl *NativeParam,
4426 const VarDecl *TargetParam) const {
4427 assert(NativeParam != TargetParam &&
4428 NativeParam->getType()->isReferenceType() &&
4429 "Native arg must not be the same as target arg.");
4430 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4431 QualType NativeParamType = NativeParam->getType();
4432 QualifierCollector QC;
4433 const Type *NonQualTy = QC.strip(NativeParamType);
4434 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4435 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004436 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004437 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004438 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004439 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004440 // First cast to generic.
4441 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4442 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4443 /*AddrSpace=*/0));
4444 // Cast from generic to native address space.
4445 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4446 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4447 NativePointeeAddrSpace));
4448 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4449 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004450 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004451 return NativeParamAddr;
4452}
4453
4454void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004455 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004456 ArrayRef<llvm::Value *> Args) const {
4457 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004458 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004459 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004460 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004461 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4462 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4463 break;
4464 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004465 llvm::Type *TargetType = FnType->getParamType(I);
4466 llvm::Value *NativeArg = Args[I];
4467 if (!TargetType->isPointerTy()) {
4468 TargetArgs.emplace_back(NativeArg);
4469 continue;
4470 }
4471 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004472 NativeArg,
4473 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004474 TargetArgs.emplace_back(
4475 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4476 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004477 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004478}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004479
4480/// Emit function which wraps the outline parallel region
4481/// and controls the arguments which are passed to this function.
4482/// The wrapper ensures that the outlined function is called
4483/// with the correct arguments when data is shared.
4484llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4485 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4486 ASTContext &Ctx = CGM.getContext();
4487 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4488
4489 // Create a function that takes as argument the source thread.
4490 FunctionArgList WrapperArgs;
4491 QualType Int16QTy =
4492 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4493 QualType Int32QTy =
4494 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004495 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004496 /*Id=*/nullptr, Int16QTy,
4497 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004498 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004499 /*Id=*/nullptr, Int32QTy,
4500 ImplicitParamDecl::Other);
4501 WrapperArgs.emplace_back(&ParallelLevelArg);
4502 WrapperArgs.emplace_back(&WrapperArg);
4503
Alexey Bataev9ff80832018-04-16 20:16:21 +00004504 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004505 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4506
4507 auto *Fn = llvm::Function::Create(
4508 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004509 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004510 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004511 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004512 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004513
4514 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4515 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004516 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004517
4518 const auto *RD = CS.getCapturedRecordDecl();
4519 auto CurField = RD->field_begin();
4520
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004521 Address ZeroAddr = CGF.CreateMemTemp(
4522 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4523 /*Name*/ ".zero.addr");
4524 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004525 // Get the array of arguments.
4526 SmallVector<llvm::Value *, 8> Args;
4527
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004528 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4529 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004530
4531 CGBuilderTy &Bld = CGF.Builder;
4532 auto CI = CS.capture_begin();
4533
4534 // Use global memory for data sharing.
4535 // Handle passing of global args to workers.
4536 Address GlobalArgs =
4537 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4538 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4539 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4540 CGF.EmitRuntimeCall(
4541 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4542 DataSharingArgs);
4543
4544 // Retrieve the shared variables from the list of references returned
4545 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004546 Address SharedArgListAddress = Address::invalid();
4547 if (CS.capture_size() > 0 ||
4548 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4549 SharedArgListAddress = CGF.EmitLoadOfPointer(
4550 GlobalArgs, CGF.getContext()
4551 .getPointerType(CGF.getContext().getPointerType(
4552 CGF.getContext().VoidPtrTy))
4553 .castAs<PointerType>());
4554 }
4555 unsigned Idx = 0;
4556 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004557 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004558 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4559 Src, CGF.SizeTy->getPointerTo());
4560 llvm::Value *LB = CGF.EmitLoadOfScalar(
4561 TypedAddress,
4562 /*Volatile=*/false,
4563 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4564 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4565 Args.emplace_back(LB);
4566 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004567 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004568 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4569 Src, CGF.SizeTy->getPointerTo());
4570 llvm::Value *UB = CGF.EmitLoadOfScalar(
4571 TypedAddress,
4572 /*Volatile=*/false,
4573 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4574 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4575 Args.emplace_back(UB);
4576 ++Idx;
4577 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004578 if (CS.capture_size() > 0) {
4579 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004580 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4581 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004582 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004583 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004584 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4585 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4586 /*Volatile=*/false,
4587 CGFContext.getPointerType(ElemTy),
4588 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004589 if (CI->capturesVariableByCopy() &&
4590 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004591 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4592 CI->getLocation());
4593 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004594 Args.emplace_back(Arg);
4595 }
4596 }
4597
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004598 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004599 CGF.FinishFunction();
4600 return Fn;
4601}
4602
4603void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4604 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004605 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4606 return;
4607
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004608 assert(D && "Expected function or captured|block decl.");
4609 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4610 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004611 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4612 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004613 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004614 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004615 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4616 Body = FD->getBody();
4617 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4618 Body = BD->getBody();
4619 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4620 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004621 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004622 if (NeedToDelayGlobalization &&
4623 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4624 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004625 }
4626 if (!Body)
4627 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004628 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004629 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004630 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004631 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004632 TeamAndReductions.first = nullptr;
4633 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004634 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4635 VarChecker.getEscapedVariableLengthDecls();
4636 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004637 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004638 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4639 I->getSecond().MappedParams =
4640 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4641 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4642 I->getSecond().EscapedParameters.insert(
4643 VarChecker.getEscapedParameters().begin(),
4644 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004645 I->getSecond().EscapedVariableLengthDecls.append(
4646 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004647 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004648 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004649 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004650 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004651 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004652 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004653 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004654 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004655 VarChecker.Visit(Body);
4656 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004657 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004658 I->getSecond().SecondaryLocalVarData.emplace();
4659 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4660 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4661 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4662 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004663 Data.insert(
4664 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004665 }
4666 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004667 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004668 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004669 struct GlobalizationScope final : EHScopeStack::Cleanup {
4670 GlobalizationScope() = default;
4671
4672 void Emit(CodeGenFunction &CGF, Flags flags) override {
4673 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004674 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004675 }
4676 };
4677 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004678 }
4679}
4680
4681Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4682 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004683 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4684 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4685 switch (A->getAllocatorType()) {
4686 // Use the default allocator here as by default local vars are
4687 // threadlocal.
4688 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4689 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004690 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4691 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004692 // Follow the user decision - use default allocation.
4693 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004694 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004695 // TODO: implement aupport for user-defined allocators.
4696 return Address::invalid();
4697 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4698 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4699 auto *GV = new llvm::GlobalVariable(
4700 CGM.getModule(), VarTy, /*isConstant=*/false,
4701 llvm::GlobalValue::InternalLinkage,
4702 llvm::Constant::getNullValue(VarTy), VD->getName(),
4703 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4704 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4705 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4706 GV->setAlignment(Align.getQuantity());
4707 return Address(GV, Align);
4708 }
4709 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4710 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4711 auto *GV = new llvm::GlobalVariable(
4712 CGM.getModule(), VarTy, /*isConstant=*/false,
4713 llvm::GlobalValue::InternalLinkage,
4714 llvm::Constant::getNullValue(VarTy), VD->getName(),
4715 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4716 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4717 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4718 GV->setAlignment(Align.getQuantity());
4719 return Address(GV, Align);
4720 }
4721 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4722 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4723 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4724 auto *GV = new llvm::GlobalVariable(
4725 CGM.getModule(), VarTy, /*isConstant=*/false,
4726 llvm::GlobalValue::InternalLinkage,
4727 llvm::Constant::getNullValue(VarTy), VD->getName());
4728 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4729 GV->setAlignment(Align.getQuantity());
4730 return Address(GV, Align);
4731 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004732 }
4733 }
4734
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004735 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4736 return Address::invalid();
4737
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004738 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004739 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4740 if (I == FunctionGlobalizedDecls.end())
4741 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004742 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004743 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004744 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004745 if (VD->hasAttrs()) {
4746 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4747 E(VD->attr_end());
4748 IT != E; ++IT) {
4749 auto VDI = I->getSecond().LocalVarData.find(
4750 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4751 ->getCanonicalDecl());
4752 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004753 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004754 }
4755 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004756
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004757 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004758}
4759
4760void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004761 FunctionGlobalizedDecls.erase(CGF.CurFn);
4762 CGOpenMPRuntime::functionFinished(CGF);
4763}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004764
4765void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4766 CodeGenFunction &CGF, const OMPLoopDirective &S,
4767 OpenMPDistScheduleClauseKind &ScheduleKind,
4768 llvm::Value *&Chunk) const {
4769 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4770 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4771 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4772 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4773 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004774 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004775 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004776 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4777 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004778}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004779
4780void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4781 CodeGenFunction &CGF, const OMPLoopDirective &S,
4782 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004783 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004784 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004785 // Chunk size is 1 in this case.
4786 llvm::APInt ChunkSize(32, 1);
4787 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4788 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4789 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004790}
Alexey Bataev60705422018-10-30 15:50:12 +00004791
4792void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4793 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4794 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4795 " Expected target-based directive.");
4796 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4797 for (const CapturedStmt::Capture &C : CS->captures()) {
4798 // Capture variables captured by reference in lambdas for target-based
4799 // directives.
4800 if (!C.capturesVariable())
4801 continue;
4802 const VarDecl *VD = C.getCapturedVar();
4803 const auto *RD = VD->getType()
4804 .getCanonicalType()
4805 .getNonReferenceType()
4806 ->getAsCXXRecordDecl();
4807 if (!RD || !RD->isLambda())
4808 continue;
4809 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4810 LValue VDLVal;
4811 if (VD->getType().getCanonicalType()->isReferenceType())
4812 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4813 else
4814 VDLVal = CGF.MakeAddrLValue(
4815 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4816 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4817 FieldDecl *ThisCapture = nullptr;
4818 RD->getCaptureFields(Captures, ThisCapture);
4819 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4820 LValue ThisLVal =
4821 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4822 llvm::Value *CXXThis = CGF.LoadCXXThis();
4823 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4824 }
4825 for (const LambdaCapture &LC : RD->captures()) {
4826 if (LC.getCaptureKind() != LCK_ByRef)
4827 continue;
4828 const VarDecl *VD = LC.getCapturedVar();
4829 if (!CS->capturesVariable(VD))
4830 continue;
4831 auto It = Captures.find(VD);
4832 assert(It != Captures.end() && "Found lambda capture without field.");
4833 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4834 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4835 if (VD->getType().getCanonicalType()->isReferenceType())
4836 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4837 VD->getType().getCanonicalType())
4838 .getAddress();
4839 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4840 }
4841 }
4842}
4843
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004844unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4845 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4846}
4847
Alexey Bataevc5687252019-03-21 19:35:27 +00004848bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4849 LangAS &AS) {
4850 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4851 return false;
4852 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4853 switch(A->getAllocatorType()) {
4854 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4855 // Not supported, fallback to the default mem space.
4856 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4857 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4858 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4859 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4860 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4861 AS = LangAS::Default;
4862 return true;
4863 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4864 AS = LangAS::cuda_constant;
4865 return true;
4866 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4867 AS = LangAS::cuda_shared;
4868 return true;
4869 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4870 llvm_unreachable("Expected predefined allocator for the variables with the "
4871 "static storage.");
4872 }
4873 return false;
4874}
4875
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004876// Get current CudaArch and ignore any unknown values
4877static CudaArch getCudaArch(CodeGenModule &CGM) {
4878 if (!CGM.getTarget().hasFeature("ptx"))
4879 return CudaArch::UNKNOWN;
4880 llvm::StringMap<bool> Features;
4881 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4882 CGM.getTarget().getTargetOpts().CPU,
4883 CGM.getTarget().getTargetOpts().Features);
4884 for (const auto &Feature : Features) {
4885 if (Feature.getValue()) {
4886 CudaArch Arch = StringToCudaArch(Feature.getKey());
4887 if (Arch != CudaArch::UNKNOWN)
4888 return Arch;
4889 }
4890 }
4891 return CudaArch::UNKNOWN;
4892}
4893
4894/// Check to see if target architecture supports unified addressing which is
4895/// a restriction for OpenMP requires clause "unified_shared_memory".
4896void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004897 const OMPRequiresDecl *D) const {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004898 for (const OMPClause *Clause : D->clauselists()) {
4899 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4900 switch (getCudaArch(CGM)) {
4901 case CudaArch::SM_20:
4902 case CudaArch::SM_21:
4903 case CudaArch::SM_30:
4904 case CudaArch::SM_32:
4905 case CudaArch::SM_35:
4906 case CudaArch::SM_37:
4907 case CudaArch::SM_50:
4908 case CudaArch::SM_52:
4909 case CudaArch::SM_53:
4910 case CudaArch::SM_60:
4911 case CudaArch::SM_61:
4912 case CudaArch::SM_62:
4913 CGM.Error(Clause->getBeginLoc(),
4914 "Target architecture does not support unified addressing");
4915 return;
4916 case CudaArch::SM_70:
4917 case CudaArch::SM_72:
4918 case CudaArch::SM_75:
4919 case CudaArch::GFX600:
4920 case CudaArch::GFX601:
4921 case CudaArch::GFX700:
4922 case CudaArch::GFX701:
4923 case CudaArch::GFX702:
4924 case CudaArch::GFX703:
4925 case CudaArch::GFX704:
4926 case CudaArch::GFX801:
4927 case CudaArch::GFX802:
4928 case CudaArch::GFX803:
4929 case CudaArch::GFX810:
4930 case CudaArch::GFX900:
4931 case CudaArch::GFX902:
4932 case CudaArch::GFX904:
4933 case CudaArch::GFX906:
4934 case CudaArch::GFX909:
4935 case CudaArch::UNKNOWN:
4936 break;
4937 case CudaArch::LAST:
4938 llvm_unreachable("Unexpected Cuda arch.");
4939 }
4940 }
4941 }
4942}
4943
Alexey Bataeve4090182018-11-02 14:54:07 +00004944/// Get number of SMs and number of blocks per SM.
4945static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4946 std::pair<unsigned, unsigned> Data;
4947 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4948 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4949 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4950 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4951 if (Data.first && Data.second)
4952 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004953 switch (getCudaArch(CGM)) {
4954 case CudaArch::SM_20:
4955 case CudaArch::SM_21:
4956 case CudaArch::SM_30:
4957 case CudaArch::SM_32:
4958 case CudaArch::SM_35:
4959 case CudaArch::SM_37:
4960 case CudaArch::SM_50:
4961 case CudaArch::SM_52:
4962 case CudaArch::SM_53:
4963 return {16, 16};
4964 case CudaArch::SM_60:
4965 case CudaArch::SM_61:
4966 case CudaArch::SM_62:
4967 return {56, 32};
4968 case CudaArch::SM_70:
4969 case CudaArch::SM_72:
4970 case CudaArch::SM_75:
4971 return {84, 32};
4972 case CudaArch::GFX600:
4973 case CudaArch::GFX601:
4974 case CudaArch::GFX700:
4975 case CudaArch::GFX701:
4976 case CudaArch::GFX702:
4977 case CudaArch::GFX703:
4978 case CudaArch::GFX704:
4979 case CudaArch::GFX801:
4980 case CudaArch::GFX802:
4981 case CudaArch::GFX803:
4982 case CudaArch::GFX810:
4983 case CudaArch::GFX900:
4984 case CudaArch::GFX902:
4985 case CudaArch::GFX904:
4986 case CudaArch::GFX906:
4987 case CudaArch::GFX909:
4988 case CudaArch::UNKNOWN:
4989 break;
4990 case CudaArch::LAST:
4991 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004992 }
4993 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4994}
4995
4996void CGOpenMPRuntimeNVPTX::clear() {
4997 if (!GlobalizedRecords.empty()) {
4998 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004999 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5000 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005001 RecordDecl *StaticRD = C.buildImplicitRecord(
5002 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5003 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005004 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5005 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5006 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005007 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5008 if (Records.Records.empty())
5009 continue;
5010 unsigned Size = 0;
5011 unsigned RecAlignment = 0;
5012 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005013 QualType RDTy = C.getRecordType(RD);
5014 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005015 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005016 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005017 Size =
5018 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5019 }
5020 Size = llvm::alignTo(Size, RecAlignment);
5021 llvm::APInt ArySize(/*numBits=*/64, Size);
5022 QualType SubTy = C.getConstantArrayType(
5023 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005024 const bool UseSharedMemory = Size <= SharedMemorySize;
5025 auto *Field =
5026 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5027 SourceLocation(), SourceLocation(), nullptr, SubTy,
5028 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5029 /*BW=*/nullptr, /*Mutable=*/false,
5030 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005031 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005032 if (UseSharedMemory) {
5033 SharedStaticRD->addDecl(Field);
5034 SharedRecs.push_back(&Records);
5035 } else {
5036 StaticRD->addDecl(Field);
5037 GlobalRecs.push_back(&Records);
5038 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005039 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005040 Records.UseSharedMemory->setInitializer(
5041 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5042 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005043 // Allocate SharedMemorySize buffer for the shared memory.
5044 // FIXME: nvlink does not handle weak linkage correctly (object with the
5045 // different size are reported as erroneous).
5046 // Restore this code as sson as nvlink is fixed.
5047 if (!SharedStaticRD->field_empty()) {
5048 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5049 QualType SubTy = C.getConstantArrayType(
5050 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5051 auto *Field = FieldDecl::Create(
5052 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5053 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5054 /*BW=*/nullptr, /*Mutable=*/false,
5055 /*InitStyle=*/ICIS_NoInit);
5056 Field->setAccess(AS_public);
5057 SharedStaticRD->addDecl(Field);
5058 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005059 SharedStaticRD->completeDefinition();
5060 if (!SharedStaticRD->field_empty()) {
5061 QualType StaticTy = C.getRecordType(SharedStaticRD);
5062 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5063 auto *GV = new llvm::GlobalVariable(
5064 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005065 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005066 llvm::Constant::getNullValue(LLVMStaticTy),
5067 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5068 llvm::GlobalValue::NotThreadLocal,
5069 C.getTargetAddressSpace(LangAS::cuda_shared));
5070 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5071 GV, CGM.VoidPtrTy);
5072 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5073 Rec->Buffer->replaceAllUsesWith(Replacement);
5074 Rec->Buffer->eraseFromParent();
5075 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005076 }
5077 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005078 if (!StaticRD->field_empty()) {
5079 QualType StaticTy = C.getRecordType(StaticRD);
5080 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5081 llvm::APInt Size1(32, SMsBlockPerSM.second);
5082 QualType Arr1Ty =
5083 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5084 /*IndexTypeQuals=*/0);
5085 llvm::APInt Size2(32, SMsBlockPerSM.first);
5086 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5087 /*IndexTypeQuals=*/0);
5088 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005089 // FIXME: nvlink does not handle weak linkage correctly (object with the
5090 // different size are reported as erroneous).
5091 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005092 auto *GV = new llvm::GlobalVariable(
5093 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005094 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005095 llvm::Constant::getNullValue(LLVMArr2Ty),
5096 "_openmp_static_glob_rd_$_");
5097 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5098 GV, CGM.VoidPtrTy);
5099 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5100 Rec->Buffer->replaceAllUsesWith(Replacement);
5101 Rec->Buffer->eraseFromParent();
5102 }
5103 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005104 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005105 if (!TeamsReductions.empty()) {
5106 ASTContext &C = CGM.getContext();
5107 RecordDecl *StaticRD = C.buildImplicitRecord(
5108 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5109 StaticRD->startDefinition();
5110 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5111 QualType RecTy = C.getRecordType(TeamReductionRec);
5112 auto *Field = FieldDecl::Create(
5113 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5114 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5115 /*BW=*/nullptr, /*Mutable=*/false,
5116 /*InitStyle=*/ICIS_NoInit);
5117 Field->setAccess(AS_public);
5118 StaticRD->addDecl(Field);
5119 }
5120 StaticRD->completeDefinition();
5121 QualType StaticTy = C.getRecordType(StaticRD);
5122 llvm::Type *LLVMReductionsBufferTy =
5123 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005124 // FIXME: nvlink does not handle weak linkage correctly (object with the
5125 // different size are reported as erroneous).
5126 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005127 auto *GV = new llvm::GlobalVariable(
5128 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005129 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005130 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5131 "_openmp_teams_reductions_buffer_$_");
5132 KernelTeamsReductionPtr->setInitializer(
5133 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5134 CGM.VoidPtrTy));
5135 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005136 CGOpenMPRuntime::clear();
5137}