blob: f4b044744fed9490ddb37958bda3a17497d72cdb [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;
Alexey Bataev1472e322019-04-19 16:48:38 +0000910 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
911 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000912 if (DKind == OMPD_parallel) {
913 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
914 /*IgnoreCaptured=*/true);
915 if (!Body)
916 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000917 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
918 if (const auto *NND =
919 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000920 DKind = NND->getDirectiveKind();
921 if (isOpenMPWorksharingDirective(DKind) &&
922 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
923 return true;
924 }
925 } else if (DKind == OMPD_teams) {
926 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
927 /*IgnoreCaptured=*/true);
928 if (!Body)
929 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000930 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
931 if (const auto *NND =
932 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000933 DKind = NND->getDirectiveKind();
934 if (isOpenMPParallelDirective(DKind) &&
935 isOpenMPWorksharingDirective(DKind) &&
936 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
937 return true;
938 if (DKind == OMPD_parallel) {
939 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
940 /*IgnoreCaptured=*/true);
941 if (!Body)
942 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000943 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
944 if (const auto *NND =
945 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000946 DKind = NND->getDirectiveKind();
947 if (isOpenMPWorksharingDirective(DKind) &&
948 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
949 return true;
950 }
951 }
952 }
953 }
954 return false;
955 case OMPD_target_teams:
956 if (isOpenMPParallelDirective(DKind) &&
957 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
958 hasStaticScheduling(*NestedDir))
959 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000960 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
961 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000962 if (DKind == OMPD_parallel) {
963 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
964 /*IgnoreCaptured=*/true);
965 if (!Body)
966 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000967 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
968 if (const auto *NND =
969 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000970 DKind = NND->getDirectiveKind();
971 if (isOpenMPWorksharingDirective(DKind) &&
972 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
973 return true;
974 }
975 }
976 return false;
977 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000978 if (DKind == OMPD_simd)
979 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000980 return isOpenMPWorksharingDirective(DKind) &&
981 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
982 case OMPD_target_teams_distribute:
983 case OMPD_target_simd:
984 case OMPD_target_parallel_for:
985 case OMPD_target_parallel_for_simd:
986 case OMPD_target_teams_distribute_simd:
987 case OMPD_target_teams_distribute_parallel_for:
988 case OMPD_target_teams_distribute_parallel_for_simd:
989 case OMPD_parallel:
990 case OMPD_for:
991 case OMPD_parallel_for:
992 case OMPD_parallel_sections:
993 case OMPD_for_simd:
994 case OMPD_parallel_for_simd:
995 case OMPD_cancel:
996 case OMPD_cancellation_point:
997 case OMPD_ordered:
998 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000999 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001000 case OMPD_task:
1001 case OMPD_simd:
1002 case OMPD_sections:
1003 case OMPD_section:
1004 case OMPD_single:
1005 case OMPD_master:
1006 case OMPD_critical:
1007 case OMPD_taskyield:
1008 case OMPD_barrier:
1009 case OMPD_taskwait:
1010 case OMPD_taskgroup:
1011 case OMPD_atomic:
1012 case OMPD_flush:
1013 case OMPD_teams:
1014 case OMPD_target_data:
1015 case OMPD_target_exit_data:
1016 case OMPD_target_enter_data:
1017 case OMPD_distribute:
1018 case OMPD_distribute_simd:
1019 case OMPD_distribute_parallel_for:
1020 case OMPD_distribute_parallel_for_simd:
1021 case OMPD_teams_distribute:
1022 case OMPD_teams_distribute_simd:
1023 case OMPD_teams_distribute_parallel_for:
1024 case OMPD_teams_distribute_parallel_for_simd:
1025 case OMPD_target_update:
1026 case OMPD_declare_simd:
1027 case OMPD_declare_target:
1028 case OMPD_end_declare_target:
1029 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001030 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001031 case OMPD_taskloop:
1032 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001033 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001034 case OMPD_unknown:
1035 llvm_unreachable("Unexpected directive.");
1036 }
1037 }
1038
1039 return false;
1040}
1041
1042/// Checks if the construct supports lightweight runtime. It must be SPMD
1043/// construct + inner loop-based construct with static scheduling.
1044static bool supportsLightweightRuntime(ASTContext &Ctx,
1045 const OMPExecutableDirective &D) {
1046 if (!supportsSPMDExecutionMode(Ctx, D))
1047 return false;
1048 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1049 switch (DirectiveKind) {
1050 case OMPD_target:
1051 case OMPD_target_teams:
1052 case OMPD_target_parallel:
1053 return hasNestedLightweightDirective(Ctx, D);
1054 case OMPD_target_parallel_for:
1055 case OMPD_target_parallel_for_simd:
1056 case OMPD_target_teams_distribute_parallel_for:
1057 case OMPD_target_teams_distribute_parallel_for_simd:
1058 // (Last|First)-privates must be shared in parallel region.
1059 return hasStaticScheduling(D);
1060 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001061 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001062 return true;
1063 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001064 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001065 case OMPD_parallel:
1066 case OMPD_for:
1067 case OMPD_parallel_for:
1068 case OMPD_parallel_sections:
1069 case OMPD_for_simd:
1070 case OMPD_parallel_for_simd:
1071 case OMPD_cancel:
1072 case OMPD_cancellation_point:
1073 case OMPD_ordered:
1074 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001075 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001076 case OMPD_task:
1077 case OMPD_simd:
1078 case OMPD_sections:
1079 case OMPD_section:
1080 case OMPD_single:
1081 case OMPD_master:
1082 case OMPD_critical:
1083 case OMPD_taskyield:
1084 case OMPD_barrier:
1085 case OMPD_taskwait:
1086 case OMPD_taskgroup:
1087 case OMPD_atomic:
1088 case OMPD_flush:
1089 case OMPD_teams:
1090 case OMPD_target_data:
1091 case OMPD_target_exit_data:
1092 case OMPD_target_enter_data:
1093 case OMPD_distribute:
1094 case OMPD_distribute_simd:
1095 case OMPD_distribute_parallel_for:
1096 case OMPD_distribute_parallel_for_simd:
1097 case OMPD_teams_distribute:
1098 case OMPD_teams_distribute_simd:
1099 case OMPD_teams_distribute_parallel_for:
1100 case OMPD_teams_distribute_parallel_for_simd:
1101 case OMPD_target_update:
1102 case OMPD_declare_simd:
1103 case OMPD_declare_target:
1104 case OMPD_end_declare_target:
1105 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001106 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001107 case OMPD_taskloop:
1108 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001109 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001110 case OMPD_unknown:
1111 break;
1112 }
1113 llvm_unreachable(
1114 "Unknown programming model for OpenMP directive on NVPTX target.");
1115}
1116
1117void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001118 StringRef ParentName,
1119 llvm::Function *&OutlinedFn,
1120 llvm::Constant *&OutlinedFnID,
1121 bool IsOffloadEntry,
1122 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001123 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001124 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001125 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001126 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001127 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001128
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001129 // Emit target region as a standalone region.
1130 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001131 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1132 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001133
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001134 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001135 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001136 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001137 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138 void Enter(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.emitNonSPMDEntryHeader(CGF, EST, WST);
1142 // Skip target region initialization.
1143 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001144 }
1145 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001146 auto &RT =
1147 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001148 RT.clearLocThreadIdInsertPt(CGF);
1149 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001150 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001151 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001152 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001153 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001154 // Reserve place for the globalized memory.
1155 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001156 if (!KernelStaticGlobalized) {
1157 KernelStaticGlobalized = new llvm::GlobalVariable(
1158 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1159 llvm::GlobalValue::InternalLinkage,
1160 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1161 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1162 llvm::GlobalValue::NotThreadLocal,
1163 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1164 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001165 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1166 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001167 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001168
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 // Now change the name of the worker function to correspond to this target
1170 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001171 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001172
1173 // Create the worker function
1174 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001175}
1176
1177// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001178void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001179 EntryFunctionState &EST,
1180 WorkerFunctionState &WST) {
1181 CGBuilderTy &Bld = CGF.Builder;
1182
1183 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1184 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1185 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1186 EST.ExitBB = CGF.createBasicBlock(".exit");
1187
Alexey Bataev9ff80832018-04-16 20:16:21 +00001188 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001189 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1190 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1191
1192 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001193 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 CGF.EmitBranch(EST.ExitBB);
1195
1196 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001197 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1199 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1200
1201 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001202 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001203 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 // First action in sequential region:
1205 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001206 // TODO: Optimize runtime initialization and pass in correct value.
1207 llvm::Value *Args[] = {getThreadLimit(CGF),
1208 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001209 CGF.EmitRuntimeCall(
1210 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001211
1212 // For data sharing, we need to initialize the stack.
1213 CGF.EmitRuntimeCall(
1214 createNVPTXRuntimeFunction(
1215 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1216
Alexey Bataevc99042b2018-03-15 18:10:54 +00001217 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001218}
1219
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001220void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001222 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001223 if (!CGF.HaveInsertPoint())
1224 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001225
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001226 emitGenericVarsEpilog(CGF);
1227
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001228 if (!EST.ExitBB)
1229 EST.ExitBB = CGF.createBasicBlock(".exit");
1230
1231 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1232 CGF.EmitBranch(TerminateBB);
1233
1234 CGF.EmitBlock(TerminateBB);
1235 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001236 // TODO: Optimize runtime initialization and pass in correct value.
1237 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001238 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001239 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001240 // Barrier to terminate worker threads.
1241 syncCTAThreads(CGF);
1242 // Master thread jumps to exit point.
1243 CGF.EmitBranch(EST.ExitBB);
1244
1245 CGF.EmitBlock(EST.ExitBB);
1246 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001247}
1248
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001249void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001250 StringRef ParentName,
1251 llvm::Function *&OutlinedFn,
1252 llvm::Constant *&OutlinedFnID,
1253 bool IsOffloadEntry,
1254 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001255 ExecutionRuntimeModesRAII ModeRAII(
1256 CurrentExecutionMode, RequiresFullRuntime,
1257 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1258 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001259 EntryFunctionState EST;
1260
1261 // Emit target region as a standalone region.
1262 class NVPTXPrePostActionTy : public PrePostActionTy {
1263 CGOpenMPRuntimeNVPTX &RT;
1264 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1265 const OMPExecutableDirective &D;
1266
1267 public:
1268 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1269 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1270 const OMPExecutableDirective &D)
1271 : RT(RT), EST(EST), D(D) {}
1272 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001273 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001274 // Skip target region initialization.
1275 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001276 }
1277 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001278 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001279 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001280 }
1281 } Action(*this, EST, D);
1282 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001283 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001284 // Reserve place for the globalized memory.
1285 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001286 if (!KernelStaticGlobalized) {
1287 KernelStaticGlobalized = new llvm::GlobalVariable(
1288 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1289 llvm::GlobalValue::InternalLinkage,
1290 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1291 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1292 llvm::GlobalValue::NotThreadLocal,
1293 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1294 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001295 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1296 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001297 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001298}
1299
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001300void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001301 CodeGenFunction &CGF, EntryFunctionState &EST,
1302 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001303 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001304
1305 // Setup BBs in entry function.
1306 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1307 EST.ExitBB = CGF.createBasicBlock(".exit");
1308
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001309 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1310 /*RequiresOMPRuntime=*/
1311 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1312 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001313 CGF.EmitRuntimeCall(
1314 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001315
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001316 if (RequiresFullRuntime) {
1317 // For data sharing, we need to initialize the stack.
1318 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1319 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1320 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001321
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001322 CGF.EmitBranch(ExecuteBB);
1323
1324 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001325
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001326 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001327}
1328
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001329void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001330 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001331 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001332 if (!CGF.HaveInsertPoint())
1333 return;
1334
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001335 if (!EST.ExitBB)
1336 EST.ExitBB = CGF.createBasicBlock(".exit");
1337
1338 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1339 CGF.EmitBranch(OMPDeInitBB);
1340
1341 CGF.EmitBlock(OMPDeInitBB);
1342 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001343 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1344 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001345 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001346 createNVPTXRuntimeFunction(
1347 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348 CGF.EmitBranch(EST.ExitBB);
1349
1350 CGF.EmitBlock(EST.ExitBB);
1351 EST.ExitBB = nullptr;
1352}
1353
1354// Create a unique global variable to indicate the execution mode of this target
1355// region. The execution mode is either 'generic', or 'spmd' depending on the
1356// target directive. This variable is picked up by the offload library to setup
1357// the device appropriately before kernel launch. If the execution mode is
1358// 'generic', the runtime reserves one warp for the master, otherwise, all
1359// warps participate in parallel work.
1360static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001361 bool Mode) {
1362 auto *GVMode =
1363 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1364 llvm::GlobalValue::WeakAnyLinkage,
1365 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1366 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001367 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001368}
1369
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001370void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001371 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001372
1373 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001374 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001375 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001376 emitWorkerLoop(CGF, WST);
1377 CGF.FinishFunction();
1378}
1379
1380void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1381 WorkerFunctionState &WST) {
1382 //
1383 // The workers enter this loop and wait for parallel work from the master.
1384 // When the master encounters a parallel region it sets up the work + variable
1385 // arguments, and wakes up the workers. The workers first check to see if
1386 // they are required for the parallel region, i.e., within the # of requested
1387 // parallel threads. The activated workers load the variable arguments and
1388 // execute the parallel work.
1389 //
1390
1391 CGBuilderTy &Bld = CGF.Builder;
1392
1393 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1394 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1395 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1396 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1397 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1398 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1399
1400 CGF.EmitBranch(AwaitBB);
1401
1402 // Workers wait for work from master.
1403 CGF.EmitBlock(AwaitBB);
1404 // Wait for parallel work
1405 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001406
1407 Address WorkFn =
1408 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1409 Address ExecStatus =
1410 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1411 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1412 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1413
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001414 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001415 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001416 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001417 llvm::Value *Ret = CGF.EmitRuntimeCall(
1418 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1419 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001420
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001421 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001422 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1423 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001424 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1425
1426 // Activate requested workers.
1427 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001428 llvm::Value *IsActive =
1429 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1430 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001431
1432 // Signal start of parallel region.
1433 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001434 // Skip initialization.
1435 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001436
1437 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001438 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001439 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001440 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001441
1442 llvm::Value *WorkFnMatch =
1443 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1444
1445 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1446 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1447 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1448
1449 // Execute this outlined function.
1450 CGF.EmitBlock(ExecuteFNBB);
1451
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001452 // Insert call to work function via shared wrapper. The shared
1453 // wrapper takes two arguments:
1454 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001455 // - the thread ID;
1456 emitCall(CGF, WST.Loc, W,
1457 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001458
1459 // Go to end of parallel region.
1460 CGF.EmitBranch(TerminateBB);
1461
1462 CGF.EmitBlock(CheckNextBB);
1463 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001464 // Default case: call to outlined function through pointer if the target
1465 // region makes a declare target call that may contain an orphaned parallel
1466 // directive.
1467 auto *ParallelFnTy =
1468 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001469 /*isVarArg=*/false);
1470 llvm::Value *WorkFnCast =
1471 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001472 // Insert call to work function via shared wrapper. The shared
1473 // wrapper takes two arguments:
1474 // - the parallelism level;
1475 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001476 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001477 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1478 // Go to end of parallel region.
1479 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001480
1481 // Signal end of parallel region.
1482 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001483 CGF.EmitRuntimeCall(
1484 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1485 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001486 CGF.EmitBranch(BarrierBB);
1487
1488 // All active and inactive workers wait at a barrier after parallel region.
1489 CGF.EmitBlock(BarrierBB);
1490 // Barrier after parallel region.
1491 syncCTAThreads(CGF);
1492 CGF.EmitBranch(AwaitBB);
1493
1494 // Exit target region.
1495 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001496 // Skip initialization.
1497 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001498}
1499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001500/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001501/// implementation. Specialized for the NVPTX device.
1502/// \param Function OpenMP runtime function.
1503/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001504llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001505CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001506 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001507 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1508 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001509 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1510 // RequiresOMPRuntime);
1511 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001512 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1515 break;
1516 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001517 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001518 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1519 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001520 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001521 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001522 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1523 break;
1524 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001525 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1526 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001527 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001528 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001529 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001530 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1531 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1532 break;
1533 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001534 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1535 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1536 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001537 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001538 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1539 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001540 break;
1541 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001542 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1543 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001544 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001545 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001546 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1549 break;
1550 }
1551 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001552 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1553 /// int16_t IsOMPRuntimeInitialized);
1554 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001555 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001556 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001557 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1558 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1559 break;
1560 }
1561 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1562 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001563 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001564 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1565 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1566 break;
1567 }
1568 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1569 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1570 // global_tid);
1571 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001572 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1575 break;
1576 }
1577 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1578 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1579 // global_tid);
1580 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001581 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1584 break;
1585 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001586 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1587 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1588 // int16_t lane_offset, int16_t warp_size);
1589 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001590 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001591 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1593 break;
1594 }
1595 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1596 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1597 // int16_t lane_offset, int16_t warp_size);
1598 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001599 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001600 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1602 break;
1603 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001604 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001605 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1606 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1607 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1608 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1609 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001610 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1611 CGM.Int16Ty, CGM.Int16Ty};
1612 auto *ShuffleReduceFnTy =
1613 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1614 /*isVarArg=*/false);
1615 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1616 auto *InterWarpCopyFnTy =
1617 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1618 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1620 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001621 CGM.Int32Ty,
1622 CGM.SizeTy,
1623 CGM.VoidPtrTy,
1624 ShuffleReduceFnTy->getPointerTo(),
1625 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001626 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001627 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1628 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001629 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001630 break;
1631 }
1632 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1633 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1634 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001635 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001636 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1637 RTLFn = CGM.CreateRuntimeFunction(
1638 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1639 break;
1640 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001641 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1642 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1643 // global_tid, void *global_buffer, int32_t num_of_records, void*
1644 // reduce_data,
1645 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1646 // lane_offset, int16_t shortCircuit),
1647 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1648 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1649 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1650 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1651 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1652 // *buffer, int idx, void *reduce_data));
1653 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1654 CGM.Int16Ty, CGM.Int16Ty};
1655 auto *ShuffleReduceFnTy =
1656 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1657 /*isVarArg=*/false);
1658 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1659 auto *InterWarpCopyFnTy =
1660 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1661 /*isVarArg=*/false);
1662 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1663 CGM.VoidPtrTy};
1664 auto *GlobalListFnTy =
1665 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1666 /*isVarArg=*/false);
1667 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1668 CGM.Int32Ty,
1669 CGM.VoidPtrTy,
1670 CGM.Int32Ty,
1671 CGM.VoidPtrTy,
1672 ShuffleReduceFnTy->getPointerTo(),
1673 InterWarpCopyFnTy->getPointerTo(),
1674 GlobalListFnTy->getPointerTo(),
1675 GlobalListFnTy->getPointerTo(),
1676 GlobalListFnTy->getPointerTo(),
1677 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001678 auto *FnTy =
1679 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1680 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001681 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001682 break;
1683 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001684 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1685 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001686 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001687 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1688 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1689 break;
1690 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001691 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1692 /// Build void __kmpc_data_sharing_init_stack_spmd();
1693 auto *FnTy =
1694 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001695 RTLFn =
1696 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001697 break;
1698 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001699 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1700 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001701 // int16_t UseSharedMemory);
1702 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001703 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001704 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1705 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001706 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001707 break;
1708 }
1709 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1710 // Build void __kmpc_data_sharing_pop_stack(void *a);
1711 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001712 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001713 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1715 /*Name=*/"__kmpc_data_sharing_pop_stack");
1716 break;
1717 }
1718 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1719 /// Build void __kmpc_begin_sharing_variables(void ***args,
1720 /// size_t n_args);
1721 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001722 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001723 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1724 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1728 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001729 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001730 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1731 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1732 break;
1733 }
1734 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1735 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1736 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001737 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1740 break;
1741 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001742 case OMPRTL_NVPTX__kmpc_parallel_level: {
1743 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1744 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1745 auto *FnTy =
1746 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1747 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1748 break;
1749 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001750 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1751 // Build int8_t __kmpc_is_spmd_exec_mode();
1752 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1753 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1754 break;
1755 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001756 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001757 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1758 // const void *buf, size_t size, int16_t is_shared, const void **res);
1759 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1760 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001761 auto *FnTy =
1762 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1763 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1764 break;
1765 }
1766 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001767 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1768 // int16_t is_shared);
1769 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001770 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001772 RTLFn =
1773 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1774 break;
1775 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001776 case OMPRTL__kmpc_barrier: {
1777 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1778 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1779 auto *FnTy =
1780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1781 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001782 cast<llvm::Function>(RTLFn.getCallee())
1783 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001784 break;
1785 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001786 case OMPRTL__kmpc_barrier_simple_spmd: {
1787 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1788 // global_tid);
1789 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1790 auto *FnTy =
1791 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1792 RTLFn =
1793 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001794 cast<llvm::Function>(RTLFn.getCallee())
1795 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001796 break;
1797 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001798 }
1799 return RTLFn;
1800}
1801
1802void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1803 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001804 uint64_t Size, int32_t,
1805 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001806 // TODO: Add support for global variables on the device after declare target
1807 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001808 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001809 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001810 llvm::Module &M = CGM.getModule();
1811 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001812
1813 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001814 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001815
1816 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001817 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001818 llvm::ConstantAsMetadata::get(
1819 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1820 // Append metadata to nvvm.annotations
1821 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1822}
1823
1824void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1825 const OMPExecutableDirective &D, StringRef ParentName,
1826 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001827 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001828 if (!IsOffloadEntry) // Nothing to do.
1829 return;
1830
1831 assert(!ParentName.empty() && "Invalid target region parent name!");
1832
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001833 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001834 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001835 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001836 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001837 else
1838 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1839 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001840
1841 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001842}
1843
Alexey Bataevceeaa482018-11-21 21:04:34 +00001844namespace {
1845LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1846/// Enum for accesseing the reserved_2 field of the ident_t struct.
1847enum ModeFlagsTy : unsigned {
1848 /// Bit set to 1 when in SPMD mode.
1849 KMP_IDENT_SPMD_MODE = 0x01,
1850 /// Bit set to 1 when a simplified runtime is used.
1851 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1852 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1853};
1854
1855/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1856static const ModeFlagsTy UndefinedMode =
1857 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1858} // anonymous namespace
1859
1860unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001861 switch (getExecutionMode()) {
1862 case EM_SPMD:
1863 if (requiresFullRuntime())
1864 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1865 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1866 case EM_NonSPMD:
1867 assert(requiresFullRuntime() && "Expected full runtime.");
1868 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1869 case EM_Unknown:
1870 return UndefinedMode;
1871 }
1872 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001873}
1874
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001875CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001876 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001877 if (!CGM.getLangOpts().OpenMPIsDevice)
1878 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001879}
Carlo Bertollic6872252016-04-04 15:55:02 +00001880
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001881void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1882 OpenMPProcBindClauseKind ProcBind,
1883 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001884 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001885 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001886 return;
1887
1888 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1889}
1890
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001891void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1892 llvm::Value *NumThreads,
1893 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001894 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001895 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001896 return;
1897
1898 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1899}
1900
Carlo Bertollic6872252016-04-04 15:55:02 +00001901void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1902 const Expr *NumTeams,
1903 const Expr *ThreadLimit,
1904 SourceLocation Loc) {}
1905
James Y Knight9871db02019-02-05 16:42:33 +00001906llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001907 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1908 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001909 // Emit target region as a standalone region.
1910 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001911 bool &IsInParallelRegion;
1912 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001913
1914 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001915 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1916 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001917 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001918 PrevIsInParallelRegion = IsInParallelRegion;
1919 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001920 }
1921 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001922 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001923 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001924 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001925 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001926 bool PrevIsInTTDRegion = IsInTTDRegion;
1927 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001928 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1929 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001930 auto *OutlinedFun =
1931 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1932 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001933 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001934 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001935 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1936 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001937 llvm::Function *WrapperFun =
1938 createParallelDataSharingWrapper(OutlinedFun, D);
1939 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1940 }
1941
1942 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001943}
1944
Alexey Bataev2adecff2018-09-21 14:22:53 +00001945/// Get list of lastprivate variables from the teams distribute ... or
1946/// teams {distribute ...} directives.
1947static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001948getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001949 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1950 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1951 "expected teams directive.");
1952 const OMPExecutableDirective *Dir = &D;
1953 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001954 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001955 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001956 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1957 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001958 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001959 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
1960 Dir = nullptr;
1961 }
1962 }
1963 if (!Dir)
1964 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001965 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001966 for (const Expr *E : C->getVarRefs())
1967 Vars.push_back(getPrivateItem(E));
1968 }
1969}
1970
1971/// Get list of reduction variables from the teams ... directives.
1972static void
1973getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
1974 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1975 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1976 "expected teams directive.");
1977 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
1978 for (const Expr *E : C->privates())
1979 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00001980 }
1981}
1982
James Y Knight9871db02019-02-05 16:42:33 +00001983llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00001984 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1985 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001986 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00001987
Alexey Bataev2adecff2018-09-21 14:22:53 +00001988 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001989 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00001990 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001991 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00001992 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
1993 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00001994 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001995 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
1996 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00001997 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00001998 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00001999 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002000 }
2001 } else if (!LastPrivatesReductions.empty()) {
2002 assert(!TeamAndReductions.first &&
2003 "Previous team declaration is not expected.");
2004 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2005 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002006 }
2007
Alexey Bataevc99042b2018-03-15 18:10:54 +00002008 // Emit target region as a standalone region.
2009 class NVPTXPrePostActionTy : public PrePostActionTy {
2010 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002011 const RecordDecl *GlobalizedRD;
2012 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2013 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002014
2015 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002016 NVPTXPrePostActionTy(
2017 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2018 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2019 &MappedDeclsFields)
2020 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2021 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002022 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002023 auto &Rt =
2024 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2025 if (GlobalizedRD) {
2026 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2027 I->getSecond().GlobalRecord = GlobalizedRD;
2028 I->getSecond().MappedParams =
2029 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2030 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2031 for (const auto &Pair : MappedDeclsFields) {
2032 assert(Pair.getFirst()->isCanonicalDecl() &&
2033 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002034 Data.insert(std::make_pair(Pair.getFirst(),
2035 MappedVarData(Pair.getSecond(),
2036 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002037 }
2038 }
2039 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002040 }
2041 void Exit(CodeGenFunction &CGF) override {
2042 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2043 .emitGenericVarsEpilog(CGF);
2044 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002045 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2046 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002047 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002048 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002049 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002050 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002051 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002052
2053 return OutlinedFun;
2054}
2055
Alexey Bataevc99042b2018-03-15 18:10:54 +00002056void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002057 SourceLocation Loc,
2058 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002059 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2060 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002061 return;
2062
Alexey Bataevc99042b2018-03-15 18:10:54 +00002063 CGBuilderTy &Bld = CGF.Builder;
2064
2065 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2066 if (I == FunctionGlobalizedDecls.end())
2067 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002068 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002069 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002070 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002071
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002072 // Recover pointer to this function's global record. The runtime will
2073 // handle the specifics of the allocation of the memory.
2074 // Use actual memory size of the record including the padding
2075 // for alignment purposes.
2076 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002077 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002078 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002079 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002080 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002081
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002082 llvm::PointerType *GlobalRecPtrTy =
2083 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002084 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002085 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002086 if (!IsInTTDRegion &&
2087 (WithSPMDCheck ||
2088 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002089 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2090 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2091 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002092 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2093 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2094 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2095 llvm::Value *PL = CGF.EmitRuntimeCall(
2096 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2097 {RTLoc, ThreadID});
2098 IsTTD = Bld.CreateIsNull(PL);
2099 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002100 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2101 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2102 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2103 // There is no need to emit line number for unconditional branch.
2104 (void)ApplyDebugLocation::CreateEmpty(CGF);
2105 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002106 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2107 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002108 CGF.EmitBranch(ExitBB);
2109 // There is no need to emit line number for unconditional branch.
2110 (void)ApplyDebugLocation::CreateEmpty(CGF);
2111 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002112 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2113 if (const RecordDecl *SecGlobalizedVarsRecord =
2114 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2115 SecGlobalRecTy =
2116 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2117
2118 // Recover pointer to this function's global record. The runtime will
2119 // handle the specifics of the allocation of the memory.
2120 // Use actual memory size of the record including the padding
2121 // for alignment purposes.
2122 unsigned Alignment =
2123 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2124 unsigned GlobalRecordSize =
2125 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2126 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2127 Size = Bld.CreateSelect(
2128 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2129 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002130 // TODO: allow the usage of shared memory to be controlled by
2131 // the user, for now, default to global.
2132 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002133 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002134 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2135 createNVPTXRuntimeFunction(
2136 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2137 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002138 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002139 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002141 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002142 /*NumReservedValues=*/2, "_select_stack");
2143 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2144 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2145 GlobalRecCastAddr = Phi;
2146 I->getSecond().GlobalRecordAddr = Phi;
2147 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002148 } else if (IsInTTDRegion) {
2149 assert(GlobalizedRecords.back().Records.size() < 2 &&
2150 "Expected less than 2 globalized records: one for target and one "
2151 "for teams.");
2152 unsigned Offset = 0;
2153 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2154 QualType RDTy = CGM.getContext().getRecordType(RD);
2155 unsigned Alignment =
2156 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2157 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2158 Offset =
2159 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2160 }
2161 unsigned Alignment =
2162 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2163 Offset = llvm::alignTo(Offset, Alignment);
2164 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2165 ++GlobalizedRecords.back().RegionCounter;
2166 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002167 assert(KernelStaticGlobalized &&
2168 "Kernel static pointer must be initialized already.");
2169 auto *UseSharedMemory = new llvm::GlobalVariable(
2170 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2171 llvm::GlobalValue::InternalLinkage, nullptr,
2172 "_openmp_static_kernel$is_shared");
2173 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2174 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2175 /*DestWidth=*/16, /*Signed=*/0);
2176 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2177 Address(UseSharedMemory,
2178 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2179 /*Volatile=*/false, Int16Ty, Loc);
2180 auto *StaticGlobalized = new llvm::GlobalVariable(
2181 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002182 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002183 auto *RecSize = new llvm::GlobalVariable(
2184 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2185 llvm::GlobalValue::InternalLinkage, nullptr,
2186 "_openmp_static_kernel$size");
2187 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2188 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002189 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002190 CGM.getContext().getSizeType(), Loc);
2191 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2192 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002193 llvm::Value *GlobalRecordSizeArg[] = {
2194 llvm::ConstantInt::get(
2195 CGM.Int16Ty,
2196 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2197 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002198 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2199 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2200 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002201 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002202 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002203 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2204 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002205 }
2206 assert(KernelStaticGlobalized && "Global address must be set already.");
2207 Address FrameAddr = CGF.EmitLoadOfPointer(
2208 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2209 CGM.getContext()
2210 .getPointerType(CGM.getContext().VoidPtrTy)
2211 .castAs<PointerType>());
2212 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002213 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002214 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2215 I->getSecond().IsInSPMDModeFlag = nullptr;
2216 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2217 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002218 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002219 // TODO: allow the usage of shared memory to be controlled by
2220 // the user, for now, default to global.
2221 llvm::Value *GlobalRecordSizeArg[] = {
2222 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2223 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002224 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2225 createNVPTXRuntimeFunction(
2226 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2227 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002228 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002229 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002230 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2231 I->getSecond().IsInSPMDModeFlag = nullptr;
2232 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002233 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002234 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002235
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002236 // Emit the "global alloca" which is a GEP from the global declaration
2237 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002238 LValue SecBase;
2239 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2240 if (IsTTD) {
2241 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2242 llvm::PointerType *SecGlobalRecPtrTy =
2243 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2244 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2245 Bld.CreatePointerBitCastOrAddrSpaceCast(
2246 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2247 SecGlobalRecTy);
2248 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002249 for (auto &Rec : I->getSecond().LocalVarData) {
2250 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2251 llvm::Value *ParValue;
2252 if (EscapedParam) {
2253 const auto *VD = cast<VarDecl>(Rec.first);
2254 LValue ParLVal =
2255 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2256 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2257 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002258 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2259 // Emit VarAddr basing on lane-id if required.
2260 QualType VarTy;
2261 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002262 VarTy = Rec.second.FD->getType();
2263 } else {
2264 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2265 VarAddr.getAddress().getPointer(),
2266 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002267 VarTy =
2268 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002269 VarAddr = CGF.MakeAddrLValue(
2270 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2271 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002272 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002273 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002274 if (!IsInTTDRegion &&
2275 (WithSPMDCheck ||
2276 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002277 assert(I->getSecond().IsInSPMDModeFlag &&
2278 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002279 if (IsTTD) {
2280 assert(SecIt->second.IsOnePerTeam &&
2281 "Secondary glob data must be one per team.");
2282 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2283 VarAddr.setAddress(
2284 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2285 VarAddr.getPointer()),
2286 VarAddr.getAlignment()));
2287 Rec.second.PrivateAddr = VarAddr.getAddress();
2288 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002289 Address GlobalPtr = Rec.second.PrivateAddr;
2290 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2291 Rec.second.PrivateAddr = Address(
2292 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2293 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2294 LocalAddr.getAlignment());
2295 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002296 if (EscapedParam) {
2297 const auto *VD = cast<VarDecl>(Rec.first);
2298 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2299 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2300 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002301 if (IsTTD)
2302 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002303 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002304 }
2305 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2306 // Recover pointer to this function's global record. The runtime will
2307 // handle the specifics of the allocation of the memory.
2308 // Use actual memory size of the record including the padding
2309 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002310 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002311 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2312 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2313 Size = Bld.CreateNUWAdd(
2314 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2315 llvm::Value *AlignVal =
2316 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2317 Size = Bld.CreateUDiv(Size, AlignVal);
2318 Size = Bld.CreateNUWMul(Size, AlignVal);
2319 // TODO: allow the usage of shared memory to be controlled by
2320 // the user, for now, default to global.
2321 llvm::Value *GlobalRecordSizeArg[] = {
2322 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2323 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002324 createNVPTXRuntimeFunction(
2325 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002326 GlobalRecordSizeArg);
2327 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2328 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2329 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2330 CGM.getContext().getDeclAlign(VD),
2331 AlignmentSource::Decl);
2332 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2333 Base.getAddress());
2334 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002335 }
2336 I->getSecond().MappedParams->apply(CGF);
2337}
2338
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002339void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2340 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002341 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2342 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002343 return;
2344
Alexey Bataevc99042b2018-03-15 18:10:54 +00002345 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002346 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002347 I->getSecond().MappedParams->restore(CGF);
2348 if (!CGF.HaveInsertPoint())
2349 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002350 for (llvm::Value *Addr :
2351 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2352 CGF.EmitRuntimeCall(
2353 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2354 Addr);
2355 }
2356 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002357 if (!IsInTTDRegion &&
2358 (WithSPMDCheck ||
2359 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002360 CGBuilderTy &Bld = CGF.Builder;
2361 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2362 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2363 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2364 // There is no need to emit line number for unconditional branch.
2365 (void)ApplyDebugLocation::CreateEmpty(CGF);
2366 CGF.EmitBlock(NonSPMDBB);
2367 CGF.EmitRuntimeCall(
2368 createNVPTXRuntimeFunction(
2369 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2370 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2371 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002372 } else if (IsInTTDRegion) {
2373 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2374 "region counter must be > 0.");
2375 --GlobalizedRecords.back().RegionCounter;
2376 // Emit the restore function only in the target region.
2377 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002378 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2379 /*DestWidth=*/16, /*Signed=*/0);
2380 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2381 Address(GlobalizedRecords.back().UseSharedMemory,
2382 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2383 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002384 llvm::Value *Args[] = {
2385 llvm::ConstantInt::get(
2386 CGM.Int16Ty,
2387 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2388 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002389 CGF.EmitRuntimeCall(
2390 createNVPTXRuntimeFunction(
2391 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002392 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002393 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002394 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002395 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2396 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2397 I->getSecond().GlobalRecordAddr);
2398 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002399 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002400 }
2401}
2402
Carlo Bertollic6872252016-04-04 15:55:02 +00002403void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2404 const OMPExecutableDirective &D,
2405 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002406 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002407 ArrayRef<llvm::Value *> CapturedVars) {
2408 if (!CGF.HaveInsertPoint())
2409 return;
2410
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002411 Address ZeroAddr = CGF.CreateMemTemp(
2412 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2413 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002414 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2415 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002416 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002417 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2418 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002419 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002420}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002421
2422void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002423 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002424 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2425 if (!CGF.HaveInsertPoint())
2426 return;
2427
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002428 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002429 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002430 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002431 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002432}
2433
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002434void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002435 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2436 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2437 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002438
2439 // Force inline this outlined function at its call site.
2440 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2441
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002442 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2443 /*DestWidth=*/32, /*Signed=*/1),
2444 ".zero.addr");
2445 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002446 // ThreadId for serialized parallels is 0.
2447 Address ThreadIDAddr = ZeroAddr;
2448 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002449 CodeGenFunction &CGF, PrePostActionTy &Action) {
2450 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002451
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002452 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2453 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2454 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2455 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2456 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2457 };
2458 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2459 PrePostActionTy &) {
2460
2461 RegionCodeGenTy RCG(CodeGen);
2462 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2463 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2464 llvm::Value *Args[] = {RTLoc, ThreadID};
2465
2466 NVPTXActionTy Action(
2467 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2468 Args,
2469 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2470 Args);
2471 RCG.setAction(Action);
2472 RCG(CGF);
2473 };
2474
2475 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2476 PrePostActionTy &Action) {
2477 CGBuilderTy &Bld = CGF.Builder;
2478 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2479 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002480 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2481
2482 // Prepare for parallel region. Indicate the outlined function.
2483 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002484 CGF.EmitRuntimeCall(
2485 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2486 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002487
2488 // Create a private scope that will globalize the arguments
2489 // passed from the outside of the target region.
2490 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2491
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002492 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002493 if (!CapturedVars.empty()) {
2494 // Prepare for parallel region. Indicate the outlined function.
2495 Address SharedArgs =
2496 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2497 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2498
2499 llvm::Value *DataSharingArgs[] = {
2500 SharedArgsPtr,
2501 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2502 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2503 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2504 DataSharingArgs);
2505
2506 // Store variable address in a list of references to pass to workers.
2507 unsigned Idx = 0;
2508 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002509 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2510 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2511 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002512 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002513 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002514 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002515 if (V->getType()->isIntegerTy())
2516 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2517 else
2518 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002519 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2520 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002521 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002522 }
2523 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002524
2525 // Activate workers. This barrier is used by the master to signal
2526 // work for the workers.
2527 syncCTAThreads(CGF);
2528
2529 // OpenMP [2.5, Parallel Construct, p.49]
2530 // There is an implied barrier at the end of a parallel region. After the
2531 // end of a parallel region, only the master thread of the team resumes
2532 // execution of the enclosing task region.
2533 //
2534 // The master waits at this barrier until all workers are done.
2535 syncCTAThreads(CGF);
2536
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002537 if (!CapturedVars.empty())
2538 CGF.EmitRuntimeCall(
2539 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2540
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002541 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002542 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002543 };
2544
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002545 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2546 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002547 if (IsInParallelRegion) {
2548 SeqGen(CGF, Action);
2549 } else if (IsInTargetMasterThreadRegion) {
2550 L0ParallelGen(CGF, Action);
2551 } else {
2552 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002553 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002554 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002555 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002556 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002557 // }
2558 CGBuilderTy &Bld = CGF.Builder;
2559 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002560 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2561 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002562 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002563 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2564 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002565 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002566 // There is no need to emit line number for unconditional branch.
2567 (void)ApplyDebugLocation::CreateEmpty(CGF);
2568 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002569 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2570 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2571 llvm::Value *PL = CGF.EmitRuntimeCall(
2572 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2573 {RTLoc, ThreadID});
2574 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002575 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002576 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002577 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002578 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002579 // There is no need to emit line number for unconditional branch.
2580 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002581 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002582 L0ParallelGen(CGF, Action);
2583 CGF.EmitBranch(ExitBB);
2584 // There is no need to emit line number for unconditional branch.
2585 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002586 // Emit the continuation block for code after the if.
2587 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2588 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002589 };
2590
Alexey Bataev9ff80832018-04-16 20:16:21 +00002591 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002592 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002593 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002594 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002595 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002596 ThenRCG(CGF);
2597 }
2598}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002599
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002600void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002601 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002602 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2603 // Just call the outlined function to execute the parallel region.
2604 // OutlinedFn(&GTid, &zero, CapturedStruct);
2605 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002606 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002607
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002608 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2609 /*DestWidth=*/32, /*Signed=*/1),
2610 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002611 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002612 // ThreadId for serialized parallels is 0.
2613 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002614 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002615 &ThreadIDAddr](CodeGenFunction &CGF,
2616 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002617 Action.Enter(CGF);
2618
2619 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2620 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2621 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2622 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2623 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2624 };
2625 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2626 PrePostActionTy &) {
2627
2628 RegionCodeGenTy RCG(CodeGen);
2629 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2630 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2631 llvm::Value *Args[] = {RTLoc, ThreadID};
2632
2633 NVPTXActionTy Action(
2634 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2635 Args,
2636 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2637 Args);
2638 RCG.setAction(Action);
2639 RCG(CGF);
2640 };
2641
2642 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002643 // In the worker need to use the real thread id.
2644 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002645 RegionCodeGenTy RCG(CodeGen);
2646 RCG(CGF);
2647 } else {
2648 // If we are not in the target region, it is definitely L2 parallelism or
2649 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2650 // need to check for orphaned directives.
2651 RegionCodeGenTy RCG(SeqGen);
2652 RCG(CGF);
2653 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002654}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002655
Alexey Bataeva3924b52019-01-03 16:25:35 +00002656void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2657 // Always emit simple barriers!
2658 if (!CGF.HaveInsertPoint())
2659 return;
2660 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2661 // This function does not use parameters, so we can emit just default values.
2662 llvm::Value *Args[] = {
2663 llvm::ConstantPointerNull::get(
2664 cast<llvm::PointerType>(getIdentTyPointerTy())),
2665 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2666 CGF.EmitRuntimeCall(
2667 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2668}
2669
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002670void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2671 SourceLocation Loc,
2672 OpenMPDirectiveKind Kind, bool,
2673 bool) {
2674 // Always emit simple barriers!
2675 if (!CGF.HaveInsertPoint())
2676 return;
2677 // Build call __kmpc_cancel_barrier(loc, thread_id);
2678 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2679 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2680 getThreadID(CGF, Loc)};
2681 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2682}
2683
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002684void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2685 CodeGenFunction &CGF, StringRef CriticalName,
2686 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2687 const Expr *Hint) {
2688 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2689 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2690 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2691 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2692 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2693
2694 // Fetch team-local id of the thread.
2695 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2696
2697 // Get the width of the team.
2698 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2699
2700 // Initialize the counter variable for the loop.
2701 QualType Int32Ty =
2702 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2703 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2704 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2705 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2706 /*isInit=*/true);
2707
2708 // Block checks if loop counter exceeds upper bound.
2709 CGF.EmitBlock(LoopBB);
2710 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2711 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2712 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2713
2714 // Block tests which single thread should execute region, and which threads
2715 // should go straight to synchronisation point.
2716 CGF.EmitBlock(TestBB);
2717 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2718 llvm::Value *CmpThreadToCounter =
2719 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2720 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2721
2722 // Block emits the body of the critical region.
2723 CGF.EmitBlock(BodyBB);
2724
2725 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002726 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2727 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002728
2729 // After the body surrounded by the critical region, the single executing
2730 // thread will jump to the synchronisation point.
2731 // Block waits for all threads in current team to finish then increments the
2732 // counter variable and returns to the loop.
2733 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002734 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2735 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002736
2737 llvm::Value *IncCounterVal =
2738 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2739 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2740 CGF.EmitBranch(LoopBB);
2741
2742 // Block that is reached when all threads in the team complete the region.
2743 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2744}
2745
Alexey Bataevb2575932018-01-04 20:18:55 +00002746/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002747static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2748 QualType ValTy, QualType CastTy,
2749 SourceLocation Loc) {
2750 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2751 "Cast type must sized.");
2752 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2753 "Val type must sized.");
2754 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2755 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002756 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002757 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2758 CGF.getContext().getTypeSizeInChars(CastTy))
2759 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2760 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2761 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2762 CastTy->hasSignedIntegerRepresentation());
2763 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002764 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2765 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002766 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2767 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002768}
2769
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002770/// This function creates calls to one of two shuffle functions to copy
2771/// variables between lanes in a warp.
2772static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002773 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002774 QualType ElemType,
2775 llvm::Value *Offset,
2776 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002777 CodeGenModule &CGM = CGF.CGM;
2778 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002779 CGOpenMPRuntimeNVPTX &RT =
2780 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2781
Alexey Bataeva453f362018-03-19 17:53:56 +00002782 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2783 assert(Size.getQuantity() <= 8 &&
2784 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002785
Alexey Bataeva453f362018-03-19 17:53:56 +00002786 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002787 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2788 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2789
2790 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002791 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2792 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2793 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002794 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002795 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002796
Alexey Bataev9ff80832018-04-16 20:16:21 +00002797 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2798 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002799
Alexey Bataeva453f362018-03-19 17:53:56 +00002800 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002801}
2802
Alexey Bataev12c62902018-06-22 19:10:38 +00002803static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2804 Address DestAddr, QualType ElemType,
2805 llvm::Value *Offset, SourceLocation Loc) {
2806 CGBuilderTy &Bld = CGF.Builder;
2807
2808 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2809 // Create the loop over the big sized data.
2810 // ptr = (void*)Elem;
2811 // ptrEnd = (void*) Elem + 1;
2812 // Step = 8;
2813 // while (ptr + Step < ptrEnd)
2814 // shuffle((int64_t)*ptr);
2815 // Step = 4;
2816 // while (ptr + Step < ptrEnd)
2817 // shuffle((int32_t)*ptr);
2818 // ...
2819 Address ElemPtr = DestAddr;
2820 Address Ptr = SrcAddr;
2821 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002822 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002823 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2824 if (Size < CharUnits::fromQuantity(IntSize))
2825 continue;
2826 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2827 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2828 /*Signed=*/1);
2829 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2830 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2831 ElemPtr =
2832 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2833 if (Size.getQuantity() / IntSize > 1) {
2834 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2835 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2836 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2837 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2838 CGF.EmitBlock(PreCondBB);
2839 llvm::PHINode *PhiSrc =
2840 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2841 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2842 llvm::PHINode *PhiDest =
2843 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2844 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2845 Ptr = Address(PhiSrc, Ptr.getAlignment());
2846 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2847 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2848 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2849 Ptr.getPointer(), CGF.VoidPtrTy));
2850 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2851 ThenBB, ExitBB);
2852 CGF.EmitBlock(ThenBB);
2853 llvm::Value *Res = createRuntimeShuffleFunction(
2854 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2855 IntType, Offset, Loc);
2856 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002857 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2858 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002859 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2860 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002861 CGF.EmitBranch(PreCondBB);
2862 CGF.EmitBlock(ExitBB);
2863 } else {
2864 llvm::Value *Res = createRuntimeShuffleFunction(
2865 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2866 IntType, Offset, Loc);
2867 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002868 Ptr = Bld.CreateConstGEP(Ptr, 1);
2869 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002870 }
2871 Size = Size % IntSize;
2872 }
2873}
2874
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002875namespace {
2876enum CopyAction : unsigned {
2877 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2878 // the warp using shuffle instructions.
2879 RemoteLaneToThread,
2880 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2881 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002882 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2883 ThreadToScratchpad,
2884 // ScratchpadToThread: Copy from a scratchpad array in global memory
2885 // containing team-reduced data to a thread's stack.
2886 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002887};
2888} // namespace
2889
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002890struct CopyOptionsTy {
2891 llvm::Value *RemoteLaneOffset;
2892 llvm::Value *ScratchpadIndex;
2893 llvm::Value *ScratchpadWidth;
2894};
2895
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002896/// Emit instructions to copy a Reduce list, which contains partially
2897/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002898static void emitReductionListCopy(
2899 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2900 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2901 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002902
Alexey Bataev9ff80832018-04-16 20:16:21 +00002903 CodeGenModule &CGM = CGF.CGM;
2904 ASTContext &C = CGM.getContext();
2905 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002906
Alexey Bataev9ff80832018-04-16 20:16:21 +00002907 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2908 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2909 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002910
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002911 // Iterates, element-by-element, through the source Reduce list and
2912 // make a copy.
2913 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002914 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002915 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002916 Address SrcElementAddr = Address::invalid();
2917 Address DestElementAddr = Address::invalid();
2918 Address DestElementPtrAddr = Address::invalid();
2919 // Should we shuffle in an element from a remote lane?
2920 bool ShuffleInElement = false;
2921 // Set to true to update the pointer in the dest Reduce list to a
2922 // newly created element.
2923 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002924 // Increment the src or dest pointer to the scratchpad, for each
2925 // new element.
2926 bool IncrScratchpadSrc = false;
2927 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002928
2929 switch (Action) {
2930 case RemoteLaneToThread: {
2931 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002932 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002933 SrcElementAddr = CGF.EmitLoadOfPointer(
2934 SrcElementPtrAddr,
2935 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002936
2937 // Step 1.2: Create a temporary to store the element in the destination
2938 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002939 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002940 DestElementAddr =
2941 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2942 ShuffleInElement = true;
2943 UpdateDestListPtr = true;
2944 break;
2945 }
2946 case ThreadCopy: {
2947 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002948 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002949 SrcElementAddr = CGF.EmitLoadOfPointer(
2950 SrcElementPtrAddr,
2951 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002952
2953 // Step 1.2: Get the address for dest element. The destination
2954 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00002955 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002956 DestElementAddr = CGF.EmitLoadOfPointer(
2957 DestElementPtrAddr,
2958 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002959 break;
2960 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002961 case ThreadToScratchpad: {
2962 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002963 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002964 SrcElementAddr = CGF.EmitLoadOfPointer(
2965 SrcElementPtrAddr,
2966 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002967
2968 // Step 1.2: Get the address for dest element:
2969 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002970 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002971 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002972 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002973 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002974 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002975 ScratchPadElemAbsolutePtrVal =
2976 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002977 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2978 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002979 IncrScratchpadDest = true;
2980 break;
2981 }
2982 case ScratchpadToThread: {
2983 // Step 1.1: Get the address for the src element in the scratchpad.
2984 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00002985 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00002986 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002987 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002988 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00002989 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002990 ScratchPadElemAbsolutePtrVal =
2991 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
2992 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
2993 C.getTypeAlignInChars(Private->getType()));
2994 IncrScratchpadSrc = true;
2995
2996 // Step 1.2: Create a temporary to store the element in the destination
2997 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002998 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002999 DestElementAddr =
3000 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3001 UpdateDestListPtr = true;
3002 break;
3003 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003004 }
3005
3006 // Regardless of src and dest of copy, we emit the load of src
3007 // element as this is required in all directions
3008 SrcElementAddr = Bld.CreateElementBitCast(
3009 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003010 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3011 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003012
3013 // Now that all active lanes have read the element in the
3014 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003015 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003016 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3017 RemoteLaneOffset, Private->getExprLoc());
3018 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003019 switch (CGF.getEvaluationKind(Private->getType())) {
3020 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003021 llvm::Value *Elem =
3022 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3023 Private->getType(), Private->getExprLoc());
3024 // Store the source element value to the dest element address.
3025 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3026 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003027 break;
3028 }
3029 case TEK_Complex: {
3030 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3031 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3032 Private->getExprLoc());
3033 CGF.EmitStoreOfComplex(
3034 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3035 /*isInit=*/false);
3036 break;
3037 }
3038 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003039 CGF.EmitAggregateCopy(
3040 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3041 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3042 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003043 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003044 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003045 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003046
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003047 // Step 3.1: Modify reference in dest Reduce list as needed.
3048 // Modifying the reference in Reduce list to point to the newly
3049 // created element. The element is live in the current function
3050 // scope and that of functions it invokes (i.e., reduce_function).
3051 // RemoteReduceData[i] = (void*)&RemoteElem
3052 if (UpdateDestListPtr) {
3053 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3054 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3055 DestElementPtrAddr, /*Volatile=*/false,
3056 C.VoidPtrTy);
3057 }
3058
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003059 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3060 // address of the next element in scratchpad memory, unless we're currently
3061 // processing the last one. Memory alignment is also taken care of here.
3062 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3063 llvm::Value *ScratchpadBasePtr =
3064 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003065 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3066 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003067 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003068 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003069
3070 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003071 ScratchpadBasePtr = Bld.CreateNUWSub(
3072 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3073 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003074 ScratchpadBasePtr,
3075 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003076 ScratchpadBasePtr = Bld.CreateNUWAdd(
3077 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3078 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003079 ScratchpadBasePtr,
3080 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3081
3082 if (IncrScratchpadDest)
3083 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3084 else /* IncrScratchpadSrc = true */
3085 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3086 }
3087
Alexey Bataev9ff80832018-04-16 20:16:21 +00003088 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003089 }
3090}
3091
3092/// This function emits a helper that gathers Reduce lists from the first
3093/// lane of every active warp to lanes in the first warp.
3094///
3095/// void inter_warp_copy_func(void* reduce_data, num_warps)
3096/// shared smem[warp_size];
3097/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003098/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003099/// If (I am the first lane in each warp)
3100/// Copy my local D to smem[warp_id]
3101/// sync
3102/// if (I am the first warp)
3103/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003104static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3105 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003106 QualType ReductionArrayTy,
3107 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003108 ASTContext &C = CGM.getContext();
3109 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003110
3111 // ReduceList: thread local Reduce list.
3112 // At the stage of the computation when this function is called, partially
3113 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003114 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3115 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003116 // NumWarps: number of warps active in the parallel region. This could
3117 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003118 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003119 C.getIntTypeForBitwidth(32, /* Signed */ true),
3120 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003121 FunctionArgList Args;
3122 Args.push_back(&ReduceListArg);
3123 Args.push_back(&NumWarpsArg);
3124
Alexey Bataev9ff80832018-04-16 20:16:21 +00003125 const CGFunctionInfo &CGFI =
3126 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003127 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3128 llvm::GlobalValue::InternalLinkage,
3129 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003130 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003131 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003132 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003133 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003134
Alexey Bataev9ff80832018-04-16 20:16:21 +00003135 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003136
3137 // This array is used as a medium to transfer, one reduce element at a time,
3138 // the data from the first lane of every warp to lanes in the first warp
3139 // in order to perform the final step of a reduction in a parallel region
3140 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3141 // for reduced latency, as well as to have a distinct copy for concurrently
3142 // executing target regions. The array is declared with common linkage so
3143 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003144 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145 "__openmp_nvptx_data_transfer_temporary_storage";
3146 llvm::GlobalVariable *TransferMedium =
3147 M.getGlobalVariable(TransferMediumName);
3148 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003149 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003150 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3151 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003152 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153 llvm::Constant::getNullValue(Ty), TransferMediumName,
3154 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3155 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003156 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003157 }
3158
3159 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003160 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003162 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003163 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003164 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003165
3166 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3167 Address LocalReduceList(
3168 Bld.CreatePointerBitCastOrAddrSpaceCast(
3169 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003170 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3172 CGF.getPointerAlign());
3173
3174 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003176 //
3177 // Warp master copies reduce element to transfer medium in __shared__
3178 // memory.
3179 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003180 unsigned RealTySize =
3181 C.getTypeSizeInChars(Private->getType())
3182 .alignTo(C.getTypeAlignInChars(Private->getType()))
3183 .getQuantity();
3184 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3185 unsigned NumIters = RealTySize / TySize;
3186 if (NumIters == 0)
3187 continue;
3188 QualType CType = C.getIntTypeForBitwidth(
3189 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3190 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3191 CharUnits Align = CharUnits::fromQuantity(TySize);
3192 llvm::Value *Cnt = nullptr;
3193 Address CntAddr = Address::invalid();
3194 llvm::BasicBlock *PrecondBB = nullptr;
3195 llvm::BasicBlock *ExitBB = nullptr;
3196 if (NumIters > 1) {
3197 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3198 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3199 /*Volatile=*/false, C.IntTy);
3200 PrecondBB = CGF.createBasicBlock("precond");
3201 ExitBB = CGF.createBasicBlock("exit");
3202 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3203 // There is no need to emit line number for unconditional branch.
3204 (void)ApplyDebugLocation::CreateEmpty(CGF);
3205 CGF.EmitBlock(PrecondBB);
3206 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3207 llvm::Value *Cmp =
3208 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3209 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3210 CGF.EmitBlock(BodyBB);
3211 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003212 // kmpc_barrier.
3213 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3214 /*EmitChecks=*/false,
3215 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003216 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3217 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3218 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003219
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003220 // if (lane_id == 0)
3221 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3222 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3223 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003224
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003225 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003226 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003227 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3228 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3229 // elemptr = ((CopyType*)(elemptrptr)) + I
3230 Address ElemPtr = Address(ElemPtrPtr, Align);
3231 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3232 if (NumIters > 1) {
3233 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3234 ElemPtr.getAlignment());
3235 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003236
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003237 // Get pointer to location in transfer medium.
3238 // MediumPtr = &medium[warp_id]
3239 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3240 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3241 Address MediumPtr(MediumPtrVal, Align);
3242 // Casting to actual data type.
3243 // MediumPtr = (CopyType*)MediumPtrAddr;
3244 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003245
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003246 // elem = *elemptr
3247 //*MediumPtr = elem
3248 llvm::Value *Elem =
3249 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003250 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003251 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003252
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003253 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003254
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003255 CGF.EmitBlock(ElseBB);
3256 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003257
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003258 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003259
Alexey Bataevae51b962018-12-14 21:00:58 +00003260 // kmpc_barrier.
3261 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3262 /*EmitChecks=*/false,
3263 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003264
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003265 //
3266 // Warp 0 copies reduce element from transfer medium.
3267 //
3268 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3269 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3270 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003271
Alexey Bataevae51b962018-12-14 21:00:58 +00003272 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3273 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3274 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3275
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 // Up to 32 threads in warp 0 are active.
3277 llvm::Value *IsActiveThread =
3278 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3279 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003280
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003281 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003282
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003283 // SrcMediumPtr = &medium[tid]
3284 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3285 TransferMedium,
3286 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3287 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3288 // SrcMediumVal = *SrcMediumPtr;
3289 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003290
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003291 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003292 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003293 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3294 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3295 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3296 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3297 if (NumIters > 1) {
3298 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3299 TargetElemPtr.getAlignment());
3300 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003301
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003302 // *TargetElemPtr = SrcMediumVal;
3303 llvm::Value *SrcMediumValue =
3304 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003305 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003306 CType);
3307 Bld.CreateBr(W0MergeBB);
3308
3309 CGF.EmitBlock(W0ElseBB);
3310 Bld.CreateBr(W0MergeBB);
3311
3312 CGF.EmitBlock(W0MergeBB);
3313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 if (NumIters > 1) {
3315 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3316 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3317 CGF.EmitBranch(PrecondBB);
3318 (void)ApplyDebugLocation::CreateEmpty(CGF);
3319 CGF.EmitBlock(ExitBB);
3320 }
3321 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003322 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003323 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003324 }
3325
3326 CGF.FinishFunction();
3327 return Fn;
3328}
3329
3330/// Emit a helper that reduces data across two OpenMP threads (lanes)
3331/// in the same warp. It uses shuffle instructions to copy over data from
3332/// a remote lane's stack. The reduction algorithm performed is specified
3333/// by the fourth parameter.
3334///
3335/// Algorithm Versions.
3336/// Full Warp Reduce (argument value 0):
3337/// This algorithm assumes that all 32 lanes are active and gathers
3338/// data from these 32 lanes, producing a single resultant value.
3339/// Contiguous Partial Warp Reduce (argument value 1):
3340/// This algorithm assumes that only a *contiguous* subset of lanes
3341/// are active. This happens for the last warp in a parallel region
3342/// when the user specified num_threads is not an integer multiple of
3343/// 32. This contiguous subset always starts with the zeroth lane.
3344/// Partial Warp Reduce (argument value 2):
3345/// This algorithm gathers data from any number of lanes at any position.
3346/// All reduced values are stored in the lowest possible lane. The set
3347/// of problems every algorithm addresses is a super set of those
3348/// addressable by algorithms with a lower version number. Overhead
3349/// increases as algorithm version increases.
3350///
3351/// Terminology
3352/// Reduce element:
3353/// Reduce element refers to the individual data field with primitive
3354/// data types to be combined and reduced across threads.
3355/// Reduce list:
3356/// Reduce list refers to a collection of local, thread-private
3357/// reduce elements.
3358/// Remote Reduce list:
3359/// Remote Reduce list refers to a collection of remote (relative to
3360/// the current thread) reduce elements.
3361///
3362/// We distinguish between three states of threads that are important to
3363/// the implementation of this function.
3364/// Alive threads:
3365/// Threads in a warp executing the SIMT instruction, as distinguished from
3366/// threads that are inactive due to divergent control flow.
3367/// Active threads:
3368/// The minimal set of threads that has to be alive upon entry to this
3369/// function. The computation is correct iff active threads are alive.
3370/// Some threads are alive but they are not active because they do not
3371/// contribute to the computation in any useful manner. Turning them off
3372/// may introduce control flow overheads without any tangible benefits.
3373/// Effective threads:
3374/// In order to comply with the argument requirements of the shuffle
3375/// function, we must keep all lanes holding data alive. But at most
3376/// half of them perform value aggregation; we refer to this half of
3377/// threads as effective. The other half is simply handing off their
3378/// data.
3379///
3380/// Procedure
3381/// Value shuffle:
3382/// In this step active threads transfer data from higher lane positions
3383/// in the warp to lower lane positions, creating Remote Reduce list.
3384/// Value aggregation:
3385/// In this step, effective threads combine their thread local Reduce list
3386/// with Remote Reduce list and store the result in the thread local
3387/// Reduce list.
3388/// Value copy:
3389/// In this step, we deal with the assumption made by algorithm 2
3390/// (i.e. contiguity assumption). When we have an odd number of lanes
3391/// active, say 2k+1, only k threads will be effective and therefore k
3392/// new values will be produced. However, the Reduce list owned by the
3393/// (2k+1)th thread is ignored in the value aggregation. Therefore
3394/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3395/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003396static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003397 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003398 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003399 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003400
3401 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003402 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3403 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003404 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003405 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3406 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003407 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003408 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3409 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003410 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003411 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3412 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003413 FunctionArgList Args;
3414 Args.push_back(&ReduceListArg);
3415 Args.push_back(&LaneIDArg);
3416 Args.push_back(&RemoteLaneOffsetArg);
3417 Args.push_back(&AlgoVerArg);
3418
Alexey Bataev9ff80832018-04-16 20:16:21 +00003419 const CGFunctionInfo &CGFI =
3420 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003421 auto *Fn = llvm::Function::Create(
3422 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3423 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003424 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003425 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003426 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003427 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003428
Alexey Bataev9ff80832018-04-16 20:16:21 +00003429 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003430
3431 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3432 Address LocalReduceList(
3433 Bld.CreatePointerBitCastOrAddrSpaceCast(
3434 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3435 C.VoidPtrTy, SourceLocation()),
3436 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3437 CGF.getPointerAlign());
3438
3439 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3440 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3441 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3442
3443 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3444 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3445 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3446
3447 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3448 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3449 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3450
3451 // Create a local thread-private variable to host the Reduce list
3452 // from a remote lane.
3453 Address RemoteReduceList =
3454 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3455
3456 // This loop iterates through the list of reduce elements and copies,
3457 // element by element, from a remote lane in the warp to RemoteReduceList,
3458 // hosted on the thread's stack.
3459 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3460 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003461 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3462 /*ScratchpadIndex=*/nullptr,
3463 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003464
3465 // The actions to be performed on the Remote Reduce list is dependent
3466 // on the algorithm version.
3467 //
3468 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3469 // LaneId % 2 == 0 && Offset > 0):
3470 // do the reduction value aggregation
3471 //
3472 // The thread local variable Reduce list is mutated in place to host the
3473 // reduced data, which is the aggregated value produced from local and
3474 // remote lanes.
3475 //
3476 // Note that AlgoVer is expected to be a constant integer known at compile
3477 // time.
3478 // When AlgoVer==0, the first conjunction evaluates to true, making
3479 // the entire predicate true during compile time.
3480 // When AlgoVer==1, the second conjunction has only the second part to be
3481 // evaluated during runtime. Other conjunctions evaluates to false
3482 // during compile time.
3483 // When AlgoVer==2, the third conjunction has only the second part to be
3484 // evaluated during runtime. Other conjunctions evaluates to false
3485 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003486 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003487
Alexey Bataev9ff80832018-04-16 20:16:21 +00003488 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3489 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003490 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3491
Alexey Bataev9ff80832018-04-16 20:16:21 +00003492 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3493 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3494 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003495 CondAlgo2 = Bld.CreateAnd(
3496 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3497
Alexey Bataev9ff80832018-04-16 20:16:21 +00003498 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003499 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3500
3501 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3502 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3503 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3504 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3505
3506 CGF.EmitBlock(ThenBB);
3507 // reduce_function(LocalReduceList, RemoteReduceList)
3508 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3509 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3510 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3511 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003512 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3513 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003514 Bld.CreateBr(MergeBB);
3515
3516 CGF.EmitBlock(ElseBB);
3517 Bld.CreateBr(MergeBB);
3518
3519 CGF.EmitBlock(MergeBB);
3520
3521 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3522 // Reduce list.
3523 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003524 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003525 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3526
3527 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3528 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3529 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3530 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3531
3532 CGF.EmitBlock(CpyThenBB);
3533 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3534 RemoteReduceList, LocalReduceList);
3535 Bld.CreateBr(CpyMergeBB);
3536
3537 CGF.EmitBlock(CpyElseBB);
3538 Bld.CreateBr(CpyMergeBB);
3539
3540 CGF.EmitBlock(CpyMergeBB);
3541
3542 CGF.FinishFunction();
3543 return Fn;
3544}
3545
Alexey Bataev8061acd2019-02-20 16:36:22 +00003546/// This function emits a helper that copies all the reduction variables from
3547/// the team into the provided global buffer for the reduction variables.
3548///
3549/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3550/// For all data entries D in reduce_data:
3551/// Copy local D to buffer.D[Idx]
3552static llvm::Value *emitListToGlobalCopyFunction(
3553 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3554 QualType ReductionArrayTy, SourceLocation Loc,
3555 const RecordDecl *TeamReductionRec,
3556 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3557 &VarFieldMap) {
3558 ASTContext &C = CGM.getContext();
3559
3560 // Buffer: global reduction buffer.
3561 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3562 C.VoidPtrTy, ImplicitParamDecl::Other);
3563 // Idx: index of the buffer.
3564 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3565 ImplicitParamDecl::Other);
3566 // ReduceList: thread local Reduce list.
3567 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3568 C.VoidPtrTy, ImplicitParamDecl::Other);
3569 FunctionArgList Args;
3570 Args.push_back(&BufferArg);
3571 Args.push_back(&IdxArg);
3572 Args.push_back(&ReduceListArg);
3573
3574 const CGFunctionInfo &CGFI =
3575 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3576 auto *Fn = llvm::Function::Create(
3577 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3578 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3579 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3580 Fn->setDoesNotRecurse();
3581 CodeGenFunction CGF(CGM);
3582 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3583
3584 CGBuilderTy &Bld = CGF.Builder;
3585
3586 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3587 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3588 Address LocalReduceList(
3589 Bld.CreatePointerBitCastOrAddrSpaceCast(
3590 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3591 C.VoidPtrTy, Loc),
3592 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3593 CGF.getPointerAlign());
3594 QualType StaticTy = C.getRecordType(TeamReductionRec);
3595 llvm::Type *LLVMReductionsBufferTy =
3596 CGM.getTypes().ConvertTypeForMem(StaticTy);
3597 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3598 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3599 LLVMReductionsBufferTy->getPointerTo());
3600 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3601 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3602 /*Volatile=*/false, C.IntTy,
3603 Loc)};
3604 unsigned Idx = 0;
3605 for (const Expr *Private : Privates) {
3606 // Reduce element = LocalReduceList[i]
3607 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3608 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3609 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3610 // elemptr = ((CopyType*)(elemptrptr)) + I
3611 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3612 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3613 Address ElemPtr =
3614 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3615 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3616 // Global = Buffer.VD[Idx];
3617 const FieldDecl *FD = VarFieldMap.lookup(VD);
3618 LValue GlobLVal = CGF.EmitLValueForField(
3619 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3620 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3621 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3622 switch (CGF.getEvaluationKind(Private->getType())) {
3623 case TEK_Scalar: {
3624 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3625 Private->getType(), Loc);
3626 CGF.EmitStoreOfScalar(V, GlobLVal);
3627 break;
3628 }
3629 case TEK_Complex: {
3630 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3631 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3632 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3633 break;
3634 }
3635 case TEK_Aggregate:
3636 CGF.EmitAggregateCopy(GlobLVal,
3637 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3638 Private->getType(), AggValueSlot::DoesNotOverlap);
3639 break;
3640 }
3641 ++Idx;
3642 }
3643
3644 CGF.FinishFunction();
3645 return Fn;
3646}
3647
3648/// This function emits a helper that reduces all the reduction variables from
3649/// the team into the provided global buffer for the reduction variables.
3650///
3651/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3652/// void *GlobPtrs[];
3653/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3654/// ...
3655/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3656/// reduce_function(GlobPtrs, reduce_data);
3657static llvm::Value *emitListToGlobalReduceFunction(
3658 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3659 QualType ReductionArrayTy, SourceLocation Loc,
3660 const RecordDecl *TeamReductionRec,
3661 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3662 &VarFieldMap,
3663 llvm::Function *ReduceFn) {
3664 ASTContext &C = CGM.getContext();
3665
3666 // Buffer: global reduction buffer.
3667 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3668 C.VoidPtrTy, ImplicitParamDecl::Other);
3669 // Idx: index of the buffer.
3670 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3671 ImplicitParamDecl::Other);
3672 // ReduceList: thread local Reduce list.
3673 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3674 C.VoidPtrTy, ImplicitParamDecl::Other);
3675 FunctionArgList Args;
3676 Args.push_back(&BufferArg);
3677 Args.push_back(&IdxArg);
3678 Args.push_back(&ReduceListArg);
3679
3680 const CGFunctionInfo &CGFI =
3681 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3682 auto *Fn = llvm::Function::Create(
3683 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3684 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3685 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3686 Fn->setDoesNotRecurse();
3687 CodeGenFunction CGF(CGM);
3688 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3689
3690 CGBuilderTy &Bld = CGF.Builder;
3691
3692 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3693 QualType StaticTy = C.getRecordType(TeamReductionRec);
3694 llvm::Type *LLVMReductionsBufferTy =
3695 CGM.getTypes().ConvertTypeForMem(StaticTy);
3696 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3697 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3698 LLVMReductionsBufferTy->getPointerTo());
3699
3700 // 1. Build a list of reduction variables.
3701 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3702 Address ReductionList =
3703 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3704 auto IPriv = Privates.begin();
3705 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3706 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3707 /*Volatile=*/false, C.IntTy,
3708 Loc)};
3709 unsigned Idx = 0;
3710 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3711 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3712 // Global = Buffer.VD[Idx];
3713 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3714 const FieldDecl *FD = VarFieldMap.lookup(VD);
3715 LValue GlobLVal = CGF.EmitLValueForField(
3716 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3717 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3718 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3719 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3720 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3721 // Store array size.
3722 ++Idx;
3723 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3724 llvm::Value *Size = CGF.Builder.CreateIntCast(
3725 CGF.getVLASize(
3726 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3727 .NumElts,
3728 CGF.SizeTy, /*isSigned=*/false);
3729 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3730 Elem);
3731 }
3732 }
3733
3734 // Call reduce_function(GlobalReduceList, ReduceList)
3735 llvm::Value *GlobalReduceList =
3736 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3737 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3738 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3739 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3740 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3741 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3742 CGF.FinishFunction();
3743 return Fn;
3744}
3745
3746/// This function emits a helper that copies all the reduction variables from
3747/// the team into the provided global buffer for the reduction variables.
3748///
3749/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3750/// For all data entries D in reduce_data:
3751/// Copy buffer.D[Idx] to local D;
3752static llvm::Value *emitGlobalToListCopyFunction(
3753 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3754 QualType ReductionArrayTy, SourceLocation Loc,
3755 const RecordDecl *TeamReductionRec,
3756 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3757 &VarFieldMap) {
3758 ASTContext &C = CGM.getContext();
3759
3760 // Buffer: global reduction buffer.
3761 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3762 C.VoidPtrTy, ImplicitParamDecl::Other);
3763 // Idx: index of the buffer.
3764 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3765 ImplicitParamDecl::Other);
3766 // ReduceList: thread local Reduce list.
3767 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3768 C.VoidPtrTy, ImplicitParamDecl::Other);
3769 FunctionArgList Args;
3770 Args.push_back(&BufferArg);
3771 Args.push_back(&IdxArg);
3772 Args.push_back(&ReduceListArg);
3773
3774 const CGFunctionInfo &CGFI =
3775 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3776 auto *Fn = llvm::Function::Create(
3777 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3778 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3779 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3780 Fn->setDoesNotRecurse();
3781 CodeGenFunction CGF(CGM);
3782 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3783
3784 CGBuilderTy &Bld = CGF.Builder;
3785
3786 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3787 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3788 Address LocalReduceList(
3789 Bld.CreatePointerBitCastOrAddrSpaceCast(
3790 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3791 C.VoidPtrTy, Loc),
3792 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3793 CGF.getPointerAlign());
3794 QualType StaticTy = C.getRecordType(TeamReductionRec);
3795 llvm::Type *LLVMReductionsBufferTy =
3796 CGM.getTypes().ConvertTypeForMem(StaticTy);
3797 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3798 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3799 LLVMReductionsBufferTy->getPointerTo());
3800
3801 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3802 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3803 /*Volatile=*/false, C.IntTy,
3804 Loc)};
3805 unsigned Idx = 0;
3806 for (const Expr *Private : Privates) {
3807 // Reduce element = LocalReduceList[i]
3808 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3809 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3810 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3811 // elemptr = ((CopyType*)(elemptrptr)) + I
3812 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3813 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3814 Address ElemPtr =
3815 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3816 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3817 // Global = Buffer.VD[Idx];
3818 const FieldDecl *FD = VarFieldMap.lookup(VD);
3819 LValue GlobLVal = CGF.EmitLValueForField(
3820 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3821 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3822 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3823 switch (CGF.getEvaluationKind(Private->getType())) {
3824 case TEK_Scalar: {
3825 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3826 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3827 break;
3828 }
3829 case TEK_Complex: {
3830 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3831 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3832 /*isInit=*/false);
3833 break;
3834 }
3835 case TEK_Aggregate:
3836 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3837 GlobLVal, Private->getType(),
3838 AggValueSlot::DoesNotOverlap);
3839 break;
3840 }
3841 ++Idx;
3842 }
3843
3844 CGF.FinishFunction();
3845 return Fn;
3846}
3847
3848/// This function emits a helper that reduces all the reduction variables from
3849/// the team into the provided global buffer for the reduction variables.
3850///
3851/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3852/// void *GlobPtrs[];
3853/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3854/// ...
3855/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3856/// reduce_function(reduce_data, GlobPtrs);
3857static llvm::Value *emitGlobalToListReduceFunction(
3858 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3859 QualType ReductionArrayTy, SourceLocation Loc,
3860 const RecordDecl *TeamReductionRec,
3861 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3862 &VarFieldMap,
3863 llvm::Function *ReduceFn) {
3864 ASTContext &C = CGM.getContext();
3865
3866 // Buffer: global reduction buffer.
3867 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3868 C.VoidPtrTy, ImplicitParamDecl::Other);
3869 // Idx: index of the buffer.
3870 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3871 ImplicitParamDecl::Other);
3872 // ReduceList: thread local Reduce list.
3873 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3874 C.VoidPtrTy, ImplicitParamDecl::Other);
3875 FunctionArgList Args;
3876 Args.push_back(&BufferArg);
3877 Args.push_back(&IdxArg);
3878 Args.push_back(&ReduceListArg);
3879
3880 const CGFunctionInfo &CGFI =
3881 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3882 auto *Fn = llvm::Function::Create(
3883 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3884 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3885 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3886 Fn->setDoesNotRecurse();
3887 CodeGenFunction CGF(CGM);
3888 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3889
3890 CGBuilderTy &Bld = CGF.Builder;
3891
3892 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3893 QualType StaticTy = C.getRecordType(TeamReductionRec);
3894 llvm::Type *LLVMReductionsBufferTy =
3895 CGM.getTypes().ConvertTypeForMem(StaticTy);
3896 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3897 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3898 LLVMReductionsBufferTy->getPointerTo());
3899
3900 // 1. Build a list of reduction variables.
3901 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3902 Address ReductionList =
3903 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3904 auto IPriv = Privates.begin();
3905 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3906 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3907 /*Volatile=*/false, C.IntTy,
3908 Loc)};
3909 unsigned Idx = 0;
3910 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3911 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3912 // Global = Buffer.VD[Idx];
3913 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3914 const FieldDecl *FD = VarFieldMap.lookup(VD);
3915 LValue GlobLVal = CGF.EmitLValueForField(
3916 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3917 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3918 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3919 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3920 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3921 // Store array size.
3922 ++Idx;
3923 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3924 llvm::Value *Size = CGF.Builder.CreateIntCast(
3925 CGF.getVLASize(
3926 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3927 .NumElts,
3928 CGF.SizeTy, /*isSigned=*/false);
3929 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3930 Elem);
3931 }
3932 }
3933
3934 // Call reduce_function(ReduceList, GlobalReduceList)
3935 llvm::Value *GlobalReduceList =
3936 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3937 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3938 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3939 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3940 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3941 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3942 CGF.FinishFunction();
3943 return Fn;
3944}
3945
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003946///
3947/// Design of OpenMP reductions on the GPU
3948///
3949/// Consider a typical OpenMP program with one or more reduction
3950/// clauses:
3951///
3952/// float foo;
3953/// double bar;
3954/// #pragma omp target teams distribute parallel for \
3955/// reduction(+:foo) reduction(*:bar)
3956/// for (int i = 0; i < N; i++) {
3957/// foo += A[i]; bar *= B[i];
3958/// }
3959///
3960/// where 'foo' and 'bar' are reduced across all OpenMP threads in
3961/// all teams. In our OpenMP implementation on the NVPTX device an
3962/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
3963/// within a team are mapped to CUDA threads within a threadblock.
3964/// Our goal is to efficiently aggregate values across all OpenMP
3965/// threads such that:
3966///
3967/// - the compiler and runtime are logically concise, and
3968/// - the reduction is performed efficiently in a hierarchical
3969/// manner as follows: within OpenMP threads in the same warp,
3970/// across warps in a threadblock, and finally across teams on
3971/// the NVPTX device.
3972///
3973/// Introduction to Decoupling
3974///
3975/// We would like to decouple the compiler and the runtime so that the
3976/// latter is ignorant of the reduction variables (number, data types)
3977/// and the reduction operators. This allows a simpler interface
3978/// and implementation while still attaining good performance.
3979///
3980/// Pseudocode for the aforementioned OpenMP program generated by the
3981/// compiler is as follows:
3982///
3983/// 1. Create private copies of reduction variables on each OpenMP
3984/// thread: 'foo_private', 'bar_private'
3985/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
3986/// to it and writes the result in 'foo_private' and 'bar_private'
3987/// respectively.
3988/// 3. Call the OpenMP runtime on the GPU to reduce within a team
3989/// and store the result on the team master:
3990///
Alexey Bataev8e009032019-01-04 17:25:09 +00003991/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003992/// reduceData, shuffleReduceFn, interWarpCpyFn)
3993///
3994/// where:
3995/// struct ReduceData {
3996/// double *foo;
3997/// double *bar;
3998/// } reduceData
3999/// reduceData.foo = &foo_private
4000/// reduceData.bar = &bar_private
4001///
4002/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4003/// auxiliary functions generated by the compiler that operate on
4004/// variables of type 'ReduceData'. They aid the runtime perform
4005/// algorithmic steps in a data agnostic manner.
4006///
4007/// 'shuffleReduceFn' is a pointer to a function that reduces data
4008/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4009/// same warp. It takes the following arguments as input:
4010///
4011/// a. variable of type 'ReduceData' on the calling lane,
4012/// b. its lane_id,
4013/// c. an offset relative to the current lane_id to generate a
4014/// remote_lane_id. The remote lane contains the second
4015/// variable of type 'ReduceData' that is to be reduced.
4016/// d. an algorithm version parameter determining which reduction
4017/// algorithm to use.
4018///
4019/// 'shuffleReduceFn' retrieves data from the remote lane using
4020/// efficient GPU shuffle intrinsics and reduces, using the
4021/// algorithm specified by the 4th parameter, the two operands
4022/// element-wise. The result is written to the first operand.
4023///
4024/// Different reduction algorithms are implemented in different
4025/// runtime functions, all calling 'shuffleReduceFn' to perform
4026/// the essential reduction step. Therefore, based on the 4th
4027/// parameter, this function behaves slightly differently to
4028/// cooperate with the runtime to ensure correctness under
4029/// different circumstances.
4030///
4031/// 'InterWarpCpyFn' is a pointer to a function that transfers
4032/// reduced variables across warps. It tunnels, through CUDA
4033/// shared memory, the thread-private data of type 'ReduceData'
4034/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004035/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4036/// The last team writes the global reduced value to memory.
4037///
4038/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4039/// reduceData, shuffleReduceFn, interWarpCpyFn,
4040/// scratchpadCopyFn, loadAndReduceFn)
4041///
4042/// 'scratchpadCopyFn' is a helper that stores reduced
4043/// data from the team master to a scratchpad array in
4044/// global memory.
4045///
4046/// 'loadAndReduceFn' is a helper that loads data from
4047/// the scratchpad array and reduces it with the input
4048/// operand.
4049///
4050/// These compiler generated functions hide address
4051/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004052/// 5. if ret == 1:
4053/// The team master of the last team stores the reduced
4054/// result to the globals in memory.
4055/// foo += reduceData.foo; bar *= reduceData.bar
4056///
4057///
4058/// Warp Reduction Algorithms
4059///
4060/// On the warp level, we have three algorithms implemented in the
4061/// OpenMP runtime depending on the number of active lanes:
4062///
4063/// Full Warp Reduction
4064///
4065/// The reduce algorithm within a warp where all lanes are active
4066/// is implemented in the runtime as follows:
4067///
4068/// full_warp_reduce(void *reduce_data,
4069/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4070/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4071/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4072/// }
4073///
4074/// The algorithm completes in log(2, WARPSIZE) steps.
4075///
4076/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4077/// not used therefore we save instructions by not retrieving lane_id
4078/// from the corresponding special registers. The 4th parameter, which
4079/// represents the version of the algorithm being used, is set to 0 to
4080/// signify full warp reduction.
4081///
4082/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4083///
4084/// #reduce_elem refers to an element in the local lane's data structure
4085/// #remote_elem is retrieved from a remote lane
4086/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4087/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4088///
4089/// Contiguous Partial Warp Reduction
4090///
4091/// This reduce algorithm is used within a warp where only the first
4092/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4093/// number of OpenMP threads in a parallel region is not a multiple of
4094/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4095///
4096/// void
4097/// contiguous_partial_reduce(void *reduce_data,
4098/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4099/// int size, int lane_id) {
4100/// int curr_size;
4101/// int offset;
4102/// curr_size = size;
4103/// mask = curr_size/2;
4104/// while (offset>0) {
4105/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4106/// curr_size = (curr_size+1)/2;
4107/// offset = curr_size/2;
4108/// }
4109/// }
4110///
4111/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4112///
4113/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4114/// if (lane_id < offset)
4115/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4116/// else
4117/// reduce_elem = remote_elem
4118///
4119/// This algorithm assumes that the data to be reduced are located in a
4120/// contiguous subset of lanes starting from the first. When there is
4121/// an odd number of active lanes, the data in the last lane is not
4122/// aggregated with any other lane's dat but is instead copied over.
4123///
4124/// Dispersed Partial Warp Reduction
4125///
4126/// This algorithm is used within a warp when any discontiguous subset of
4127/// lanes are active. It is used to implement the reduction operation
4128/// across lanes in an OpenMP simd region or in a nested parallel region.
4129///
4130/// void
4131/// dispersed_partial_reduce(void *reduce_data,
4132/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4133/// int size, remote_id;
4134/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4135/// do {
4136/// remote_id = next_active_lane_id_right_after_me();
4137/// # the above function returns 0 of no active lane
4138/// # is present right after the current lane.
4139/// size = number_of_active_lanes_in_this_warp();
4140/// logical_lane_id /= 2;
4141/// ShuffleReduceFn(reduce_data, logical_lane_id,
4142/// remote_id-1-threadIdx.x, 2);
4143/// } while (logical_lane_id % 2 == 0 && size > 1);
4144/// }
4145///
4146/// There is no assumption made about the initial state of the reduction.
4147/// Any number of lanes (>=1) could be active at any position. The reduction
4148/// result is returned in the first active lane.
4149///
4150/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4151///
4152/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4153/// if (lane_id % 2 == 0 && offset > 0)
4154/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4155/// else
4156/// reduce_elem = remote_elem
4157///
4158///
4159/// Intra-Team Reduction
4160///
4161/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004162/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004163/// threads in a team. It first reduces within a warp using the
4164/// aforementioned algorithms. We then proceed to gather all such
4165/// reduced values at the first warp.
4166///
4167/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4168/// data from each of the "warp master" (zeroth lane of each warp, where
4169/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4170/// a mathematical sense) the problem of reduction across warp masters in
4171/// a block to the problem of warp reduction.
4172///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004173///
4174/// Inter-Team Reduction
4175///
4176/// Once a team has reduced its data to a single value, it is stored in
4177/// a global scratchpad array. Since each team has a distinct slot, this
4178/// can be done without locking.
4179///
4180/// The last team to write to the scratchpad array proceeds to reduce the
4181/// scratchpad array. One or more workers in the last team use the helper
4182/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4183/// the k'th worker reduces every k'th element.
4184///
Alexey Bataev8e009032019-01-04 17:25:09 +00004185/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004186/// reduce across workers and compute a globally reduced value.
4187///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004188void CGOpenMPRuntimeNVPTX::emitReduction(
4189 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4190 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4191 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4192 if (!CGF.HaveInsertPoint())
4193 return;
4194
4195 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004196#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004197 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004198#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004199
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004200 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004201 assert(!TeamsReduction && !ParallelReduction &&
4202 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004203 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4204 ReductionOps, Options);
4205 return;
4206 }
4207
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004208 assert((TeamsReduction || ParallelReduction) &&
4209 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004210
Alexey Bataeva1166022018-11-27 21:24:54 +00004211 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004212 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004213 // or
4214 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004215 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004216 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004217
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004218 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004219 ASTContext &C = CGM.getContext();
4220 // 1. Build a list of reduction variables.
4221 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4222 auto Size = RHSExprs.size();
4223 for (const Expr *E : Privates) {
4224 if (E->getType()->isVariablyModifiedType())
4225 // Reserve place for array size.
4226 ++Size;
4227 }
4228 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4229 QualType ReductionArrayTy =
4230 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4231 /*IndexTypeQuals=*/0);
4232 Address ReductionList =
4233 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4234 auto IPriv = Privates.begin();
4235 unsigned Idx = 0;
4236 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4237 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4238 CGF.Builder.CreateStore(
4239 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4240 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4241 Elem);
4242 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4243 // Store array size.
4244 ++Idx;
4245 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4246 llvm::Value *Size = CGF.Builder.CreateIntCast(
4247 CGF.getVLASize(
4248 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4249 .NumElts,
4250 CGF.SizeTy, /*isSigned=*/false);
4251 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4252 Elem);
4253 }
4254 }
4255
4256 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4257 ReductionList.getPointer(), CGF.VoidPtrTy);
4258 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004259 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4260 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004261 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4262 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4263 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4264 llvm::Value *InterWarpCopyFn =
4265 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4266
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004267 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004268 llvm::Value *Args[] = {RTLoc,
4269 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004270 CGF.Builder.getInt32(RHSExprs.size()),
4271 ReductionArrayTySize,
4272 RL,
4273 ShuffleAndReduceFn,
4274 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004275
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004276 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004277 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004278 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4279 Args);
4280 } else {
4281 assert(TeamsReduction && "expected teams reduction.");
4282 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4283 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4284 int Cnt = 0;
4285 for (const Expr *DRE : Privates) {
4286 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4287 ++Cnt;
4288 }
4289 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4290 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4291 C.getLangOpts().OpenMPCUDAReductionBufNum);
4292 TeamsReductions.push_back(TeamReductionRec);
4293 if (!KernelTeamsReductionPtr) {
4294 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4295 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4296 llvm::GlobalValue::InternalLinkage, nullptr,
4297 "_openmp_teams_reductions_buffer_$_$ptr");
4298 }
4299 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4300 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4301 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4302 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4303 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4304 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4305 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4306 ReductionFn);
4307 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4308 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4309 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4310 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4311 ReductionFn);
4312
4313 llvm::Value *Args[] = {
4314 RTLoc,
4315 ThreadId,
4316 GlobalBufferPtr,
4317 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4318 RL,
4319 ShuffleAndReduceFn,
4320 InterWarpCopyFn,
4321 GlobalToBufferCpyFn,
4322 GlobalToBufferRedFn,
4323 BufferToGlobalCpyFn,
4324 BufferToGlobalRedFn};
4325
4326 Res = CGF.EmitRuntimeCall(
4327 createNVPTXRuntimeFunction(
4328 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004329 Args);
4330 }
4331
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004332 // 5. Build if (res == 1)
4333 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4334 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4335 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4336 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4337 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004338
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004339 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004340 // thread in each team.
4341 // __kmpc_end_reduce{_nowait}(<gtid>);
4342 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004343 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004344
4345 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004346 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004347 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4348 auto IPriv = Privates.begin();
4349 auto ILHS = LHSExprs.begin();
4350 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004351 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004352 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4353 cast<DeclRefExpr>(*IRHS));
4354 ++IPriv;
4355 ++ILHS;
4356 ++IRHS;
4357 }
4358 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004359 llvm::Value *EndArgs[] = {ThreadId};
4360 RegionCodeGenTy RCG(CodeGen);
4361 NVPTXActionTy Action(
4362 nullptr, llvm::None,
4363 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4364 EndArgs);
4365 RCG.setAction(Action);
4366 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004367 // There is no need to emit line number for unconditional branch.
4368 (void)ApplyDebugLocation::CreateEmpty(CGF);
4369 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004370}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004371
4372const VarDecl *
4373CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4374 const VarDecl *NativeParam) const {
4375 if (!NativeParam->getType()->isReferenceType())
4376 return NativeParam;
4377 QualType ArgType = NativeParam->getType();
4378 QualifierCollector QC;
4379 const Type *NonQualTy = QC.strip(ArgType);
4380 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4381 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4382 if (Attr->getCaptureKind() == OMPC_map) {
4383 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4384 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004385 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4386 PointeeTy.isConstant(CGM.getContext())) {
4387 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4388 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004389 }
4390 }
4391 ArgType = CGM.getContext().getPointerType(PointeeTy);
4392 QC.addRestrict();
4393 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004394 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004395 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004396 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004397 return ImplicitParamDecl::Create(
4398 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4399 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004400 return ParmVarDecl::Create(
4401 CGM.getContext(),
4402 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004403 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004404 NativeParam->getIdentifier(), ArgType,
4405 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004406}
4407
4408Address
4409CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4410 const VarDecl *NativeParam,
4411 const VarDecl *TargetParam) const {
4412 assert(NativeParam != TargetParam &&
4413 NativeParam->getType()->isReferenceType() &&
4414 "Native arg must not be the same as target arg.");
4415 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4416 QualType NativeParamType = NativeParam->getType();
4417 QualifierCollector QC;
4418 const Type *NonQualTy = QC.strip(NativeParamType);
4419 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4420 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004421 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004422 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004423 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004424 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004425 // First cast to generic.
4426 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4427 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4428 /*AddrSpace=*/0));
4429 // Cast from generic to native address space.
4430 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4431 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4432 NativePointeeAddrSpace));
4433 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4434 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004435 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004436 return NativeParamAddr;
4437}
4438
4439void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004440 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004441 ArrayRef<llvm::Value *> Args) const {
4442 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004443 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004444 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004445 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004446 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4447 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4448 break;
4449 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004450 llvm::Type *TargetType = FnType->getParamType(I);
4451 llvm::Value *NativeArg = Args[I];
4452 if (!TargetType->isPointerTy()) {
4453 TargetArgs.emplace_back(NativeArg);
4454 continue;
4455 }
4456 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004457 NativeArg,
4458 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004459 TargetArgs.emplace_back(
4460 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4461 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004462 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004463}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004464
4465/// Emit function which wraps the outline parallel region
4466/// and controls the arguments which are passed to this function.
4467/// The wrapper ensures that the outlined function is called
4468/// with the correct arguments when data is shared.
4469llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4470 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4471 ASTContext &Ctx = CGM.getContext();
4472 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4473
4474 // Create a function that takes as argument the source thread.
4475 FunctionArgList WrapperArgs;
4476 QualType Int16QTy =
4477 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4478 QualType Int32QTy =
4479 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004480 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004481 /*Id=*/nullptr, Int16QTy,
4482 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004483 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004484 /*Id=*/nullptr, Int32QTy,
4485 ImplicitParamDecl::Other);
4486 WrapperArgs.emplace_back(&ParallelLevelArg);
4487 WrapperArgs.emplace_back(&WrapperArg);
4488
Alexey Bataev9ff80832018-04-16 20:16:21 +00004489 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004490 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4491
4492 auto *Fn = llvm::Function::Create(
4493 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004494 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004495 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004496 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004497 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004498
4499 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4500 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004501 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004502
4503 const auto *RD = CS.getCapturedRecordDecl();
4504 auto CurField = RD->field_begin();
4505
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004506 Address ZeroAddr = CGF.CreateMemTemp(
4507 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4508 /*Name*/ ".zero.addr");
4509 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004510 // Get the array of arguments.
4511 SmallVector<llvm::Value *, 8> Args;
4512
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004513 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4514 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004515
4516 CGBuilderTy &Bld = CGF.Builder;
4517 auto CI = CS.capture_begin();
4518
4519 // Use global memory for data sharing.
4520 // Handle passing of global args to workers.
4521 Address GlobalArgs =
4522 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4523 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4524 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4525 CGF.EmitRuntimeCall(
4526 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4527 DataSharingArgs);
4528
4529 // Retrieve the shared variables from the list of references returned
4530 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004531 Address SharedArgListAddress = Address::invalid();
4532 if (CS.capture_size() > 0 ||
4533 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4534 SharedArgListAddress = CGF.EmitLoadOfPointer(
4535 GlobalArgs, CGF.getContext()
4536 .getPointerType(CGF.getContext().getPointerType(
4537 CGF.getContext().VoidPtrTy))
4538 .castAs<PointerType>());
4539 }
4540 unsigned Idx = 0;
4541 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004542 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004543 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4544 Src, CGF.SizeTy->getPointerTo());
4545 llvm::Value *LB = CGF.EmitLoadOfScalar(
4546 TypedAddress,
4547 /*Volatile=*/false,
4548 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4549 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4550 Args.emplace_back(LB);
4551 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004552 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004553 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4554 Src, CGF.SizeTy->getPointerTo());
4555 llvm::Value *UB = CGF.EmitLoadOfScalar(
4556 TypedAddress,
4557 /*Volatile=*/false,
4558 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4559 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4560 Args.emplace_back(UB);
4561 ++Idx;
4562 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004563 if (CS.capture_size() > 0) {
4564 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004565 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4566 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004567 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004568 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004569 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4570 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4571 /*Volatile=*/false,
4572 CGFContext.getPointerType(ElemTy),
4573 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004574 if (CI->capturesVariableByCopy() &&
4575 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004576 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4577 CI->getLocation());
4578 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004579 Args.emplace_back(Arg);
4580 }
4581 }
4582
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004583 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004584 CGF.FinishFunction();
4585 return Fn;
4586}
4587
4588void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4589 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004590 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4591 return;
4592
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004593 assert(D && "Expected function or captured|block decl.");
4594 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4595 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004596 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4597 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004598 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004599 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004600 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4601 Body = FD->getBody();
4602 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4603 Body = BD->getBody();
4604 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4605 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004606 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004607 if (NeedToDelayGlobalization &&
4608 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4609 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004610 }
4611 if (!Body)
4612 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004613 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004614 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004615 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004616 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004617 TeamAndReductions.first = nullptr;
4618 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004619 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4620 VarChecker.getEscapedVariableLengthDecls();
4621 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004622 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004623 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4624 I->getSecond().MappedParams =
4625 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4626 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4627 I->getSecond().EscapedParameters.insert(
4628 VarChecker.getEscapedParameters().begin(),
4629 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004630 I->getSecond().EscapedVariableLengthDecls.append(
4631 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004632 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004633 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004634 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004635 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004636 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004637 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004638 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004639 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004640 VarChecker.Visit(Body);
4641 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004642 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004643 I->getSecond().SecondaryLocalVarData.emplace();
4644 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4645 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4646 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4647 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004648 Data.insert(
4649 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004650 }
4651 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004652 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004653 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004654 struct GlobalizationScope final : EHScopeStack::Cleanup {
4655 GlobalizationScope() = default;
4656
4657 void Emit(CodeGenFunction &CGF, Flags flags) override {
4658 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004659 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004660 }
4661 };
4662 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004663 }
4664}
4665
4666Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4667 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004668 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4669 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4670 switch (A->getAllocatorType()) {
4671 // Use the default allocator here as by default local vars are
4672 // threadlocal.
4673 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4674 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004675 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4676 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004677 // Follow the user decision - use default allocation.
4678 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004679 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004680 // TODO: implement aupport for user-defined allocators.
4681 return Address::invalid();
4682 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4683 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4684 auto *GV = new llvm::GlobalVariable(
4685 CGM.getModule(), VarTy, /*isConstant=*/false,
4686 llvm::GlobalValue::InternalLinkage,
4687 llvm::Constant::getNullValue(VarTy), VD->getName(),
4688 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4689 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4690 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4691 GV->setAlignment(Align.getQuantity());
4692 return Address(GV, Align);
4693 }
4694 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4695 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4696 auto *GV = new llvm::GlobalVariable(
4697 CGM.getModule(), VarTy, /*isConstant=*/false,
4698 llvm::GlobalValue::InternalLinkage,
4699 llvm::Constant::getNullValue(VarTy), VD->getName(),
4700 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4701 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4702 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4703 GV->setAlignment(Align.getQuantity());
4704 return Address(GV, Align);
4705 }
4706 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4707 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4708 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4709 auto *GV = new llvm::GlobalVariable(
4710 CGM.getModule(), VarTy, /*isConstant=*/false,
4711 llvm::GlobalValue::InternalLinkage,
4712 llvm::Constant::getNullValue(VarTy), VD->getName());
4713 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4714 GV->setAlignment(Align.getQuantity());
4715 return Address(GV, Align);
4716 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004717 }
4718 }
4719
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004720 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4721 return Address::invalid();
4722
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004723 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004724 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4725 if (I == FunctionGlobalizedDecls.end())
4726 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004727 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004728 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004729 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004730 if (VD->hasAttrs()) {
4731 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4732 E(VD->attr_end());
4733 IT != E; ++IT) {
4734 auto VDI = I->getSecond().LocalVarData.find(
4735 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4736 ->getCanonicalDecl());
4737 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004738 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004739 }
4740 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004741
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004742 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004743}
4744
4745void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004746 FunctionGlobalizedDecls.erase(CGF.CurFn);
4747 CGOpenMPRuntime::functionFinished(CGF);
4748}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004749
4750void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4751 CodeGenFunction &CGF, const OMPLoopDirective &S,
4752 OpenMPDistScheduleClauseKind &ScheduleKind,
4753 llvm::Value *&Chunk) const {
4754 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4755 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4756 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4757 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4758 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004759 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004760 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004761 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4762 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004763}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004764
4765void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4766 CodeGenFunction &CGF, const OMPLoopDirective &S,
4767 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004768 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004769 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004770 // Chunk size is 1 in this case.
4771 llvm::APInt ChunkSize(32, 1);
4772 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4773 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4774 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004775}
Alexey Bataev60705422018-10-30 15:50:12 +00004776
4777void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4778 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4779 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4780 " Expected target-based directive.");
4781 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4782 for (const CapturedStmt::Capture &C : CS->captures()) {
4783 // Capture variables captured by reference in lambdas for target-based
4784 // directives.
4785 if (!C.capturesVariable())
4786 continue;
4787 const VarDecl *VD = C.getCapturedVar();
4788 const auto *RD = VD->getType()
4789 .getCanonicalType()
4790 .getNonReferenceType()
4791 ->getAsCXXRecordDecl();
4792 if (!RD || !RD->isLambda())
4793 continue;
4794 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4795 LValue VDLVal;
4796 if (VD->getType().getCanonicalType()->isReferenceType())
4797 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4798 else
4799 VDLVal = CGF.MakeAddrLValue(
4800 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4801 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4802 FieldDecl *ThisCapture = nullptr;
4803 RD->getCaptureFields(Captures, ThisCapture);
4804 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4805 LValue ThisLVal =
4806 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4807 llvm::Value *CXXThis = CGF.LoadCXXThis();
4808 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4809 }
4810 for (const LambdaCapture &LC : RD->captures()) {
4811 if (LC.getCaptureKind() != LCK_ByRef)
4812 continue;
4813 const VarDecl *VD = LC.getCapturedVar();
4814 if (!CS->capturesVariable(VD))
4815 continue;
4816 auto It = Captures.find(VD);
4817 assert(It != Captures.end() && "Found lambda capture without field.");
4818 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4819 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4820 if (VD->getType().getCanonicalType()->isReferenceType())
4821 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4822 VD->getType().getCanonicalType())
4823 .getAddress();
4824 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4825 }
4826 }
4827}
4828
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004829unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4830 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4831}
4832
Alexey Bataevc5687252019-03-21 19:35:27 +00004833bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4834 LangAS &AS) {
4835 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4836 return false;
4837 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4838 switch(A->getAllocatorType()) {
4839 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4840 // Not supported, fallback to the default mem space.
4841 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4842 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4843 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4844 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4845 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4846 AS = LangAS::Default;
4847 return true;
4848 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4849 AS = LangAS::cuda_constant;
4850 return true;
4851 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4852 AS = LangAS::cuda_shared;
4853 return true;
4854 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4855 llvm_unreachable("Expected predefined allocator for the variables with the "
4856 "static storage.");
4857 }
4858 return false;
4859}
4860
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004861// Get current CudaArch and ignore any unknown values
4862static CudaArch getCudaArch(CodeGenModule &CGM) {
4863 if (!CGM.getTarget().hasFeature("ptx"))
4864 return CudaArch::UNKNOWN;
4865 llvm::StringMap<bool> Features;
4866 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4867 CGM.getTarget().getTargetOpts().CPU,
4868 CGM.getTarget().getTargetOpts().Features);
4869 for (const auto &Feature : Features) {
4870 if (Feature.getValue()) {
4871 CudaArch Arch = StringToCudaArch(Feature.getKey());
4872 if (Arch != CudaArch::UNKNOWN)
4873 return Arch;
4874 }
4875 }
4876 return CudaArch::UNKNOWN;
4877}
4878
4879/// Check to see if target architecture supports unified addressing which is
4880/// a restriction for OpenMP requires clause "unified_shared_memory".
4881void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004882 const OMPRequiresDecl *D) const {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004883 for (const OMPClause *Clause : D->clauselists()) {
4884 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4885 switch (getCudaArch(CGM)) {
4886 case CudaArch::SM_20:
4887 case CudaArch::SM_21:
4888 case CudaArch::SM_30:
4889 case CudaArch::SM_32:
4890 case CudaArch::SM_35:
4891 case CudaArch::SM_37:
4892 case CudaArch::SM_50:
4893 case CudaArch::SM_52:
4894 case CudaArch::SM_53:
4895 case CudaArch::SM_60:
4896 case CudaArch::SM_61:
4897 case CudaArch::SM_62:
4898 CGM.Error(Clause->getBeginLoc(),
4899 "Target architecture does not support unified addressing");
4900 return;
4901 case CudaArch::SM_70:
4902 case CudaArch::SM_72:
4903 case CudaArch::SM_75:
4904 case CudaArch::GFX600:
4905 case CudaArch::GFX601:
4906 case CudaArch::GFX700:
4907 case CudaArch::GFX701:
4908 case CudaArch::GFX702:
4909 case CudaArch::GFX703:
4910 case CudaArch::GFX704:
4911 case CudaArch::GFX801:
4912 case CudaArch::GFX802:
4913 case CudaArch::GFX803:
4914 case CudaArch::GFX810:
4915 case CudaArch::GFX900:
4916 case CudaArch::GFX902:
4917 case CudaArch::GFX904:
4918 case CudaArch::GFX906:
4919 case CudaArch::GFX909:
4920 case CudaArch::UNKNOWN:
4921 break;
4922 case CudaArch::LAST:
4923 llvm_unreachable("Unexpected Cuda arch.");
4924 }
4925 }
4926 }
4927}
4928
Alexey Bataeve4090182018-11-02 14:54:07 +00004929/// Get number of SMs and number of blocks per SM.
4930static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4931 std::pair<unsigned, unsigned> Data;
4932 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4933 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4934 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4935 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4936 if (Data.first && Data.second)
4937 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004938 switch (getCudaArch(CGM)) {
4939 case CudaArch::SM_20:
4940 case CudaArch::SM_21:
4941 case CudaArch::SM_30:
4942 case CudaArch::SM_32:
4943 case CudaArch::SM_35:
4944 case CudaArch::SM_37:
4945 case CudaArch::SM_50:
4946 case CudaArch::SM_52:
4947 case CudaArch::SM_53:
4948 return {16, 16};
4949 case CudaArch::SM_60:
4950 case CudaArch::SM_61:
4951 case CudaArch::SM_62:
4952 return {56, 32};
4953 case CudaArch::SM_70:
4954 case CudaArch::SM_72:
4955 case CudaArch::SM_75:
4956 return {84, 32};
4957 case CudaArch::GFX600:
4958 case CudaArch::GFX601:
4959 case CudaArch::GFX700:
4960 case CudaArch::GFX701:
4961 case CudaArch::GFX702:
4962 case CudaArch::GFX703:
4963 case CudaArch::GFX704:
4964 case CudaArch::GFX801:
4965 case CudaArch::GFX802:
4966 case CudaArch::GFX803:
4967 case CudaArch::GFX810:
4968 case CudaArch::GFX900:
4969 case CudaArch::GFX902:
4970 case CudaArch::GFX904:
4971 case CudaArch::GFX906:
4972 case CudaArch::GFX909:
4973 case CudaArch::UNKNOWN:
4974 break;
4975 case CudaArch::LAST:
4976 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004977 }
4978 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4979}
4980
4981void CGOpenMPRuntimeNVPTX::clear() {
4982 if (!GlobalizedRecords.empty()) {
4983 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004984 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4985 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004986 RecordDecl *StaticRD = C.buildImplicitRecord(
4987 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4988 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004989 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4990 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4991 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004992 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4993 if (Records.Records.empty())
4994 continue;
4995 unsigned Size = 0;
4996 unsigned RecAlignment = 0;
4997 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004998 QualType RDTy = C.getRecordType(RD);
4999 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005000 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005001 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005002 Size =
5003 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5004 }
5005 Size = llvm::alignTo(Size, RecAlignment);
5006 llvm::APInt ArySize(/*numBits=*/64, Size);
5007 QualType SubTy = C.getConstantArrayType(
5008 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005009 const bool UseSharedMemory = Size <= SharedMemorySize;
5010 auto *Field =
5011 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5012 SourceLocation(), SourceLocation(), nullptr, SubTy,
5013 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5014 /*BW=*/nullptr, /*Mutable=*/false,
5015 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005016 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005017 if (UseSharedMemory) {
5018 SharedStaticRD->addDecl(Field);
5019 SharedRecs.push_back(&Records);
5020 } else {
5021 StaticRD->addDecl(Field);
5022 GlobalRecs.push_back(&Records);
5023 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005024 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005025 Records.UseSharedMemory->setInitializer(
5026 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5027 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005028 // Allocate SharedMemorySize buffer for the shared memory.
5029 // FIXME: nvlink does not handle weak linkage correctly (object with the
5030 // different size are reported as erroneous).
5031 // Restore this code as sson as nvlink is fixed.
5032 if (!SharedStaticRD->field_empty()) {
5033 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5034 QualType SubTy = C.getConstantArrayType(
5035 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5036 auto *Field = FieldDecl::Create(
5037 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5038 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5039 /*BW=*/nullptr, /*Mutable=*/false,
5040 /*InitStyle=*/ICIS_NoInit);
5041 Field->setAccess(AS_public);
5042 SharedStaticRD->addDecl(Field);
5043 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005044 SharedStaticRD->completeDefinition();
5045 if (!SharedStaticRD->field_empty()) {
5046 QualType StaticTy = C.getRecordType(SharedStaticRD);
5047 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5048 auto *GV = new llvm::GlobalVariable(
5049 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005050 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005051 llvm::Constant::getNullValue(LLVMStaticTy),
5052 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5053 llvm::GlobalValue::NotThreadLocal,
5054 C.getTargetAddressSpace(LangAS::cuda_shared));
5055 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5056 GV, CGM.VoidPtrTy);
5057 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5058 Rec->Buffer->replaceAllUsesWith(Replacement);
5059 Rec->Buffer->eraseFromParent();
5060 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005061 }
5062 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005063 if (!StaticRD->field_empty()) {
5064 QualType StaticTy = C.getRecordType(StaticRD);
5065 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5066 llvm::APInt Size1(32, SMsBlockPerSM.second);
5067 QualType Arr1Ty =
5068 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5069 /*IndexTypeQuals=*/0);
5070 llvm::APInt Size2(32, SMsBlockPerSM.first);
5071 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5072 /*IndexTypeQuals=*/0);
5073 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005074 // FIXME: nvlink does not handle weak linkage correctly (object with the
5075 // different size are reported as erroneous).
5076 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005077 auto *GV = new llvm::GlobalVariable(
5078 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005079 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005080 llvm::Constant::getNullValue(LLVMArr2Ty),
5081 "_openmp_static_glob_rd_$_");
5082 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5083 GV, CGM.VoidPtrTy);
5084 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5085 Rec->Buffer->replaceAllUsesWith(Replacement);
5086 Rec->Buffer->eraseFromParent();
5087 }
5088 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005089 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005090 if (!TeamsReductions.empty()) {
5091 ASTContext &C = CGM.getContext();
5092 RecordDecl *StaticRD = C.buildImplicitRecord(
5093 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5094 StaticRD->startDefinition();
5095 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5096 QualType RecTy = C.getRecordType(TeamReductionRec);
5097 auto *Field = FieldDecl::Create(
5098 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5099 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5100 /*BW=*/nullptr, /*Mutable=*/false,
5101 /*InitStyle=*/ICIS_NoInit);
5102 Field->setAccess(AS_public);
5103 StaticRD->addDecl(Field);
5104 }
5105 StaticRD->completeDefinition();
5106 QualType StaticTy = C.getRecordType(StaticRD);
5107 llvm::Type *LLVMReductionsBufferTy =
5108 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005109 // FIXME: nvlink does not handle weak linkage correctly (object with the
5110 // different size are reported as erroneous).
5111 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005112 auto *GV = new llvm::GlobalVariable(
5113 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005114 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005115 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5116 "_openmp_teams_reductions_buffer_$_");
5117 KernelTeamsReductionPtr->setInitializer(
5118 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5119 CGM.VoidPtrTy));
5120 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005121 CGOpenMPRuntime::clear();
5122}