blob: 16f6c125fe06facc5e6b1e8a150e725ad813ddff [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 for inner (nested) SPMD construct, if any
718static bool hasNestedSPMDDirective(ASTContext &Ctx,
719 const OMPExecutableDirective &D) {
720 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000721 const auto *Body =
722 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000723 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000724
Alexey Bataev5c427362019-04-10 19:11:33 +0000725 if (const auto *NestedDir =
726 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000727 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000728 switch (D.getDirectiveKind()) {
729 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000730 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000731 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000732 if (DKind == OMPD_teams) {
733 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
734 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000735 if (!Body)
736 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000737 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
738 if (const auto *NND =
739 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000740 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000741 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000742 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000743 }
744 }
745 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000746 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000747 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000748 case OMPD_target_simd:
749 case OMPD_target_parallel:
750 case OMPD_target_parallel_for:
751 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000752 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000753 case OMPD_target_teams_distribute_simd:
754 case OMPD_target_teams_distribute_parallel_for:
755 case OMPD_target_teams_distribute_parallel_for_simd:
756 case OMPD_parallel:
757 case OMPD_for:
758 case OMPD_parallel_for:
759 case OMPD_parallel_sections:
760 case OMPD_for_simd:
761 case OMPD_parallel_for_simd:
762 case OMPD_cancel:
763 case OMPD_cancellation_point:
764 case OMPD_ordered:
765 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000766 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000767 case OMPD_task:
768 case OMPD_simd:
769 case OMPD_sections:
770 case OMPD_section:
771 case OMPD_single:
772 case OMPD_master:
773 case OMPD_critical:
774 case OMPD_taskyield:
775 case OMPD_barrier:
776 case OMPD_taskwait:
777 case OMPD_taskgroup:
778 case OMPD_atomic:
779 case OMPD_flush:
780 case OMPD_teams:
781 case OMPD_target_data:
782 case OMPD_target_exit_data:
783 case OMPD_target_enter_data:
784 case OMPD_distribute:
785 case OMPD_distribute_simd:
786 case OMPD_distribute_parallel_for:
787 case OMPD_distribute_parallel_for_simd:
788 case OMPD_teams_distribute:
789 case OMPD_teams_distribute_simd:
790 case OMPD_teams_distribute_parallel_for:
791 case OMPD_teams_distribute_parallel_for_simd:
792 case OMPD_target_update:
793 case OMPD_declare_simd:
794 case OMPD_declare_target:
795 case OMPD_end_declare_target:
796 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000797 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000798 case OMPD_taskloop:
799 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000800 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000801 case OMPD_unknown:
802 llvm_unreachable("Unexpected directive.");
803 }
804 }
805
806 return false;
807}
808
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000809static bool supportsSPMDExecutionMode(ASTContext &Ctx,
810 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000811 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
812 switch (DirectiveKind) {
813 case OMPD_target:
814 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000815 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000816 case OMPD_target_parallel:
817 case OMPD_target_parallel_for:
818 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 case OMPD_target_teams_distribute_parallel_for:
820 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000821 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000822 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000823 return true;
824 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000825 return false;
826 case OMPD_parallel:
827 case OMPD_for:
828 case OMPD_parallel_for:
829 case OMPD_parallel_sections:
830 case OMPD_for_simd:
831 case OMPD_parallel_for_simd:
832 case OMPD_cancel:
833 case OMPD_cancellation_point:
834 case OMPD_ordered:
835 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000836 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000837 case OMPD_task:
838 case OMPD_simd:
839 case OMPD_sections:
840 case OMPD_section:
841 case OMPD_single:
842 case OMPD_master:
843 case OMPD_critical:
844 case OMPD_taskyield:
845 case OMPD_barrier:
846 case OMPD_taskwait:
847 case OMPD_taskgroup:
848 case OMPD_atomic:
849 case OMPD_flush:
850 case OMPD_teams:
851 case OMPD_target_data:
852 case OMPD_target_exit_data:
853 case OMPD_target_enter_data:
854 case OMPD_distribute:
855 case OMPD_distribute_simd:
856 case OMPD_distribute_parallel_for:
857 case OMPD_distribute_parallel_for_simd:
858 case OMPD_teams_distribute:
859 case OMPD_teams_distribute_simd:
860 case OMPD_teams_distribute_parallel_for:
861 case OMPD_teams_distribute_parallel_for_simd:
862 case OMPD_target_update:
863 case OMPD_declare_simd:
864 case OMPD_declare_target:
865 case OMPD_end_declare_target:
866 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000867 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000868 case OMPD_taskloop:
869 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000870 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_unknown:
872 break;
873 }
874 llvm_unreachable(
875 "Unknown programming model for OpenMP directive on NVPTX target.");
876}
877
878/// Check if the directive is loops based and has schedule clause at all or has
879/// static scheduling.
880static bool hasStaticScheduling(const OMPExecutableDirective &D) {
881 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
882 isOpenMPLoopDirective(D.getDirectiveKind()) &&
883 "Expected loop-based directive.");
884 return !D.hasClausesOfKind<OMPOrderedClause>() &&
885 (!D.hasClausesOfKind<OMPScheduleClause>() ||
886 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
887 [](const OMPScheduleClause *C) {
888 return C->getScheduleKind() == OMPC_SCHEDULE_static;
889 }));
890}
891
892/// Check for inner (nested) lightweight runtime construct, if any
893static bool hasNestedLightweightDirective(ASTContext &Ctx,
894 const OMPExecutableDirective &D) {
895 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
896 const auto *CS = D.getInnermostCapturedStmt();
897 const auto *Body =
898 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000899 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000900
Alexey Bataev5c427362019-04-10 19:11:33 +0000901 if (const auto *NestedDir =
902 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000903 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
904 switch (D.getDirectiveKind()) {
905 case OMPD_target:
906 if (isOpenMPParallelDirective(DKind) &&
907 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
908 hasStaticScheduling(*NestedDir))
909 return true;
910 if (DKind == OMPD_parallel) {
911 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
912 /*IgnoreCaptured=*/true);
913 if (!Body)
914 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000915 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
916 if (const auto *NND =
917 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000918 DKind = NND->getDirectiveKind();
919 if (isOpenMPWorksharingDirective(DKind) &&
920 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
921 return true;
922 }
923 } else if (DKind == OMPD_teams) {
924 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
925 /*IgnoreCaptured=*/true);
926 if (!Body)
927 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000928 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
929 if (const auto *NND =
930 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000931 DKind = NND->getDirectiveKind();
932 if (isOpenMPParallelDirective(DKind) &&
933 isOpenMPWorksharingDirective(DKind) &&
934 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
935 return true;
936 if (DKind == OMPD_parallel) {
937 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
938 /*IgnoreCaptured=*/true);
939 if (!Body)
940 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000941 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
942 if (const auto *NND =
943 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000944 DKind = NND->getDirectiveKind();
945 if (isOpenMPWorksharingDirective(DKind) &&
946 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
947 return true;
948 }
949 }
950 }
951 }
952 return false;
953 case OMPD_target_teams:
954 if (isOpenMPParallelDirective(DKind) &&
955 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
956 hasStaticScheduling(*NestedDir))
957 return true;
958 if (DKind == OMPD_parallel) {
959 Body = NestedDir->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 return false;
973 case OMPD_target_parallel:
974 return isOpenMPWorksharingDirective(DKind) &&
975 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
976 case OMPD_target_teams_distribute:
977 case OMPD_target_simd:
978 case OMPD_target_parallel_for:
979 case OMPD_target_parallel_for_simd:
980 case OMPD_target_teams_distribute_simd:
981 case OMPD_target_teams_distribute_parallel_for:
982 case OMPD_target_teams_distribute_parallel_for_simd:
983 case OMPD_parallel:
984 case OMPD_for:
985 case OMPD_parallel_for:
986 case OMPD_parallel_sections:
987 case OMPD_for_simd:
988 case OMPD_parallel_for_simd:
989 case OMPD_cancel:
990 case OMPD_cancellation_point:
991 case OMPD_ordered:
992 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000993 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000994 case OMPD_task:
995 case OMPD_simd:
996 case OMPD_sections:
997 case OMPD_section:
998 case OMPD_single:
999 case OMPD_master:
1000 case OMPD_critical:
1001 case OMPD_taskyield:
1002 case OMPD_barrier:
1003 case OMPD_taskwait:
1004 case OMPD_taskgroup:
1005 case OMPD_atomic:
1006 case OMPD_flush:
1007 case OMPD_teams:
1008 case OMPD_target_data:
1009 case OMPD_target_exit_data:
1010 case OMPD_target_enter_data:
1011 case OMPD_distribute:
1012 case OMPD_distribute_simd:
1013 case OMPD_distribute_parallel_for:
1014 case OMPD_distribute_parallel_for_simd:
1015 case OMPD_teams_distribute:
1016 case OMPD_teams_distribute_simd:
1017 case OMPD_teams_distribute_parallel_for:
1018 case OMPD_teams_distribute_parallel_for_simd:
1019 case OMPD_target_update:
1020 case OMPD_declare_simd:
1021 case OMPD_declare_target:
1022 case OMPD_end_declare_target:
1023 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001024 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001025 case OMPD_taskloop:
1026 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001027 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001028 case OMPD_unknown:
1029 llvm_unreachable("Unexpected directive.");
1030 }
1031 }
1032
1033 return false;
1034}
1035
1036/// Checks if the construct supports lightweight runtime. It must be SPMD
1037/// construct + inner loop-based construct with static scheduling.
1038static bool supportsLightweightRuntime(ASTContext &Ctx,
1039 const OMPExecutableDirective &D) {
1040 if (!supportsSPMDExecutionMode(Ctx, D))
1041 return false;
1042 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1043 switch (DirectiveKind) {
1044 case OMPD_target:
1045 case OMPD_target_teams:
1046 case OMPD_target_parallel:
1047 return hasNestedLightweightDirective(Ctx, D);
1048 case OMPD_target_parallel_for:
1049 case OMPD_target_parallel_for_simd:
1050 case OMPD_target_teams_distribute_parallel_for:
1051 case OMPD_target_teams_distribute_parallel_for_simd:
1052 // (Last|First)-privates must be shared in parallel region.
1053 return hasStaticScheduling(D);
1054 case OMPD_target_simd:
1055 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001056 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001057 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001058 case OMPD_parallel:
1059 case OMPD_for:
1060 case OMPD_parallel_for:
1061 case OMPD_parallel_sections:
1062 case OMPD_for_simd:
1063 case OMPD_parallel_for_simd:
1064 case OMPD_cancel:
1065 case OMPD_cancellation_point:
1066 case OMPD_ordered:
1067 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001068 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001069 case OMPD_task:
1070 case OMPD_simd:
1071 case OMPD_sections:
1072 case OMPD_section:
1073 case OMPD_single:
1074 case OMPD_master:
1075 case OMPD_critical:
1076 case OMPD_taskyield:
1077 case OMPD_barrier:
1078 case OMPD_taskwait:
1079 case OMPD_taskgroup:
1080 case OMPD_atomic:
1081 case OMPD_flush:
1082 case OMPD_teams:
1083 case OMPD_target_data:
1084 case OMPD_target_exit_data:
1085 case OMPD_target_enter_data:
1086 case OMPD_distribute:
1087 case OMPD_distribute_simd:
1088 case OMPD_distribute_parallel_for:
1089 case OMPD_distribute_parallel_for_simd:
1090 case OMPD_teams_distribute:
1091 case OMPD_teams_distribute_simd:
1092 case OMPD_teams_distribute_parallel_for:
1093 case OMPD_teams_distribute_parallel_for_simd:
1094 case OMPD_target_update:
1095 case OMPD_declare_simd:
1096 case OMPD_declare_target:
1097 case OMPD_end_declare_target:
1098 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001099 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001100 case OMPD_taskloop:
1101 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001102 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001103 case OMPD_unknown:
1104 break;
1105 }
1106 llvm_unreachable(
1107 "Unknown programming model for OpenMP directive on NVPTX target.");
1108}
1109
1110void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001111 StringRef ParentName,
1112 llvm::Function *&OutlinedFn,
1113 llvm::Constant *&OutlinedFnID,
1114 bool IsOffloadEntry,
1115 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001116 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001117 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001118 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001119 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001120 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001121
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001122 // Emit target region as a standalone region.
1123 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001124 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1125 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001126
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001128 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001129 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001130 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001131 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001132 auto &RT =
1133 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001134 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1135 // Skip target region initialization.
1136 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001137 }
1138 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001139 auto &RT =
1140 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001141 RT.clearLocThreadIdInsertPt(CGF);
1142 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001143 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001144 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001145 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001146 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001147 // Reserve place for the globalized memory.
1148 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001149 if (!KernelStaticGlobalized) {
1150 KernelStaticGlobalized = new llvm::GlobalVariable(
1151 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1152 llvm::GlobalValue::InternalLinkage,
1153 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1154 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1155 llvm::GlobalValue::NotThreadLocal,
1156 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1157 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001158 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1159 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001160 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001161
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001162 // Now change the name of the worker function to correspond to this target
1163 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001164 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001165
1166 // Create the worker function
1167 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168}
1169
1170// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001171void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001172 EntryFunctionState &EST,
1173 WorkerFunctionState &WST) {
1174 CGBuilderTy &Bld = CGF.Builder;
1175
1176 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1177 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1178 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1179 EST.ExitBB = CGF.createBasicBlock(".exit");
1180
Alexey Bataev9ff80832018-04-16 20:16:21 +00001181 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1183 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1184
1185 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001186 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001187 CGF.EmitBranch(EST.ExitBB);
1188
1189 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001190 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001191 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1192 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1193
1194 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001195 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001196 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001197 // First action in sequential region:
1198 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001199 // TODO: Optimize runtime initialization and pass in correct value.
1200 llvm::Value *Args[] = {getThreadLimit(CGF),
1201 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001202 CGF.EmitRuntimeCall(
1203 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001204
1205 // For data sharing, we need to initialize the stack.
1206 CGF.EmitRuntimeCall(
1207 createNVPTXRuntimeFunction(
1208 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1209
Alexey Bataevc99042b2018-03-15 18:10:54 +00001210 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211}
1212
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001213void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001214 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001215 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001216 if (!CGF.HaveInsertPoint())
1217 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001218
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001219 emitGenericVarsEpilog(CGF);
1220
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221 if (!EST.ExitBB)
1222 EST.ExitBB = CGF.createBasicBlock(".exit");
1223
1224 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1225 CGF.EmitBranch(TerminateBB);
1226
1227 CGF.EmitBlock(TerminateBB);
1228 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001229 // TODO: Optimize runtime initialization and pass in correct value.
1230 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001231 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001232 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001233 // Barrier to terminate worker threads.
1234 syncCTAThreads(CGF);
1235 // Master thread jumps to exit point.
1236 CGF.EmitBranch(EST.ExitBB);
1237
1238 CGF.EmitBlock(EST.ExitBB);
1239 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001240}
1241
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001242void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001243 StringRef ParentName,
1244 llvm::Function *&OutlinedFn,
1245 llvm::Constant *&OutlinedFnID,
1246 bool IsOffloadEntry,
1247 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001248 ExecutionRuntimeModesRAII ModeRAII(
1249 CurrentExecutionMode, RequiresFullRuntime,
1250 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1251 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001252 EntryFunctionState EST;
1253
1254 // Emit target region as a standalone region.
1255 class NVPTXPrePostActionTy : public PrePostActionTy {
1256 CGOpenMPRuntimeNVPTX &RT;
1257 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1258 const OMPExecutableDirective &D;
1259
1260 public:
1261 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1262 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1263 const OMPExecutableDirective &D)
1264 : RT(RT), EST(EST), D(D) {}
1265 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001266 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001267 // Skip target region initialization.
1268 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001269 }
1270 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001271 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001272 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001273 }
1274 } Action(*this, EST, D);
1275 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001276 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001277 // Reserve place for the globalized memory.
1278 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001279 if (!KernelStaticGlobalized) {
1280 KernelStaticGlobalized = new llvm::GlobalVariable(
1281 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1282 llvm::GlobalValue::InternalLinkage,
1283 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1284 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1285 llvm::GlobalValue::NotThreadLocal,
1286 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1287 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001288 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1289 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001290 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001291}
1292
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001293void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001294 CodeGenFunction &CGF, EntryFunctionState &EST,
1295 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001296 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001297
1298 // Setup BBs in entry function.
1299 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1300 EST.ExitBB = CGF.createBasicBlock(".exit");
1301
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001302 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1303 /*RequiresOMPRuntime=*/
1304 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1305 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001306 CGF.EmitRuntimeCall(
1307 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001308
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001309 if (RequiresFullRuntime) {
1310 // For data sharing, we need to initialize the stack.
1311 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1312 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1313 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001314
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001315 CGF.EmitBranch(ExecuteBB);
1316
1317 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001318
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001319 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001320}
1321
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001322void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001323 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001324 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001325 if (!CGF.HaveInsertPoint())
1326 return;
1327
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001328 if (!EST.ExitBB)
1329 EST.ExitBB = CGF.createBasicBlock(".exit");
1330
1331 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1332 CGF.EmitBranch(OMPDeInitBB);
1333
1334 CGF.EmitBlock(OMPDeInitBB);
1335 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001336 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1337 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001338 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001339 createNVPTXRuntimeFunction(
1340 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001341 CGF.EmitBranch(EST.ExitBB);
1342
1343 CGF.EmitBlock(EST.ExitBB);
1344 EST.ExitBB = nullptr;
1345}
1346
1347// Create a unique global variable to indicate the execution mode of this target
1348// region. The execution mode is either 'generic', or 'spmd' depending on the
1349// target directive. This variable is picked up by the offload library to setup
1350// the device appropriately before kernel launch. If the execution mode is
1351// 'generic', the runtime reserves one warp for the master, otherwise, all
1352// warps participate in parallel work.
1353static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001354 bool Mode) {
1355 auto *GVMode =
1356 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1357 llvm::GlobalValue::WeakAnyLinkage,
1358 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1359 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001360 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001361}
1362
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001363void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001364 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001365
1366 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001367 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001368 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001369 emitWorkerLoop(CGF, WST);
1370 CGF.FinishFunction();
1371}
1372
1373void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1374 WorkerFunctionState &WST) {
1375 //
1376 // The workers enter this loop and wait for parallel work from the master.
1377 // When the master encounters a parallel region it sets up the work + variable
1378 // arguments, and wakes up the workers. The workers first check to see if
1379 // they are required for the parallel region, i.e., within the # of requested
1380 // parallel threads. The activated workers load the variable arguments and
1381 // execute the parallel work.
1382 //
1383
1384 CGBuilderTy &Bld = CGF.Builder;
1385
1386 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1387 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1388 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1389 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1390 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1391 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1392
1393 CGF.EmitBranch(AwaitBB);
1394
1395 // Workers wait for work from master.
1396 CGF.EmitBlock(AwaitBB);
1397 // Wait for parallel work
1398 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001399
1400 Address WorkFn =
1401 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1402 Address ExecStatus =
1403 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1404 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1405 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1406
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001407 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001408 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001409 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001410 llvm::Value *Ret = CGF.EmitRuntimeCall(
1411 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1412 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001413
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001414 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001415 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1416 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001417 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1418
1419 // Activate requested workers.
1420 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001421 llvm::Value *IsActive =
1422 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1423 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001424
1425 // Signal start of parallel region.
1426 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001427 // Skip initialization.
1428 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001429
1430 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001431 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001432 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001433 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001434
1435 llvm::Value *WorkFnMatch =
1436 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1437
1438 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1439 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1440 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1441
1442 // Execute this outlined function.
1443 CGF.EmitBlock(ExecuteFNBB);
1444
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001445 // Insert call to work function via shared wrapper. The shared
1446 // wrapper takes two arguments:
1447 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001448 // - the thread ID;
1449 emitCall(CGF, WST.Loc, W,
1450 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001451
1452 // Go to end of parallel region.
1453 CGF.EmitBranch(TerminateBB);
1454
1455 CGF.EmitBlock(CheckNextBB);
1456 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001457 // Default case: call to outlined function through pointer if the target
1458 // region makes a declare target call that may contain an orphaned parallel
1459 // directive.
1460 auto *ParallelFnTy =
1461 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001462 /*isVarArg=*/false);
1463 llvm::Value *WorkFnCast =
1464 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001465 // Insert call to work function via shared wrapper. The shared
1466 // wrapper takes two arguments:
1467 // - the parallelism level;
1468 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001469 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001470 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1471 // Go to end of parallel region.
1472 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001473
1474 // Signal end of parallel region.
1475 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001476 CGF.EmitRuntimeCall(
1477 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1478 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001479 CGF.EmitBranch(BarrierBB);
1480
1481 // All active and inactive workers wait at a barrier after parallel region.
1482 CGF.EmitBlock(BarrierBB);
1483 // Barrier after parallel region.
1484 syncCTAThreads(CGF);
1485 CGF.EmitBranch(AwaitBB);
1486
1487 // Exit target region.
1488 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001489 // Skip initialization.
1490 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001491}
1492
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001493/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001494/// implementation. Specialized for the NVPTX device.
1495/// \param Function OpenMP runtime function.
1496/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001497llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001498CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001499 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001500 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1501 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001502 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1503 // RequiresOMPRuntime);
1504 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001505 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1508 break;
1509 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001510 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001511 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1512 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001513 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001515 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1516 break;
1517 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001518 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1519 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001520 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001521 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001522 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001523 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1524 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1525 break;
1526 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001527 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1528 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1529 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001530 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001531 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1532 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001533 break;
1534 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001535 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1536 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001537 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001538 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001539 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001540 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1541 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1542 break;
1543 }
1544 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001545 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1546 /// int16_t IsOMPRuntimeInitialized);
1547 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001548 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001549 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001550 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1552 break;
1553 }
1554 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1555 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001556 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001557 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1558 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1559 break;
1560 }
1561 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1562 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1563 // global_tid);
1564 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001565 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1568 break;
1569 }
1570 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1571 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1572 // global_tid);
1573 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001574 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001575 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1576 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1577 break;
1578 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001579 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1580 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1581 // int16_t lane_offset, int16_t warp_size);
1582 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001583 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001584 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1585 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1586 break;
1587 }
1588 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1589 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1590 // int16_t lane_offset, int16_t warp_size);
1591 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001592 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001593 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1594 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1595 break;
1596 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001597 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001598 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1599 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1600 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1601 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1602 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001603 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1604 CGM.Int16Ty, CGM.Int16Ty};
1605 auto *ShuffleReduceFnTy =
1606 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1607 /*isVarArg=*/false);
1608 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1609 auto *InterWarpCopyFnTy =
1610 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1611 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001612 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1613 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001614 CGM.Int32Ty,
1615 CGM.SizeTy,
1616 CGM.VoidPtrTy,
1617 ShuffleReduceFnTy->getPointerTo(),
1618 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001619 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001620 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1621 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001622 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001623 break;
1624 }
1625 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1626 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1627 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001628 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001629 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1630 RTLFn = CGM.CreateRuntimeFunction(
1631 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1632 break;
1633 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001634 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1635 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1636 // global_tid, void *global_buffer, int32_t num_of_records, void*
1637 // reduce_data,
1638 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1639 // lane_offset, int16_t shortCircuit),
1640 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1641 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1642 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1643 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1644 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1645 // *buffer, int idx, void *reduce_data));
1646 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1647 CGM.Int16Ty, CGM.Int16Ty};
1648 auto *ShuffleReduceFnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1650 /*isVarArg=*/false);
1651 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1652 auto *InterWarpCopyFnTy =
1653 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1654 /*isVarArg=*/false);
1655 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1656 CGM.VoidPtrTy};
1657 auto *GlobalListFnTy =
1658 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1659 /*isVarArg=*/false);
1660 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1661 CGM.Int32Ty,
1662 CGM.VoidPtrTy,
1663 CGM.Int32Ty,
1664 CGM.VoidPtrTy,
1665 ShuffleReduceFnTy->getPointerTo(),
1666 InterWarpCopyFnTy->getPointerTo(),
1667 GlobalListFnTy->getPointerTo(),
1668 GlobalListFnTy->getPointerTo(),
1669 GlobalListFnTy->getPointerTo(),
1670 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001671 auto *FnTy =
1672 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1673 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001674 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001675 break;
1676 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001677 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1678 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001679 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001680 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1681 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1682 break;
1683 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001684 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1685 /// Build void __kmpc_data_sharing_init_stack_spmd();
1686 auto *FnTy =
1687 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001688 RTLFn =
1689 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001690 break;
1691 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001692 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1693 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001694 // int16_t UseSharedMemory);
1695 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001696 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001697 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1698 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001699 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001700 break;
1701 }
1702 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1703 // Build void __kmpc_data_sharing_pop_stack(void *a);
1704 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001705 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001706 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1707 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1708 /*Name=*/"__kmpc_data_sharing_pop_stack");
1709 break;
1710 }
1711 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1712 /// Build void __kmpc_begin_sharing_variables(void ***args,
1713 /// size_t n_args);
1714 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001715 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001716 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1718 break;
1719 }
1720 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1721 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001722 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001723 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1728 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1729 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001730 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001731 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1732 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1733 break;
1734 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001735 case OMPRTL_NVPTX__kmpc_parallel_level: {
1736 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1737 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1738 auto *FnTy =
1739 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1740 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1741 break;
1742 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001743 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1744 // Build int8_t __kmpc_is_spmd_exec_mode();
1745 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1746 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1747 break;
1748 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001749 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001750 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1751 // const void *buf, size_t size, int16_t is_shared, const void **res);
1752 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1753 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001754 auto *FnTy =
1755 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1757 break;
1758 }
1759 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001760 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1761 // int16_t is_shared);
1762 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001763 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001764 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001765 RTLFn =
1766 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1767 break;
1768 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001769 case OMPRTL__kmpc_barrier: {
1770 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1771 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1772 auto *FnTy =
1773 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001775 cast<llvm::Function>(RTLFn.getCallee())
1776 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001777 break;
1778 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001779 case OMPRTL__kmpc_barrier_simple_spmd: {
1780 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1781 // global_tid);
1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1783 auto *FnTy =
1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1785 RTLFn =
1786 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001787 cast<llvm::Function>(RTLFn.getCallee())
1788 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001789 break;
1790 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001791 }
1792 return RTLFn;
1793}
1794
1795void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1796 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001797 uint64_t Size, int32_t,
1798 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001799 // TODO: Add support for global variables on the device after declare target
1800 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001801 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001802 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001803 llvm::Module &M = CGM.getModule();
1804 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001805
1806 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001807 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001808
1809 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001810 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001811 llvm::ConstantAsMetadata::get(
1812 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1813 // Append metadata to nvvm.annotations
1814 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1815}
1816
1817void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1818 const OMPExecutableDirective &D, StringRef ParentName,
1819 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001820 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001821 if (!IsOffloadEntry) // Nothing to do.
1822 return;
1823
1824 assert(!ParentName.empty() && "Invalid target region parent name!");
1825
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001826 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001827 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001828 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001829 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001830 else
1831 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1832 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001833
1834 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001835}
1836
Alexey Bataevceeaa482018-11-21 21:04:34 +00001837namespace {
1838LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1839/// Enum for accesseing the reserved_2 field of the ident_t struct.
1840enum ModeFlagsTy : unsigned {
1841 /// Bit set to 1 when in SPMD mode.
1842 KMP_IDENT_SPMD_MODE = 0x01,
1843 /// Bit set to 1 when a simplified runtime is used.
1844 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1845 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1846};
1847
1848/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1849static const ModeFlagsTy UndefinedMode =
1850 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1851} // anonymous namespace
1852
1853unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001854 switch (getExecutionMode()) {
1855 case EM_SPMD:
1856 if (requiresFullRuntime())
1857 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1858 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1859 case EM_NonSPMD:
1860 assert(requiresFullRuntime() && "Expected full runtime.");
1861 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1862 case EM_Unknown:
1863 return UndefinedMode;
1864 }
1865 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001866}
1867
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001868CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001869 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001870 if (!CGM.getLangOpts().OpenMPIsDevice)
1871 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001872}
Carlo Bertollic6872252016-04-04 15:55:02 +00001873
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001874void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1875 OpenMPProcBindClauseKind ProcBind,
1876 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001877 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001878 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001879 return;
1880
1881 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1882}
1883
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001884void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1885 llvm::Value *NumThreads,
1886 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001887 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001888 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001889 return;
1890
1891 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1892}
1893
Carlo Bertollic6872252016-04-04 15:55:02 +00001894void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1895 const Expr *NumTeams,
1896 const Expr *ThreadLimit,
1897 SourceLocation Loc) {}
1898
James Y Knight9871db02019-02-05 16:42:33 +00001899llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001900 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1901 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001902 // Emit target region as a standalone region.
1903 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001904 bool &IsInParallelRegion;
1905 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001906
1907 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001908 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1909 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001910 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001911 PrevIsInParallelRegion = IsInParallelRegion;
1912 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001913 }
1914 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001915 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001916 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001917 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001918 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001919 bool PrevIsInTTDRegion = IsInTTDRegion;
1920 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001921 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1922 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001923 auto *OutlinedFun =
1924 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1925 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001926 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001927 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001928 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1929 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001930 llvm::Function *WrapperFun =
1931 createParallelDataSharingWrapper(OutlinedFun, D);
1932 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1933 }
1934
1935 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001936}
1937
Alexey Bataev2adecff2018-09-21 14:22:53 +00001938/// Get list of lastprivate variables from the teams distribute ... or
1939/// teams {distribute ...} directives.
1940static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001941getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001942 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1943 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1944 "expected teams directive.");
1945 const OMPExecutableDirective *Dir = &D;
1946 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001947 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001948 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001949 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1950 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001951 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001952 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1953 Dir = nullptr;
1954 }
1955 }
1956 if (!Dir)
1957 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001958 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001959 for (const Expr *E : C->getVarRefs())
1960 Vars.push_back(getPrivateItem(E));
1961 }
1962}
1963
1964/// Get list of reduction variables from the teams ... directives.
1965static void
1966getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1967 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1968 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1969 "expected teams directive.");
1970 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1971 for (const Expr *E : C->privates())
1972 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001973 }
1974}
1975
James Y Knight9871db02019-02-05 16:42:33 +00001976llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001977 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1978 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001979 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001980
Alexey Bataev2adecff2018-09-21 14:22:53 +00001981 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001982 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001983 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001984 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00001985 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1986 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001987 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001988 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1989 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001990 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001991 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00001992 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001993 }
1994 } else if (!LastPrivatesReductions.empty()) {
1995 assert(!TeamAndReductions.first &&
1996 "Previous team declaration is not expected.");
1997 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
1998 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001999 }
2000
Alexey Bataevc99042b2018-03-15 18:10:54 +00002001 // Emit target region as a standalone region.
2002 class NVPTXPrePostActionTy : public PrePostActionTy {
2003 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002004 const RecordDecl *GlobalizedRD;
2005 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2006 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002007
2008 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002009 NVPTXPrePostActionTy(
2010 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2011 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2012 &MappedDeclsFields)
2013 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2014 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002015 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002016 auto &Rt =
2017 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2018 if (GlobalizedRD) {
2019 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2020 I->getSecond().GlobalRecord = GlobalizedRD;
2021 I->getSecond().MappedParams =
2022 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2023 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2024 for (const auto &Pair : MappedDeclsFields) {
2025 assert(Pair.getFirst()->isCanonicalDecl() &&
2026 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002027 Data.insert(std::make_pair(Pair.getFirst(),
2028 MappedVarData(Pair.getSecond(),
2029 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002030 }
2031 }
2032 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002033 }
2034 void Exit(CodeGenFunction &CGF) override {
2035 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2036 .emitGenericVarsEpilog(CGF);
2037 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002038 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2039 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002040 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002041 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002042 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002043 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002044 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002045
2046 return OutlinedFun;
2047}
2048
Alexey Bataevc99042b2018-03-15 18:10:54 +00002049void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002050 SourceLocation Loc,
2051 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002052 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2053 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002054 return;
2055
Alexey Bataevc99042b2018-03-15 18:10:54 +00002056 CGBuilderTy &Bld = CGF.Builder;
2057
2058 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2059 if (I == FunctionGlobalizedDecls.end())
2060 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002061 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002062 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002063 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002064
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002065 // Recover pointer to this function's global record. The runtime will
2066 // handle the specifics of the allocation of the memory.
2067 // Use actual memory size of the record including the padding
2068 // for alignment purposes.
2069 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002070 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002071 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002072 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002073 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002074
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002075 llvm::PointerType *GlobalRecPtrTy =
2076 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002077 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002078 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002079 if (!IsInTTDRegion &&
2080 (WithSPMDCheck ||
2081 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002082 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2083 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2084 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002085 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2086 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2087 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2088 llvm::Value *PL = CGF.EmitRuntimeCall(
2089 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2090 {RTLoc, ThreadID});
2091 IsTTD = Bld.CreateIsNull(PL);
2092 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002093 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2094 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2095 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2096 // There is no need to emit line number for unconditional branch.
2097 (void)ApplyDebugLocation::CreateEmpty(CGF);
2098 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002099 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2100 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002101 CGF.EmitBranch(ExitBB);
2102 // There is no need to emit line number for unconditional branch.
2103 (void)ApplyDebugLocation::CreateEmpty(CGF);
2104 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002105 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2106 if (const RecordDecl *SecGlobalizedVarsRecord =
2107 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2108 SecGlobalRecTy =
2109 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2110
2111 // Recover pointer to this function's global record. The runtime will
2112 // handle the specifics of the allocation of the memory.
2113 // Use actual memory size of the record including the padding
2114 // for alignment purposes.
2115 unsigned Alignment =
2116 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2117 unsigned GlobalRecordSize =
2118 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2119 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2120 Size = Bld.CreateSelect(
2121 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2122 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002123 // TODO: allow the usage of shared memory to be controlled by
2124 // the user, for now, default to global.
2125 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002126 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002127 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2128 createNVPTXRuntimeFunction(
2129 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2130 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002131 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002132 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002133 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002134 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002135 /*NumReservedValues=*/2, "_select_stack");
2136 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2137 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2138 GlobalRecCastAddr = Phi;
2139 I->getSecond().GlobalRecordAddr = Phi;
2140 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002141 } else if (IsInTTDRegion) {
2142 assert(GlobalizedRecords.back().Records.size() < 2 &&
2143 "Expected less than 2 globalized records: one for target and one "
2144 "for teams.");
2145 unsigned Offset = 0;
2146 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2147 QualType RDTy = CGM.getContext().getRecordType(RD);
2148 unsigned Alignment =
2149 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2150 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2151 Offset =
2152 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2153 }
2154 unsigned Alignment =
2155 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2156 Offset = llvm::alignTo(Offset, Alignment);
2157 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2158 ++GlobalizedRecords.back().RegionCounter;
2159 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002160 assert(KernelStaticGlobalized &&
2161 "Kernel static pointer must be initialized already.");
2162 auto *UseSharedMemory = new llvm::GlobalVariable(
2163 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2164 llvm::GlobalValue::InternalLinkage, nullptr,
2165 "_openmp_static_kernel$is_shared");
2166 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2167 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2168 /*DestWidth=*/16, /*Signed=*/0);
2169 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2170 Address(UseSharedMemory,
2171 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2172 /*Volatile=*/false, Int16Ty, Loc);
2173 auto *StaticGlobalized = new llvm::GlobalVariable(
2174 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002175 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002176 auto *RecSize = new llvm::GlobalVariable(
2177 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2178 llvm::GlobalValue::InternalLinkage, nullptr,
2179 "_openmp_static_kernel$size");
2180 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2181 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002182 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002183 CGM.getContext().getSizeType(), Loc);
2184 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2185 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002186 llvm::Value *GlobalRecordSizeArg[] = {
2187 llvm::ConstantInt::get(
2188 CGM.Int16Ty,
2189 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2190 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002191 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2192 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2193 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002194 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002195 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002196 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2197 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002198 }
2199 assert(KernelStaticGlobalized && "Global address must be set already.");
2200 Address FrameAddr = CGF.EmitLoadOfPointer(
2201 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2202 CGM.getContext()
2203 .getPointerType(CGM.getContext().VoidPtrTy)
2204 .castAs<PointerType>());
2205 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002206 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002207 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2208 I->getSecond().IsInSPMDModeFlag = nullptr;
2209 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2210 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002211 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002212 // TODO: allow the usage of shared memory to be controlled by
2213 // the user, for now, default to global.
2214 llvm::Value *GlobalRecordSizeArg[] = {
2215 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2216 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002217 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2218 createNVPTXRuntimeFunction(
2219 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2220 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002221 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002222 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002223 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2224 I->getSecond().IsInSPMDModeFlag = nullptr;
2225 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002226 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002227 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002228
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002229 // Emit the "global alloca" which is a GEP from the global declaration
2230 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002231 LValue SecBase;
2232 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2233 if (IsTTD) {
2234 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2235 llvm::PointerType *SecGlobalRecPtrTy =
2236 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2237 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2238 Bld.CreatePointerBitCastOrAddrSpaceCast(
2239 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2240 SecGlobalRecTy);
2241 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002242 for (auto &Rec : I->getSecond().LocalVarData) {
2243 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2244 llvm::Value *ParValue;
2245 if (EscapedParam) {
2246 const auto *VD = cast<VarDecl>(Rec.first);
2247 LValue ParLVal =
2248 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2249 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2250 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002251 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2252 // Emit VarAddr basing on lane-id if required.
2253 QualType VarTy;
2254 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002255 VarTy = Rec.second.FD->getType();
2256 } else {
2257 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2258 VarAddr.getAddress().getPointer(),
2259 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002260 VarTy =
2261 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002262 VarAddr = CGF.MakeAddrLValue(
2263 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2264 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002265 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002266 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002267 if (!IsInTTDRegion &&
2268 (WithSPMDCheck ||
2269 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002270 assert(I->getSecond().IsInSPMDModeFlag &&
2271 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002272 if (IsTTD) {
2273 assert(SecIt->second.IsOnePerTeam &&
2274 "Secondary glob data must be one per team.");
2275 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2276 VarAddr.setAddress(
2277 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2278 VarAddr.getPointer()),
2279 VarAddr.getAlignment()));
2280 Rec.second.PrivateAddr = VarAddr.getAddress();
2281 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002282 Address GlobalPtr = Rec.second.PrivateAddr;
2283 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2284 Rec.second.PrivateAddr = Address(
2285 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2286 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2287 LocalAddr.getAlignment());
2288 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002289 if (EscapedParam) {
2290 const auto *VD = cast<VarDecl>(Rec.first);
2291 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2292 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2293 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002294 if (IsTTD)
2295 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002296 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002297 }
2298 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2299 // Recover pointer to this function's global record. The runtime will
2300 // handle the specifics of the allocation of the memory.
2301 // Use actual memory size of the record including the padding
2302 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002303 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002304 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2305 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2306 Size = Bld.CreateNUWAdd(
2307 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2308 llvm::Value *AlignVal =
2309 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2310 Size = Bld.CreateUDiv(Size, AlignVal);
2311 Size = Bld.CreateNUWMul(Size, AlignVal);
2312 // TODO: allow the usage of shared memory to be controlled by
2313 // the user, for now, default to global.
2314 llvm::Value *GlobalRecordSizeArg[] = {
2315 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2316 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002317 createNVPTXRuntimeFunction(
2318 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002319 GlobalRecordSizeArg);
2320 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2321 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2322 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2323 CGM.getContext().getDeclAlign(VD),
2324 AlignmentSource::Decl);
2325 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2326 Base.getAddress());
2327 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002328 }
2329 I->getSecond().MappedParams->apply(CGF);
2330}
2331
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002332void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2333 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002334 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2335 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002336 return;
2337
Alexey Bataevc99042b2018-03-15 18:10:54 +00002338 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002339 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002340 I->getSecond().MappedParams->restore(CGF);
2341 if (!CGF.HaveInsertPoint())
2342 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002343 for (llvm::Value *Addr :
2344 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2345 CGF.EmitRuntimeCall(
2346 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2347 Addr);
2348 }
2349 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002350 if (!IsInTTDRegion &&
2351 (WithSPMDCheck ||
2352 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002353 CGBuilderTy &Bld = CGF.Builder;
2354 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2355 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2356 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2357 // There is no need to emit line number for unconditional branch.
2358 (void)ApplyDebugLocation::CreateEmpty(CGF);
2359 CGF.EmitBlock(NonSPMDBB);
2360 CGF.EmitRuntimeCall(
2361 createNVPTXRuntimeFunction(
2362 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2363 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2364 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002365 } else if (IsInTTDRegion) {
2366 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2367 "region counter must be > 0.");
2368 --GlobalizedRecords.back().RegionCounter;
2369 // Emit the restore function only in the target region.
2370 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002371 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2372 /*DestWidth=*/16, /*Signed=*/0);
2373 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2374 Address(GlobalizedRecords.back().UseSharedMemory,
2375 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2376 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002377 llvm::Value *Args[] = {
2378 llvm::ConstantInt::get(
2379 CGM.Int16Ty,
2380 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2381 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002382 CGF.EmitRuntimeCall(
2383 createNVPTXRuntimeFunction(
2384 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002385 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002386 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002387 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002388 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2389 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2390 I->getSecond().GlobalRecordAddr);
2391 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002392 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002393 }
2394}
2395
Carlo Bertollic6872252016-04-04 15:55:02 +00002396void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2397 const OMPExecutableDirective &D,
2398 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002399 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002400 ArrayRef<llvm::Value *> CapturedVars) {
2401 if (!CGF.HaveInsertPoint())
2402 return;
2403
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002404 Address ZeroAddr = CGF.CreateMemTemp(
2405 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2406 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002407 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2408 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002409 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002410 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2411 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002412 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002413}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002414
2415void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002416 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002417 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2418 if (!CGF.HaveInsertPoint())
2419 return;
2420
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002421 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002422 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002423 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002424 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002425}
2426
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002427void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002428 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2429 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2430 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002431
2432 // Force inline this outlined function at its call site.
2433 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2434
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002435 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2436 /*DestWidth=*/32, /*Signed=*/1),
2437 ".zero.addr");
2438 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002439 // ThreadId for serialized parallels is 0.
2440 Address ThreadIDAddr = ZeroAddr;
2441 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002442 CodeGenFunction &CGF, PrePostActionTy &Action) {
2443 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002444
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002445 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2446 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2447 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2448 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2449 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2450 };
2451 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2452 PrePostActionTy &) {
2453
2454 RegionCodeGenTy RCG(CodeGen);
2455 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2456 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2457 llvm::Value *Args[] = {RTLoc, ThreadID};
2458
2459 NVPTXActionTy Action(
2460 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2461 Args,
2462 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2463 Args);
2464 RCG.setAction(Action);
2465 RCG(CGF);
2466 };
2467
2468 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2469 PrePostActionTy &Action) {
2470 CGBuilderTy &Bld = CGF.Builder;
2471 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2472 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002473 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2474
2475 // Prepare for parallel region. Indicate the outlined function.
2476 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002477 CGF.EmitRuntimeCall(
2478 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2479 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002480
2481 // Create a private scope that will globalize the arguments
2482 // passed from the outside of the target region.
2483 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2484
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002485 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002486 if (!CapturedVars.empty()) {
2487 // Prepare for parallel region. Indicate the outlined function.
2488 Address SharedArgs =
2489 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2490 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2491
2492 llvm::Value *DataSharingArgs[] = {
2493 SharedArgsPtr,
2494 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2495 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2496 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2497 DataSharingArgs);
2498
2499 // Store variable address in a list of references to pass to workers.
2500 unsigned Idx = 0;
2501 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002502 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2503 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2504 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002505 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002506 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002507 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002508 if (V->getType()->isIntegerTy())
2509 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2510 else
2511 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002512 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2513 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002514 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002515 }
2516 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002517
2518 // Activate workers. This barrier is used by the master to signal
2519 // work for the workers.
2520 syncCTAThreads(CGF);
2521
2522 // OpenMP [2.5, Parallel Construct, p.49]
2523 // There is an implied barrier at the end of a parallel region. After the
2524 // end of a parallel region, only the master thread of the team resumes
2525 // execution of the enclosing task region.
2526 //
2527 // The master waits at this barrier until all workers are done.
2528 syncCTAThreads(CGF);
2529
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002530 if (!CapturedVars.empty())
2531 CGF.EmitRuntimeCall(
2532 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2533
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002534 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002535 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002536 };
2537
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002538 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2539 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002540 if (IsInParallelRegion) {
2541 SeqGen(CGF, Action);
2542 } else if (IsInTargetMasterThreadRegion) {
2543 L0ParallelGen(CGF, Action);
2544 } else {
2545 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002546 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002547 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002548 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002549 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002550 // }
2551 CGBuilderTy &Bld = CGF.Builder;
2552 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002553 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2554 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002555 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002556 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2557 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002558 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002559 // There is no need to emit line number for unconditional branch.
2560 (void)ApplyDebugLocation::CreateEmpty(CGF);
2561 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002562 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2563 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2564 llvm::Value *PL = CGF.EmitRuntimeCall(
2565 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2566 {RTLoc, ThreadID});
2567 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002568 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002569 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002570 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002571 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002572 // There is no need to emit line number for unconditional branch.
2573 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002574 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002575 L0ParallelGen(CGF, Action);
2576 CGF.EmitBranch(ExitBB);
2577 // There is no need to emit line number for unconditional branch.
2578 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002579 // Emit the continuation block for code after the if.
2580 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2581 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002582 };
2583
Alexey Bataev9ff80832018-04-16 20:16:21 +00002584 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002585 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002586 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002587 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002588 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002589 ThenRCG(CGF);
2590 }
2591}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002592
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002593void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002594 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002595 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2596 // Just call the outlined function to execute the parallel region.
2597 // OutlinedFn(&GTid, &zero, CapturedStruct);
2598 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002599 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002600
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002601 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2602 /*DestWidth=*/32, /*Signed=*/1),
2603 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002604 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002605 // ThreadId for serialized parallels is 0.
2606 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002607 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002608 &ThreadIDAddr](CodeGenFunction &CGF,
2609 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002610 Action.Enter(CGF);
2611
2612 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2613 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2614 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2615 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2616 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2617 };
2618 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2619 PrePostActionTy &) {
2620
2621 RegionCodeGenTy RCG(CodeGen);
2622 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2623 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2624 llvm::Value *Args[] = {RTLoc, ThreadID};
2625
2626 NVPTXActionTy Action(
2627 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2628 Args,
2629 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2630 Args);
2631 RCG.setAction(Action);
2632 RCG(CGF);
2633 };
2634
2635 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002636 // In the worker need to use the real thread id.
2637 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002638 RegionCodeGenTy RCG(CodeGen);
2639 RCG(CGF);
2640 } else {
2641 // If we are not in the target region, it is definitely L2 parallelism or
2642 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2643 // need to check for orphaned directives.
2644 RegionCodeGenTy RCG(SeqGen);
2645 RCG(CGF);
2646 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002647}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002648
Alexey Bataeva3924b52019-01-03 16:25:35 +00002649void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2650 // Always emit simple barriers!
2651 if (!CGF.HaveInsertPoint())
2652 return;
2653 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2654 // This function does not use parameters, so we can emit just default values.
2655 llvm::Value *Args[] = {
2656 llvm::ConstantPointerNull::get(
2657 cast<llvm::PointerType>(getIdentTyPointerTy())),
2658 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2659 CGF.EmitRuntimeCall(
2660 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2661}
2662
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002663void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2664 SourceLocation Loc,
2665 OpenMPDirectiveKind Kind, bool,
2666 bool) {
2667 // Always emit simple barriers!
2668 if (!CGF.HaveInsertPoint())
2669 return;
2670 // Build call __kmpc_cancel_barrier(loc, thread_id);
2671 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2672 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2673 getThreadID(CGF, Loc)};
2674 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2675}
2676
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002677void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2678 CodeGenFunction &CGF, StringRef CriticalName,
2679 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2680 const Expr *Hint) {
2681 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2682 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2683 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2684 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2685 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2686
2687 // Fetch team-local id of the thread.
2688 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2689
2690 // Get the width of the team.
2691 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2692
2693 // Initialize the counter variable for the loop.
2694 QualType Int32Ty =
2695 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2696 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2697 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2698 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2699 /*isInit=*/true);
2700
2701 // Block checks if loop counter exceeds upper bound.
2702 CGF.EmitBlock(LoopBB);
2703 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2704 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2705 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2706
2707 // Block tests which single thread should execute region, and which threads
2708 // should go straight to synchronisation point.
2709 CGF.EmitBlock(TestBB);
2710 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2711 llvm::Value *CmpThreadToCounter =
2712 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2713 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2714
2715 // Block emits the body of the critical region.
2716 CGF.EmitBlock(BodyBB);
2717
2718 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002719 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2720 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002721
2722 // After the body surrounded by the critical region, the single executing
2723 // thread will jump to the synchronisation point.
2724 // Block waits for all threads in current team to finish then increments the
2725 // counter variable and returns to the loop.
2726 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002727 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2728 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002729
2730 llvm::Value *IncCounterVal =
2731 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2732 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2733 CGF.EmitBranch(LoopBB);
2734
2735 // Block that is reached when all threads in the team complete the region.
2736 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2737}
2738
Alexey Bataevb2575932018-01-04 20:18:55 +00002739/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002740static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2741 QualType ValTy, QualType CastTy,
2742 SourceLocation Loc) {
2743 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2744 "Cast type must sized.");
2745 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2746 "Val type must sized.");
2747 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2748 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002749 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002750 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2751 CGF.getContext().getTypeSizeInChars(CastTy))
2752 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2753 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2754 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2755 CastTy->hasSignedIntegerRepresentation());
2756 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002757 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2758 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002759 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2760 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002761}
2762
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002763/// This function creates calls to one of two shuffle functions to copy
2764/// variables between lanes in a warp.
2765static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002766 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002767 QualType ElemType,
2768 llvm::Value *Offset,
2769 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002770 CodeGenModule &CGM = CGF.CGM;
2771 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002772 CGOpenMPRuntimeNVPTX &RT =
2773 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2774
Alexey Bataeva453f362018-03-19 17:53:56 +00002775 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2776 assert(Size.getQuantity() <= 8 &&
2777 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002778
Alexey Bataeva453f362018-03-19 17:53:56 +00002779 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002780 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2781 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2782
2783 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002784 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2785 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2786 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002787 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002788 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002789
Alexey Bataev9ff80832018-04-16 20:16:21 +00002790 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2791 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002792
Alexey Bataeva453f362018-03-19 17:53:56 +00002793 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002794}
2795
Alexey Bataev12c62902018-06-22 19:10:38 +00002796static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2797 Address DestAddr, QualType ElemType,
2798 llvm::Value *Offset, SourceLocation Loc) {
2799 CGBuilderTy &Bld = CGF.Builder;
2800
2801 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2802 // Create the loop over the big sized data.
2803 // ptr = (void*)Elem;
2804 // ptrEnd = (void*) Elem + 1;
2805 // Step = 8;
2806 // while (ptr + Step < ptrEnd)
2807 // shuffle((int64_t)*ptr);
2808 // Step = 4;
2809 // while (ptr + Step < ptrEnd)
2810 // shuffle((int32_t)*ptr);
2811 // ...
2812 Address ElemPtr = DestAddr;
2813 Address Ptr = SrcAddr;
2814 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002815 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002816 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2817 if (Size < CharUnits::fromQuantity(IntSize))
2818 continue;
2819 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2820 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2821 /*Signed=*/1);
2822 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2823 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2824 ElemPtr =
2825 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2826 if (Size.getQuantity() / IntSize > 1) {
2827 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2828 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2829 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2830 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2831 CGF.EmitBlock(PreCondBB);
2832 llvm::PHINode *PhiSrc =
2833 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2834 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2835 llvm::PHINode *PhiDest =
2836 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2837 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2838 Ptr = Address(PhiSrc, Ptr.getAlignment());
2839 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2840 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2841 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2842 Ptr.getPointer(), CGF.VoidPtrTy));
2843 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2844 ThenBB, ExitBB);
2845 CGF.EmitBlock(ThenBB);
2846 llvm::Value *Res = createRuntimeShuffleFunction(
2847 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2848 IntType, Offset, Loc);
2849 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002850 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2851 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002852 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2853 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002854 CGF.EmitBranch(PreCondBB);
2855 CGF.EmitBlock(ExitBB);
2856 } else {
2857 llvm::Value *Res = createRuntimeShuffleFunction(
2858 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2859 IntType, Offset, Loc);
2860 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002861 Ptr = Bld.CreateConstGEP(Ptr, 1);
2862 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002863 }
2864 Size = Size % IntSize;
2865 }
2866}
2867
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002868namespace {
2869enum CopyAction : unsigned {
2870 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2871 // the warp using shuffle instructions.
2872 RemoteLaneToThread,
2873 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2874 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002875 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2876 ThreadToScratchpad,
2877 // ScratchpadToThread: Copy from a scratchpad array in global memory
2878 // containing team-reduced data to a thread's stack.
2879 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002880};
2881} // namespace
2882
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002883struct CopyOptionsTy {
2884 llvm::Value *RemoteLaneOffset;
2885 llvm::Value *ScratchpadIndex;
2886 llvm::Value *ScratchpadWidth;
2887};
2888
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002889/// Emit instructions to copy a Reduce list, which contains partially
2890/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002891static void emitReductionListCopy(
2892 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2893 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2894 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002895
Alexey Bataev9ff80832018-04-16 20:16:21 +00002896 CodeGenModule &CGM = CGF.CGM;
2897 ASTContext &C = CGM.getContext();
2898 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002899
Alexey Bataev9ff80832018-04-16 20:16:21 +00002900 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2901 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2902 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002903
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002904 // Iterates, element-by-element, through the source Reduce list and
2905 // make a copy.
2906 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002907 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002908 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002909 Address SrcElementAddr = Address::invalid();
2910 Address DestElementAddr = Address::invalid();
2911 Address DestElementPtrAddr = Address::invalid();
2912 // Should we shuffle in an element from a remote lane?
2913 bool ShuffleInElement = false;
2914 // Set to true to update the pointer in the dest Reduce list to a
2915 // newly created element.
2916 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002917 // Increment the src or dest pointer to the scratchpad, for each
2918 // new element.
2919 bool IncrScratchpadSrc = false;
2920 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002921
2922 switch (Action) {
2923 case RemoteLaneToThread: {
2924 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002925 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002926 SrcElementAddr = CGF.EmitLoadOfPointer(
2927 SrcElementPtrAddr,
2928 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929
2930 // Step 1.2: Create a temporary to store the element in the destination
2931 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002932 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002933 DestElementAddr =
2934 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2935 ShuffleInElement = true;
2936 UpdateDestListPtr = true;
2937 break;
2938 }
2939 case ThreadCopy: {
2940 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002941 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002942 SrcElementAddr = CGF.EmitLoadOfPointer(
2943 SrcElementPtrAddr,
2944 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002945
2946 // Step 1.2: Get the address for dest element. The destination
2947 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002948 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002949 DestElementAddr = CGF.EmitLoadOfPointer(
2950 DestElementPtrAddr,
2951 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002952 break;
2953 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002954 case ThreadToScratchpad: {
2955 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002956 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002957 SrcElementAddr = CGF.EmitLoadOfPointer(
2958 SrcElementPtrAddr,
2959 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002960
2961 // Step 1.2: Get the address for dest element:
2962 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002963 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002964 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002965 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002966 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002967 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002968 ScratchPadElemAbsolutePtrVal =
2969 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002970 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2971 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002972 IncrScratchpadDest = true;
2973 break;
2974 }
2975 case ScratchpadToThread: {
2976 // Step 1.1: Get the address for the src element in the scratchpad.
2977 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002978 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002979 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002980 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002981 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002982 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002983 ScratchPadElemAbsolutePtrVal =
2984 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2985 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2986 C.getTypeAlignInChars(Private->getType()));
2987 IncrScratchpadSrc = true;
2988
2989 // Step 1.2: Create a temporary to store the element in the destination
2990 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002991 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002992 DestElementAddr =
2993 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2994 UpdateDestListPtr = true;
2995 break;
2996 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002997 }
2998
2999 // Regardless of src and dest of copy, we emit the load of src
3000 // element as this is required in all directions
3001 SrcElementAddr = Bld.CreateElementBitCast(
3002 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003003 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3004 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003005
3006 // Now that all active lanes have read the element in the
3007 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003008 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003009 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3010 RemoteLaneOffset, Private->getExprLoc());
3011 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003012 switch (CGF.getEvaluationKind(Private->getType())) {
3013 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003014 llvm::Value *Elem =
3015 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3016 Private->getType(), Private->getExprLoc());
3017 // Store the source element value to the dest element address.
3018 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3019 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003020 break;
3021 }
3022 case TEK_Complex: {
3023 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3024 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3025 Private->getExprLoc());
3026 CGF.EmitStoreOfComplex(
3027 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3028 /*isInit=*/false);
3029 break;
3030 }
3031 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003032 CGF.EmitAggregateCopy(
3033 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3034 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3035 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003036 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003037 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003038 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003039
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003040 // Step 3.1: Modify reference in dest Reduce list as needed.
3041 // Modifying the reference in Reduce list to point to the newly
3042 // created element. The element is live in the current function
3043 // scope and that of functions it invokes (i.e., reduce_function).
3044 // RemoteReduceData[i] = (void*)&RemoteElem
3045 if (UpdateDestListPtr) {
3046 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3047 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3048 DestElementPtrAddr, /*Volatile=*/false,
3049 C.VoidPtrTy);
3050 }
3051
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003052 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3053 // address of the next element in scratchpad memory, unless we're currently
3054 // processing the last one. Memory alignment is also taken care of here.
3055 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3056 llvm::Value *ScratchpadBasePtr =
3057 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003058 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3059 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003060 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003061 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003062
3063 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003064 ScratchpadBasePtr = Bld.CreateNUWSub(
3065 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3066 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003067 ScratchpadBasePtr,
3068 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003069 ScratchpadBasePtr = Bld.CreateNUWAdd(
3070 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3071 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003072 ScratchpadBasePtr,
3073 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3074
3075 if (IncrScratchpadDest)
3076 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3077 else /* IncrScratchpadSrc = true */
3078 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3079 }
3080
Alexey Bataev9ff80832018-04-16 20:16:21 +00003081 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003082 }
3083}
3084
3085/// This function emits a helper that gathers Reduce lists from the first
3086/// lane of every active warp to lanes in the first warp.
3087///
3088/// void inter_warp_copy_func(void* reduce_data, num_warps)
3089/// shared smem[warp_size];
3090/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003091/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003092/// If (I am the first lane in each warp)
3093/// Copy my local D to smem[warp_id]
3094/// sync
3095/// if (I am the first warp)
3096/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003097static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3098 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003099 QualType ReductionArrayTy,
3100 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003101 ASTContext &C = CGM.getContext();
3102 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103
3104 // ReduceList: thread local Reduce list.
3105 // At the stage of the computation when this function is called, partially
3106 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003107 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3108 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109 // NumWarps: number of warps active in the parallel region. This could
3110 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003111 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003112 C.getIntTypeForBitwidth(32, /* Signed */ true),
3113 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003114 FunctionArgList Args;
3115 Args.push_back(&ReduceListArg);
3116 Args.push_back(&NumWarpsArg);
3117
Alexey Bataev9ff80832018-04-16 20:16:21 +00003118 const CGFunctionInfo &CGFI =
3119 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003120 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3121 llvm::GlobalValue::InternalLinkage,
3122 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003123 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003125 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003126 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003127
Alexey Bataev9ff80832018-04-16 20:16:21 +00003128 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003129
3130 // This array is used as a medium to transfer, one reduce element at a time,
3131 // the data from the first lane of every warp to lanes in the first warp
3132 // in order to perform the final step of a reduction in a parallel region
3133 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3134 // for reduced latency, as well as to have a distinct copy for concurrently
3135 // executing target regions. The array is declared with common linkage so
3136 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003137 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003138 "__openmp_nvptx_data_transfer_temporary_storage";
3139 llvm::GlobalVariable *TransferMedium =
3140 M.getGlobalVariable(TransferMediumName);
3141 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003142 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3144 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003145 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003146 llvm::Constant::getNullValue(Ty), TransferMediumName,
3147 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3148 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003149 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150 }
3151
3152 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003153 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003154 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003155 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003156 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003157 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158
3159 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3160 Address LocalReduceList(
3161 Bld.CreatePointerBitCastOrAddrSpaceCast(
3162 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003163 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3165 CGF.getPointerAlign());
3166
3167 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003168 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003169 //
3170 // Warp master copies reduce element to transfer medium in __shared__
3171 // memory.
3172 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003173 unsigned RealTySize =
3174 C.getTypeSizeInChars(Private->getType())
3175 .alignTo(C.getTypeAlignInChars(Private->getType()))
3176 .getQuantity();
3177 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3178 unsigned NumIters = RealTySize / TySize;
3179 if (NumIters == 0)
3180 continue;
3181 QualType CType = C.getIntTypeForBitwidth(
3182 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3183 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3184 CharUnits Align = CharUnits::fromQuantity(TySize);
3185 llvm::Value *Cnt = nullptr;
3186 Address CntAddr = Address::invalid();
3187 llvm::BasicBlock *PrecondBB = nullptr;
3188 llvm::BasicBlock *ExitBB = nullptr;
3189 if (NumIters > 1) {
3190 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3191 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3192 /*Volatile=*/false, C.IntTy);
3193 PrecondBB = CGF.createBasicBlock("precond");
3194 ExitBB = CGF.createBasicBlock("exit");
3195 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3196 // There is no need to emit line number for unconditional branch.
3197 (void)ApplyDebugLocation::CreateEmpty(CGF);
3198 CGF.EmitBlock(PrecondBB);
3199 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3200 llvm::Value *Cmp =
3201 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3202 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3203 CGF.EmitBlock(BodyBB);
3204 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003205 // kmpc_barrier.
3206 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3207 /*EmitChecks=*/false,
3208 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003209 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3210 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3211 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003212
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003213 // if (lane_id == 0)
3214 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3215 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3216 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003217
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003218 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003219 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003220 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3221 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3222 // elemptr = ((CopyType*)(elemptrptr)) + I
3223 Address ElemPtr = Address(ElemPtrPtr, Align);
3224 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3225 if (NumIters > 1) {
3226 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3227 ElemPtr.getAlignment());
3228 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003229
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003230 // Get pointer to location in transfer medium.
3231 // MediumPtr = &medium[warp_id]
3232 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3233 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3234 Address MediumPtr(MediumPtrVal, Align);
3235 // Casting to actual data type.
3236 // MediumPtr = (CopyType*)MediumPtrAddr;
3237 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003238
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003239 // elem = *elemptr
3240 //*MediumPtr = elem
3241 llvm::Value *Elem =
3242 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003243 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003244 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003246 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003247
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003248 CGF.EmitBlock(ElseBB);
3249 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003250
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003252
Alexey Bataevae51b962018-12-14 21:00:58 +00003253 // kmpc_barrier.
3254 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3255 /*EmitChecks=*/false,
3256 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003257
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003258 //
3259 // Warp 0 copies reduce element from transfer medium.
3260 //
3261 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3262 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3263 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003264
Alexey Bataevae51b962018-12-14 21:00:58 +00003265 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3266 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3267 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3268
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003269 // Up to 32 threads in warp 0 are active.
3270 llvm::Value *IsActiveThread =
3271 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3272 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003273
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003274 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 // SrcMediumPtr = &medium[tid]
3277 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3278 TransferMedium,
3279 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3280 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3281 // SrcMediumVal = *SrcMediumPtr;
3282 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003283
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003284 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003285 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003286 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3287 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3288 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3289 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3290 if (NumIters > 1) {
3291 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3292 TargetElemPtr.getAlignment());
3293 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003294
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003295 // *TargetElemPtr = SrcMediumVal;
3296 llvm::Value *SrcMediumValue =
3297 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003298 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003299 CType);
3300 Bld.CreateBr(W0MergeBB);
3301
3302 CGF.EmitBlock(W0ElseBB);
3303 Bld.CreateBr(W0MergeBB);
3304
3305 CGF.EmitBlock(W0MergeBB);
3306
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003307 if (NumIters > 1) {
3308 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3309 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3310 CGF.EmitBranch(PrecondBB);
3311 (void)ApplyDebugLocation::CreateEmpty(CGF);
3312 CGF.EmitBlock(ExitBB);
3313 }
3314 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003315 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003316 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003317 }
3318
3319 CGF.FinishFunction();
3320 return Fn;
3321}
3322
3323/// Emit a helper that reduces data across two OpenMP threads (lanes)
3324/// in the same warp. It uses shuffle instructions to copy over data from
3325/// a remote lane's stack. The reduction algorithm performed is specified
3326/// by the fourth parameter.
3327///
3328/// Algorithm Versions.
3329/// Full Warp Reduce (argument value 0):
3330/// This algorithm assumes that all 32 lanes are active and gathers
3331/// data from these 32 lanes, producing a single resultant value.
3332/// Contiguous Partial Warp Reduce (argument value 1):
3333/// This algorithm assumes that only a *contiguous* subset of lanes
3334/// are active. This happens for the last warp in a parallel region
3335/// when the user specified num_threads is not an integer multiple of
3336/// 32. This contiguous subset always starts with the zeroth lane.
3337/// Partial Warp Reduce (argument value 2):
3338/// This algorithm gathers data from any number of lanes at any position.
3339/// All reduced values are stored in the lowest possible lane. The set
3340/// of problems every algorithm addresses is a super set of those
3341/// addressable by algorithms with a lower version number. Overhead
3342/// increases as algorithm version increases.
3343///
3344/// Terminology
3345/// Reduce element:
3346/// Reduce element refers to the individual data field with primitive
3347/// data types to be combined and reduced across threads.
3348/// Reduce list:
3349/// Reduce list refers to a collection of local, thread-private
3350/// reduce elements.
3351/// Remote Reduce list:
3352/// Remote Reduce list refers to a collection of remote (relative to
3353/// the current thread) reduce elements.
3354///
3355/// We distinguish between three states of threads that are important to
3356/// the implementation of this function.
3357/// Alive threads:
3358/// Threads in a warp executing the SIMT instruction, as distinguished from
3359/// threads that are inactive due to divergent control flow.
3360/// Active threads:
3361/// The minimal set of threads that has to be alive upon entry to this
3362/// function. The computation is correct iff active threads are alive.
3363/// Some threads are alive but they are not active because they do not
3364/// contribute to the computation in any useful manner. Turning them off
3365/// may introduce control flow overheads without any tangible benefits.
3366/// Effective threads:
3367/// In order to comply with the argument requirements of the shuffle
3368/// function, we must keep all lanes holding data alive. But at most
3369/// half of them perform value aggregation; we refer to this half of
3370/// threads as effective. The other half is simply handing off their
3371/// data.
3372///
3373/// Procedure
3374/// Value shuffle:
3375/// In this step active threads transfer data from higher lane positions
3376/// in the warp to lower lane positions, creating Remote Reduce list.
3377/// Value aggregation:
3378/// In this step, effective threads combine their thread local Reduce list
3379/// with Remote Reduce list and store the result in the thread local
3380/// Reduce list.
3381/// Value copy:
3382/// In this step, we deal with the assumption made by algorithm 2
3383/// (i.e. contiguity assumption). When we have an odd number of lanes
3384/// active, say 2k+1, only k threads will be effective and therefore k
3385/// new values will be produced. However, the Reduce list owned by the
3386/// (2k+1)th thread is ignored in the value aggregation. Therefore
3387/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3388/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003389static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003390 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003391 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003392 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003393
3394 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003395 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3396 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003397 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003398 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3399 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003400 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003401 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3402 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003403 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003404 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3405 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003406 FunctionArgList Args;
3407 Args.push_back(&ReduceListArg);
3408 Args.push_back(&LaneIDArg);
3409 Args.push_back(&RemoteLaneOffsetArg);
3410 Args.push_back(&AlgoVerArg);
3411
Alexey Bataev9ff80832018-04-16 20:16:21 +00003412 const CGFunctionInfo &CGFI =
3413 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003414 auto *Fn = llvm::Function::Create(
3415 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3416 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003417 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003418 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003419 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003420 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003421
Alexey Bataev9ff80832018-04-16 20:16:21 +00003422 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003423
3424 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3425 Address LocalReduceList(
3426 Bld.CreatePointerBitCastOrAddrSpaceCast(
3427 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3428 C.VoidPtrTy, SourceLocation()),
3429 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3430 CGF.getPointerAlign());
3431
3432 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3433 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3434 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3435
3436 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3437 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3438 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3439
3440 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3441 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3442 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3443
3444 // Create a local thread-private variable to host the Reduce list
3445 // from a remote lane.
3446 Address RemoteReduceList =
3447 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3448
3449 // This loop iterates through the list of reduce elements and copies,
3450 // element by element, from a remote lane in the warp to RemoteReduceList,
3451 // hosted on the thread's stack.
3452 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3453 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003454 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3455 /*ScratchpadIndex=*/nullptr,
3456 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003457
3458 // The actions to be performed on the Remote Reduce list is dependent
3459 // on the algorithm version.
3460 //
3461 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3462 // LaneId % 2 == 0 && Offset > 0):
3463 // do the reduction value aggregation
3464 //
3465 // The thread local variable Reduce list is mutated in place to host the
3466 // reduced data, which is the aggregated value produced from local and
3467 // remote lanes.
3468 //
3469 // Note that AlgoVer is expected to be a constant integer known at compile
3470 // time.
3471 // When AlgoVer==0, the first conjunction evaluates to true, making
3472 // the entire predicate true during compile time.
3473 // When AlgoVer==1, the second conjunction has only the second part to be
3474 // evaluated during runtime. Other conjunctions evaluates to false
3475 // during compile time.
3476 // When AlgoVer==2, the third conjunction has only the second part to be
3477 // evaluated during runtime. Other conjunctions evaluates to false
3478 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003479 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003480
Alexey Bataev9ff80832018-04-16 20:16:21 +00003481 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3482 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003483 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3484
Alexey Bataev9ff80832018-04-16 20:16:21 +00003485 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3486 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3487 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003488 CondAlgo2 = Bld.CreateAnd(
3489 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3490
Alexey Bataev9ff80832018-04-16 20:16:21 +00003491 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003492 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3493
3494 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3495 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3496 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3497 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3498
3499 CGF.EmitBlock(ThenBB);
3500 // reduce_function(LocalReduceList, RemoteReduceList)
3501 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3502 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3503 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3504 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003505 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3506 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003507 Bld.CreateBr(MergeBB);
3508
3509 CGF.EmitBlock(ElseBB);
3510 Bld.CreateBr(MergeBB);
3511
3512 CGF.EmitBlock(MergeBB);
3513
3514 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3515 // Reduce list.
3516 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003517 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003518 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3519
3520 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3521 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3522 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3523 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3524
3525 CGF.EmitBlock(CpyThenBB);
3526 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3527 RemoteReduceList, LocalReduceList);
3528 Bld.CreateBr(CpyMergeBB);
3529
3530 CGF.EmitBlock(CpyElseBB);
3531 Bld.CreateBr(CpyMergeBB);
3532
3533 CGF.EmitBlock(CpyMergeBB);
3534
3535 CGF.FinishFunction();
3536 return Fn;
3537}
3538
Alexey Bataev8061acd2019-02-20 16:36:22 +00003539/// This function emits a helper that copies all the reduction variables from
3540/// the team into the provided global buffer for the reduction variables.
3541///
3542/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3543/// For all data entries D in reduce_data:
3544/// Copy local D to buffer.D[Idx]
3545static llvm::Value *emitListToGlobalCopyFunction(
3546 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3547 QualType ReductionArrayTy, SourceLocation Loc,
3548 const RecordDecl *TeamReductionRec,
3549 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3550 &VarFieldMap) {
3551 ASTContext &C = CGM.getContext();
3552
3553 // Buffer: global reduction buffer.
3554 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3555 C.VoidPtrTy, ImplicitParamDecl::Other);
3556 // Idx: index of the buffer.
3557 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3558 ImplicitParamDecl::Other);
3559 // ReduceList: thread local Reduce list.
3560 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3561 C.VoidPtrTy, ImplicitParamDecl::Other);
3562 FunctionArgList Args;
3563 Args.push_back(&BufferArg);
3564 Args.push_back(&IdxArg);
3565 Args.push_back(&ReduceListArg);
3566
3567 const CGFunctionInfo &CGFI =
3568 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3569 auto *Fn = llvm::Function::Create(
3570 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3571 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3572 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3573 Fn->setDoesNotRecurse();
3574 CodeGenFunction CGF(CGM);
3575 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3576
3577 CGBuilderTy &Bld = CGF.Builder;
3578
3579 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3580 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3581 Address LocalReduceList(
3582 Bld.CreatePointerBitCastOrAddrSpaceCast(
3583 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3584 C.VoidPtrTy, Loc),
3585 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3586 CGF.getPointerAlign());
3587 QualType StaticTy = C.getRecordType(TeamReductionRec);
3588 llvm::Type *LLVMReductionsBufferTy =
3589 CGM.getTypes().ConvertTypeForMem(StaticTy);
3590 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3591 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3592 LLVMReductionsBufferTy->getPointerTo());
3593 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3594 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3595 /*Volatile=*/false, C.IntTy,
3596 Loc)};
3597 unsigned Idx = 0;
3598 for (const Expr *Private : Privates) {
3599 // Reduce element = LocalReduceList[i]
3600 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3601 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3602 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3603 // elemptr = ((CopyType*)(elemptrptr)) + I
3604 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3605 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3606 Address ElemPtr =
3607 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3608 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3609 // Global = Buffer.VD[Idx];
3610 const FieldDecl *FD = VarFieldMap.lookup(VD);
3611 LValue GlobLVal = CGF.EmitLValueForField(
3612 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3613 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3614 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3615 switch (CGF.getEvaluationKind(Private->getType())) {
3616 case TEK_Scalar: {
3617 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3618 Private->getType(), Loc);
3619 CGF.EmitStoreOfScalar(V, GlobLVal);
3620 break;
3621 }
3622 case TEK_Complex: {
3623 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3624 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3625 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3626 break;
3627 }
3628 case TEK_Aggregate:
3629 CGF.EmitAggregateCopy(GlobLVal,
3630 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3631 Private->getType(), AggValueSlot::DoesNotOverlap);
3632 break;
3633 }
3634 ++Idx;
3635 }
3636
3637 CGF.FinishFunction();
3638 return Fn;
3639}
3640
3641/// This function emits a helper that reduces all the reduction variables from
3642/// the team into the provided global buffer for the reduction variables.
3643///
3644/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3645/// void *GlobPtrs[];
3646/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3647/// ...
3648/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3649/// reduce_function(GlobPtrs, reduce_data);
3650static llvm::Value *emitListToGlobalReduceFunction(
3651 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3652 QualType ReductionArrayTy, SourceLocation Loc,
3653 const RecordDecl *TeamReductionRec,
3654 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3655 &VarFieldMap,
3656 llvm::Function *ReduceFn) {
3657 ASTContext &C = CGM.getContext();
3658
3659 // Buffer: global reduction buffer.
3660 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3661 C.VoidPtrTy, ImplicitParamDecl::Other);
3662 // Idx: index of the buffer.
3663 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3664 ImplicitParamDecl::Other);
3665 // ReduceList: thread local Reduce list.
3666 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3667 C.VoidPtrTy, ImplicitParamDecl::Other);
3668 FunctionArgList Args;
3669 Args.push_back(&BufferArg);
3670 Args.push_back(&IdxArg);
3671 Args.push_back(&ReduceListArg);
3672
3673 const CGFunctionInfo &CGFI =
3674 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3675 auto *Fn = llvm::Function::Create(
3676 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3677 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3678 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3679 Fn->setDoesNotRecurse();
3680 CodeGenFunction CGF(CGM);
3681 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3682
3683 CGBuilderTy &Bld = CGF.Builder;
3684
3685 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3686 QualType StaticTy = C.getRecordType(TeamReductionRec);
3687 llvm::Type *LLVMReductionsBufferTy =
3688 CGM.getTypes().ConvertTypeForMem(StaticTy);
3689 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3690 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3691 LLVMReductionsBufferTy->getPointerTo());
3692
3693 // 1. Build a list of reduction variables.
3694 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3695 Address ReductionList =
3696 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3697 auto IPriv = Privates.begin();
3698 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3699 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3700 /*Volatile=*/false, C.IntTy,
3701 Loc)};
3702 unsigned Idx = 0;
3703 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3704 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3705 // Global = Buffer.VD[Idx];
3706 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3707 const FieldDecl *FD = VarFieldMap.lookup(VD);
3708 LValue GlobLVal = CGF.EmitLValueForField(
3709 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3710 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3711 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3712 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3713 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3714 // Store array size.
3715 ++Idx;
3716 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3717 llvm::Value *Size = CGF.Builder.CreateIntCast(
3718 CGF.getVLASize(
3719 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3720 .NumElts,
3721 CGF.SizeTy, /*isSigned=*/false);
3722 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3723 Elem);
3724 }
3725 }
3726
3727 // Call reduce_function(GlobalReduceList, ReduceList)
3728 llvm::Value *GlobalReduceList =
3729 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3730 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3731 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3732 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3733 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3734 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3735 CGF.FinishFunction();
3736 return Fn;
3737}
3738
3739/// This function emits a helper that copies all the reduction variables from
3740/// the team into the provided global buffer for the reduction variables.
3741///
3742/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3743/// For all data entries D in reduce_data:
3744/// Copy buffer.D[Idx] to local D;
3745static llvm::Value *emitGlobalToListCopyFunction(
3746 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3747 QualType ReductionArrayTy, SourceLocation Loc,
3748 const RecordDecl *TeamReductionRec,
3749 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3750 &VarFieldMap) {
3751 ASTContext &C = CGM.getContext();
3752
3753 // Buffer: global reduction buffer.
3754 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3755 C.VoidPtrTy, ImplicitParamDecl::Other);
3756 // Idx: index of the buffer.
3757 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3758 ImplicitParamDecl::Other);
3759 // ReduceList: thread local Reduce list.
3760 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3761 C.VoidPtrTy, ImplicitParamDecl::Other);
3762 FunctionArgList Args;
3763 Args.push_back(&BufferArg);
3764 Args.push_back(&IdxArg);
3765 Args.push_back(&ReduceListArg);
3766
3767 const CGFunctionInfo &CGFI =
3768 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3769 auto *Fn = llvm::Function::Create(
3770 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3771 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3772 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3773 Fn->setDoesNotRecurse();
3774 CodeGenFunction CGF(CGM);
3775 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3776
3777 CGBuilderTy &Bld = CGF.Builder;
3778
3779 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3780 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3781 Address LocalReduceList(
3782 Bld.CreatePointerBitCastOrAddrSpaceCast(
3783 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3784 C.VoidPtrTy, Loc),
3785 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3786 CGF.getPointerAlign());
3787 QualType StaticTy = C.getRecordType(TeamReductionRec);
3788 llvm::Type *LLVMReductionsBufferTy =
3789 CGM.getTypes().ConvertTypeForMem(StaticTy);
3790 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3791 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3792 LLVMReductionsBufferTy->getPointerTo());
3793
3794 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3795 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3796 /*Volatile=*/false, C.IntTy,
3797 Loc)};
3798 unsigned Idx = 0;
3799 for (const Expr *Private : Privates) {
3800 // Reduce element = LocalReduceList[i]
3801 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3802 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3803 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3804 // elemptr = ((CopyType*)(elemptrptr)) + I
3805 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3806 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3807 Address ElemPtr =
3808 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3809 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3810 // Global = Buffer.VD[Idx];
3811 const FieldDecl *FD = VarFieldMap.lookup(VD);
3812 LValue GlobLVal = CGF.EmitLValueForField(
3813 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3814 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3815 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3816 switch (CGF.getEvaluationKind(Private->getType())) {
3817 case TEK_Scalar: {
3818 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3819 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3820 break;
3821 }
3822 case TEK_Complex: {
3823 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3824 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3825 /*isInit=*/false);
3826 break;
3827 }
3828 case TEK_Aggregate:
3829 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3830 GlobLVal, Private->getType(),
3831 AggValueSlot::DoesNotOverlap);
3832 break;
3833 }
3834 ++Idx;
3835 }
3836
3837 CGF.FinishFunction();
3838 return Fn;
3839}
3840
3841/// This function emits a helper that reduces all the reduction variables from
3842/// the team into the provided global buffer for the reduction variables.
3843///
3844/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3845/// void *GlobPtrs[];
3846/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3847/// ...
3848/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3849/// reduce_function(reduce_data, GlobPtrs);
3850static llvm::Value *emitGlobalToListReduceFunction(
3851 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3852 QualType ReductionArrayTy, SourceLocation Loc,
3853 const RecordDecl *TeamReductionRec,
3854 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3855 &VarFieldMap,
3856 llvm::Function *ReduceFn) {
3857 ASTContext &C = CGM.getContext();
3858
3859 // Buffer: global reduction buffer.
3860 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3861 C.VoidPtrTy, ImplicitParamDecl::Other);
3862 // Idx: index of the buffer.
3863 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3864 ImplicitParamDecl::Other);
3865 // ReduceList: thread local Reduce list.
3866 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3867 C.VoidPtrTy, ImplicitParamDecl::Other);
3868 FunctionArgList Args;
3869 Args.push_back(&BufferArg);
3870 Args.push_back(&IdxArg);
3871 Args.push_back(&ReduceListArg);
3872
3873 const CGFunctionInfo &CGFI =
3874 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3875 auto *Fn = llvm::Function::Create(
3876 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3877 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3878 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3879 Fn->setDoesNotRecurse();
3880 CodeGenFunction CGF(CGM);
3881 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3882
3883 CGBuilderTy &Bld = CGF.Builder;
3884
3885 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3886 QualType StaticTy = C.getRecordType(TeamReductionRec);
3887 llvm::Type *LLVMReductionsBufferTy =
3888 CGM.getTypes().ConvertTypeForMem(StaticTy);
3889 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3890 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3891 LLVMReductionsBufferTy->getPointerTo());
3892
3893 // 1. Build a list of reduction variables.
3894 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3895 Address ReductionList =
3896 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3897 auto IPriv = Privates.begin();
3898 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3899 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3900 /*Volatile=*/false, C.IntTy,
3901 Loc)};
3902 unsigned Idx = 0;
3903 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3904 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3905 // Global = Buffer.VD[Idx];
3906 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3907 const FieldDecl *FD = VarFieldMap.lookup(VD);
3908 LValue GlobLVal = CGF.EmitLValueForField(
3909 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3910 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3911 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3912 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3913 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3914 // Store array size.
3915 ++Idx;
3916 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3917 llvm::Value *Size = CGF.Builder.CreateIntCast(
3918 CGF.getVLASize(
3919 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3920 .NumElts,
3921 CGF.SizeTy, /*isSigned=*/false);
3922 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3923 Elem);
3924 }
3925 }
3926
3927 // Call reduce_function(ReduceList, GlobalReduceList)
3928 llvm::Value *GlobalReduceList =
3929 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3930 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3931 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3932 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3933 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3934 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3935 CGF.FinishFunction();
3936 return Fn;
3937}
3938
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003939///
3940/// Design of OpenMP reductions on the GPU
3941///
3942/// Consider a typical OpenMP program with one or more reduction
3943/// clauses:
3944///
3945/// float foo;
3946/// double bar;
3947/// #pragma omp target teams distribute parallel for \
3948/// reduction(+:foo) reduction(*:bar)
3949/// for (int i = 0; i < N; i++) {
3950/// foo += A[i]; bar *= B[i];
3951/// }
3952///
3953/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3954/// all teams. In our OpenMP implementation on the NVPTX device an
3955/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3956/// within a team are mapped to CUDA threads within a threadblock.
3957/// Our goal is to efficiently aggregate values across all OpenMP
3958/// threads such that:
3959///
3960/// - the compiler and runtime are logically concise, and
3961/// - the reduction is performed efficiently in a hierarchical
3962/// manner as follows: within OpenMP threads in the same warp,
3963/// across warps in a threadblock, and finally across teams on
3964/// the NVPTX device.
3965///
3966/// Introduction to Decoupling
3967///
3968/// We would like to decouple the compiler and the runtime so that the
3969/// latter is ignorant of the reduction variables (number, data types)
3970/// and the reduction operators. This allows a simpler interface
3971/// and implementation while still attaining good performance.
3972///
3973/// Pseudocode for the aforementioned OpenMP program generated by the
3974/// compiler is as follows:
3975///
3976/// 1. Create private copies of reduction variables on each OpenMP
3977/// thread: 'foo_private', 'bar_private'
3978/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3979/// to it and writes the result in 'foo_private' and 'bar_private'
3980/// respectively.
3981/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3982/// and store the result on the team master:
3983///
Alexey Bataev8e009032019-01-04 17:25:09 +00003984/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003985/// reduceData, shuffleReduceFn, interWarpCpyFn)
3986///
3987/// where:
3988/// struct ReduceData {
3989/// double *foo;
3990/// double *bar;
3991/// } reduceData
3992/// reduceData.foo = &foo_private
3993/// reduceData.bar = &bar_private
3994///
3995/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
3996/// auxiliary functions generated by the compiler that operate on
3997/// variables of type 'ReduceData'. They aid the runtime perform
3998/// algorithmic steps in a data agnostic manner.
3999///
4000/// 'shuffleReduceFn' is a pointer to a function that reduces data
4001/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4002/// same warp. It takes the following arguments as input:
4003///
4004/// a. variable of type 'ReduceData' on the calling lane,
4005/// b. its lane_id,
4006/// c. an offset relative to the current lane_id to generate a
4007/// remote_lane_id. The remote lane contains the second
4008/// variable of type 'ReduceData' that is to be reduced.
4009/// d. an algorithm version parameter determining which reduction
4010/// algorithm to use.
4011///
4012/// 'shuffleReduceFn' retrieves data from the remote lane using
4013/// efficient GPU shuffle intrinsics and reduces, using the
4014/// algorithm specified by the 4th parameter, the two operands
4015/// element-wise. The result is written to the first operand.
4016///
4017/// Different reduction algorithms are implemented in different
4018/// runtime functions, all calling 'shuffleReduceFn' to perform
4019/// the essential reduction step. Therefore, based on the 4th
4020/// parameter, this function behaves slightly differently to
4021/// cooperate with the runtime to ensure correctness under
4022/// different circumstances.
4023///
4024/// 'InterWarpCpyFn' is a pointer to a function that transfers
4025/// reduced variables across warps. It tunnels, through CUDA
4026/// shared memory, the thread-private data of type 'ReduceData'
4027/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004028/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4029/// The last team writes the global reduced value to memory.
4030///
4031/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4032/// reduceData, shuffleReduceFn, interWarpCpyFn,
4033/// scratchpadCopyFn, loadAndReduceFn)
4034///
4035/// 'scratchpadCopyFn' is a helper that stores reduced
4036/// data from the team master to a scratchpad array in
4037/// global memory.
4038///
4039/// 'loadAndReduceFn' is a helper that loads data from
4040/// the scratchpad array and reduces it with the input
4041/// operand.
4042///
4043/// These compiler generated functions hide address
4044/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004045/// 5. if ret == 1:
4046/// The team master of the last team stores the reduced
4047/// result to the globals in memory.
4048/// foo += reduceData.foo; bar *= reduceData.bar
4049///
4050///
4051/// Warp Reduction Algorithms
4052///
4053/// On the warp level, we have three algorithms implemented in the
4054/// OpenMP runtime depending on the number of active lanes:
4055///
4056/// Full Warp Reduction
4057///
4058/// The reduce algorithm within a warp where all lanes are active
4059/// is implemented in the runtime as follows:
4060///
4061/// full_warp_reduce(void *reduce_data,
4062/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4063/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4064/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4065/// }
4066///
4067/// The algorithm completes in log(2, WARPSIZE) steps.
4068///
4069/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4070/// not used therefore we save instructions by not retrieving lane_id
4071/// from the corresponding special registers. The 4th parameter, which
4072/// represents the version of the algorithm being used, is set to 0 to
4073/// signify full warp reduction.
4074///
4075/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4076///
4077/// #reduce_elem refers to an element in the local lane's data structure
4078/// #remote_elem is retrieved from a remote lane
4079/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4080/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4081///
4082/// Contiguous Partial Warp Reduction
4083///
4084/// This reduce algorithm is used within a warp where only the first
4085/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4086/// number of OpenMP threads in a parallel region is not a multiple of
4087/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4088///
4089/// void
4090/// contiguous_partial_reduce(void *reduce_data,
4091/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4092/// int size, int lane_id) {
4093/// int curr_size;
4094/// int offset;
4095/// curr_size = size;
4096/// mask = curr_size/2;
4097/// while (offset>0) {
4098/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4099/// curr_size = (curr_size+1)/2;
4100/// offset = curr_size/2;
4101/// }
4102/// }
4103///
4104/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4105///
4106/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4107/// if (lane_id < offset)
4108/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4109/// else
4110/// reduce_elem = remote_elem
4111///
4112/// This algorithm assumes that the data to be reduced are located in a
4113/// contiguous subset of lanes starting from the first. When there is
4114/// an odd number of active lanes, the data in the last lane is not
4115/// aggregated with any other lane's dat but is instead copied over.
4116///
4117/// Dispersed Partial Warp Reduction
4118///
4119/// This algorithm is used within a warp when any discontiguous subset of
4120/// lanes are active. It is used to implement the reduction operation
4121/// across lanes in an OpenMP simd region or in a nested parallel region.
4122///
4123/// void
4124/// dispersed_partial_reduce(void *reduce_data,
4125/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4126/// int size, remote_id;
4127/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4128/// do {
4129/// remote_id = next_active_lane_id_right_after_me();
4130/// # the above function returns 0 of no active lane
4131/// # is present right after the current lane.
4132/// size = number_of_active_lanes_in_this_warp();
4133/// logical_lane_id /= 2;
4134/// ShuffleReduceFn(reduce_data, logical_lane_id,
4135/// remote_id-1-threadIdx.x, 2);
4136/// } while (logical_lane_id % 2 == 0 && size > 1);
4137/// }
4138///
4139/// There is no assumption made about the initial state of the reduction.
4140/// Any number of lanes (>=1) could be active at any position. The reduction
4141/// result is returned in the first active lane.
4142///
4143/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4144///
4145/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4146/// if (lane_id % 2 == 0 && offset > 0)
4147/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4148/// else
4149/// reduce_elem = remote_elem
4150///
4151///
4152/// Intra-Team Reduction
4153///
4154/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004155/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004156/// threads in a team. It first reduces within a warp using the
4157/// aforementioned algorithms. We then proceed to gather all such
4158/// reduced values at the first warp.
4159///
4160/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4161/// data from each of the "warp master" (zeroth lane of each warp, where
4162/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4163/// a mathematical sense) the problem of reduction across warp masters in
4164/// a block to the problem of warp reduction.
4165///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004166///
4167/// Inter-Team Reduction
4168///
4169/// Once a team has reduced its data to a single value, it is stored in
4170/// a global scratchpad array. Since each team has a distinct slot, this
4171/// can be done without locking.
4172///
4173/// The last team to write to the scratchpad array proceeds to reduce the
4174/// scratchpad array. One or more workers in the last team use the helper
4175/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4176/// the k'th worker reduces every k'th element.
4177///
Alexey Bataev8e009032019-01-04 17:25:09 +00004178/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004179/// reduce across workers and compute a globally reduced value.
4180///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004181void CGOpenMPRuntimeNVPTX::emitReduction(
4182 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4183 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4184 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4185 if (!CGF.HaveInsertPoint())
4186 return;
4187
4188 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004189#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004190 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004191#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004192
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004193 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004194 assert(!TeamsReduction && !ParallelReduction &&
4195 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004196 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4197 ReductionOps, Options);
4198 return;
4199 }
4200
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004201 assert((TeamsReduction || ParallelReduction) &&
4202 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004203
Alexey Bataeva1166022018-11-27 21:24:54 +00004204 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004205 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004206 // or
4207 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004208 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004209 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004210
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004211 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004212 ASTContext &C = CGM.getContext();
4213 // 1. Build a list of reduction variables.
4214 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4215 auto Size = RHSExprs.size();
4216 for (const Expr *E : Privates) {
4217 if (E->getType()->isVariablyModifiedType())
4218 // Reserve place for array size.
4219 ++Size;
4220 }
4221 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4222 QualType ReductionArrayTy =
4223 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4224 /*IndexTypeQuals=*/0);
4225 Address ReductionList =
4226 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4227 auto IPriv = Privates.begin();
4228 unsigned Idx = 0;
4229 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4230 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4231 CGF.Builder.CreateStore(
4232 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4233 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4234 Elem);
4235 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4236 // Store array size.
4237 ++Idx;
4238 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4239 llvm::Value *Size = CGF.Builder.CreateIntCast(
4240 CGF.getVLASize(
4241 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4242 .NumElts,
4243 CGF.SizeTy, /*isSigned=*/false);
4244 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4245 Elem);
4246 }
4247 }
4248
4249 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4250 ReductionList.getPointer(), CGF.VoidPtrTy);
4251 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004252 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4253 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004254 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4255 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4256 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4257 llvm::Value *InterWarpCopyFn =
4258 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4259
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004260 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004261 llvm::Value *Args[] = {RTLoc,
4262 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004263 CGF.Builder.getInt32(RHSExprs.size()),
4264 ReductionArrayTySize,
4265 RL,
4266 ShuffleAndReduceFn,
4267 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004268
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004269 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004270 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004271 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4272 Args);
4273 } else {
4274 assert(TeamsReduction && "expected teams reduction.");
4275 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4276 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4277 int Cnt = 0;
4278 for (const Expr *DRE : Privates) {
4279 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4280 ++Cnt;
4281 }
4282 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4283 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4284 C.getLangOpts().OpenMPCUDAReductionBufNum);
4285 TeamsReductions.push_back(TeamReductionRec);
4286 if (!KernelTeamsReductionPtr) {
4287 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4288 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4289 llvm::GlobalValue::InternalLinkage, nullptr,
4290 "_openmp_teams_reductions_buffer_$_$ptr");
4291 }
4292 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4293 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4294 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4295 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4296 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4297 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4298 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4299 ReductionFn);
4300 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4301 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4302 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4303 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4304 ReductionFn);
4305
4306 llvm::Value *Args[] = {
4307 RTLoc,
4308 ThreadId,
4309 GlobalBufferPtr,
4310 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4311 RL,
4312 ShuffleAndReduceFn,
4313 InterWarpCopyFn,
4314 GlobalToBufferCpyFn,
4315 GlobalToBufferRedFn,
4316 BufferToGlobalCpyFn,
4317 BufferToGlobalRedFn};
4318
4319 Res = CGF.EmitRuntimeCall(
4320 createNVPTXRuntimeFunction(
4321 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004322 Args);
4323 }
4324
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004325 // 5. Build if (res == 1)
4326 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4327 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4328 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4329 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4330 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004331
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004332 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004333 // thread in each team.
4334 // __kmpc_end_reduce{_nowait}(<gtid>);
4335 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004336 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004337
4338 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004339 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004340 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4341 auto IPriv = Privates.begin();
4342 auto ILHS = LHSExprs.begin();
4343 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004344 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004345 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4346 cast<DeclRefExpr>(*IRHS));
4347 ++IPriv;
4348 ++ILHS;
4349 ++IRHS;
4350 }
4351 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004352 llvm::Value *EndArgs[] = {ThreadId};
4353 RegionCodeGenTy RCG(CodeGen);
4354 NVPTXActionTy Action(
4355 nullptr, llvm::None,
4356 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4357 EndArgs);
4358 RCG.setAction(Action);
4359 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004360 // There is no need to emit line number for unconditional branch.
4361 (void)ApplyDebugLocation::CreateEmpty(CGF);
4362 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004363}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004364
4365const VarDecl *
4366CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4367 const VarDecl *NativeParam) const {
4368 if (!NativeParam->getType()->isReferenceType())
4369 return NativeParam;
4370 QualType ArgType = NativeParam->getType();
4371 QualifierCollector QC;
4372 const Type *NonQualTy = QC.strip(ArgType);
4373 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4374 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4375 if (Attr->getCaptureKind() == OMPC_map) {
4376 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4377 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004378 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4379 PointeeTy.isConstant(CGM.getContext())) {
4380 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4381 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004382 }
4383 }
4384 ArgType = CGM.getContext().getPointerType(PointeeTy);
4385 QC.addRestrict();
4386 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004387 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004388 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004389 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004390 return ImplicitParamDecl::Create(
4391 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4392 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004393 return ParmVarDecl::Create(
4394 CGM.getContext(),
4395 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004396 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004397 NativeParam->getIdentifier(), ArgType,
4398 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004399}
4400
4401Address
4402CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4403 const VarDecl *NativeParam,
4404 const VarDecl *TargetParam) const {
4405 assert(NativeParam != TargetParam &&
4406 NativeParam->getType()->isReferenceType() &&
4407 "Native arg must not be the same as target arg.");
4408 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4409 QualType NativeParamType = NativeParam->getType();
4410 QualifierCollector QC;
4411 const Type *NonQualTy = QC.strip(NativeParamType);
4412 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4413 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004414 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004415 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004416 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004417 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004418 // First cast to generic.
4419 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4420 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4421 /*AddrSpace=*/0));
4422 // Cast from generic to native address space.
4423 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4424 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4425 NativePointeeAddrSpace));
4426 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4427 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004428 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004429 return NativeParamAddr;
4430}
4431
4432void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004433 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004434 ArrayRef<llvm::Value *> Args) const {
4435 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004436 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004437 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004438 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004439 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4440 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4441 break;
4442 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004443 llvm::Type *TargetType = FnType->getParamType(I);
4444 llvm::Value *NativeArg = Args[I];
4445 if (!TargetType->isPointerTy()) {
4446 TargetArgs.emplace_back(NativeArg);
4447 continue;
4448 }
4449 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004450 NativeArg,
4451 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004452 TargetArgs.emplace_back(
4453 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4454 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004455 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004456}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004457
4458/// Emit function which wraps the outline parallel region
4459/// and controls the arguments which are passed to this function.
4460/// The wrapper ensures that the outlined function is called
4461/// with the correct arguments when data is shared.
4462llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4463 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4464 ASTContext &Ctx = CGM.getContext();
4465 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4466
4467 // Create a function that takes as argument the source thread.
4468 FunctionArgList WrapperArgs;
4469 QualType Int16QTy =
4470 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4471 QualType Int32QTy =
4472 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004473 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004474 /*Id=*/nullptr, Int16QTy,
4475 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004476 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004477 /*Id=*/nullptr, Int32QTy,
4478 ImplicitParamDecl::Other);
4479 WrapperArgs.emplace_back(&ParallelLevelArg);
4480 WrapperArgs.emplace_back(&WrapperArg);
4481
Alexey Bataev9ff80832018-04-16 20:16:21 +00004482 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004483 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4484
4485 auto *Fn = llvm::Function::Create(
4486 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004487 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004488 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004489 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004490 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004491
4492 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4493 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004494 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004495
4496 const auto *RD = CS.getCapturedRecordDecl();
4497 auto CurField = RD->field_begin();
4498
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004499 Address ZeroAddr = CGF.CreateMemTemp(
4500 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4501 /*Name*/ ".zero.addr");
4502 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004503 // Get the array of arguments.
4504 SmallVector<llvm::Value *, 8> Args;
4505
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004506 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4507 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004508
4509 CGBuilderTy &Bld = CGF.Builder;
4510 auto CI = CS.capture_begin();
4511
4512 // Use global memory for data sharing.
4513 // Handle passing of global args to workers.
4514 Address GlobalArgs =
4515 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4516 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4517 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4518 CGF.EmitRuntimeCall(
4519 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4520 DataSharingArgs);
4521
4522 // Retrieve the shared variables from the list of references returned
4523 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004524 Address SharedArgListAddress = Address::invalid();
4525 if (CS.capture_size() > 0 ||
4526 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4527 SharedArgListAddress = CGF.EmitLoadOfPointer(
4528 GlobalArgs, CGF.getContext()
4529 .getPointerType(CGF.getContext().getPointerType(
4530 CGF.getContext().VoidPtrTy))
4531 .castAs<PointerType>());
4532 }
4533 unsigned Idx = 0;
4534 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004535 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004536 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4537 Src, CGF.SizeTy->getPointerTo());
4538 llvm::Value *LB = CGF.EmitLoadOfScalar(
4539 TypedAddress,
4540 /*Volatile=*/false,
4541 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4542 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4543 Args.emplace_back(LB);
4544 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004545 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004546 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4547 Src, CGF.SizeTy->getPointerTo());
4548 llvm::Value *UB = CGF.EmitLoadOfScalar(
4549 TypedAddress,
4550 /*Volatile=*/false,
4551 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4552 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4553 Args.emplace_back(UB);
4554 ++Idx;
4555 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004556 if (CS.capture_size() > 0) {
4557 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004558 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4559 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004560 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004561 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4563 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4564 /*Volatile=*/false,
4565 CGFContext.getPointerType(ElemTy),
4566 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004567 if (CI->capturesVariableByCopy() &&
4568 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004569 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4570 CI->getLocation());
4571 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004572 Args.emplace_back(Arg);
4573 }
4574 }
4575
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004576 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004577 CGF.FinishFunction();
4578 return Fn;
4579}
4580
4581void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4582 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004583 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4584 return;
4585
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004586 assert(D && "Expected function or captured|block decl.");
4587 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4588 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004589 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4590 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004591 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004592 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004593 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4594 Body = FD->getBody();
4595 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4596 Body = BD->getBody();
4597 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4598 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004599 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004600 if (NeedToDelayGlobalization &&
4601 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4602 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004603 }
4604 if (!Body)
4605 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004606 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004607 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004608 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004609 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004610 TeamAndReductions.first = nullptr;
4611 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004612 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4613 VarChecker.getEscapedVariableLengthDecls();
4614 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004615 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004616 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4617 I->getSecond().MappedParams =
4618 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4619 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4620 I->getSecond().EscapedParameters.insert(
4621 VarChecker.getEscapedParameters().begin(),
4622 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004623 I->getSecond().EscapedVariableLengthDecls.append(
4624 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004625 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004626 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004627 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004628 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004629 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004630 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004631 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004632 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004633 VarChecker.Visit(Body);
4634 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004635 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004636 I->getSecond().SecondaryLocalVarData.emplace();
4637 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4638 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4639 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4640 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004641 Data.insert(
4642 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004643 }
4644 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004645 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004646 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004647 struct GlobalizationScope final : EHScopeStack::Cleanup {
4648 GlobalizationScope() = default;
4649
4650 void Emit(CodeGenFunction &CGF, Flags flags) override {
4651 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004652 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004653 }
4654 };
4655 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004656 }
4657}
4658
4659Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4660 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004661 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4662 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4663 switch (A->getAllocatorType()) {
4664 // Use the default allocator here as by default local vars are
4665 // threadlocal.
4666 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4667 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004668 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4669 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004670 // Follow the user decision - use default allocation.
4671 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004672 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004673 // TODO: implement aupport for user-defined allocators.
4674 return Address::invalid();
4675 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4676 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4677 auto *GV = new llvm::GlobalVariable(
4678 CGM.getModule(), VarTy, /*isConstant=*/false,
4679 llvm::GlobalValue::InternalLinkage,
4680 llvm::Constant::getNullValue(VarTy), VD->getName(),
4681 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4682 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4683 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4684 GV->setAlignment(Align.getQuantity());
4685 return Address(GV, Align);
4686 }
4687 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4688 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4689 auto *GV = new llvm::GlobalVariable(
4690 CGM.getModule(), VarTy, /*isConstant=*/false,
4691 llvm::GlobalValue::InternalLinkage,
4692 llvm::Constant::getNullValue(VarTy), VD->getName(),
4693 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4694 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4695 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4696 GV->setAlignment(Align.getQuantity());
4697 return Address(GV, Align);
4698 }
4699 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4700 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4701 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4702 auto *GV = new llvm::GlobalVariable(
4703 CGM.getModule(), VarTy, /*isConstant=*/false,
4704 llvm::GlobalValue::InternalLinkage,
4705 llvm::Constant::getNullValue(VarTy), VD->getName());
4706 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4707 GV->setAlignment(Align.getQuantity());
4708 return Address(GV, Align);
4709 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004710 }
4711 }
4712
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004713 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4714 return Address::invalid();
4715
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004716 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004717 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4718 if (I == FunctionGlobalizedDecls.end())
4719 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004720 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004721 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004722 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004723 if (VD->hasAttrs()) {
4724 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4725 E(VD->attr_end());
4726 IT != E; ++IT) {
4727 auto VDI = I->getSecond().LocalVarData.find(
4728 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4729 ->getCanonicalDecl());
4730 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004731 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004732 }
4733 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004734
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004735 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004736}
4737
4738void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004739 FunctionGlobalizedDecls.erase(CGF.CurFn);
4740 CGOpenMPRuntime::functionFinished(CGF);
4741}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004742
4743void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4744 CodeGenFunction &CGF, const OMPLoopDirective &S,
4745 OpenMPDistScheduleClauseKind &ScheduleKind,
4746 llvm::Value *&Chunk) const {
4747 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4748 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4749 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4750 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4751 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004752 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004753 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004754 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4755 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004756}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004757
4758void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4759 CodeGenFunction &CGF, const OMPLoopDirective &S,
4760 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004761 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004762 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004763 // Chunk size is 1 in this case.
4764 llvm::APInt ChunkSize(32, 1);
4765 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4766 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4767 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004768}
Alexey Bataev60705422018-10-30 15:50:12 +00004769
4770void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4771 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4772 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4773 " Expected target-based directive.");
4774 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4775 for (const CapturedStmt::Capture &C : CS->captures()) {
4776 // Capture variables captured by reference in lambdas for target-based
4777 // directives.
4778 if (!C.capturesVariable())
4779 continue;
4780 const VarDecl *VD = C.getCapturedVar();
4781 const auto *RD = VD->getType()
4782 .getCanonicalType()
4783 .getNonReferenceType()
4784 ->getAsCXXRecordDecl();
4785 if (!RD || !RD->isLambda())
4786 continue;
4787 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4788 LValue VDLVal;
4789 if (VD->getType().getCanonicalType()->isReferenceType())
4790 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4791 else
4792 VDLVal = CGF.MakeAddrLValue(
4793 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4794 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4795 FieldDecl *ThisCapture = nullptr;
4796 RD->getCaptureFields(Captures, ThisCapture);
4797 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4798 LValue ThisLVal =
4799 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4800 llvm::Value *CXXThis = CGF.LoadCXXThis();
4801 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4802 }
4803 for (const LambdaCapture &LC : RD->captures()) {
4804 if (LC.getCaptureKind() != LCK_ByRef)
4805 continue;
4806 const VarDecl *VD = LC.getCapturedVar();
4807 if (!CS->capturesVariable(VD))
4808 continue;
4809 auto It = Captures.find(VD);
4810 assert(It != Captures.end() && "Found lambda capture without field.");
4811 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4812 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4813 if (VD->getType().getCanonicalType()->isReferenceType())
4814 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4815 VD->getType().getCanonicalType())
4816 .getAddress();
4817 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4818 }
4819 }
4820}
4821
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004822unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4823 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4824}
4825
Alexey Bataevc5687252019-03-21 19:35:27 +00004826bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4827 LangAS &AS) {
4828 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4829 return false;
4830 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4831 switch(A->getAllocatorType()) {
4832 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4833 // Not supported, fallback to the default mem space.
4834 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4835 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4836 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4837 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4838 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4839 AS = LangAS::Default;
4840 return true;
4841 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4842 AS = LangAS::cuda_constant;
4843 return true;
4844 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4845 AS = LangAS::cuda_shared;
4846 return true;
4847 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4848 llvm_unreachable("Expected predefined allocator for the variables with the "
4849 "static storage.");
4850 }
4851 return false;
4852}
4853
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004854// Get current CudaArch and ignore any unknown values
4855static CudaArch getCudaArch(CodeGenModule &CGM) {
4856 if (!CGM.getTarget().hasFeature("ptx"))
4857 return CudaArch::UNKNOWN;
4858 llvm::StringMap<bool> Features;
4859 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4860 CGM.getTarget().getTargetOpts().CPU,
4861 CGM.getTarget().getTargetOpts().Features);
4862 for (const auto &Feature : Features) {
4863 if (Feature.getValue()) {
4864 CudaArch Arch = StringToCudaArch(Feature.getKey());
4865 if (Arch != CudaArch::UNKNOWN)
4866 return Arch;
4867 }
4868 }
4869 return CudaArch::UNKNOWN;
4870}
4871
4872/// Check to see if target architecture supports unified addressing which is
4873/// a restriction for OpenMP requires clause "unified_shared_memory".
4874void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004875 const OMPRequiresDecl *D) const {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004876 for (const OMPClause *Clause : D->clauselists()) {
4877 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4878 switch (getCudaArch(CGM)) {
4879 case CudaArch::SM_20:
4880 case CudaArch::SM_21:
4881 case CudaArch::SM_30:
4882 case CudaArch::SM_32:
4883 case CudaArch::SM_35:
4884 case CudaArch::SM_37:
4885 case CudaArch::SM_50:
4886 case CudaArch::SM_52:
4887 case CudaArch::SM_53:
4888 case CudaArch::SM_60:
4889 case CudaArch::SM_61:
4890 case CudaArch::SM_62:
4891 CGM.Error(Clause->getBeginLoc(),
4892 "Target architecture does not support unified addressing");
4893 return;
4894 case CudaArch::SM_70:
4895 case CudaArch::SM_72:
4896 case CudaArch::SM_75:
4897 case CudaArch::GFX600:
4898 case CudaArch::GFX601:
4899 case CudaArch::GFX700:
4900 case CudaArch::GFX701:
4901 case CudaArch::GFX702:
4902 case CudaArch::GFX703:
4903 case CudaArch::GFX704:
4904 case CudaArch::GFX801:
4905 case CudaArch::GFX802:
4906 case CudaArch::GFX803:
4907 case CudaArch::GFX810:
4908 case CudaArch::GFX900:
4909 case CudaArch::GFX902:
4910 case CudaArch::GFX904:
4911 case CudaArch::GFX906:
4912 case CudaArch::GFX909:
4913 case CudaArch::UNKNOWN:
4914 break;
4915 case CudaArch::LAST:
4916 llvm_unreachable("Unexpected Cuda arch.");
4917 }
4918 }
4919 }
4920}
4921
Alexey Bataeve4090182018-11-02 14:54:07 +00004922/// Get number of SMs and number of blocks per SM.
4923static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4924 std::pair<unsigned, unsigned> Data;
4925 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4926 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4927 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4928 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4929 if (Data.first && Data.second)
4930 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004931 switch (getCudaArch(CGM)) {
4932 case CudaArch::SM_20:
4933 case CudaArch::SM_21:
4934 case CudaArch::SM_30:
4935 case CudaArch::SM_32:
4936 case CudaArch::SM_35:
4937 case CudaArch::SM_37:
4938 case CudaArch::SM_50:
4939 case CudaArch::SM_52:
4940 case CudaArch::SM_53:
4941 return {16, 16};
4942 case CudaArch::SM_60:
4943 case CudaArch::SM_61:
4944 case CudaArch::SM_62:
4945 return {56, 32};
4946 case CudaArch::SM_70:
4947 case CudaArch::SM_72:
4948 case CudaArch::SM_75:
4949 return {84, 32};
4950 case CudaArch::GFX600:
4951 case CudaArch::GFX601:
4952 case CudaArch::GFX700:
4953 case CudaArch::GFX701:
4954 case CudaArch::GFX702:
4955 case CudaArch::GFX703:
4956 case CudaArch::GFX704:
4957 case CudaArch::GFX801:
4958 case CudaArch::GFX802:
4959 case CudaArch::GFX803:
4960 case CudaArch::GFX810:
4961 case CudaArch::GFX900:
4962 case CudaArch::GFX902:
4963 case CudaArch::GFX904:
4964 case CudaArch::GFX906:
4965 case CudaArch::GFX909:
4966 case CudaArch::UNKNOWN:
4967 break;
4968 case CudaArch::LAST:
4969 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004970 }
4971 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4972}
4973
4974void CGOpenMPRuntimeNVPTX::clear() {
4975 if (!GlobalizedRecords.empty()) {
4976 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004977 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4978 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004979 RecordDecl *StaticRD = C.buildImplicitRecord(
4980 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4981 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004982 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4983 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4984 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004985 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4986 if (Records.Records.empty())
4987 continue;
4988 unsigned Size = 0;
4989 unsigned RecAlignment = 0;
4990 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004991 QualType RDTy = C.getRecordType(RD);
4992 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004993 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004994 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004995 Size =
4996 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4997 }
4998 Size = llvm::alignTo(Size, RecAlignment);
4999 llvm::APInt ArySize(/*numBits=*/64, Size);
5000 QualType SubTy = C.getConstantArrayType(
5001 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005002 const bool UseSharedMemory = Size <= SharedMemorySize;
5003 auto *Field =
5004 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5005 SourceLocation(), SourceLocation(), nullptr, SubTy,
5006 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5007 /*BW=*/nullptr, /*Mutable=*/false,
5008 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005009 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005010 if (UseSharedMemory) {
5011 SharedStaticRD->addDecl(Field);
5012 SharedRecs.push_back(&Records);
5013 } else {
5014 StaticRD->addDecl(Field);
5015 GlobalRecs.push_back(&Records);
5016 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005017 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005018 Records.UseSharedMemory->setInitializer(
5019 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5020 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005021 // Allocate SharedMemorySize buffer for the shared memory.
5022 // FIXME: nvlink does not handle weak linkage correctly (object with the
5023 // different size are reported as erroneous).
5024 // Restore this code as sson as nvlink is fixed.
5025 if (!SharedStaticRD->field_empty()) {
5026 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5027 QualType SubTy = C.getConstantArrayType(
5028 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5029 auto *Field = FieldDecl::Create(
5030 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5031 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5032 /*BW=*/nullptr, /*Mutable=*/false,
5033 /*InitStyle=*/ICIS_NoInit);
5034 Field->setAccess(AS_public);
5035 SharedStaticRD->addDecl(Field);
5036 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005037 SharedStaticRD->completeDefinition();
5038 if (!SharedStaticRD->field_empty()) {
5039 QualType StaticTy = C.getRecordType(SharedStaticRD);
5040 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5041 auto *GV = new llvm::GlobalVariable(
5042 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005043 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005044 llvm::Constant::getNullValue(LLVMStaticTy),
5045 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5046 llvm::GlobalValue::NotThreadLocal,
5047 C.getTargetAddressSpace(LangAS::cuda_shared));
5048 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5049 GV, CGM.VoidPtrTy);
5050 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5051 Rec->Buffer->replaceAllUsesWith(Replacement);
5052 Rec->Buffer->eraseFromParent();
5053 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005054 }
5055 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005056 if (!StaticRD->field_empty()) {
5057 QualType StaticTy = C.getRecordType(StaticRD);
5058 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5059 llvm::APInt Size1(32, SMsBlockPerSM.second);
5060 QualType Arr1Ty =
5061 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5062 /*IndexTypeQuals=*/0);
5063 llvm::APInt Size2(32, SMsBlockPerSM.first);
5064 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5065 /*IndexTypeQuals=*/0);
5066 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005067 // FIXME: nvlink does not handle weak linkage correctly (object with the
5068 // different size are reported as erroneous).
5069 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005070 auto *GV = new llvm::GlobalVariable(
5071 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005072 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005073 llvm::Constant::getNullValue(LLVMArr2Ty),
5074 "_openmp_static_glob_rd_$_");
5075 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5076 GV, CGM.VoidPtrTy);
5077 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5078 Rec->Buffer->replaceAllUsesWith(Replacement);
5079 Rec->Buffer->eraseFromParent();
5080 }
5081 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005082 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005083 if (!TeamsReductions.empty()) {
5084 ASTContext &C = CGM.getContext();
5085 RecordDecl *StaticRD = C.buildImplicitRecord(
5086 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5087 StaticRD->startDefinition();
5088 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5089 QualType RecTy = C.getRecordType(TeamReductionRec);
5090 auto *Field = FieldDecl::Create(
5091 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5092 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5093 /*BW=*/nullptr, /*Mutable=*/false,
5094 /*InitStyle=*/ICIS_NoInit);
5095 Field->setAccess(AS_public);
5096 StaticRD->addDecl(Field);
5097 }
5098 StaticRD->completeDefinition();
5099 QualType StaticTy = C.getRecordType(StaticRD);
5100 llvm::Type *LLVMReductionsBufferTy =
5101 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005102 // FIXME: nvlink does not handle weak linkage correctly (object with the
5103 // different size are reported as erroneous).
5104 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005105 auto *GV = new llvm::GlobalVariable(
5106 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005107 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005108 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5109 "_openmp_teams_reductions_buffer_$_");
5110 KernelTeamsReductionPtr->setInitializer(
5111 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5112 CGM.VoidPtrTy));
5113 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005114 CGOpenMPRuntime::clear();
5115}