blob: 17ee48fe01f0ea22083e60f408526a3388f91140 [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 Bataevc99042b2018-03-15 18:10:54 +0000321 // Variables captured by value must be globalized.
322 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000323 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000324 // Check if need to capture the variable that was already captured by
325 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000326 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000327 if (!FD->hasAttrs())
328 return;
329 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
330 if (!Attr)
331 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000332 if (((Attr->getCaptureKind() != OMPC_map) &&
333 !isOpenMPPrivate(
334 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
335 ((Attr->getCaptureKind() == OMPC_map) &&
336 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000337 return;
338 }
339 if (!FD->getType()->isReferenceType()) {
340 assert(!VD->getType()->isVariablyModifiedType() &&
341 "Parameter captured by value with variably modified type");
342 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000343 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000344 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000345 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000346 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000347 }
348 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000349 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000350 VD->getType()->isReferenceType())
351 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000352 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000353 if (VD->getType()->isVariablyModifiedType())
354 EscapedVariableLengthDecls.insert(VD);
355 else
356 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000357 }
358
359 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000360 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000361 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000362 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
363 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
364 const bool SavedAllEscaped = AllEscaped;
365 AllEscaped = VD->getType()->isLValueReferenceType();
366 Visit(VarD->getInit());
367 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000368 }
369 }
370 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000371 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
372 ArrayRef<OMPClause *> Clauses,
373 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000374 if (!S)
375 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000376 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000377 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
378 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000379 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
380 if (IsCombinedParallelRegion) {
381 // Check if the variable is privatized in the combined construct and
382 // those private copies must be shared in the inner parallel
383 // directive.
384 IsForCombinedParallelRegion = false;
385 for (const OMPClause *C : Clauses) {
386 if (!isOpenMPPrivate(C->getClauseKind()) ||
387 C->getClauseKind() == OMPC_reduction ||
388 C->getClauseKind() == OMPC_linear ||
389 C->getClauseKind() == OMPC_private)
390 continue;
391 ArrayRef<const Expr *> Vars;
392 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
393 Vars = PC->getVarRefs();
394 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
395 Vars = PC->getVarRefs();
396 else
397 llvm_unreachable("Unexpected clause.");
398 for (const auto *E : Vars) {
399 const Decl *D =
400 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
401 if (D == VD->getCanonicalDecl()) {
402 IsForCombinedParallelRegion = true;
403 break;
404 }
405 }
406 if (IsForCombinedParallelRegion)
407 break;
408 }
409 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000410 markAsEscaped(VD);
411 if (isa<OMPCapturedExprDecl>(VD))
412 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000413 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000414 }
415 }
416 }
417
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000418 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000419 assert(!GlobalizedRD &&
420 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000421 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000422 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000423 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
424 else
425 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000426 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000427 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000428 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000429 }
430
431public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000432 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
433 ArrayRef<const ValueDecl *> TeamsReductions)
434 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
435 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000436 virtual ~CheckVarsEscapingDeclContext() = default;
437 void VisitDeclStmt(const DeclStmt *S) {
438 if (!S)
439 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000440 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000441 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
442 VisitValueDecl(VD);
443 }
444 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
445 if (!D)
446 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000447 if (!D->hasAssociatedStmt())
448 return;
449 if (const auto *S =
450 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
451 // Do not analyze directives that do not actually require capturing,
452 // like `omp for` or `omp simd` directives.
453 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
454 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
455 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
456 VisitStmt(S->getCapturedStmt());
457 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000458 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000459 VisitOpenMPCapturedStmt(
460 S, D->clauses(),
461 CaptureRegions.back() == OMPD_parallel &&
462 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000463 }
464 }
465 void VisitCapturedStmt(const CapturedStmt *S) {
466 if (!S)
467 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000468 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000469 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
470 const ValueDecl *VD = C.getCapturedVar();
471 markAsEscaped(VD);
472 if (isa<OMPCapturedExprDecl>(VD))
473 VisitValueDecl(VD);
474 }
475 }
476 }
477 void VisitLambdaExpr(const LambdaExpr *E) {
478 if (!E)
479 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000480 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000481 if (C.capturesVariable()) {
482 if (C.getCaptureKind() == LCK_ByRef) {
483 const ValueDecl *VD = C.getCapturedVar();
484 markAsEscaped(VD);
485 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
486 VisitValueDecl(VD);
487 }
488 }
489 }
490 }
491 void VisitBlockExpr(const BlockExpr *E) {
492 if (!E)
493 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000494 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000495 if (C.isByRef()) {
496 const VarDecl *VD = C.getVariable();
497 markAsEscaped(VD);
498 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
499 VisitValueDecl(VD);
500 }
501 }
502 }
503 void VisitCallExpr(const CallExpr *E) {
504 if (!E)
505 return;
506 for (const Expr *Arg : E->arguments()) {
507 if (!Arg)
508 continue;
509 if (Arg->isLValue()) {
510 const bool SavedAllEscaped = AllEscaped;
511 AllEscaped = true;
512 Visit(Arg);
513 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000514 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000515 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000516 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000517 }
518 Visit(E->getCallee());
519 }
520 void VisitDeclRefExpr(const DeclRefExpr *E) {
521 if (!E)
522 return;
523 const ValueDecl *VD = E->getDecl();
524 if (AllEscaped)
525 markAsEscaped(VD);
526 if (isa<OMPCapturedExprDecl>(VD))
527 VisitValueDecl(VD);
528 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
529 if (VarD->isInitCapture())
530 VisitValueDecl(VD);
531 }
532 void VisitUnaryOperator(const UnaryOperator *E) {
533 if (!E)
534 return;
535 if (E->getOpcode() == UO_AddrOf) {
536 const bool SavedAllEscaped = AllEscaped;
537 AllEscaped = true;
538 Visit(E->getSubExpr());
539 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000540 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000541 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000542 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000543 }
544 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
545 if (!E)
546 return;
547 if (E->getCastKind() == CK_ArrayToPointerDecay) {
548 const bool SavedAllEscaped = AllEscaped;
549 AllEscaped = true;
550 Visit(E->getSubExpr());
551 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000552 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000553 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000554 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000555 }
556 void VisitExpr(const Expr *E) {
557 if (!E)
558 return;
559 bool SavedAllEscaped = AllEscaped;
560 if (!E->isLValue())
561 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000562 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000563 if (Child)
564 Visit(Child);
565 AllEscaped = SavedAllEscaped;
566 }
567 void VisitStmt(const Stmt *S) {
568 if (!S)
569 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000570 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 if (Child)
572 Visit(Child);
573 }
574
Alexey Bataevc99042b2018-03-15 18:10:54 +0000575 /// Returns the record that handles all the escaped local variables and used
576 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000577 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000578 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000579 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000580 return GlobalizedRD;
581 }
582
Alexey Bataevc99042b2018-03-15 18:10:54 +0000583 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000584 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
585 assert(GlobalizedRD &&
586 "Record for globalized variables must be generated already.");
587 auto I = MappedDeclsFields.find(VD);
588 if (I == MappedDeclsFields.end())
589 return nullptr;
590 return I->getSecond();
591 }
592
Alexey Bataevc99042b2018-03-15 18:10:54 +0000593 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000594 ArrayRef<const ValueDecl *> getEscapedDecls() const {
595 return EscapedDecls.getArrayRef();
596 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000597
598 /// Checks if the escaped local variable is actually a parameter passed by
599 /// value.
600 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
601 return EscapedParameters;
602 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000603
604 /// Returns the list of the escaped variables with the variably modified
605 /// types.
606 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
607 return EscapedVariableLengthDecls.getArrayRef();
608 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000609};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000610} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000611
612/// Get the GPU warp size.
613static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000614 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000615 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000616 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000617 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000618}
619
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000620/// Get the id of the current thread on the GPU.
621static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000622 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000623 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000624 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000625 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626}
627
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000628/// Get the id of the warp in the block.
629/// We assume that the warp size is 32, which is always the case
630/// on the NVPTX device, to generate more efficient code.
631static llvm::Value *getNVPTXWarpID(CodeGenFunction &CGF) {
632 CGBuilderTy &Bld = CGF.Builder;
633 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
634}
635
636/// Get the id of the current lane in the Warp.
637/// We assume that the warp size is 32, which is always the case
638/// on the NVPTX device, to generate more efficient code.
639static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
640 CGBuilderTy &Bld = CGF.Builder;
641 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
642 "nvptx_lane_id");
643}
644
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000645/// Get the maximum number of threads in a block of the GPU.
646static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000647 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000648 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000649 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000650 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000651}
652
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000653/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000654/// For the 'generic' execution mode, the runtime encodes thread_limit in
655/// the launch parameters, always starting thread_limit+warpSize threads per
656/// CTA. The threads in the last warp are reserved for master execution.
657/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
658static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000659 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000660 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000661 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000662 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000663 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
664 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000665}
666
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000667/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000668/// The master thread id is the first thread (lane) of the last warp in the
669/// GPU block. Warp size is assumed to be some power of 2.
670/// Thread id is 0 indexed.
671/// E.g: If NumThreads is 33, master id is 32.
672/// If NumThreads is 64, master id is 32.
673/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000674static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000675 CGBuilderTy &Bld = CGF.Builder;
676 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
677
678 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000679 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000680
Alexey Bataeve290ec02018-04-06 16:03:36 +0000681 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000682 Bld.CreateNot(Mask), "master_tid");
683}
684
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000685CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000686 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000687 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
688 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000689 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000690}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000691
692void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
693 CodeGenModule &CGM) {
694 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000695
696 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000697 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000698 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000699 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000700 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000701}
702
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000703CGOpenMPRuntimeNVPTX::ExecutionMode
704CGOpenMPRuntimeNVPTX::getExecutionMode() const {
705 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000706}
707
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000708static CGOpenMPRuntimeNVPTX::DataSharingMode
709getDataSharingMode(CodeGenModule &CGM) {
710 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
711 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000712}
713
Alexey Bataev7bb33532019-01-07 21:30:43 +0000714/// Checks if the expression is constant or does not have non-trivial function
715/// calls.
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000716static bool isTrivial(ASTContext &Ctx, const Expr * E) {
717 // We can skip constant expressions.
718 // We can skip expressions with trivial calls or simple expressions.
719 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
720 !E->hasNonTrivialCall(Ctx)) &&
721 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
722}
723
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000724/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000725/// iff there is only one that is not evaluatable at the compile time.
726static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
727 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
728 const Stmt *Child = nullptr;
729 for (const Stmt *S : C->body()) {
730 if (const auto *E = dyn_cast<Expr>(S)) {
731 if (isTrivial(Ctx, E))
732 continue;
733 }
734 // Some of the statements can be ignored.
735 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
736 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
737 continue;
738 // Analyze declarations.
739 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
740 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
741 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
742 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
743 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
744 isa<UsingDirectiveDecl>(D) ||
745 isa<OMPDeclareReductionDecl>(D) ||
746 isa<OMPThreadPrivateDecl>(D))
747 return true;
748 const auto *VD = dyn_cast<VarDecl>(D);
749 if (!VD)
750 return false;
751 return VD->isConstexpr() ||
752 ((VD->getType().isTrivialType(Ctx) ||
753 VD->getType()->isReferenceType()) &&
754 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
755 }))
756 continue;
757 }
758 // Found multiple children - cannot get the one child only.
759 if (Child)
760 return Body;
761 Child = S;
762 }
763 if (Child)
764 return Child;
765 }
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000766 return Body;
767}
768
769/// Check if the parallel directive has an 'if' clause with non-constant or
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000770/// false condition. Also, check if the number of threads is strictly specified
771/// and run those directives in non-SPMD mode.
772static bool hasParallelIfNumThreadsClause(ASTContext &Ctx,
773 const OMPExecutableDirective &D) {
774 if (D.hasClausesOfKind<OMPNumThreadsClause>())
775 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000776 for (const auto *C : D.getClausesOfKind<OMPIfClause>()) {
777 OpenMPDirectiveKind NameModifier = C->getNameModifier();
778 if (NameModifier != OMPD_parallel && NameModifier != OMPD_unknown)
779 continue;
780 const Expr *Cond = C->getCondition();
781 bool Result;
782 if (!Cond->EvaluateAsBooleanCondition(Result, Ctx) || !Result)
783 return true;
784 }
785 return false;
786}
787
788/// Check for inner (nested) SPMD construct, if any
789static bool hasNestedSPMDDirective(ASTContext &Ctx,
790 const OMPExecutableDirective &D) {
791 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000792 const auto *Body =
793 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000794 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000795
796 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
797 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000798 switch (D.getDirectiveKind()) {
799 case OMPD_target:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000800 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000801 !hasParallelIfNumThreadsClause(Ctx, *NestedDir))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000802 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000803 if (DKind == OMPD_teams) {
804 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
805 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000806 if (!Body)
807 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000808 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000809 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
810 DKind = NND->getDirectiveKind();
Alexey Bataevdf093e72018-05-11 19:45:14 +0000811 if (isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000812 !hasParallelIfNumThreadsClause(Ctx, *NND))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000813 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000814 }
815 }
816 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000817 case OMPD_target_teams:
Alexey Bataevdf093e72018-05-11 19:45:14 +0000818 return isOpenMPParallelDirective(DKind) &&
Alexey Bataev2adecff2018-09-21 14:22:53 +0000819 !hasParallelIfNumThreadsClause(Ctx, *NestedDir);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000820 case OMPD_target_simd:
821 case OMPD_target_parallel:
822 case OMPD_target_parallel_for:
823 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000824 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000825 case OMPD_target_teams_distribute_simd:
826 case OMPD_target_teams_distribute_parallel_for:
827 case OMPD_target_teams_distribute_parallel_for_simd:
828 case OMPD_parallel:
829 case OMPD_for:
830 case OMPD_parallel_for:
831 case OMPD_parallel_sections:
832 case OMPD_for_simd:
833 case OMPD_parallel_for_simd:
834 case OMPD_cancel:
835 case OMPD_cancellation_point:
836 case OMPD_ordered:
837 case OMPD_threadprivate:
838 case OMPD_task:
839 case OMPD_simd:
840 case OMPD_sections:
841 case OMPD_section:
842 case OMPD_single:
843 case OMPD_master:
844 case OMPD_critical:
845 case OMPD_taskyield:
846 case OMPD_barrier:
847 case OMPD_taskwait:
848 case OMPD_taskgroup:
849 case OMPD_atomic:
850 case OMPD_flush:
851 case OMPD_teams:
852 case OMPD_target_data:
853 case OMPD_target_exit_data:
854 case OMPD_target_enter_data:
855 case OMPD_distribute:
856 case OMPD_distribute_simd:
857 case OMPD_distribute_parallel_for:
858 case OMPD_distribute_parallel_for_simd:
859 case OMPD_teams_distribute:
860 case OMPD_teams_distribute_simd:
861 case OMPD_teams_distribute_parallel_for:
862 case OMPD_teams_distribute_parallel_for_simd:
863 case OMPD_target_update:
864 case OMPD_declare_simd:
865 case OMPD_declare_target:
866 case OMPD_end_declare_target:
867 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000868 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000869 case OMPD_taskloop:
870 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000871 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000872 case OMPD_unknown:
873 llvm_unreachable("Unexpected directive.");
874 }
875 }
876
877 return false;
878}
879
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000880static bool supportsSPMDExecutionMode(ASTContext &Ctx,
881 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000882 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
883 switch (DirectiveKind) {
884 case OMPD_target:
885 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000886 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000887 case OMPD_target_parallel:
888 case OMPD_target_parallel_for:
889 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000890 case OMPD_target_teams_distribute_parallel_for:
891 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev2adecff2018-09-21 14:22:53 +0000892 return !hasParallelIfNumThreadsClause(Ctx, D);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000893 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000894 case OMPD_target_teams_distribute:
895 case OMPD_target_teams_distribute_simd:
896 return false;
897 case OMPD_parallel:
898 case OMPD_for:
899 case OMPD_parallel_for:
900 case OMPD_parallel_sections:
901 case OMPD_for_simd:
902 case OMPD_parallel_for_simd:
903 case OMPD_cancel:
904 case OMPD_cancellation_point:
905 case OMPD_ordered:
906 case OMPD_threadprivate:
907 case OMPD_task:
908 case OMPD_simd:
909 case OMPD_sections:
910 case OMPD_section:
911 case OMPD_single:
912 case OMPD_master:
913 case OMPD_critical:
914 case OMPD_taskyield:
915 case OMPD_barrier:
916 case OMPD_taskwait:
917 case OMPD_taskgroup:
918 case OMPD_atomic:
919 case OMPD_flush:
920 case OMPD_teams:
921 case OMPD_target_data:
922 case OMPD_target_exit_data:
923 case OMPD_target_enter_data:
924 case OMPD_distribute:
925 case OMPD_distribute_simd:
926 case OMPD_distribute_parallel_for:
927 case OMPD_distribute_parallel_for_simd:
928 case OMPD_teams_distribute:
929 case OMPD_teams_distribute_simd:
930 case OMPD_teams_distribute_parallel_for:
931 case OMPD_teams_distribute_parallel_for_simd:
932 case OMPD_target_update:
933 case OMPD_declare_simd:
934 case OMPD_declare_target:
935 case OMPD_end_declare_target:
936 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000937 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000938 case OMPD_taskloop:
939 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000940 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000941 case OMPD_unknown:
942 break;
943 }
944 llvm_unreachable(
945 "Unknown programming model for OpenMP directive on NVPTX target.");
946}
947
948/// Check if the directive is loops based and has schedule clause at all or has
949/// static scheduling.
950static bool hasStaticScheduling(const OMPExecutableDirective &D) {
951 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
952 isOpenMPLoopDirective(D.getDirectiveKind()) &&
953 "Expected loop-based directive.");
954 return !D.hasClausesOfKind<OMPOrderedClause>() &&
955 (!D.hasClausesOfKind<OMPScheduleClause>() ||
956 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
957 [](const OMPScheduleClause *C) {
958 return C->getScheduleKind() == OMPC_SCHEDULE_static;
959 }));
960}
961
962/// Check for inner (nested) lightweight runtime construct, if any
963static bool hasNestedLightweightDirective(ASTContext &Ctx,
964 const OMPExecutableDirective &D) {
965 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
966 const auto *CS = D.getInnermostCapturedStmt();
967 const auto *Body =
968 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000969 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000970
971 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
972 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
973 switch (D.getDirectiveKind()) {
974 case OMPD_target:
975 if (isOpenMPParallelDirective(DKind) &&
976 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
977 hasStaticScheduling(*NestedDir))
978 return true;
979 if (DKind == OMPD_parallel) {
980 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
981 /*IgnoreCaptured=*/true);
982 if (!Body)
983 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000984 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000985 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
986 DKind = NND->getDirectiveKind();
987 if (isOpenMPWorksharingDirective(DKind) &&
988 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
989 return true;
990 }
991 } else if (DKind == OMPD_teams) {
992 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
993 /*IgnoreCaptured=*/true);
994 if (!Body)
995 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +0000996 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000997 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
998 DKind = NND->getDirectiveKind();
999 if (isOpenMPParallelDirective(DKind) &&
1000 isOpenMPWorksharingDirective(DKind) &&
1001 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1002 return true;
1003 if (DKind == OMPD_parallel) {
1004 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
1005 /*IgnoreCaptured=*/true);
1006 if (!Body)
1007 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001008 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001009 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1010 DKind = NND->getDirectiveKind();
1011 if (isOpenMPWorksharingDirective(DKind) &&
1012 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1013 return true;
1014 }
1015 }
1016 }
1017 }
1018 return false;
1019 case OMPD_target_teams:
1020 if (isOpenMPParallelDirective(DKind) &&
1021 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
1022 hasStaticScheduling(*NestedDir))
1023 return true;
1024 if (DKind == OMPD_parallel) {
1025 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
1026 /*IgnoreCaptured=*/true);
1027 if (!Body)
1028 return false;
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001029 ChildStmt = getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001030 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
1031 DKind = NND->getDirectiveKind();
1032 if (isOpenMPWorksharingDirective(DKind) &&
1033 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
1034 return true;
1035 }
1036 }
1037 return false;
1038 case OMPD_target_parallel:
1039 return isOpenMPWorksharingDirective(DKind) &&
1040 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
1041 case OMPD_target_teams_distribute:
1042 case OMPD_target_simd:
1043 case OMPD_target_parallel_for:
1044 case OMPD_target_parallel_for_simd:
1045 case OMPD_target_teams_distribute_simd:
1046 case OMPD_target_teams_distribute_parallel_for:
1047 case OMPD_target_teams_distribute_parallel_for_simd:
1048 case OMPD_parallel:
1049 case OMPD_for:
1050 case OMPD_parallel_for:
1051 case OMPD_parallel_sections:
1052 case OMPD_for_simd:
1053 case OMPD_parallel_for_simd:
1054 case OMPD_cancel:
1055 case OMPD_cancellation_point:
1056 case OMPD_ordered:
1057 case OMPD_threadprivate:
1058 case OMPD_task:
1059 case OMPD_simd:
1060 case OMPD_sections:
1061 case OMPD_section:
1062 case OMPD_single:
1063 case OMPD_master:
1064 case OMPD_critical:
1065 case OMPD_taskyield:
1066 case OMPD_barrier:
1067 case OMPD_taskwait:
1068 case OMPD_taskgroup:
1069 case OMPD_atomic:
1070 case OMPD_flush:
1071 case OMPD_teams:
1072 case OMPD_target_data:
1073 case OMPD_target_exit_data:
1074 case OMPD_target_enter_data:
1075 case OMPD_distribute:
1076 case OMPD_distribute_simd:
1077 case OMPD_distribute_parallel_for:
1078 case OMPD_distribute_parallel_for_simd:
1079 case OMPD_teams_distribute:
1080 case OMPD_teams_distribute_simd:
1081 case OMPD_teams_distribute_parallel_for:
1082 case OMPD_teams_distribute_parallel_for_simd:
1083 case OMPD_target_update:
1084 case OMPD_declare_simd:
1085 case OMPD_declare_target:
1086 case OMPD_end_declare_target:
1087 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001088 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001089 case OMPD_taskloop:
1090 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001091 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001092 case OMPD_unknown:
1093 llvm_unreachable("Unexpected directive.");
1094 }
1095 }
1096
1097 return false;
1098}
1099
1100/// Checks if the construct supports lightweight runtime. It must be SPMD
1101/// construct + inner loop-based construct with static scheduling.
1102static bool supportsLightweightRuntime(ASTContext &Ctx,
1103 const OMPExecutableDirective &D) {
1104 if (!supportsSPMDExecutionMode(Ctx, D))
1105 return false;
1106 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1107 switch (DirectiveKind) {
1108 case OMPD_target:
1109 case OMPD_target_teams:
1110 case OMPD_target_parallel:
1111 return hasNestedLightweightDirective(Ctx, D);
1112 case OMPD_target_parallel_for:
1113 case OMPD_target_parallel_for_simd:
1114 case OMPD_target_teams_distribute_parallel_for:
1115 case OMPD_target_teams_distribute_parallel_for_simd:
1116 // (Last|First)-privates must be shared in parallel region.
1117 return hasStaticScheduling(D);
1118 case OMPD_target_simd:
1119 case OMPD_target_teams_distribute:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001120 case OMPD_target_teams_distribute_simd:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001121 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001122 case OMPD_parallel:
1123 case OMPD_for:
1124 case OMPD_parallel_for:
1125 case OMPD_parallel_sections:
1126 case OMPD_for_simd:
1127 case OMPD_parallel_for_simd:
1128 case OMPD_cancel:
1129 case OMPD_cancellation_point:
1130 case OMPD_ordered:
1131 case OMPD_threadprivate:
1132 case OMPD_task:
1133 case OMPD_simd:
1134 case OMPD_sections:
1135 case OMPD_section:
1136 case OMPD_single:
1137 case OMPD_master:
1138 case OMPD_critical:
1139 case OMPD_taskyield:
1140 case OMPD_barrier:
1141 case OMPD_taskwait:
1142 case OMPD_taskgroup:
1143 case OMPD_atomic:
1144 case OMPD_flush:
1145 case OMPD_teams:
1146 case OMPD_target_data:
1147 case OMPD_target_exit_data:
1148 case OMPD_target_enter_data:
1149 case OMPD_distribute:
1150 case OMPD_distribute_simd:
1151 case OMPD_distribute_parallel_for:
1152 case OMPD_distribute_parallel_for_simd:
1153 case OMPD_teams_distribute:
1154 case OMPD_teams_distribute_simd:
1155 case OMPD_teams_distribute_parallel_for:
1156 case OMPD_teams_distribute_parallel_for_simd:
1157 case OMPD_target_update:
1158 case OMPD_declare_simd:
1159 case OMPD_declare_target:
1160 case OMPD_end_declare_target:
1161 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001162 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001163 case OMPD_taskloop:
1164 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001165 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001166 case OMPD_unknown:
1167 break;
1168 }
1169 llvm_unreachable(
1170 "Unknown programming model for OpenMP directive on NVPTX target.");
1171}
1172
1173void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174 StringRef ParentName,
1175 llvm::Function *&OutlinedFn,
1176 llvm::Constant *&OutlinedFnID,
1177 bool IsOffloadEntry,
1178 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001179 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001180 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001181 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001182 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001183 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001184
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001185 // Emit target region as a standalone region.
1186 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001187 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1188 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001189
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001190 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001191 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001193 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001195 auto &RT =
1196 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001197 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1198 // Skip target region initialization.
1199 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001200 }
1201 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001202 auto &RT =
1203 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001204 RT.clearLocThreadIdInsertPt(CGF);
1205 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001206 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001207 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001208 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001209 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001210 // Reserve place for the globalized memory.
1211 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001212 if (!KernelStaticGlobalized) {
1213 KernelStaticGlobalized = new llvm::GlobalVariable(
1214 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1215 llvm::GlobalValue::InternalLinkage,
1216 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1217 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1218 llvm::GlobalValue::NotThreadLocal,
1219 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1220 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1222 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001223 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001224
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001225 // Now change the name of the worker function to correspond to this target
1226 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001227 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001228
1229 // Create the worker function
1230 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001231}
1232
1233// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001234void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001235 EntryFunctionState &EST,
1236 WorkerFunctionState &WST) {
1237 CGBuilderTy &Bld = CGF.Builder;
1238
1239 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1240 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1241 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1242 EST.ExitBB = CGF.createBasicBlock(".exit");
1243
Alexey Bataev9ff80832018-04-16 20:16:21 +00001244 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001245 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1246 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1247
1248 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001249 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001250 CGF.EmitBranch(EST.ExitBB);
1251
1252 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001253 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001254 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1255 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1256
1257 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001258 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001259 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001260 // First action in sequential region:
1261 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001262 // TODO: Optimize runtime initialization and pass in correct value.
1263 llvm::Value *Args[] = {getThreadLimit(CGF),
1264 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001265 CGF.EmitRuntimeCall(
1266 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001267
1268 // For data sharing, we need to initialize the stack.
1269 CGF.EmitRuntimeCall(
1270 createNVPTXRuntimeFunction(
1271 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1272
Alexey Bataevc99042b2018-03-15 18:10:54 +00001273 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001274}
1275
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001276void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001277 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001278 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001279 if (!CGF.HaveInsertPoint())
1280 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001281
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001282 emitGenericVarsEpilog(CGF);
1283
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001284 if (!EST.ExitBB)
1285 EST.ExitBB = CGF.createBasicBlock(".exit");
1286
1287 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1288 CGF.EmitBranch(TerminateBB);
1289
1290 CGF.EmitBlock(TerminateBB);
1291 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001292 // TODO: Optimize runtime initialization and pass in correct value.
1293 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001294 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001295 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001296 // Barrier to terminate worker threads.
1297 syncCTAThreads(CGF);
1298 // Master thread jumps to exit point.
1299 CGF.EmitBranch(EST.ExitBB);
1300
1301 CGF.EmitBlock(EST.ExitBB);
1302 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001303}
1304
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001305void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001306 StringRef ParentName,
1307 llvm::Function *&OutlinedFn,
1308 llvm::Constant *&OutlinedFnID,
1309 bool IsOffloadEntry,
1310 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001311 ExecutionRuntimeModesRAII ModeRAII(
1312 CurrentExecutionMode, RequiresFullRuntime,
1313 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1314 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001315 EntryFunctionState EST;
1316
1317 // Emit target region as a standalone region.
1318 class NVPTXPrePostActionTy : public PrePostActionTy {
1319 CGOpenMPRuntimeNVPTX &RT;
1320 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1321 const OMPExecutableDirective &D;
1322
1323 public:
1324 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1325 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1326 const OMPExecutableDirective &D)
1327 : RT(RT), EST(EST), D(D) {}
1328 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001329 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001330 // Skip target region initialization.
1331 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001332 }
1333 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001334 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001335 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001336 }
1337 } Action(*this, EST, D);
1338 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001339 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001340 // Reserve place for the globalized memory.
1341 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001342 if (!KernelStaticGlobalized) {
1343 KernelStaticGlobalized = new llvm::GlobalVariable(
1344 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1345 llvm::GlobalValue::InternalLinkage,
1346 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1347 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1348 llvm::GlobalValue::NotThreadLocal,
1349 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1350 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001351 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1352 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001353 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001354}
1355
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001356void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001357 CodeGenFunction &CGF, EntryFunctionState &EST,
1358 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001359 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001360
1361 // Setup BBs in entry function.
1362 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1363 EST.ExitBB = CGF.createBasicBlock(".exit");
1364
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001365 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1366 /*RequiresOMPRuntime=*/
1367 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1368 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001369 CGF.EmitRuntimeCall(
1370 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001371
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001372 if (RequiresFullRuntime) {
1373 // For data sharing, we need to initialize the stack.
1374 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1375 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1376 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001377
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001378 CGF.EmitBranch(ExecuteBB);
1379
1380 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001381
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001382 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001383}
1384
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001385void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001386 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001387 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001388 if (!CGF.HaveInsertPoint())
1389 return;
1390
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001391 if (!EST.ExitBB)
1392 EST.ExitBB = CGF.createBasicBlock(".exit");
1393
1394 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1395 CGF.EmitBranch(OMPDeInitBB);
1396
1397 CGF.EmitBlock(OMPDeInitBB);
1398 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001399 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1400 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001401 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001402 createNVPTXRuntimeFunction(
1403 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001404 CGF.EmitBranch(EST.ExitBB);
1405
1406 CGF.EmitBlock(EST.ExitBB);
1407 EST.ExitBB = nullptr;
1408}
1409
1410// Create a unique global variable to indicate the execution mode of this target
1411// region. The execution mode is either 'generic', or 'spmd' depending on the
1412// target directive. This variable is picked up by the offload library to setup
1413// the device appropriately before kernel launch. If the execution mode is
1414// 'generic', the runtime reserves one warp for the master, otherwise, all
1415// warps participate in parallel work.
1416static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001417 bool Mode) {
1418 auto *GVMode =
1419 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1420 llvm::GlobalValue::WeakAnyLinkage,
1421 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1422 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001423 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001424}
1425
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001426void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001427 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001428
1429 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001430 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001431 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001432 emitWorkerLoop(CGF, WST);
1433 CGF.FinishFunction();
1434}
1435
1436void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1437 WorkerFunctionState &WST) {
1438 //
1439 // The workers enter this loop and wait for parallel work from the master.
1440 // When the master encounters a parallel region it sets up the work + variable
1441 // arguments, and wakes up the workers. The workers first check to see if
1442 // they are required for the parallel region, i.e., within the # of requested
1443 // parallel threads. The activated workers load the variable arguments and
1444 // execute the parallel work.
1445 //
1446
1447 CGBuilderTy &Bld = CGF.Builder;
1448
1449 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1450 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1451 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1452 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1453 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1454 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1455
1456 CGF.EmitBranch(AwaitBB);
1457
1458 // Workers wait for work from master.
1459 CGF.EmitBlock(AwaitBB);
1460 // Wait for parallel work
1461 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001462
1463 Address WorkFn =
1464 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1465 Address ExecStatus =
1466 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1467 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1468 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1469
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001470 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001471 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001472 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001473 llvm::Value *Ret = CGF.EmitRuntimeCall(
1474 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1475 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001476
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001477 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001478 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1479 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001480 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1481
1482 // Activate requested workers.
1483 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001484 llvm::Value *IsActive =
1485 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1486 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001487
1488 // Signal start of parallel region.
1489 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001490 // Skip initialization.
1491 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001492
1493 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001494 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001495 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001496 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001497
1498 llvm::Value *WorkFnMatch =
1499 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1500
1501 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1502 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1503 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1504
1505 // Execute this outlined function.
1506 CGF.EmitBlock(ExecuteFNBB);
1507
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001508 // Insert call to work function via shared wrapper. The shared
1509 // wrapper takes two arguments:
1510 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001511 // - the thread ID;
1512 emitCall(CGF, WST.Loc, W,
1513 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001514
1515 // Go to end of parallel region.
1516 CGF.EmitBranch(TerminateBB);
1517
1518 CGF.EmitBlock(CheckNextBB);
1519 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001520 // Default case: call to outlined function through pointer if the target
1521 // region makes a declare target call that may contain an orphaned parallel
1522 // directive.
1523 auto *ParallelFnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001525 /*isVarArg=*/false);
1526 llvm::Value *WorkFnCast =
1527 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001528 // Insert call to work function via shared wrapper. The shared
1529 // wrapper takes two arguments:
1530 // - the parallelism level;
1531 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001532 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001533 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1534 // Go to end of parallel region.
1535 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001536
1537 // Signal end of parallel region.
1538 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001539 CGF.EmitRuntimeCall(
1540 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1541 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001542 CGF.EmitBranch(BarrierBB);
1543
1544 // All active and inactive workers wait at a barrier after parallel region.
1545 CGF.EmitBlock(BarrierBB);
1546 // Barrier after parallel region.
1547 syncCTAThreads(CGF);
1548 CGF.EmitBranch(AwaitBB);
1549
1550 // Exit target region.
1551 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001552 // Skip initialization.
1553 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001554}
1555
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001556/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001557/// implementation. Specialized for the NVPTX device.
1558/// \param Function OpenMP runtime function.
1559/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001560llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001561CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001562 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001563 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1564 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001565 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1566 // RequiresOMPRuntime);
1567 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001568 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001569 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1571 break;
1572 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001573 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001574 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1575 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001576 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001577 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1579 break;
1580 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001581 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1582 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001583 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001584 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001585 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001586 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1588 break;
1589 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001590 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1591 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1592 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001593 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001594 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1595 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001596 break;
1597 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001598 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1599 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001600 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001601 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001602 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001603 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1604 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1605 break;
1606 }
1607 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001608 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1609 /// int16_t IsOMPRuntimeInitialized);
1610 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001611 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001612 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001613 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1615 break;
1616 }
1617 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1618 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001619 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001620 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1622 break;
1623 }
1624 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1625 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1626 // global_tid);
1627 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001628 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001629 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1630 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1631 break;
1632 }
1633 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1634 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1635 // global_tid);
1636 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001637 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001638 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1639 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1640 break;
1641 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001642 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1643 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1644 // int16_t lane_offset, int16_t warp_size);
1645 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001646 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001647 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1648 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1649 break;
1650 }
1651 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1652 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1653 // int16_t lane_offset, int16_t warp_size);
1654 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001655 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001656 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1658 break;
1659 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001660 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001661 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1662 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1663 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1664 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1665 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001666 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1667 CGM.Int16Ty, CGM.Int16Ty};
1668 auto *ShuffleReduceFnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1670 /*isVarArg=*/false);
1671 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1672 auto *InterWarpCopyFnTy =
1673 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1674 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001675 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1676 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001677 CGM.Int32Ty,
1678 CGM.SizeTy,
1679 CGM.VoidPtrTy,
1680 ShuffleReduceFnTy->getPointerTo(),
1681 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001682 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1684 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001685 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001686 break;
1687 }
1688 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1689 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1690 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001691 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1693 RTLFn = CGM.CreateRuntimeFunction(
1694 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1695 break;
1696 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001697 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1698 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1699 // global_tid, void *global_buffer, int32_t num_of_records, void*
1700 // reduce_data,
1701 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1702 // lane_offset, int16_t shortCircuit),
1703 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1704 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1705 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1706 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1707 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1708 // *buffer, int idx, void *reduce_data));
1709 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1710 CGM.Int16Ty, CGM.Int16Ty};
1711 auto *ShuffleReduceFnTy =
1712 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1713 /*isVarArg=*/false);
1714 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1715 auto *InterWarpCopyFnTy =
1716 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1717 /*isVarArg=*/false);
1718 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1719 CGM.VoidPtrTy};
1720 auto *GlobalListFnTy =
1721 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1722 /*isVarArg=*/false);
1723 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1724 CGM.Int32Ty,
1725 CGM.VoidPtrTy,
1726 CGM.Int32Ty,
1727 CGM.VoidPtrTy,
1728 ShuffleReduceFnTy->getPointerTo(),
1729 InterWarpCopyFnTy->getPointerTo(),
1730 GlobalListFnTy->getPointerTo(),
1731 GlobalListFnTy->getPointerTo(),
1732 GlobalListFnTy->getPointerTo(),
1733 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001734 auto *FnTy =
1735 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1736 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001737 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001738 break;
1739 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001740 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1741 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001742 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001743 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1745 break;
1746 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001747 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1748 /// Build void __kmpc_data_sharing_init_stack_spmd();
1749 auto *FnTy =
1750 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001751 RTLFn =
1752 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001753 break;
1754 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001755 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1756 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001757 // int16_t UseSharedMemory);
1758 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001759 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001760 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1761 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001762 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001763 break;
1764 }
1765 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1766 // Build void __kmpc_data_sharing_pop_stack(void *a);
1767 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001768 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001769 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1771 /*Name=*/"__kmpc_data_sharing_pop_stack");
1772 break;
1773 }
1774 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1775 /// Build void __kmpc_begin_sharing_variables(void ***args,
1776 /// size_t n_args);
1777 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001778 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001779 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1781 break;
1782 }
1783 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1784 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001785 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001786 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1788 break;
1789 }
1790 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1791 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1792 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001793 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1795 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1796 break;
1797 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001798 case OMPRTL_NVPTX__kmpc_parallel_level: {
1799 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1800 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1801 auto *FnTy =
1802 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1804 break;
1805 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001806 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1807 // Build int8_t __kmpc_is_spmd_exec_mode();
1808 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1809 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1810 break;
1811 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001812 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001813 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1814 // const void *buf, size_t size, int16_t is_shared, const void **res);
1815 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1816 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001817 auto *FnTy =
1818 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1820 break;
1821 }
1822 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001823 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1824 // int16_t is_shared);
1825 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001826 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001827 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001828 RTLFn =
1829 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1830 break;
1831 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001832 case OMPRTL__kmpc_barrier: {
1833 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1834 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1835 auto *FnTy =
1836 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1837 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001838 cast<llvm::Function>(RTLFn.getCallee())
1839 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001840 break;
1841 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001842 case OMPRTL__kmpc_barrier_simple_spmd: {
1843 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1844 // global_tid);
1845 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1846 auto *FnTy =
1847 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1848 RTLFn =
1849 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001850 cast<llvm::Function>(RTLFn.getCallee())
1851 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001852 break;
1853 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001854 }
1855 return RTLFn;
1856}
1857
1858void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1859 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001860 uint64_t Size, int32_t,
1861 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001862 // TODO: Add support for global variables on the device after declare target
1863 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001864 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001865 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001866 llvm::Module &M = CGM.getModule();
1867 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001868
1869 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001870 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001871
1872 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001873 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001874 llvm::ConstantAsMetadata::get(
1875 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1876 // Append metadata to nvvm.annotations
1877 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1878}
1879
1880void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1881 const OMPExecutableDirective &D, StringRef ParentName,
1882 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001883 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001884 if (!IsOffloadEntry) // Nothing to do.
1885 return;
1886
1887 assert(!ParentName.empty() && "Invalid target region parent name!");
1888
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001889 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001890 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001891 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001892 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001893 else
1894 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1895 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001896
1897 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001898}
1899
Alexey Bataevceeaa482018-11-21 21:04:34 +00001900namespace {
1901LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1902/// Enum for accesseing the reserved_2 field of the ident_t struct.
1903enum ModeFlagsTy : unsigned {
1904 /// Bit set to 1 when in SPMD mode.
1905 KMP_IDENT_SPMD_MODE = 0x01,
1906 /// Bit set to 1 when a simplified runtime is used.
1907 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1908 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1909};
1910
1911/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1912static const ModeFlagsTy UndefinedMode =
1913 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1914} // anonymous namespace
1915
1916unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001917 switch (getExecutionMode()) {
1918 case EM_SPMD:
1919 if (requiresFullRuntime())
1920 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1921 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1922 case EM_NonSPMD:
1923 assert(requiresFullRuntime() && "Expected full runtime.");
1924 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1925 case EM_Unknown:
1926 return UndefinedMode;
1927 }
1928 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001929}
1930
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001931CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001932 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001933 if (!CGM.getLangOpts().OpenMPIsDevice)
1934 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001935}
Carlo Bertollic6872252016-04-04 15:55:02 +00001936
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001937void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1938 OpenMPProcBindClauseKind ProcBind,
1939 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001940 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001941 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001942 return;
1943
1944 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1945}
1946
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001947void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1948 llvm::Value *NumThreads,
1949 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001950 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001951 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001952 return;
1953
1954 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1955}
1956
Carlo Bertollic6872252016-04-04 15:55:02 +00001957void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1958 const Expr *NumTeams,
1959 const Expr *ThreadLimit,
1960 SourceLocation Loc) {}
1961
James Y Knight9871db02019-02-05 16:42:33 +00001962llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001963 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1964 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001965 // Emit target region as a standalone region.
1966 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001967 bool &IsInParallelRegion;
1968 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969
1970 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001971 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1972 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001973 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001974 PrevIsInParallelRegion = IsInParallelRegion;
1975 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001976 }
1977 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001978 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001979 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001980 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001981 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001982 bool PrevIsInTTDRegion = IsInTTDRegion;
1983 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001984 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1985 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001986 auto *OutlinedFun =
1987 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1988 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001989 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001990 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001991 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1992 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001993 llvm::Function *WrapperFun =
1994 createParallelDataSharingWrapper(OutlinedFun, D);
1995 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1996 }
1997
1998 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001999}
2000
Alexey Bataev2adecff2018-09-21 14:22:53 +00002001/// Get list of lastprivate variables from the teams distribute ... or
2002/// teams {distribute ...} directives.
2003static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002004getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2006 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2007 "expected teams directive.");
2008 const OMPExecutableDirective *Dir = &D;
2009 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
2010 if (const Stmt *S = getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002011 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002012 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2013 /*IgnoreCaptured=*/true))) {
2014 Dir = dyn_cast<OMPExecutableDirective>(S);
2015 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2016 Dir = nullptr;
2017 }
2018 }
2019 if (!Dir)
2020 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002021 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002022 for (const Expr *E : C->getVarRefs())
2023 Vars.push_back(getPrivateItem(E));
2024 }
2025}
2026
2027/// Get list of reduction variables from the teams ... directives.
2028static void
2029getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2030 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2031 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2032 "expected teams directive.");
2033 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2034 for (const Expr *E : C->privates())
2035 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002036 }
2037}
2038
James Y Knight9871db02019-02-05 16:42:33 +00002039llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002040 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2041 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002042 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002043
Alexey Bataev2adecff2018-09-21 14:22:53 +00002044 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002045 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002046 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002047 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002048 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2049 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002050 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002051 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2052 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002053 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002054 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002055 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002056 }
2057 } else if (!LastPrivatesReductions.empty()) {
2058 assert(!TeamAndReductions.first &&
2059 "Previous team declaration is not expected.");
2060 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2061 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002062 }
2063
Alexey Bataevc99042b2018-03-15 18:10:54 +00002064 // Emit target region as a standalone region.
2065 class NVPTXPrePostActionTy : public PrePostActionTy {
2066 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002067 const RecordDecl *GlobalizedRD;
2068 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2069 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002070
2071 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002072 NVPTXPrePostActionTy(
2073 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2074 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2075 &MappedDeclsFields)
2076 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2077 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002078 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002079 auto &Rt =
2080 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2081 if (GlobalizedRD) {
2082 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2083 I->getSecond().GlobalRecord = GlobalizedRD;
2084 I->getSecond().MappedParams =
2085 llvm::make_unique<CodeGenFunction::OMPMapVars>();
2086 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2087 for (const auto &Pair : MappedDeclsFields) {
2088 assert(Pair.getFirst()->isCanonicalDecl() &&
2089 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002090 Data.insert(std::make_pair(Pair.getFirst(),
2091 MappedVarData(Pair.getSecond(),
2092 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002093 }
2094 }
2095 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002096 }
2097 void Exit(CodeGenFunction &CGF) override {
2098 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2099 .emitGenericVarsEpilog(CGF);
2100 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002101 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2102 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002103 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002104 D, ThreadIDVar, InnermostKind, CodeGen);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002105 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00002106 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002107 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
Carlo Bertollic6872252016-04-04 15:55:02 +00002108
2109 return OutlinedFun;
2110}
2111
Alexey Bataevc99042b2018-03-15 18:10:54 +00002112void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002113 SourceLocation Loc,
2114 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002115 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2116 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002117 return;
2118
Alexey Bataevc99042b2018-03-15 18:10:54 +00002119 CGBuilderTy &Bld = CGF.Builder;
2120
2121 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2122 if (I == FunctionGlobalizedDecls.end())
2123 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002124 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002125 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002126 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002127
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002128 // Recover pointer to this function's global record. The runtime will
2129 // handle the specifics of the allocation of the memory.
2130 // Use actual memory size of the record including the padding
2131 // for alignment purposes.
2132 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002133 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002134 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002135 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002136 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002137
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002138 llvm::PointerType *GlobalRecPtrTy =
2139 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002141 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002142 if (!IsInTTDRegion &&
2143 (WithSPMDCheck ||
2144 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002145 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2146 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2147 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002148 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2149 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2150 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2151 llvm::Value *PL = CGF.EmitRuntimeCall(
2152 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2153 {RTLoc, ThreadID});
2154 IsTTD = Bld.CreateIsNull(PL);
2155 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002156 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2157 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2158 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2159 // There is no need to emit line number for unconditional branch.
2160 (void)ApplyDebugLocation::CreateEmpty(CGF);
2161 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002162 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2163 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002164 CGF.EmitBranch(ExitBB);
2165 // There is no need to emit line number for unconditional branch.
2166 (void)ApplyDebugLocation::CreateEmpty(CGF);
2167 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002168 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2169 if (const RecordDecl *SecGlobalizedVarsRecord =
2170 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2171 SecGlobalRecTy =
2172 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2173
2174 // Recover pointer to this function's global record. The runtime will
2175 // handle the specifics of the allocation of the memory.
2176 // Use actual memory size of the record including the padding
2177 // for alignment purposes.
2178 unsigned Alignment =
2179 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2180 unsigned GlobalRecordSize =
2181 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2182 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2183 Size = Bld.CreateSelect(
2184 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2185 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002186 // TODO: allow the usage of shared memory to be controlled by
2187 // the user, for now, default to global.
2188 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002189 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002190 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2191 createNVPTXRuntimeFunction(
2192 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2193 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002194 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002195 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002196 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002197 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002198 /*NumReservedValues=*/2, "_select_stack");
2199 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2200 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2201 GlobalRecCastAddr = Phi;
2202 I->getSecond().GlobalRecordAddr = Phi;
2203 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002204 } else if (IsInTTDRegion) {
2205 assert(GlobalizedRecords.back().Records.size() < 2 &&
2206 "Expected less than 2 globalized records: one for target and one "
2207 "for teams.");
2208 unsigned Offset = 0;
2209 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2210 QualType RDTy = CGM.getContext().getRecordType(RD);
2211 unsigned Alignment =
2212 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2213 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2214 Offset =
2215 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2216 }
2217 unsigned Alignment =
2218 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2219 Offset = llvm::alignTo(Offset, Alignment);
2220 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2221 ++GlobalizedRecords.back().RegionCounter;
2222 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002223 assert(KernelStaticGlobalized &&
2224 "Kernel static pointer must be initialized already.");
2225 auto *UseSharedMemory = new llvm::GlobalVariable(
2226 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2227 llvm::GlobalValue::InternalLinkage, nullptr,
2228 "_openmp_static_kernel$is_shared");
2229 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2230 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2231 /*DestWidth=*/16, /*Signed=*/0);
2232 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2233 Address(UseSharedMemory,
2234 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2235 /*Volatile=*/false, Int16Ty, Loc);
2236 auto *StaticGlobalized = new llvm::GlobalVariable(
2237 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002238 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002239 auto *RecSize = new llvm::GlobalVariable(
2240 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2241 llvm::GlobalValue::InternalLinkage, nullptr,
2242 "_openmp_static_kernel$size");
2243 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2244 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002245 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002246 CGM.getContext().getSizeType(), Loc);
2247 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2248 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002249 llvm::Value *GlobalRecordSizeArg[] = {
2250 llvm::ConstantInt::get(
2251 CGM.Int16Ty,
2252 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2253 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002254 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2255 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2256 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002257 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002258 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002259 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2260 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002261 }
2262 assert(KernelStaticGlobalized && "Global address must be set already.");
2263 Address FrameAddr = CGF.EmitLoadOfPointer(
2264 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2265 CGM.getContext()
2266 .getPointerType(CGM.getContext().VoidPtrTy)
2267 .castAs<PointerType>());
2268 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002269 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002270 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2271 I->getSecond().IsInSPMDModeFlag = nullptr;
2272 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2273 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002274 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002275 // TODO: allow the usage of shared memory to be controlled by
2276 // the user, for now, default to global.
2277 llvm::Value *GlobalRecordSizeArg[] = {
2278 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2279 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002280 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2281 createNVPTXRuntimeFunction(
2282 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2283 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002284 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002285 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002286 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2287 I->getSecond().IsInSPMDModeFlag = nullptr;
2288 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002289 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002290 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002291
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002292 // Emit the "global alloca" which is a GEP from the global declaration
2293 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002294 LValue SecBase;
2295 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2296 if (IsTTD) {
2297 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2298 llvm::PointerType *SecGlobalRecPtrTy =
2299 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2300 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2301 Bld.CreatePointerBitCastOrAddrSpaceCast(
2302 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2303 SecGlobalRecTy);
2304 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002305 for (auto &Rec : I->getSecond().LocalVarData) {
2306 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2307 llvm::Value *ParValue;
2308 if (EscapedParam) {
2309 const auto *VD = cast<VarDecl>(Rec.first);
2310 LValue ParLVal =
2311 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2312 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2313 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002314 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2315 // Emit VarAddr basing on lane-id if required.
2316 QualType VarTy;
2317 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002318 VarTy = Rec.second.FD->getType();
2319 } else {
2320 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2321 VarAddr.getAddress().getPointer(),
2322 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002323 VarTy =
2324 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002325 VarAddr = CGF.MakeAddrLValue(
2326 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2327 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002328 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002329 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002330 if (!IsInTTDRegion &&
2331 (WithSPMDCheck ||
2332 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002333 assert(I->getSecond().IsInSPMDModeFlag &&
2334 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002335 if (IsTTD) {
2336 assert(SecIt->second.IsOnePerTeam &&
2337 "Secondary glob data must be one per team.");
2338 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2339 VarAddr.setAddress(
2340 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2341 VarAddr.getPointer()),
2342 VarAddr.getAlignment()));
2343 Rec.second.PrivateAddr = VarAddr.getAddress();
2344 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002345 Address GlobalPtr = Rec.second.PrivateAddr;
2346 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2347 Rec.second.PrivateAddr = Address(
2348 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2349 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2350 LocalAddr.getAlignment());
2351 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002352 if (EscapedParam) {
2353 const auto *VD = cast<VarDecl>(Rec.first);
2354 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2355 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2356 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002357 if (IsTTD)
2358 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002359 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002360 }
2361 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2362 // Recover pointer to this function's global record. The runtime will
2363 // handle the specifics of the allocation of the memory.
2364 // Use actual memory size of the record including the padding
2365 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002366 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002367 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2368 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2369 Size = Bld.CreateNUWAdd(
2370 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2371 llvm::Value *AlignVal =
2372 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2373 Size = Bld.CreateUDiv(Size, AlignVal);
2374 Size = Bld.CreateNUWMul(Size, AlignVal);
2375 // TODO: allow the usage of shared memory to be controlled by
2376 // the user, for now, default to global.
2377 llvm::Value *GlobalRecordSizeArg[] = {
2378 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2379 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002380 createNVPTXRuntimeFunction(
2381 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002382 GlobalRecordSizeArg);
2383 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2384 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2385 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2386 CGM.getContext().getDeclAlign(VD),
2387 AlignmentSource::Decl);
2388 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2389 Base.getAddress());
2390 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002391 }
2392 I->getSecond().MappedParams->apply(CGF);
2393}
2394
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002395void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2396 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002397 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2398 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002399 return;
2400
Alexey Bataevc99042b2018-03-15 18:10:54 +00002401 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002402 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002403 I->getSecond().MappedParams->restore(CGF);
2404 if (!CGF.HaveInsertPoint())
2405 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002406 for (llvm::Value *Addr :
2407 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2408 CGF.EmitRuntimeCall(
2409 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2410 Addr);
2411 }
2412 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002413 if (!IsInTTDRegion &&
2414 (WithSPMDCheck ||
2415 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002416 CGBuilderTy &Bld = CGF.Builder;
2417 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2418 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2419 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2420 // There is no need to emit line number for unconditional branch.
2421 (void)ApplyDebugLocation::CreateEmpty(CGF);
2422 CGF.EmitBlock(NonSPMDBB);
2423 CGF.EmitRuntimeCall(
2424 createNVPTXRuntimeFunction(
2425 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2426 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2427 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002428 } else if (IsInTTDRegion) {
2429 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2430 "region counter must be > 0.");
2431 --GlobalizedRecords.back().RegionCounter;
2432 // Emit the restore function only in the target region.
2433 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002434 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2435 /*DestWidth=*/16, /*Signed=*/0);
2436 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2437 Address(GlobalizedRecords.back().UseSharedMemory,
2438 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2439 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002440 llvm::Value *Args[] = {
2441 llvm::ConstantInt::get(
2442 CGM.Int16Ty,
2443 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2444 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002445 CGF.EmitRuntimeCall(
2446 createNVPTXRuntimeFunction(
2447 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002448 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002449 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002450 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002451 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2452 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2453 I->getSecond().GlobalRecordAddr);
2454 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002455 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002456 }
2457}
2458
Carlo Bertollic6872252016-04-04 15:55:02 +00002459void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2460 const OMPExecutableDirective &D,
2461 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002462 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002463 ArrayRef<llvm::Value *> CapturedVars) {
2464 if (!CGF.HaveInsertPoint())
2465 return;
2466
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002467 Address ZeroAddr = CGF.CreateMemTemp(
2468 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2469 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002470 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2471 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002472 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002473 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2474 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002475 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002476}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002477
2478void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002479 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002480 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2481 if (!CGF.HaveInsertPoint())
2482 return;
2483
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002484 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002485 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002486 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002487 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002488}
2489
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002490void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002491 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2492 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2493 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002494
2495 // Force inline this outlined function at its call site.
2496 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2497
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002498 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2499 /*DestWidth=*/32, /*Signed=*/1),
2500 ".zero.addr");
2501 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002502 // ThreadId for serialized parallels is 0.
2503 Address ThreadIDAddr = ZeroAddr;
2504 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002505 CodeGenFunction &CGF, PrePostActionTy &Action) {
2506 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002507
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002508 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2509 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2510 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2511 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2512 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2513 };
2514 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2515 PrePostActionTy &) {
2516
2517 RegionCodeGenTy RCG(CodeGen);
2518 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2519 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2520 llvm::Value *Args[] = {RTLoc, ThreadID};
2521
2522 NVPTXActionTy Action(
2523 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2524 Args,
2525 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2526 Args);
2527 RCG.setAction(Action);
2528 RCG(CGF);
2529 };
2530
2531 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2532 PrePostActionTy &Action) {
2533 CGBuilderTy &Bld = CGF.Builder;
2534 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2535 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002536 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2537
2538 // Prepare for parallel region. Indicate the outlined function.
2539 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002540 CGF.EmitRuntimeCall(
2541 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2542 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002543
2544 // Create a private scope that will globalize the arguments
2545 // passed from the outside of the target region.
2546 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2547
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002548 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002549 if (!CapturedVars.empty()) {
2550 // Prepare for parallel region. Indicate the outlined function.
2551 Address SharedArgs =
2552 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2553 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2554
2555 llvm::Value *DataSharingArgs[] = {
2556 SharedArgsPtr,
2557 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2558 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2559 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2560 DataSharingArgs);
2561
2562 // Store variable address in a list of references to pass to workers.
2563 unsigned Idx = 0;
2564 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002565 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2566 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2567 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002568 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002569 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002570 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002571 if (V->getType()->isIntegerTy())
2572 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2573 else
2574 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002575 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2576 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002577 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002578 }
2579 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002580
2581 // Activate workers. This barrier is used by the master to signal
2582 // work for the workers.
2583 syncCTAThreads(CGF);
2584
2585 // OpenMP [2.5, Parallel Construct, p.49]
2586 // There is an implied barrier at the end of a parallel region. After the
2587 // end of a parallel region, only the master thread of the team resumes
2588 // execution of the enclosing task region.
2589 //
2590 // The master waits at this barrier until all workers are done.
2591 syncCTAThreads(CGF);
2592
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002593 if (!CapturedVars.empty())
2594 CGF.EmitRuntimeCall(
2595 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2596
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002597 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002598 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002599 };
2600
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002601 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2602 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002603 if (IsInParallelRegion) {
2604 SeqGen(CGF, Action);
2605 } else if (IsInTargetMasterThreadRegion) {
2606 L0ParallelGen(CGF, Action);
2607 } else {
2608 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002609 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002610 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002611 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002612 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002613 // }
2614 CGBuilderTy &Bld = CGF.Builder;
2615 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002616 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2617 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002618 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002619 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2620 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002621 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002622 // There is no need to emit line number for unconditional branch.
2623 (void)ApplyDebugLocation::CreateEmpty(CGF);
2624 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002625 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2626 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2627 llvm::Value *PL = CGF.EmitRuntimeCall(
2628 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2629 {RTLoc, ThreadID});
2630 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002631 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002632 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002633 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002634 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002635 // There is no need to emit line number for unconditional branch.
2636 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002637 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002638 L0ParallelGen(CGF, Action);
2639 CGF.EmitBranch(ExitBB);
2640 // There is no need to emit line number for unconditional branch.
2641 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002642 // Emit the continuation block for code after the if.
2643 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2644 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002645 };
2646
Alexey Bataev9ff80832018-04-16 20:16:21 +00002647 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002648 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002649 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002650 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002651 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002652 ThenRCG(CGF);
2653 }
2654}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002655
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002656void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002657 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002658 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2659 // Just call the outlined function to execute the parallel region.
2660 // OutlinedFn(&GTid, &zero, CapturedStruct);
2661 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002662 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002663
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002664 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2665 /*DestWidth=*/32, /*Signed=*/1),
2666 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002667 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002668 // ThreadId for serialized parallels is 0.
2669 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002670 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002671 &ThreadIDAddr](CodeGenFunction &CGF,
2672 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002673 Action.Enter(CGF);
2674
2675 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2676 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2677 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2678 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2679 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2680 };
2681 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2682 PrePostActionTy &) {
2683
2684 RegionCodeGenTy RCG(CodeGen);
2685 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2686 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2687 llvm::Value *Args[] = {RTLoc, ThreadID};
2688
2689 NVPTXActionTy Action(
2690 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2691 Args,
2692 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2693 Args);
2694 RCG.setAction(Action);
2695 RCG(CGF);
2696 };
2697
2698 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002699 // In the worker need to use the real thread id.
2700 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002701 RegionCodeGenTy RCG(CodeGen);
2702 RCG(CGF);
2703 } else {
2704 // If we are not in the target region, it is definitely L2 parallelism or
2705 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2706 // need to check for orphaned directives.
2707 RegionCodeGenTy RCG(SeqGen);
2708 RCG(CGF);
2709 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002710}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002711
Alexey Bataeva3924b52019-01-03 16:25:35 +00002712void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2713 // Always emit simple barriers!
2714 if (!CGF.HaveInsertPoint())
2715 return;
2716 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2717 // This function does not use parameters, so we can emit just default values.
2718 llvm::Value *Args[] = {
2719 llvm::ConstantPointerNull::get(
2720 cast<llvm::PointerType>(getIdentTyPointerTy())),
2721 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
2722 CGF.EmitRuntimeCall(
2723 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
2724}
2725
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002726void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2727 SourceLocation Loc,
2728 OpenMPDirectiveKind Kind, bool,
2729 bool) {
2730 // Always emit simple barriers!
2731 if (!CGF.HaveInsertPoint())
2732 return;
2733 // Build call __kmpc_cancel_barrier(loc, thread_id);
2734 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2735 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2736 getThreadID(CGF, Loc)};
2737 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2738}
2739
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002740void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2741 CodeGenFunction &CGF, StringRef CriticalName,
2742 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2743 const Expr *Hint) {
2744 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2745 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2746 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2747 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2748 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2749
2750 // Fetch team-local id of the thread.
2751 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2752
2753 // Get the width of the team.
2754 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2755
2756 // Initialize the counter variable for the loop.
2757 QualType Int32Ty =
2758 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2759 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2760 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2761 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2762 /*isInit=*/true);
2763
2764 // Block checks if loop counter exceeds upper bound.
2765 CGF.EmitBlock(LoopBB);
2766 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2767 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2768 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2769
2770 // Block tests which single thread should execute region, and which threads
2771 // should go straight to synchronisation point.
2772 CGF.EmitBlock(TestBB);
2773 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2774 llvm::Value *CmpThreadToCounter =
2775 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2776 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2777
2778 // Block emits the body of the critical region.
2779 CGF.EmitBlock(BodyBB);
2780
2781 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002782 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2783 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002784
2785 // After the body surrounded by the critical region, the single executing
2786 // thread will jump to the synchronisation point.
2787 // Block waits for all threads in current team to finish then increments the
2788 // counter variable and returns to the loop.
2789 CGF.EmitBlock(SyncBB);
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002790 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false,
2791 /*ForceSimpleCall=*/true);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002792
2793 llvm::Value *IncCounterVal =
2794 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2795 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2796 CGF.EmitBranch(LoopBB);
2797
2798 // Block that is reached when all threads in the team complete the region.
2799 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2800}
2801
Alexey Bataevb2575932018-01-04 20:18:55 +00002802/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002803static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2804 QualType ValTy, QualType CastTy,
2805 SourceLocation Loc) {
2806 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2807 "Cast type must sized.");
2808 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2809 "Val type must sized.");
2810 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2811 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002812 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002813 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2814 CGF.getContext().getTypeSizeInChars(CastTy))
2815 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2816 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2817 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2818 CastTy->hasSignedIntegerRepresentation());
2819 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002820 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2821 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002822 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2823 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002824}
2825
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002826/// This function creates calls to one of two shuffle functions to copy
2827/// variables between lanes in a warp.
2828static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002830 QualType ElemType,
2831 llvm::Value *Offset,
2832 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002833 CodeGenModule &CGM = CGF.CGM;
2834 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002835 CGOpenMPRuntimeNVPTX &RT =
2836 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2837
Alexey Bataeva453f362018-03-19 17:53:56 +00002838 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2839 assert(Size.getQuantity() <= 8 &&
2840 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002841
Alexey Bataeva453f362018-03-19 17:53:56 +00002842 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002843 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2844 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2845
2846 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002847 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2848 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2849 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002850 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002851 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002852
Alexey Bataev9ff80832018-04-16 20:16:21 +00002853 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2854 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002855
Alexey Bataeva453f362018-03-19 17:53:56 +00002856 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002857}
2858
Alexey Bataev12c62902018-06-22 19:10:38 +00002859static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2860 Address DestAddr, QualType ElemType,
2861 llvm::Value *Offset, SourceLocation Loc) {
2862 CGBuilderTy &Bld = CGF.Builder;
2863
2864 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2865 // Create the loop over the big sized data.
2866 // ptr = (void*)Elem;
2867 // ptrEnd = (void*) Elem + 1;
2868 // Step = 8;
2869 // while (ptr + Step < ptrEnd)
2870 // shuffle((int64_t)*ptr);
2871 // Step = 4;
2872 // while (ptr + Step < ptrEnd)
2873 // shuffle((int32_t)*ptr);
2874 // ...
2875 Address ElemPtr = DestAddr;
2876 Address Ptr = SrcAddr;
2877 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002878 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002879 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2880 if (Size < CharUnits::fromQuantity(IntSize))
2881 continue;
2882 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2883 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2884 /*Signed=*/1);
2885 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2886 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2887 ElemPtr =
2888 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2889 if (Size.getQuantity() / IntSize > 1) {
2890 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2891 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2892 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2893 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2894 CGF.EmitBlock(PreCondBB);
2895 llvm::PHINode *PhiSrc =
2896 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2897 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2898 llvm::PHINode *PhiDest =
2899 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2900 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2901 Ptr = Address(PhiSrc, Ptr.getAlignment());
2902 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2903 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2904 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2905 Ptr.getPointer(), CGF.VoidPtrTy));
2906 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2907 ThenBB, ExitBB);
2908 CGF.EmitBlock(ThenBB);
2909 llvm::Value *Res = createRuntimeShuffleFunction(
2910 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2911 IntType, Offset, Loc);
2912 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002913 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2914 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002915 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2916 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002917 CGF.EmitBranch(PreCondBB);
2918 CGF.EmitBlock(ExitBB);
2919 } else {
2920 llvm::Value *Res = createRuntimeShuffleFunction(
2921 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2922 IntType, Offset, Loc);
2923 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002924 Ptr = Bld.CreateConstGEP(Ptr, 1);
2925 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002926 }
2927 Size = Size % IntSize;
2928 }
2929}
2930
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002931namespace {
2932enum CopyAction : unsigned {
2933 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2934 // the warp using shuffle instructions.
2935 RemoteLaneToThread,
2936 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2937 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002938 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2939 ThreadToScratchpad,
2940 // ScratchpadToThread: Copy from a scratchpad array in global memory
2941 // containing team-reduced data to a thread's stack.
2942 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002943};
2944} // namespace
2945
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002946struct CopyOptionsTy {
2947 llvm::Value *RemoteLaneOffset;
2948 llvm::Value *ScratchpadIndex;
2949 llvm::Value *ScratchpadWidth;
2950};
2951
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002952/// Emit instructions to copy a Reduce list, which contains partially
2953/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002954static void emitReductionListCopy(
2955 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2956 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2957 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958
Alexey Bataev9ff80832018-04-16 20:16:21 +00002959 CodeGenModule &CGM = CGF.CGM;
2960 ASTContext &C = CGM.getContext();
2961 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002962
Alexey Bataev9ff80832018-04-16 20:16:21 +00002963 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2964 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2965 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002966
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002967 // Iterates, element-by-element, through the source Reduce list and
2968 // make a copy.
2969 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002970 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002971 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002972 Address SrcElementAddr = Address::invalid();
2973 Address DestElementAddr = Address::invalid();
2974 Address DestElementPtrAddr = Address::invalid();
2975 // Should we shuffle in an element from a remote lane?
2976 bool ShuffleInElement = false;
2977 // Set to true to update the pointer in the dest Reduce list to a
2978 // newly created element.
2979 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002980 // Increment the src or dest pointer to the scratchpad, for each
2981 // new element.
2982 bool IncrScratchpadSrc = false;
2983 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002984
2985 switch (Action) {
2986 case RemoteLaneToThread: {
2987 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002988 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002989 SrcElementAddr = CGF.EmitLoadOfPointer(
2990 SrcElementPtrAddr,
2991 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002992
2993 // Step 1.2: Create a temporary to store the element in the destination
2994 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002995 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002996 DestElementAddr =
2997 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2998 ShuffleInElement = true;
2999 UpdateDestListPtr = true;
3000 break;
3001 }
3002 case ThreadCopy: {
3003 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003004 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003005 SrcElementAddr = CGF.EmitLoadOfPointer(
3006 SrcElementPtrAddr,
3007 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003008
3009 // Step 1.2: Get the address for dest element. The destination
3010 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003011 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003012 DestElementAddr = CGF.EmitLoadOfPointer(
3013 DestElementPtrAddr,
3014 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003015 break;
3016 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003017 case ThreadToScratchpad: {
3018 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003019 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003020 SrcElementAddr = CGF.EmitLoadOfPointer(
3021 SrcElementPtrAddr,
3022 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003023
3024 // Step 1.2: Get the address for dest element:
3025 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003026 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003027 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003028 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003029 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003030 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003031 ScratchPadElemAbsolutePtrVal =
3032 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003033 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3034 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003035 IncrScratchpadDest = true;
3036 break;
3037 }
3038 case ScratchpadToThread: {
3039 // Step 1.1: Get the address for the src element in the scratchpad.
3040 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003041 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003042 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003043 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003044 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003045 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003046 ScratchPadElemAbsolutePtrVal =
3047 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3048 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3049 C.getTypeAlignInChars(Private->getType()));
3050 IncrScratchpadSrc = true;
3051
3052 // Step 1.2: Create a temporary to store the element in the destination
3053 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003054 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003055 DestElementAddr =
3056 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3057 UpdateDestListPtr = true;
3058 break;
3059 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003060 }
3061
3062 // Regardless of src and dest of copy, we emit the load of src
3063 // element as this is required in all directions
3064 SrcElementAddr = Bld.CreateElementBitCast(
3065 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003066 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3067 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003068
3069 // Now that all active lanes have read the element in the
3070 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003071 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003072 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3073 RemoteLaneOffset, Private->getExprLoc());
3074 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003075 switch (CGF.getEvaluationKind(Private->getType())) {
3076 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003077 llvm::Value *Elem =
3078 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3079 Private->getType(), Private->getExprLoc());
3080 // Store the source element value to the dest element address.
3081 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3082 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003083 break;
3084 }
3085 case TEK_Complex: {
3086 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3087 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3088 Private->getExprLoc());
3089 CGF.EmitStoreOfComplex(
3090 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3091 /*isInit=*/false);
3092 break;
3093 }
3094 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003095 CGF.EmitAggregateCopy(
3096 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3097 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3098 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003099 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003100 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003101 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003102
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003103 // Step 3.1: Modify reference in dest Reduce list as needed.
3104 // Modifying the reference in Reduce list to point to the newly
3105 // created element. The element is live in the current function
3106 // scope and that of functions it invokes (i.e., reduce_function).
3107 // RemoteReduceData[i] = (void*)&RemoteElem
3108 if (UpdateDestListPtr) {
3109 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3110 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3111 DestElementPtrAddr, /*Volatile=*/false,
3112 C.VoidPtrTy);
3113 }
3114
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003115 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3116 // address of the next element in scratchpad memory, unless we're currently
3117 // processing the last one. Memory alignment is also taken care of here.
3118 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3119 llvm::Value *ScratchpadBasePtr =
3120 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003121 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3122 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003123 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003124 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003125
3126 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003127 ScratchpadBasePtr = Bld.CreateNUWSub(
3128 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3129 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003130 ScratchpadBasePtr,
3131 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003132 ScratchpadBasePtr = Bld.CreateNUWAdd(
3133 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3134 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003135 ScratchpadBasePtr,
3136 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3137
3138 if (IncrScratchpadDest)
3139 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3140 else /* IncrScratchpadSrc = true */
3141 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3142 }
3143
Alexey Bataev9ff80832018-04-16 20:16:21 +00003144 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003145 }
3146}
3147
3148/// This function emits a helper that gathers Reduce lists from the first
3149/// lane of every active warp to lanes in the first warp.
3150///
3151/// void inter_warp_copy_func(void* reduce_data, num_warps)
3152/// shared smem[warp_size];
3153/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003154/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003155/// If (I am the first lane in each warp)
3156/// Copy my local D to smem[warp_id]
3157/// sync
3158/// if (I am the first warp)
3159/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3161 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003162 QualType ReductionArrayTy,
3163 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003164 ASTContext &C = CGM.getContext();
3165 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166
3167 // ReduceList: thread local Reduce list.
3168 // At the stage of the computation when this function is called, partially
3169 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003170 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3171 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172 // NumWarps: number of warps active in the parallel region. This could
3173 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003174 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003175 C.getIntTypeForBitwidth(32, /* Signed */ true),
3176 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003177 FunctionArgList Args;
3178 Args.push_back(&ReduceListArg);
3179 Args.push_back(&NumWarpsArg);
3180
Alexey Bataev9ff80832018-04-16 20:16:21 +00003181 const CGFunctionInfo &CGFI =
3182 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003183 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3184 llvm::GlobalValue::InternalLinkage,
3185 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003186 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003187 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003188 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003189 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003190
Alexey Bataev9ff80832018-04-16 20:16:21 +00003191 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003192
3193 // This array is used as a medium to transfer, one reduce element at a time,
3194 // the data from the first lane of every warp to lanes in the first warp
3195 // in order to perform the final step of a reduction in a parallel region
3196 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3197 // for reduced latency, as well as to have a distinct copy for concurrently
3198 // executing target regions. The array is declared with common linkage so
3199 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003200 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003201 "__openmp_nvptx_data_transfer_temporary_storage";
3202 llvm::GlobalVariable *TransferMedium =
3203 M.getGlobalVariable(TransferMediumName);
3204 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003205 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003206 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3207 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003208 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003209 llvm::Constant::getNullValue(Ty), TransferMediumName,
3210 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3211 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003212 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003213 }
3214
3215 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003216 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003217 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003218 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003219 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003220 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003221
3222 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3223 Address LocalReduceList(
3224 Bld.CreatePointerBitCastOrAddrSpaceCast(
3225 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003226 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003227 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3228 CGF.getPointerAlign());
3229
3230 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003231 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003232 //
3233 // Warp master copies reduce element to transfer medium in __shared__
3234 // memory.
3235 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003236 unsigned RealTySize =
3237 C.getTypeSizeInChars(Private->getType())
3238 .alignTo(C.getTypeAlignInChars(Private->getType()))
3239 .getQuantity();
3240 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3241 unsigned NumIters = RealTySize / TySize;
3242 if (NumIters == 0)
3243 continue;
3244 QualType CType = C.getIntTypeForBitwidth(
3245 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3246 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3247 CharUnits Align = CharUnits::fromQuantity(TySize);
3248 llvm::Value *Cnt = nullptr;
3249 Address CntAddr = Address::invalid();
3250 llvm::BasicBlock *PrecondBB = nullptr;
3251 llvm::BasicBlock *ExitBB = nullptr;
3252 if (NumIters > 1) {
3253 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3254 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3255 /*Volatile=*/false, C.IntTy);
3256 PrecondBB = CGF.createBasicBlock("precond");
3257 ExitBB = CGF.createBasicBlock("exit");
3258 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3259 // There is no need to emit line number for unconditional branch.
3260 (void)ApplyDebugLocation::CreateEmpty(CGF);
3261 CGF.EmitBlock(PrecondBB);
3262 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3263 llvm::Value *Cmp =
3264 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3265 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3266 CGF.EmitBlock(BodyBB);
3267 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003268 // kmpc_barrier.
3269 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3270 /*EmitChecks=*/false,
3271 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003272 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3273 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3274 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003275
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003276 // if (lane_id == 0)
3277 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3278 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3279 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003280
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003281 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003282 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003283 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3284 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3285 // elemptr = ((CopyType*)(elemptrptr)) + I
3286 Address ElemPtr = Address(ElemPtrPtr, Align);
3287 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3288 if (NumIters > 1) {
3289 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3290 ElemPtr.getAlignment());
3291 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003292
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003293 // Get pointer to location in transfer medium.
3294 // MediumPtr = &medium[warp_id]
3295 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3296 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3297 Address MediumPtr(MediumPtrVal, Align);
3298 // Casting to actual data type.
3299 // MediumPtr = (CopyType*)MediumPtrAddr;
3300 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003301
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003302 // elem = *elemptr
3303 //*MediumPtr = elem
3304 llvm::Value *Elem =
3305 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003306 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003307 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003308
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003309 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003310
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003311 CGF.EmitBlock(ElseBB);
3312 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003315
Alexey Bataevae51b962018-12-14 21:00:58 +00003316 // kmpc_barrier.
3317 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3318 /*EmitChecks=*/false,
3319 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003320
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003321 //
3322 // Warp 0 copies reduce element from transfer medium.
3323 //
3324 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3325 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3326 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327
Alexey Bataevae51b962018-12-14 21:00:58 +00003328 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3329 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3330 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3331
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003332 // Up to 32 threads in warp 0 are active.
3333 llvm::Value *IsActiveThread =
3334 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3335 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003336
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003337 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003338
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003339 // SrcMediumPtr = &medium[tid]
3340 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3341 TransferMedium,
3342 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3343 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3344 // SrcMediumVal = *SrcMediumPtr;
3345 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003346
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003347 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003348 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003349 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3350 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3351 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3352 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3353 if (NumIters > 1) {
3354 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3355 TargetElemPtr.getAlignment());
3356 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003357
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003358 // *TargetElemPtr = SrcMediumVal;
3359 llvm::Value *SrcMediumValue =
3360 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003361 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003362 CType);
3363 Bld.CreateBr(W0MergeBB);
3364
3365 CGF.EmitBlock(W0ElseBB);
3366 Bld.CreateBr(W0MergeBB);
3367
3368 CGF.EmitBlock(W0MergeBB);
3369
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003370 if (NumIters > 1) {
3371 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3372 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3373 CGF.EmitBranch(PrecondBB);
3374 (void)ApplyDebugLocation::CreateEmpty(CGF);
3375 CGF.EmitBlock(ExitBB);
3376 }
3377 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003378 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003379 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003380 }
3381
3382 CGF.FinishFunction();
3383 return Fn;
3384}
3385
3386/// Emit a helper that reduces data across two OpenMP threads (lanes)
3387/// in the same warp. It uses shuffle instructions to copy over data from
3388/// a remote lane's stack. The reduction algorithm performed is specified
3389/// by the fourth parameter.
3390///
3391/// Algorithm Versions.
3392/// Full Warp Reduce (argument value 0):
3393/// This algorithm assumes that all 32 lanes are active and gathers
3394/// data from these 32 lanes, producing a single resultant value.
3395/// Contiguous Partial Warp Reduce (argument value 1):
3396/// This algorithm assumes that only a *contiguous* subset of lanes
3397/// are active. This happens for the last warp in a parallel region
3398/// when the user specified num_threads is not an integer multiple of
3399/// 32. This contiguous subset always starts with the zeroth lane.
3400/// Partial Warp Reduce (argument value 2):
3401/// This algorithm gathers data from any number of lanes at any position.
3402/// All reduced values are stored in the lowest possible lane. The set
3403/// of problems every algorithm addresses is a super set of those
3404/// addressable by algorithms with a lower version number. Overhead
3405/// increases as algorithm version increases.
3406///
3407/// Terminology
3408/// Reduce element:
3409/// Reduce element refers to the individual data field with primitive
3410/// data types to be combined and reduced across threads.
3411/// Reduce list:
3412/// Reduce list refers to a collection of local, thread-private
3413/// reduce elements.
3414/// Remote Reduce list:
3415/// Remote Reduce list refers to a collection of remote (relative to
3416/// the current thread) reduce elements.
3417///
3418/// We distinguish between three states of threads that are important to
3419/// the implementation of this function.
3420/// Alive threads:
3421/// Threads in a warp executing the SIMT instruction, as distinguished from
3422/// threads that are inactive due to divergent control flow.
3423/// Active threads:
3424/// The minimal set of threads that has to be alive upon entry to this
3425/// function. The computation is correct iff active threads are alive.
3426/// Some threads are alive but they are not active because they do not
3427/// contribute to the computation in any useful manner. Turning them off
3428/// may introduce control flow overheads without any tangible benefits.
3429/// Effective threads:
3430/// In order to comply with the argument requirements of the shuffle
3431/// function, we must keep all lanes holding data alive. But at most
3432/// half of them perform value aggregation; we refer to this half of
3433/// threads as effective. The other half is simply handing off their
3434/// data.
3435///
3436/// Procedure
3437/// Value shuffle:
3438/// In this step active threads transfer data from higher lane positions
3439/// in the warp to lower lane positions, creating Remote Reduce list.
3440/// Value aggregation:
3441/// In this step, effective threads combine their thread local Reduce list
3442/// with Remote Reduce list and store the result in the thread local
3443/// Reduce list.
3444/// Value copy:
3445/// In this step, we deal with the assumption made by algorithm 2
3446/// (i.e. contiguity assumption). When we have an odd number of lanes
3447/// active, say 2k+1, only k threads will be effective and therefore k
3448/// new values will be produced. However, the Reduce list owned by the
3449/// (2k+1)th thread is ignored in the value aggregation. Therefore
3450/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3451/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003452static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003453 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003454 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003455 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003456
3457 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003458 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3459 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003461 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3462 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003463 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003464 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3465 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003466 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003467 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3468 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003469 FunctionArgList Args;
3470 Args.push_back(&ReduceListArg);
3471 Args.push_back(&LaneIDArg);
3472 Args.push_back(&RemoteLaneOffsetArg);
3473 Args.push_back(&AlgoVerArg);
3474
Alexey Bataev9ff80832018-04-16 20:16:21 +00003475 const CGFunctionInfo &CGFI =
3476 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003477 auto *Fn = llvm::Function::Create(
3478 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3479 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003480 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003481 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003482 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003483 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003484
Alexey Bataev9ff80832018-04-16 20:16:21 +00003485 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003486
3487 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3488 Address LocalReduceList(
3489 Bld.CreatePointerBitCastOrAddrSpaceCast(
3490 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3491 C.VoidPtrTy, SourceLocation()),
3492 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3493 CGF.getPointerAlign());
3494
3495 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3496 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3497 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3498
3499 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3500 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3501 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3502
3503 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3504 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3505 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3506
3507 // Create a local thread-private variable to host the Reduce list
3508 // from a remote lane.
3509 Address RemoteReduceList =
3510 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3511
3512 // This loop iterates through the list of reduce elements and copies,
3513 // element by element, from a remote lane in the warp to RemoteReduceList,
3514 // hosted on the thread's stack.
3515 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3516 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003517 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3518 /*ScratchpadIndex=*/nullptr,
3519 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003520
3521 // The actions to be performed on the Remote Reduce list is dependent
3522 // on the algorithm version.
3523 //
3524 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3525 // LaneId % 2 == 0 && Offset > 0):
3526 // do the reduction value aggregation
3527 //
3528 // The thread local variable Reduce list is mutated in place to host the
3529 // reduced data, which is the aggregated value produced from local and
3530 // remote lanes.
3531 //
3532 // Note that AlgoVer is expected to be a constant integer known at compile
3533 // time.
3534 // When AlgoVer==0, the first conjunction evaluates to true, making
3535 // the entire predicate true during compile time.
3536 // When AlgoVer==1, the second conjunction has only the second part to be
3537 // evaluated during runtime. Other conjunctions evaluates to false
3538 // during compile time.
3539 // When AlgoVer==2, the third conjunction has only the second part to be
3540 // evaluated during runtime. Other conjunctions evaluates to false
3541 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003542 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003543
Alexey Bataev9ff80832018-04-16 20:16:21 +00003544 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3545 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003546 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3547
Alexey Bataev9ff80832018-04-16 20:16:21 +00003548 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3549 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3550 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003551 CondAlgo2 = Bld.CreateAnd(
3552 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3553
Alexey Bataev9ff80832018-04-16 20:16:21 +00003554 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003555 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3556
3557 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3558 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3559 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3560 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3561
3562 CGF.EmitBlock(ThenBB);
3563 // reduce_function(LocalReduceList, RemoteReduceList)
3564 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3565 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3566 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3567 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003568 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3569 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003570 Bld.CreateBr(MergeBB);
3571
3572 CGF.EmitBlock(ElseBB);
3573 Bld.CreateBr(MergeBB);
3574
3575 CGF.EmitBlock(MergeBB);
3576
3577 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3578 // Reduce list.
3579 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003580 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003581 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3582
3583 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3584 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3585 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3586 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3587
3588 CGF.EmitBlock(CpyThenBB);
3589 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3590 RemoteReduceList, LocalReduceList);
3591 Bld.CreateBr(CpyMergeBB);
3592
3593 CGF.EmitBlock(CpyElseBB);
3594 Bld.CreateBr(CpyMergeBB);
3595
3596 CGF.EmitBlock(CpyMergeBB);
3597
3598 CGF.FinishFunction();
3599 return Fn;
3600}
3601
Alexey Bataev8061acd2019-02-20 16:36:22 +00003602/// This function emits a helper that copies all the reduction variables from
3603/// the team into the provided global buffer for the reduction variables.
3604///
3605/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3606/// For all data entries D in reduce_data:
3607/// Copy local D to buffer.D[Idx]
3608static llvm::Value *emitListToGlobalCopyFunction(
3609 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3610 QualType ReductionArrayTy, SourceLocation Loc,
3611 const RecordDecl *TeamReductionRec,
3612 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3613 &VarFieldMap) {
3614 ASTContext &C = CGM.getContext();
3615
3616 // Buffer: global reduction buffer.
3617 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3618 C.VoidPtrTy, ImplicitParamDecl::Other);
3619 // Idx: index of the buffer.
3620 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3621 ImplicitParamDecl::Other);
3622 // ReduceList: thread local Reduce list.
3623 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3624 C.VoidPtrTy, ImplicitParamDecl::Other);
3625 FunctionArgList Args;
3626 Args.push_back(&BufferArg);
3627 Args.push_back(&IdxArg);
3628 Args.push_back(&ReduceListArg);
3629
3630 const CGFunctionInfo &CGFI =
3631 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3632 auto *Fn = llvm::Function::Create(
3633 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3634 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3635 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3636 Fn->setDoesNotRecurse();
3637 CodeGenFunction CGF(CGM);
3638 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3639
3640 CGBuilderTy &Bld = CGF.Builder;
3641
3642 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3643 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3644 Address LocalReduceList(
3645 Bld.CreatePointerBitCastOrAddrSpaceCast(
3646 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3647 C.VoidPtrTy, Loc),
3648 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3649 CGF.getPointerAlign());
3650 QualType StaticTy = C.getRecordType(TeamReductionRec);
3651 llvm::Type *LLVMReductionsBufferTy =
3652 CGM.getTypes().ConvertTypeForMem(StaticTy);
3653 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3654 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3655 LLVMReductionsBufferTy->getPointerTo());
3656 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3657 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3658 /*Volatile=*/false, C.IntTy,
3659 Loc)};
3660 unsigned Idx = 0;
3661 for (const Expr *Private : Privates) {
3662 // Reduce element = LocalReduceList[i]
3663 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3664 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3665 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3666 // elemptr = ((CopyType*)(elemptrptr)) + I
3667 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3668 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3669 Address ElemPtr =
3670 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3671 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3672 // Global = Buffer.VD[Idx];
3673 const FieldDecl *FD = VarFieldMap.lookup(VD);
3674 LValue GlobLVal = CGF.EmitLValueForField(
3675 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3676 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3677 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3678 switch (CGF.getEvaluationKind(Private->getType())) {
3679 case TEK_Scalar: {
3680 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3681 Private->getType(), Loc);
3682 CGF.EmitStoreOfScalar(V, GlobLVal);
3683 break;
3684 }
3685 case TEK_Complex: {
3686 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3687 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3688 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3689 break;
3690 }
3691 case TEK_Aggregate:
3692 CGF.EmitAggregateCopy(GlobLVal,
3693 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3694 Private->getType(), AggValueSlot::DoesNotOverlap);
3695 break;
3696 }
3697 ++Idx;
3698 }
3699
3700 CGF.FinishFunction();
3701 return Fn;
3702}
3703
3704/// This function emits a helper that reduces all the reduction variables from
3705/// the team into the provided global buffer for the reduction variables.
3706///
3707/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3708/// void *GlobPtrs[];
3709/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3710/// ...
3711/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3712/// reduce_function(GlobPtrs, reduce_data);
3713static llvm::Value *emitListToGlobalReduceFunction(
3714 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3715 QualType ReductionArrayTy, SourceLocation Loc,
3716 const RecordDecl *TeamReductionRec,
3717 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3718 &VarFieldMap,
3719 llvm::Function *ReduceFn) {
3720 ASTContext &C = CGM.getContext();
3721
3722 // Buffer: global reduction buffer.
3723 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3724 C.VoidPtrTy, ImplicitParamDecl::Other);
3725 // Idx: index of the buffer.
3726 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3727 ImplicitParamDecl::Other);
3728 // ReduceList: thread local Reduce list.
3729 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3730 C.VoidPtrTy, ImplicitParamDecl::Other);
3731 FunctionArgList Args;
3732 Args.push_back(&BufferArg);
3733 Args.push_back(&IdxArg);
3734 Args.push_back(&ReduceListArg);
3735
3736 const CGFunctionInfo &CGFI =
3737 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3738 auto *Fn = llvm::Function::Create(
3739 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3740 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3741 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3742 Fn->setDoesNotRecurse();
3743 CodeGenFunction CGF(CGM);
3744 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3745
3746 CGBuilderTy &Bld = CGF.Builder;
3747
3748 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3749 QualType StaticTy = C.getRecordType(TeamReductionRec);
3750 llvm::Type *LLVMReductionsBufferTy =
3751 CGM.getTypes().ConvertTypeForMem(StaticTy);
3752 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3753 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3754 LLVMReductionsBufferTy->getPointerTo());
3755
3756 // 1. Build a list of reduction variables.
3757 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3758 Address ReductionList =
3759 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3760 auto IPriv = Privates.begin();
3761 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3762 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3763 /*Volatile=*/false, C.IntTy,
3764 Loc)};
3765 unsigned Idx = 0;
3766 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3767 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3768 // Global = Buffer.VD[Idx];
3769 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3770 const FieldDecl *FD = VarFieldMap.lookup(VD);
3771 LValue GlobLVal = CGF.EmitLValueForField(
3772 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3773 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3774 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3775 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3776 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3777 // Store array size.
3778 ++Idx;
3779 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3780 llvm::Value *Size = CGF.Builder.CreateIntCast(
3781 CGF.getVLASize(
3782 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3783 .NumElts,
3784 CGF.SizeTy, /*isSigned=*/false);
3785 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3786 Elem);
3787 }
3788 }
3789
3790 // Call reduce_function(GlobalReduceList, ReduceList)
3791 llvm::Value *GlobalReduceList =
3792 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3793 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3794 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3795 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3796 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3797 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3798 CGF.FinishFunction();
3799 return Fn;
3800}
3801
3802/// This function emits a helper that copies all the reduction variables from
3803/// the team into the provided global buffer for the reduction variables.
3804///
3805/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3806/// For all data entries D in reduce_data:
3807/// Copy buffer.D[Idx] to local D;
3808static llvm::Value *emitGlobalToListCopyFunction(
3809 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3810 QualType ReductionArrayTy, SourceLocation Loc,
3811 const RecordDecl *TeamReductionRec,
3812 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3813 &VarFieldMap) {
3814 ASTContext &C = CGM.getContext();
3815
3816 // Buffer: global reduction buffer.
3817 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3818 C.VoidPtrTy, ImplicitParamDecl::Other);
3819 // Idx: index of the buffer.
3820 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3821 ImplicitParamDecl::Other);
3822 // ReduceList: thread local Reduce list.
3823 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3824 C.VoidPtrTy, ImplicitParamDecl::Other);
3825 FunctionArgList Args;
3826 Args.push_back(&BufferArg);
3827 Args.push_back(&IdxArg);
3828 Args.push_back(&ReduceListArg);
3829
3830 const CGFunctionInfo &CGFI =
3831 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3832 auto *Fn = llvm::Function::Create(
3833 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3834 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3835 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3836 Fn->setDoesNotRecurse();
3837 CodeGenFunction CGF(CGM);
3838 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3839
3840 CGBuilderTy &Bld = CGF.Builder;
3841
3842 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3843 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3844 Address LocalReduceList(
3845 Bld.CreatePointerBitCastOrAddrSpaceCast(
3846 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3847 C.VoidPtrTy, Loc),
3848 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3849 CGF.getPointerAlign());
3850 QualType StaticTy = C.getRecordType(TeamReductionRec);
3851 llvm::Type *LLVMReductionsBufferTy =
3852 CGM.getTypes().ConvertTypeForMem(StaticTy);
3853 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3854 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3855 LLVMReductionsBufferTy->getPointerTo());
3856
3857 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3858 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3859 /*Volatile=*/false, C.IntTy,
3860 Loc)};
3861 unsigned Idx = 0;
3862 for (const Expr *Private : Privates) {
3863 // Reduce element = LocalReduceList[i]
3864 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3865 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3866 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3867 // elemptr = ((CopyType*)(elemptrptr)) + I
3868 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3869 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3870 Address ElemPtr =
3871 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3872 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3873 // Global = Buffer.VD[Idx];
3874 const FieldDecl *FD = VarFieldMap.lookup(VD);
3875 LValue GlobLVal = CGF.EmitLValueForField(
3876 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3877 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3878 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3879 switch (CGF.getEvaluationKind(Private->getType())) {
3880 case TEK_Scalar: {
3881 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3882 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3883 break;
3884 }
3885 case TEK_Complex: {
3886 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3887 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3888 /*isInit=*/false);
3889 break;
3890 }
3891 case TEK_Aggregate:
3892 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3893 GlobLVal, Private->getType(),
3894 AggValueSlot::DoesNotOverlap);
3895 break;
3896 }
3897 ++Idx;
3898 }
3899
3900 CGF.FinishFunction();
3901 return Fn;
3902}
3903
3904/// This function emits a helper that reduces all the reduction variables from
3905/// the team into the provided global buffer for the reduction variables.
3906///
3907/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3908/// void *GlobPtrs[];
3909/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3910/// ...
3911/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3912/// reduce_function(reduce_data, GlobPtrs);
3913static llvm::Value *emitGlobalToListReduceFunction(
3914 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3915 QualType ReductionArrayTy, SourceLocation Loc,
3916 const RecordDecl *TeamReductionRec,
3917 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3918 &VarFieldMap,
3919 llvm::Function *ReduceFn) {
3920 ASTContext &C = CGM.getContext();
3921
3922 // Buffer: global reduction buffer.
3923 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3924 C.VoidPtrTy, ImplicitParamDecl::Other);
3925 // Idx: index of the buffer.
3926 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3927 ImplicitParamDecl::Other);
3928 // ReduceList: thread local Reduce list.
3929 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3930 C.VoidPtrTy, ImplicitParamDecl::Other);
3931 FunctionArgList Args;
3932 Args.push_back(&BufferArg);
3933 Args.push_back(&IdxArg);
3934 Args.push_back(&ReduceListArg);
3935
3936 const CGFunctionInfo &CGFI =
3937 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3938 auto *Fn = llvm::Function::Create(
3939 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3940 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3941 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3942 Fn->setDoesNotRecurse();
3943 CodeGenFunction CGF(CGM);
3944 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3945
3946 CGBuilderTy &Bld = CGF.Builder;
3947
3948 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3949 QualType StaticTy = C.getRecordType(TeamReductionRec);
3950 llvm::Type *LLVMReductionsBufferTy =
3951 CGM.getTypes().ConvertTypeForMem(StaticTy);
3952 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3953 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3954 LLVMReductionsBufferTy->getPointerTo());
3955
3956 // 1. Build a list of reduction variables.
3957 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3958 Address ReductionList =
3959 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3960 auto IPriv = Privates.begin();
3961 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3962 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3963 /*Volatile=*/false, C.IntTy,
3964 Loc)};
3965 unsigned Idx = 0;
3966 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3967 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3968 // Global = Buffer.VD[Idx];
3969 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3970 const FieldDecl *FD = VarFieldMap.lookup(VD);
3971 LValue GlobLVal = CGF.EmitLValueForField(
3972 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3973 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3974 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3975 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3976 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3977 // Store array size.
3978 ++Idx;
3979 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3980 llvm::Value *Size = CGF.Builder.CreateIntCast(
3981 CGF.getVLASize(
3982 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3983 .NumElts,
3984 CGF.SizeTy, /*isSigned=*/false);
3985 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3986 Elem);
3987 }
3988 }
3989
3990 // Call reduce_function(ReduceList, GlobalReduceList)
3991 llvm::Value *GlobalReduceList =
3992 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3993 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3994 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3995 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3996 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3997 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
3998 CGF.FinishFunction();
3999 return Fn;
4000}
4001
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004002///
4003/// Design of OpenMP reductions on the GPU
4004///
4005/// Consider a typical OpenMP program with one or more reduction
4006/// clauses:
4007///
4008/// float foo;
4009/// double bar;
4010/// #pragma omp target teams distribute parallel for \
4011/// reduction(+:foo) reduction(*:bar)
4012/// for (int i = 0; i < N; i++) {
4013/// foo += A[i]; bar *= B[i];
4014/// }
4015///
4016/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4017/// all teams. In our OpenMP implementation on the NVPTX device an
4018/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4019/// within a team are mapped to CUDA threads within a threadblock.
4020/// Our goal is to efficiently aggregate values across all OpenMP
4021/// threads such that:
4022///
4023/// - the compiler and runtime are logically concise, and
4024/// - the reduction is performed efficiently in a hierarchical
4025/// manner as follows: within OpenMP threads in the same warp,
4026/// across warps in a threadblock, and finally across teams on
4027/// the NVPTX device.
4028///
4029/// Introduction to Decoupling
4030///
4031/// We would like to decouple the compiler and the runtime so that the
4032/// latter is ignorant of the reduction variables (number, data types)
4033/// and the reduction operators. This allows a simpler interface
4034/// and implementation while still attaining good performance.
4035///
4036/// Pseudocode for the aforementioned OpenMP program generated by the
4037/// compiler is as follows:
4038///
4039/// 1. Create private copies of reduction variables on each OpenMP
4040/// thread: 'foo_private', 'bar_private'
4041/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4042/// to it and writes the result in 'foo_private' and 'bar_private'
4043/// respectively.
4044/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4045/// and store the result on the team master:
4046///
Alexey Bataev8e009032019-01-04 17:25:09 +00004047/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004048/// reduceData, shuffleReduceFn, interWarpCpyFn)
4049///
4050/// where:
4051/// struct ReduceData {
4052/// double *foo;
4053/// double *bar;
4054/// } reduceData
4055/// reduceData.foo = &foo_private
4056/// reduceData.bar = &bar_private
4057///
4058/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4059/// auxiliary functions generated by the compiler that operate on
4060/// variables of type 'ReduceData'. They aid the runtime perform
4061/// algorithmic steps in a data agnostic manner.
4062///
4063/// 'shuffleReduceFn' is a pointer to a function that reduces data
4064/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4065/// same warp. It takes the following arguments as input:
4066///
4067/// a. variable of type 'ReduceData' on the calling lane,
4068/// b. its lane_id,
4069/// c. an offset relative to the current lane_id to generate a
4070/// remote_lane_id. The remote lane contains the second
4071/// variable of type 'ReduceData' that is to be reduced.
4072/// d. an algorithm version parameter determining which reduction
4073/// algorithm to use.
4074///
4075/// 'shuffleReduceFn' retrieves data from the remote lane using
4076/// efficient GPU shuffle intrinsics and reduces, using the
4077/// algorithm specified by the 4th parameter, the two operands
4078/// element-wise. The result is written to the first operand.
4079///
4080/// Different reduction algorithms are implemented in different
4081/// runtime functions, all calling 'shuffleReduceFn' to perform
4082/// the essential reduction step. Therefore, based on the 4th
4083/// parameter, this function behaves slightly differently to
4084/// cooperate with the runtime to ensure correctness under
4085/// different circumstances.
4086///
4087/// 'InterWarpCpyFn' is a pointer to a function that transfers
4088/// reduced variables across warps. It tunnels, through CUDA
4089/// shared memory, the thread-private data of type 'ReduceData'
4090/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004091/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4092/// The last team writes the global reduced value to memory.
4093///
4094/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4095/// reduceData, shuffleReduceFn, interWarpCpyFn,
4096/// scratchpadCopyFn, loadAndReduceFn)
4097///
4098/// 'scratchpadCopyFn' is a helper that stores reduced
4099/// data from the team master to a scratchpad array in
4100/// global memory.
4101///
4102/// 'loadAndReduceFn' is a helper that loads data from
4103/// the scratchpad array and reduces it with the input
4104/// operand.
4105///
4106/// These compiler generated functions hide address
4107/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004108/// 5. if ret == 1:
4109/// The team master of the last team stores the reduced
4110/// result to the globals in memory.
4111/// foo += reduceData.foo; bar *= reduceData.bar
4112///
4113///
4114/// Warp Reduction Algorithms
4115///
4116/// On the warp level, we have three algorithms implemented in the
4117/// OpenMP runtime depending on the number of active lanes:
4118///
4119/// Full Warp Reduction
4120///
4121/// The reduce algorithm within a warp where all lanes are active
4122/// is implemented in the runtime as follows:
4123///
4124/// full_warp_reduce(void *reduce_data,
4125/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4126/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4127/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4128/// }
4129///
4130/// The algorithm completes in log(2, WARPSIZE) steps.
4131///
4132/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4133/// not used therefore we save instructions by not retrieving lane_id
4134/// from the corresponding special registers. The 4th parameter, which
4135/// represents the version of the algorithm being used, is set to 0 to
4136/// signify full warp reduction.
4137///
4138/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4139///
4140/// #reduce_elem refers to an element in the local lane's data structure
4141/// #remote_elem is retrieved from a remote lane
4142/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4143/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4144///
4145/// Contiguous Partial Warp Reduction
4146///
4147/// This reduce algorithm is used within a warp where only the first
4148/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4149/// number of OpenMP threads in a parallel region is not a multiple of
4150/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4151///
4152/// void
4153/// contiguous_partial_reduce(void *reduce_data,
4154/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4155/// int size, int lane_id) {
4156/// int curr_size;
4157/// int offset;
4158/// curr_size = size;
4159/// mask = curr_size/2;
4160/// while (offset>0) {
4161/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4162/// curr_size = (curr_size+1)/2;
4163/// offset = curr_size/2;
4164/// }
4165/// }
4166///
4167/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4168///
4169/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4170/// if (lane_id < offset)
4171/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4172/// else
4173/// reduce_elem = remote_elem
4174///
4175/// This algorithm assumes that the data to be reduced are located in a
4176/// contiguous subset of lanes starting from the first. When there is
4177/// an odd number of active lanes, the data in the last lane is not
4178/// aggregated with any other lane's dat but is instead copied over.
4179///
4180/// Dispersed Partial Warp Reduction
4181///
4182/// This algorithm is used within a warp when any discontiguous subset of
4183/// lanes are active. It is used to implement the reduction operation
4184/// across lanes in an OpenMP simd region or in a nested parallel region.
4185///
4186/// void
4187/// dispersed_partial_reduce(void *reduce_data,
4188/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4189/// int size, remote_id;
4190/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4191/// do {
4192/// remote_id = next_active_lane_id_right_after_me();
4193/// # the above function returns 0 of no active lane
4194/// # is present right after the current lane.
4195/// size = number_of_active_lanes_in_this_warp();
4196/// logical_lane_id /= 2;
4197/// ShuffleReduceFn(reduce_data, logical_lane_id,
4198/// remote_id-1-threadIdx.x, 2);
4199/// } while (logical_lane_id % 2 == 0 && size > 1);
4200/// }
4201///
4202/// There is no assumption made about the initial state of the reduction.
4203/// Any number of lanes (>=1) could be active at any position. The reduction
4204/// result is returned in the first active lane.
4205///
4206/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4207///
4208/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4209/// if (lane_id % 2 == 0 && offset > 0)
4210/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4211/// else
4212/// reduce_elem = remote_elem
4213///
4214///
4215/// Intra-Team Reduction
4216///
4217/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004218/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004219/// threads in a team. It first reduces within a warp using the
4220/// aforementioned algorithms. We then proceed to gather all such
4221/// reduced values at the first warp.
4222///
4223/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4224/// data from each of the "warp master" (zeroth lane of each warp, where
4225/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4226/// a mathematical sense) the problem of reduction across warp masters in
4227/// a block to the problem of warp reduction.
4228///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004229///
4230/// Inter-Team Reduction
4231///
4232/// Once a team has reduced its data to a single value, it is stored in
4233/// a global scratchpad array. Since each team has a distinct slot, this
4234/// can be done without locking.
4235///
4236/// The last team to write to the scratchpad array proceeds to reduce the
4237/// scratchpad array. One or more workers in the last team use the helper
4238/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4239/// the k'th worker reduces every k'th element.
4240///
Alexey Bataev8e009032019-01-04 17:25:09 +00004241/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004242/// reduce across workers and compute a globally reduced value.
4243///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004244void CGOpenMPRuntimeNVPTX::emitReduction(
4245 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4246 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4247 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4248 if (!CGF.HaveInsertPoint())
4249 return;
4250
4251 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004252#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004253 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004254#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004255
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004256 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004257 assert(!TeamsReduction && !ParallelReduction &&
4258 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004259 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4260 ReductionOps, Options);
4261 return;
4262 }
4263
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004264 assert((TeamsReduction || ParallelReduction) &&
4265 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004266
Alexey Bataeva1166022018-11-27 21:24:54 +00004267 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004268 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004269 // or
4270 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004271 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004272 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004273
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004274 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004275 ASTContext &C = CGM.getContext();
4276 // 1. Build a list of reduction variables.
4277 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4278 auto Size = RHSExprs.size();
4279 for (const Expr *E : Privates) {
4280 if (E->getType()->isVariablyModifiedType())
4281 // Reserve place for array size.
4282 ++Size;
4283 }
4284 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4285 QualType ReductionArrayTy =
4286 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4287 /*IndexTypeQuals=*/0);
4288 Address ReductionList =
4289 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4290 auto IPriv = Privates.begin();
4291 unsigned Idx = 0;
4292 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4293 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4294 CGF.Builder.CreateStore(
4295 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4296 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4297 Elem);
4298 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4299 // Store array size.
4300 ++Idx;
4301 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4302 llvm::Value *Size = CGF.Builder.CreateIntCast(
4303 CGF.getVLASize(
4304 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4305 .NumElts,
4306 CGF.SizeTy, /*isSigned=*/false);
4307 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4308 Elem);
4309 }
4310 }
4311
4312 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4313 ReductionList.getPointer(), CGF.VoidPtrTy);
4314 llvm::Function *ReductionFn = emitReductionFunction(
4315 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
4316 Privates, LHSExprs, RHSExprs, ReductionOps);
4317 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4318 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4319 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4320 llvm::Value *InterWarpCopyFn =
4321 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4322
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004323 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004324 llvm::Value *Args[] = {RTLoc,
4325 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004326 CGF.Builder.getInt32(RHSExprs.size()),
4327 ReductionArrayTySize,
4328 RL,
4329 ShuffleAndReduceFn,
4330 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004331
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004332 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004333 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004334 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4335 Args);
4336 } else {
4337 assert(TeamsReduction && "expected teams reduction.");
4338 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4339 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4340 int Cnt = 0;
4341 for (const Expr *DRE : Privates) {
4342 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4343 ++Cnt;
4344 }
4345 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4346 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4347 C.getLangOpts().OpenMPCUDAReductionBufNum);
4348 TeamsReductions.push_back(TeamReductionRec);
4349 if (!KernelTeamsReductionPtr) {
4350 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4351 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4352 llvm::GlobalValue::InternalLinkage, nullptr,
4353 "_openmp_teams_reductions_buffer_$_$ptr");
4354 }
4355 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4356 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4357 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4358 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4359 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4360 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4361 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4362 ReductionFn);
4363 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4364 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4365 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4366 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4367 ReductionFn);
4368
4369 llvm::Value *Args[] = {
4370 RTLoc,
4371 ThreadId,
4372 GlobalBufferPtr,
4373 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4374 RL,
4375 ShuffleAndReduceFn,
4376 InterWarpCopyFn,
4377 GlobalToBufferCpyFn,
4378 GlobalToBufferRedFn,
4379 BufferToGlobalCpyFn,
4380 BufferToGlobalRedFn};
4381
4382 Res = CGF.EmitRuntimeCall(
4383 createNVPTXRuntimeFunction(
4384 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004385 Args);
4386 }
4387
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004388 // 5. Build if (res == 1)
4389 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4390 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4391 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4392 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4393 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004394
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004395 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004396 // thread in each team.
4397 // __kmpc_end_reduce{_nowait}(<gtid>);
4398 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004399 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004400
4401 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004402 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004403 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4404 auto IPriv = Privates.begin();
4405 auto ILHS = LHSExprs.begin();
4406 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004407 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004408 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4409 cast<DeclRefExpr>(*IRHS));
4410 ++IPriv;
4411 ++ILHS;
4412 ++IRHS;
4413 }
4414 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004415 llvm::Value *EndArgs[] = {ThreadId};
4416 RegionCodeGenTy RCG(CodeGen);
4417 NVPTXActionTy Action(
4418 nullptr, llvm::None,
4419 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4420 EndArgs);
4421 RCG.setAction(Action);
4422 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004423 // There is no need to emit line number for unconditional branch.
4424 (void)ApplyDebugLocation::CreateEmpty(CGF);
4425 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004426}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004427
4428const VarDecl *
4429CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4430 const VarDecl *NativeParam) const {
4431 if (!NativeParam->getType()->isReferenceType())
4432 return NativeParam;
4433 QualType ArgType = NativeParam->getType();
4434 QualifierCollector QC;
4435 const Type *NonQualTy = QC.strip(ArgType);
4436 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4437 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4438 if (Attr->getCaptureKind() == OMPC_map) {
4439 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4440 LangAS::opencl_global);
4441 }
4442 }
4443 ArgType = CGM.getContext().getPointerType(PointeeTy);
4444 QC.addRestrict();
4445 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004446 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004447 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004448 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004449 return ImplicitParamDecl::Create(
4450 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4451 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004452 return ParmVarDecl::Create(
4453 CGM.getContext(),
4454 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004455 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004456 NativeParam->getIdentifier(), ArgType,
4457 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004458}
4459
4460Address
4461CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4462 const VarDecl *NativeParam,
4463 const VarDecl *TargetParam) const {
4464 assert(NativeParam != TargetParam &&
4465 NativeParam->getType()->isReferenceType() &&
4466 "Native arg must not be the same as target arg.");
4467 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4468 QualType NativeParamType = NativeParam->getType();
4469 QualifierCollector QC;
4470 const Type *NonQualTy = QC.strip(NativeParamType);
4471 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4472 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004473 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004474 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004475 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004476 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004477 // First cast to generic.
4478 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4479 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4480 /*AddrSpace=*/0));
4481 // Cast from generic to native address space.
4482 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4483 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4484 NativePointeeAddrSpace));
4485 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4486 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004487 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004488 return NativeParamAddr;
4489}
4490
4491void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004492 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004493 ArrayRef<llvm::Value *> Args) const {
4494 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004495 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004496 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004497 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004498 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4499 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4500 break;
4501 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004502 llvm::Type *TargetType = FnType->getParamType(I);
4503 llvm::Value *NativeArg = Args[I];
4504 if (!TargetType->isPointerTy()) {
4505 TargetArgs.emplace_back(NativeArg);
4506 continue;
4507 }
4508 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004509 NativeArg,
4510 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004511 TargetArgs.emplace_back(
4512 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4513 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004514 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004515}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004516
4517/// Emit function which wraps the outline parallel region
4518/// and controls the arguments which are passed to this function.
4519/// The wrapper ensures that the outlined function is called
4520/// with the correct arguments when data is shared.
4521llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4522 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4523 ASTContext &Ctx = CGM.getContext();
4524 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4525
4526 // Create a function that takes as argument the source thread.
4527 FunctionArgList WrapperArgs;
4528 QualType Int16QTy =
4529 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4530 QualType Int32QTy =
4531 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004532 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004533 /*Id=*/nullptr, Int16QTy,
4534 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004535 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004536 /*Id=*/nullptr, Int32QTy,
4537 ImplicitParamDecl::Other);
4538 WrapperArgs.emplace_back(&ParallelLevelArg);
4539 WrapperArgs.emplace_back(&WrapperArg);
4540
Alexey Bataev9ff80832018-04-16 20:16:21 +00004541 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004542 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4543
4544 auto *Fn = llvm::Function::Create(
4545 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004546 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004547 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004548 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004549 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004550
4551 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4552 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004553 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004554
4555 const auto *RD = CS.getCapturedRecordDecl();
4556 auto CurField = RD->field_begin();
4557
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004558 Address ZeroAddr = CGF.CreateMemTemp(
4559 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4560 /*Name*/ ".zero.addr");
4561 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562 // Get the array of arguments.
4563 SmallVector<llvm::Value *, 8> Args;
4564
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004565 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4566 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004567
4568 CGBuilderTy &Bld = CGF.Builder;
4569 auto CI = CS.capture_begin();
4570
4571 // Use global memory for data sharing.
4572 // Handle passing of global args to workers.
4573 Address GlobalArgs =
4574 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4575 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4576 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4577 CGF.EmitRuntimeCall(
4578 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4579 DataSharingArgs);
4580
4581 // Retrieve the shared variables from the list of references returned
4582 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004583 Address SharedArgListAddress = Address::invalid();
4584 if (CS.capture_size() > 0 ||
4585 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4586 SharedArgListAddress = CGF.EmitLoadOfPointer(
4587 GlobalArgs, CGF.getContext()
4588 .getPointerType(CGF.getContext().getPointerType(
4589 CGF.getContext().VoidPtrTy))
4590 .castAs<PointerType>());
4591 }
4592 unsigned Idx = 0;
4593 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004594 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004595 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4596 Src, CGF.SizeTy->getPointerTo());
4597 llvm::Value *LB = CGF.EmitLoadOfScalar(
4598 TypedAddress,
4599 /*Volatile=*/false,
4600 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4601 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4602 Args.emplace_back(LB);
4603 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004604 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004605 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4606 Src, CGF.SizeTy->getPointerTo());
4607 llvm::Value *UB = CGF.EmitLoadOfScalar(
4608 TypedAddress,
4609 /*Volatile=*/false,
4610 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4611 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4612 Args.emplace_back(UB);
4613 ++Idx;
4614 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004615 if (CS.capture_size() > 0) {
4616 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004617 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4618 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004619 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004620 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004621 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4622 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4623 /*Volatile=*/false,
4624 CGFContext.getPointerType(ElemTy),
4625 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004626 if (CI->capturesVariableByCopy() &&
4627 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004628 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4629 CI->getLocation());
4630 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004631 Args.emplace_back(Arg);
4632 }
4633 }
4634
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004635 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004636 CGF.FinishFunction();
4637 return Fn;
4638}
4639
4640void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4641 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004642 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4643 return;
4644
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004645 assert(D && "Expected function or captured|block decl.");
4646 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4647 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004648 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4649 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004650 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004651 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004652 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4653 Body = FD->getBody();
4654 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4655 Body = BD->getBody();
4656 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4657 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004658 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004659 if (NeedToDelayGlobalization &&
4660 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4661 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004662 }
4663 if (!Body)
4664 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004665 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004666 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004667 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004668 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004669 TeamAndReductions.first = nullptr;
4670 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004671 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4672 VarChecker.getEscapedVariableLengthDecls();
4673 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004674 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004675 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4676 I->getSecond().MappedParams =
4677 llvm::make_unique<CodeGenFunction::OMPMapVars>();
4678 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4679 I->getSecond().EscapedParameters.insert(
4680 VarChecker.getEscapedParameters().begin(),
4681 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004682 I->getSecond().EscapedVariableLengthDecls.append(
4683 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004684 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004685 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004686 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004687 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004688 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004689 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004690 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004691 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004692 VarChecker.Visit(Body);
4693 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004694 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004695 I->getSecond().SecondaryLocalVarData.emplace();
4696 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4697 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4698 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4699 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004700 Data.insert(
4701 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004702 }
4703 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004704 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004705 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004706 struct GlobalizationScope final : EHScopeStack::Cleanup {
4707 GlobalizationScope() = default;
4708
4709 void Emit(CodeGenFunction &CGF, Flags flags) override {
4710 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004711 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004712 }
4713 };
4714 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004715 }
4716}
4717
4718Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4719 const VarDecl *VD) {
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 }
4741 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004742}
4743
4744void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004745 FunctionGlobalizedDecls.erase(CGF.CurFn);
4746 CGOpenMPRuntime::functionFinished(CGF);
4747}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004748
4749void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4750 CodeGenFunction &CGF, const OMPLoopDirective &S,
4751 OpenMPDistScheduleClauseKind &ScheduleKind,
4752 llvm::Value *&Chunk) const {
4753 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4754 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4755 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4756 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4757 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004758 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004759 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004760 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4761 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004762}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004763
4764void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4765 CodeGenFunction &CGF, const OMPLoopDirective &S,
4766 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004767 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004768 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004769 // Chunk size is 1 in this case.
4770 llvm::APInt ChunkSize(32, 1);
4771 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4772 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4773 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004774}
Alexey Bataev60705422018-10-30 15:50:12 +00004775
4776void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4777 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4778 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4779 " Expected target-based directive.");
4780 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4781 for (const CapturedStmt::Capture &C : CS->captures()) {
4782 // Capture variables captured by reference in lambdas for target-based
4783 // directives.
4784 if (!C.capturesVariable())
4785 continue;
4786 const VarDecl *VD = C.getCapturedVar();
4787 const auto *RD = VD->getType()
4788 .getCanonicalType()
4789 .getNonReferenceType()
4790 ->getAsCXXRecordDecl();
4791 if (!RD || !RD->isLambda())
4792 continue;
4793 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4794 LValue VDLVal;
4795 if (VD->getType().getCanonicalType()->isReferenceType())
4796 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4797 else
4798 VDLVal = CGF.MakeAddrLValue(
4799 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4800 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4801 FieldDecl *ThisCapture = nullptr;
4802 RD->getCaptureFields(Captures, ThisCapture);
4803 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4804 LValue ThisLVal =
4805 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4806 llvm::Value *CXXThis = CGF.LoadCXXThis();
4807 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4808 }
4809 for (const LambdaCapture &LC : RD->captures()) {
4810 if (LC.getCaptureKind() != LCK_ByRef)
4811 continue;
4812 const VarDecl *VD = LC.getCapturedVar();
4813 if (!CS->capturesVariable(VD))
4814 continue;
4815 auto It = Captures.find(VD);
4816 assert(It != Captures.end() && "Found lambda capture without field.");
4817 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4818 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4819 if (VD->getType().getCanonicalType()->isReferenceType())
4820 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4821 VD->getType().getCanonicalType())
4822 .getAddress();
4823 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4824 }
4825 }
4826}
4827
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004828// Get current CudaArch and ignore any unknown values
4829static CudaArch getCudaArch(CodeGenModule &CGM) {
4830 if (!CGM.getTarget().hasFeature("ptx"))
4831 return CudaArch::UNKNOWN;
4832 llvm::StringMap<bool> Features;
4833 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4834 CGM.getTarget().getTargetOpts().CPU,
4835 CGM.getTarget().getTargetOpts().Features);
4836 for (const auto &Feature : Features) {
4837 if (Feature.getValue()) {
4838 CudaArch Arch = StringToCudaArch(Feature.getKey());
4839 if (Arch != CudaArch::UNKNOWN)
4840 return Arch;
4841 }
4842 }
4843 return CudaArch::UNKNOWN;
4844}
4845
4846/// Check to see if target architecture supports unified addressing which is
4847/// a restriction for OpenMP requires clause "unified_shared_memory".
4848void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
4849 CodeGenModule &CGM, const OMPRequiresDecl *D) const {
4850 for (const OMPClause *Clause : D->clauselists()) {
4851 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4852 switch (getCudaArch(CGM)) {
4853 case CudaArch::SM_20:
4854 case CudaArch::SM_21:
4855 case CudaArch::SM_30:
4856 case CudaArch::SM_32:
4857 case CudaArch::SM_35:
4858 case CudaArch::SM_37:
4859 case CudaArch::SM_50:
4860 case CudaArch::SM_52:
4861 case CudaArch::SM_53:
4862 case CudaArch::SM_60:
4863 case CudaArch::SM_61:
4864 case CudaArch::SM_62:
4865 CGM.Error(Clause->getBeginLoc(),
4866 "Target architecture does not support unified addressing");
4867 return;
4868 case CudaArch::SM_70:
4869 case CudaArch::SM_72:
4870 case CudaArch::SM_75:
4871 case CudaArch::GFX600:
4872 case CudaArch::GFX601:
4873 case CudaArch::GFX700:
4874 case CudaArch::GFX701:
4875 case CudaArch::GFX702:
4876 case CudaArch::GFX703:
4877 case CudaArch::GFX704:
4878 case CudaArch::GFX801:
4879 case CudaArch::GFX802:
4880 case CudaArch::GFX803:
4881 case CudaArch::GFX810:
4882 case CudaArch::GFX900:
4883 case CudaArch::GFX902:
4884 case CudaArch::GFX904:
4885 case CudaArch::GFX906:
4886 case CudaArch::GFX909:
4887 case CudaArch::UNKNOWN:
4888 break;
4889 case CudaArch::LAST:
4890 llvm_unreachable("Unexpected Cuda arch.");
4891 }
4892 }
4893 }
4894}
4895
Alexey Bataeve4090182018-11-02 14:54:07 +00004896/// Get number of SMs and number of blocks per SM.
4897static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4898 std::pair<unsigned, unsigned> Data;
4899 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4900 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4901 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4902 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4903 if (Data.first && Data.second)
4904 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004905 switch (getCudaArch(CGM)) {
4906 case CudaArch::SM_20:
4907 case CudaArch::SM_21:
4908 case CudaArch::SM_30:
4909 case CudaArch::SM_32:
4910 case CudaArch::SM_35:
4911 case CudaArch::SM_37:
4912 case CudaArch::SM_50:
4913 case CudaArch::SM_52:
4914 case CudaArch::SM_53:
4915 return {16, 16};
4916 case CudaArch::SM_60:
4917 case CudaArch::SM_61:
4918 case CudaArch::SM_62:
4919 return {56, 32};
4920 case CudaArch::SM_70:
4921 case CudaArch::SM_72:
4922 case CudaArch::SM_75:
4923 return {84, 32};
4924 case CudaArch::GFX600:
4925 case CudaArch::GFX601:
4926 case CudaArch::GFX700:
4927 case CudaArch::GFX701:
4928 case CudaArch::GFX702:
4929 case CudaArch::GFX703:
4930 case CudaArch::GFX704:
4931 case CudaArch::GFX801:
4932 case CudaArch::GFX802:
4933 case CudaArch::GFX803:
4934 case CudaArch::GFX810:
4935 case CudaArch::GFX900:
4936 case CudaArch::GFX902:
4937 case CudaArch::GFX904:
4938 case CudaArch::GFX906:
4939 case CudaArch::GFX909:
4940 case CudaArch::UNKNOWN:
4941 break;
4942 case CudaArch::LAST:
4943 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00004944 }
4945 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
4946}
4947
4948void CGOpenMPRuntimeNVPTX::clear() {
Alexey Bataeve4e9ba22019-01-28 20:03:02 +00004949 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
4950 if (CGM.getCodeGenOpts().getDebugInfo() >=
4951 codegenoptions::LimitedDebugInfo) {
4952 ASTContext &C = CGM.getContext();
4953 auto *VD = VarDecl::Create(
4954 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
4955 &C.Idents.get("_$_"), C.IntTy, /*TInfo=*/nullptr, SC_Static);
4956 auto *Var = cast<llvm::GlobalVariable>(
4957 CGM.CreateRuntimeVariable(CGM.IntTy, "_$_"));
4958 Var->setInitializer(llvm::ConstantInt::getNullValue(CGM.IntTy));
4959 Var->setLinkage(llvm::GlobalVariable::CommonLinkage);
4960 CGM.addCompilerUsedGlobal(Var);
4961 DI->EmitGlobalVariable(Var, VD);
4962 }
Alexey Bataeve4090182018-11-02 14:54:07 +00004963 if (!GlobalizedRecords.empty()) {
4964 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004965 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
4966 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00004967 RecordDecl *StaticRD = C.buildImplicitRecord(
4968 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4969 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004970 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
4971 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
4972 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00004973 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
4974 if (Records.Records.empty())
4975 continue;
4976 unsigned Size = 0;
4977 unsigned RecAlignment = 0;
4978 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004979 QualType RDTy = C.getRecordType(RD);
4980 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004981 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004982 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00004983 Size =
4984 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
4985 }
4986 Size = llvm::alignTo(Size, RecAlignment);
4987 llvm::APInt ArySize(/*numBits=*/64, Size);
4988 QualType SubTy = C.getConstantArrayType(
4989 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004990 const bool UseSharedMemory = Size <= SharedMemorySize;
4991 auto *Field =
4992 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
4993 SourceLocation(), SourceLocation(), nullptr, SubTy,
4994 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
4995 /*BW=*/nullptr, /*Mutable=*/false,
4996 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00004997 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00004998 if (UseSharedMemory) {
4999 SharedStaticRD->addDecl(Field);
5000 SharedRecs.push_back(&Records);
5001 } else {
5002 StaticRD->addDecl(Field);
5003 GlobalRecs.push_back(&Records);
5004 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005005 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005006 Records.UseSharedMemory->setInitializer(
5007 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5008 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005009 // Allocate SharedMemorySize buffer for the shared memory.
5010 // FIXME: nvlink does not handle weak linkage correctly (object with the
5011 // different size are reported as erroneous).
5012 // Restore this code as sson as nvlink is fixed.
5013 if (!SharedStaticRD->field_empty()) {
5014 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5015 QualType SubTy = C.getConstantArrayType(
5016 C.CharTy, ArySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5017 auto *Field = FieldDecl::Create(
5018 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5019 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5020 /*BW=*/nullptr, /*Mutable=*/false,
5021 /*InitStyle=*/ICIS_NoInit);
5022 Field->setAccess(AS_public);
5023 SharedStaticRD->addDecl(Field);
5024 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005025 SharedStaticRD->completeDefinition();
5026 if (!SharedStaticRD->field_empty()) {
5027 QualType StaticTy = C.getRecordType(SharedStaticRD);
5028 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5029 auto *GV = new llvm::GlobalVariable(
5030 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005031 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005032 llvm::Constant::getNullValue(LLVMStaticTy),
5033 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5034 llvm::GlobalValue::NotThreadLocal,
5035 C.getTargetAddressSpace(LangAS::cuda_shared));
5036 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5037 GV, CGM.VoidPtrTy);
5038 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5039 Rec->Buffer->replaceAllUsesWith(Replacement);
5040 Rec->Buffer->eraseFromParent();
5041 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005042 }
5043 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005044 if (!StaticRD->field_empty()) {
5045 QualType StaticTy = C.getRecordType(StaticRD);
5046 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5047 llvm::APInt Size1(32, SMsBlockPerSM.second);
5048 QualType Arr1Ty =
5049 C.getConstantArrayType(StaticTy, Size1, ArrayType::Normal,
5050 /*IndexTypeQuals=*/0);
5051 llvm::APInt Size2(32, SMsBlockPerSM.first);
5052 QualType Arr2Ty = C.getConstantArrayType(Arr1Ty, Size2, ArrayType::Normal,
5053 /*IndexTypeQuals=*/0);
5054 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
5055 auto *GV = new llvm::GlobalVariable(
5056 CGM.getModule(), LLVMArr2Ty,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005057 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005058 llvm::Constant::getNullValue(LLVMArr2Ty),
5059 "_openmp_static_glob_rd_$_");
5060 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5061 GV, CGM.VoidPtrTy);
5062 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5063 Rec->Buffer->replaceAllUsesWith(Replacement);
5064 Rec->Buffer->eraseFromParent();
5065 }
5066 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005067 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005068 if (!TeamsReductions.empty()) {
5069 ASTContext &C = CGM.getContext();
5070 RecordDecl *StaticRD = C.buildImplicitRecord(
5071 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5072 StaticRD->startDefinition();
5073 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5074 QualType RecTy = C.getRecordType(TeamReductionRec);
5075 auto *Field = FieldDecl::Create(
5076 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5077 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5078 /*BW=*/nullptr, /*Mutable=*/false,
5079 /*InitStyle=*/ICIS_NoInit);
5080 Field->setAccess(AS_public);
5081 StaticRD->addDecl(Field);
5082 }
5083 StaticRD->completeDefinition();
5084 QualType StaticTy = C.getRecordType(StaticRD);
5085 llvm::Type *LLVMReductionsBufferTy =
5086 CGM.getTypes().ConvertTypeForMem(StaticTy);
5087 auto *GV = new llvm::GlobalVariable(
5088 CGM.getModule(), LLVMReductionsBufferTy,
5089 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
5090 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5091 "_openmp_teams_reductions_buffer_$_");
5092 KernelTeamsReductionPtr->setInitializer(
5093 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5094 CGM.VoidPtrTy));
5095 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005096 CGOpenMPRuntime::clear();
5097}