blob: 83f74fef3b7572490c7caf8d709f103310b098cf [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,
Alexey Bataev2cd7faf2019-08-26 19:07:48 +0000110 /// Call to int32_t __kmpc_warp_active_thread_mask(void);
111 OMPRTL_NVPTX__kmpc_warp_active_thread_mask,
112 /// Call to void __kmpc_syncwarp(int32_t Mask);
113 OMPRTL_NVPTX__kmpc_syncwarp,
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000114};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115
116/// Pre(post)-action for different OpenMP constructs specialized for NVPTX.
117class NVPTXActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +0000118 llvm::FunctionCallee EnterCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000119 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +0000120 llvm::FunctionCallee ExitCallee = nullptr;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000121 ArrayRef<llvm::Value *> ExitArgs;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000122 bool Conditional = false;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000123 llvm::BasicBlock *ContBlock = nullptr;
124
125public:
James Y Knight9871db02019-02-05 16:42:33 +0000126 NVPTXActionTy(llvm::FunctionCallee EnterCallee,
127 ArrayRef<llvm::Value *> EnterArgs,
128 llvm::FunctionCallee ExitCallee,
129 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000130 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
131 ExitArgs(ExitArgs), Conditional(Conditional) {}
132 void Enter(CodeGenFunction &CGF) override {
133 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
134 if (Conditional) {
135 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
136 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
137 ContBlock = CGF.createBasicBlock("omp_if.end");
138 // Generate the branch (If-stmt)
139 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
140 CGF.EmitBlock(ThenBlock);
141 }
142 }
143 void Done(CodeGenFunction &CGF) {
144 // Emit the rest of blocks/branches
145 CGF.EmitBranch(ContBlock);
146 CGF.EmitBlock(ContBlock, true);
147 }
148 void Exit(CodeGenFunction &CGF) override {
149 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
150 }
151};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000152
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000153/// A class to track the execution mode when codegening directives within
154/// a target region. The appropriate mode (SPMD|NON-SPMD) is set on entry
155/// to the target region and used by containing directives such as 'parallel'
156/// to emit optimized code.
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000157class ExecutionRuntimeModesRAII {
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000158private:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000159 CGOpenMPRuntimeNVPTX::ExecutionMode SavedExecMode =
160 CGOpenMPRuntimeNVPTX::EM_Unknown;
161 CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode;
162 bool SavedRuntimeMode = false;
163 bool *RuntimeMode = nullptr;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000164
165public:
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000166 /// Constructor for Non-SPMD mode.
167 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode)
168 : ExecMode(ExecMode) {
169 SavedExecMode = ExecMode;
170 ExecMode = CGOpenMPRuntimeNVPTX::EM_NonSPMD;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000171 }
Alexey Bataeve8ad4b72018-11-26 18:37:09 +0000172 /// Constructor for SPMD mode.
173 ExecutionRuntimeModesRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &ExecMode,
174 bool &RuntimeMode, bool FullRuntimeMode)
175 : ExecMode(ExecMode), RuntimeMode(&RuntimeMode) {
176 SavedExecMode = ExecMode;
177 SavedRuntimeMode = RuntimeMode;
178 ExecMode = CGOpenMPRuntimeNVPTX::EM_SPMD;
179 RuntimeMode = FullRuntimeMode;
180 }
181 ~ExecutionRuntimeModesRAII() {
182 ExecMode = SavedExecMode;
183 if (RuntimeMode)
184 *RuntimeMode = SavedRuntimeMode;
185 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000186};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000187
188/// GPU Configuration: This information can be derived from cuda registers,
189/// however, providing compile time constants helps generate more efficient
190/// code. For all practical purposes this is fine because the configuration
191/// is the same for all known NVPTX architectures.
192enum MachineConfiguration : unsigned {
193 WarpSize = 32,
194 /// Number of bits required to represent a lane identifier, which is
195 /// computed as log_2(WarpSize).
196 LaneIDBits = 5,
197 LaneIDMask = WarpSize - 1,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +0000198
199 /// Global memory alignment for performance.
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000200 GlobalMemoryAlignment = 128,
Alexey Bataev09c9eea2018-11-09 16:18:04 +0000201
202 /// Maximal size of the shared memory buffer.
203 SharedMemorySize = 128,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000204};
205
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000206static const ValueDecl *getPrivateItem(const Expr *RefExpr) {
207 RefExpr = RefExpr->IgnoreParens();
208 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr)) {
209 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
210 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
211 Base = TempASE->getBase()->IgnoreParenImpCasts();
212 RefExpr = Base;
213 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr)) {
214 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
215 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
216 Base = TempOASE->getBase()->IgnoreParenImpCasts();
217 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
218 Base = TempASE->getBase()->IgnoreParenImpCasts();
219 RefExpr = Base;
220 }
221 RefExpr = RefExpr->IgnoreParenImpCasts();
222 if (const auto *DE = dyn_cast<DeclRefExpr>(RefExpr))
223 return cast<ValueDecl>(DE->getDecl()->getCanonicalDecl());
224 const auto *ME = cast<MemberExpr>(RefExpr);
225 return cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
226}
227
Alexey Bataev2adecff2018-09-21 14:22:53 +0000228
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) {
Fangrui Song899d1392019-04-24 14:43:05 +0000234 using VarsDataTy = std::pair<CharUnits /*Align*/, const ValueDecl *>;
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000235 if (EscapedDecls.empty() && EscapedDeclsForTeams.empty())
Alexey Bataev2adecff2018-09-21 14:22:53 +0000236 return nullptr;
237 SmallVector<VarsDataTy, 4> GlobalizedVars;
238 for (const ValueDecl *D : EscapedDecls)
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000239 GlobalizedVars.emplace_back(
240 CharUnits::fromQuantity(std::max(
241 C.getDeclAlign(D).getQuantity(),
242 static_cast<CharUnits::QuantityType>(GlobalMemoryAlignment))),
243 D);
244 for (const ValueDecl *D : EscapedDeclsForTeams)
Alexey Bataev2adecff2018-09-21 14:22:53 +0000245 GlobalizedVars.emplace_back(C.getDeclAlign(D), D);
Fangrui Song899d1392019-04-24 14:43:05 +0000246 llvm::stable_sort(GlobalizedVars, [](VarsDataTy L, VarsDataTy R) {
247 return L.first > R.first;
248 });
249
Alexey Bataev2adecff2018-09-21 14:22:53 +0000250 // Build struct _globalized_locals_ty {
Alexey Bataevff23bb62018-10-11 18:30:31 +0000251 // /* globalized vars */[WarSize] align (max(decl_align,
252 // GlobalMemoryAlignment))
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000253 // /* globalized vars */ for EscapedDeclsForTeams
Alexey Bataev2adecff2018-09-21 14:22:53 +0000254 // };
255 RecordDecl *GlobalizedRD = C.buildImplicitRecord("_globalized_locals_ty");
256 GlobalizedRD->startDefinition();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000257 llvm::SmallPtrSet<const ValueDecl *, 16> SingleEscaped(
258 EscapedDeclsForTeams.begin(), EscapedDeclsForTeams.end());
Alexey Bataev2adecff2018-09-21 14:22:53 +0000259 for (const auto &Pair : GlobalizedVars) {
260 const ValueDecl *VD = Pair.second;
261 QualType Type = VD->getType();
262 if (Type->isLValueReferenceType())
263 Type = C.getPointerType(Type.getNonReferenceType());
264 else
265 Type = Type.getNonReferenceType();
266 SourceLocation Loc = VD->getLocation();
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000267 FieldDecl *Field;
268 if (SingleEscaped.count(VD)) {
269 Field = FieldDecl::Create(
270 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
271 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
272 /*BW=*/nullptr, /*Mutable=*/false,
273 /*InitStyle=*/ICIS_NoInit);
274 Field->setAccess(AS_public);
275 if (VD->hasAttrs()) {
276 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
277 E(VD->getAttrs().end());
278 I != E; ++I)
279 Field->addAttr(*I);
280 }
281 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +0000282 llvm::APInt ArraySize(32, BufSize);
Richard Smith772e2662019-10-04 01:25:59 +0000283 Type = C.getConstantArrayType(Type, ArraySize, nullptr, ArrayType::Normal,
284 0);
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000285 Field = FieldDecl::Create(
286 C, GlobalizedRD, Loc, Loc, VD->getIdentifier(), Type,
287 C.getTrivialTypeSourceInfo(Type, SourceLocation()),
288 /*BW=*/nullptr, /*Mutable=*/false,
289 /*InitStyle=*/ICIS_NoInit);
290 Field->setAccess(AS_public);
291 llvm::APInt Align(32, std::max(C.getDeclAlign(VD).getQuantity(),
292 static_cast<CharUnits::QuantityType>(
293 GlobalMemoryAlignment)));
294 Field->addAttr(AlignedAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +0000295 C, /*IsAlignmentExpr=*/true,
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000296 IntegerLiteral::Create(C, Align,
297 C.getIntTypeForBitwidth(32, /*Signed=*/0),
Erich Keane6a24e802019-09-13 17:39:31 +0000298 SourceLocation()),
299 {}, AttributeCommonInfo::AS_GNU, AlignedAttr::GNU_aligned));
Alexey Bataev2adecff2018-09-21 14:22:53 +0000300 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +0000301 GlobalizedRD->addDecl(Field);
Alexey Bataev2adecff2018-09-21 14:22:53 +0000302 MappedDeclsFields.try_emplace(VD, Field);
303 }
304 GlobalizedRD->completeDefinition();
305 return GlobalizedRD;
306}
307
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000308/// Get the list of variables that can escape their declaration context.
309class CheckVarsEscapingDeclContext final
310 : public ConstStmtVisitor<CheckVarsEscapingDeclContext> {
311 CodeGenFunction &CGF;
312 llvm::SetVector<const ValueDecl *> EscapedDecls;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000313 llvm::SetVector<const ValueDecl *> EscapedVariableLengthDecls;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000314 llvm::SmallPtrSet<const Decl *, 4> EscapedParameters;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000315 RecordDecl *GlobalizedRD = nullptr;
316 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000317 bool AllEscaped = false;
Alexey Bataev91433f62018-06-26 17:24:03 +0000318 bool IsForCombinedParallelRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000319
320 void markAsEscaped(const ValueDecl *VD) {
Alexey Bataev03f270c2018-03-30 18:31:07 +0000321 // Do not globalize declare target variables.
Alexey Bataev97b72212018-08-14 18:31:20 +0000322 if (!isa<VarDecl>(VD) ||
323 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev03f270c2018-03-30 18:31:07 +0000324 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000325 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +0000326 // Use user-specified allocation.
327 if (VD->hasAttrs() && VD->hasAttr<OMPAllocateDeclAttr>())
328 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +0000329 // Variables captured by value must be globalized.
330 if (auto *CSI = CGF.CapturedStmtInfo) {
Mikael Holmen9f373a32018-03-16 07:27:57 +0000331 if (const FieldDecl *FD = CSI->lookup(cast<VarDecl>(VD))) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000332 // Check if need to capture the variable that was already captured by
333 // value in the outer region.
Alexey Bataev91433f62018-06-26 17:24:03 +0000334 if (!IsForCombinedParallelRegion) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000335 if (!FD->hasAttrs())
336 return;
337 const auto *Attr = FD->getAttr<OMPCaptureKindAttr>();
338 if (!Attr)
339 return;
Alexey Bataev6393eb72018-12-06 15:35:13 +0000340 if (((Attr->getCaptureKind() != OMPC_map) &&
341 !isOpenMPPrivate(
342 static_cast<OpenMPClauseKind>(Attr->getCaptureKind()))) ||
343 ((Attr->getCaptureKind() == OMPC_map) &&
344 !FD->getType()->isAnyPointerType()))
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000345 return;
346 }
347 if (!FD->getType()->isReferenceType()) {
348 assert(!VD->getType()->isVariablyModifiedType() &&
349 "Parameter captured by value with variably modified type");
350 EscapedParameters.insert(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000351 } else if (!IsForCombinedParallelRegion) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000352 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000353 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000354 }
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000355 }
356 if ((!CGF.CapturedStmtInfo ||
Alexey Bataev91433f62018-06-26 17:24:03 +0000357 (IsForCombinedParallelRegion && CGF.CapturedStmtInfo)) &&
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000358 VD->getType()->isReferenceType())
359 // Do not globalize variables with reference type.
Alexey Bataev2a3320a2018-05-15 18:01:01 +0000360 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000361 if (VD->getType()->isVariablyModifiedType())
362 EscapedVariableLengthDecls.insert(VD);
363 else
364 EscapedDecls.insert(VD);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000365 }
366
367 void VisitValueDecl(const ValueDecl *VD) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000368 if (VD->getType()->isLValueReferenceType())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000369 markAsEscaped(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000370 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
371 if (!isa<ParmVarDecl>(VarD) && VarD->hasInit()) {
372 const bool SavedAllEscaped = AllEscaped;
373 AllEscaped = VD->getType()->isLValueReferenceType();
374 Visit(VarD->getInit());
375 AllEscaped = SavedAllEscaped;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000376 }
377 }
378 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000379 void VisitOpenMPCapturedStmt(const CapturedStmt *S,
380 ArrayRef<OMPClause *> Clauses,
381 bool IsCombinedParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000382 if (!S)
383 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000384 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000385 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
386 const ValueDecl *VD = C.getCapturedVar();
Alexey Bataev91433f62018-06-26 17:24:03 +0000387 bool SavedIsForCombinedParallelRegion = IsForCombinedParallelRegion;
388 if (IsCombinedParallelRegion) {
389 // Check if the variable is privatized in the combined construct and
390 // those private copies must be shared in the inner parallel
391 // directive.
392 IsForCombinedParallelRegion = false;
393 for (const OMPClause *C : Clauses) {
394 if (!isOpenMPPrivate(C->getClauseKind()) ||
395 C->getClauseKind() == OMPC_reduction ||
396 C->getClauseKind() == OMPC_linear ||
397 C->getClauseKind() == OMPC_private)
398 continue;
399 ArrayRef<const Expr *> Vars;
400 if (const auto *PC = dyn_cast<OMPFirstprivateClause>(C))
401 Vars = PC->getVarRefs();
402 else if (const auto *PC = dyn_cast<OMPLastprivateClause>(C))
403 Vars = PC->getVarRefs();
404 else
405 llvm_unreachable("Unexpected clause.");
406 for (const auto *E : Vars) {
407 const Decl *D =
408 cast<DeclRefExpr>(E)->getDecl()->getCanonicalDecl();
409 if (D == VD->getCanonicalDecl()) {
410 IsForCombinedParallelRegion = true;
411 break;
412 }
413 }
414 if (IsForCombinedParallelRegion)
415 break;
416 }
417 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000418 markAsEscaped(VD);
419 if (isa<OMPCapturedExprDecl>(VD))
420 VisitValueDecl(VD);
Alexey Bataev91433f62018-06-26 17:24:03 +0000421 IsForCombinedParallelRegion = SavedIsForCombinedParallelRegion;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000422 }
423 }
424 }
425
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000426 void buildRecordForGlobalizedVars(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000427 assert(!GlobalizedRD &&
428 "Record for globalized variables is built already.");
Alexey Bataevff23bb62018-10-11 18:30:31 +0000429 ArrayRef<const ValueDecl *> EscapedDeclsForParallel, EscapedDeclsForTeams;
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000430 if (IsInTTDRegion)
Alexey Bataevff23bb62018-10-11 18:30:31 +0000431 EscapedDeclsForTeams = EscapedDecls.getArrayRef();
432 else
433 EscapedDeclsForParallel = EscapedDecls.getArrayRef();
Alexey Bataev2adecff2018-09-21 14:22:53 +0000434 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevff23bb62018-10-11 18:30:31 +0000435 CGF.getContext(), EscapedDeclsForParallel, EscapedDeclsForTeams,
Alexey Bataev8061acd2019-02-20 16:36:22 +0000436 MappedDeclsFields, WarpSize);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000437 }
438
439public:
Alexey Bataevf2f39be2018-11-16 19:38:21 +0000440 CheckVarsEscapingDeclContext(CodeGenFunction &CGF,
441 ArrayRef<const ValueDecl *> TeamsReductions)
442 : CGF(CGF), EscapedDecls(TeamsReductions.begin(), TeamsReductions.end()) {
443 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000444 virtual ~CheckVarsEscapingDeclContext() = default;
445 void VisitDeclStmt(const DeclStmt *S) {
446 if (!S)
447 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000448 for (const Decl *D : S->decls())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000449 if (const auto *VD = dyn_cast_or_null<ValueDecl>(D))
450 VisitValueDecl(VD);
451 }
452 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
453 if (!D)
454 return;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000455 if (!D->hasAssociatedStmt())
456 return;
457 if (const auto *S =
458 dyn_cast_or_null<CapturedStmt>(D->getAssociatedStmt())) {
459 // Do not analyze directives that do not actually require capturing,
460 // like `omp for` or `omp simd` directives.
461 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
462 getOpenMPCaptureRegions(CaptureRegions, D->getDirectiveKind());
463 if (CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown) {
464 VisitStmt(S->getCapturedStmt());
465 return;
Alexey Bataev673110d2018-05-16 13:36:30 +0000466 }
Alexey Bataev91433f62018-06-26 17:24:03 +0000467 VisitOpenMPCapturedStmt(
468 S, D->clauses(),
469 CaptureRegions.back() == OMPD_parallel &&
470 isOpenMPDistributeDirective(D->getDirectiveKind()));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000471 }
472 }
473 void VisitCapturedStmt(const CapturedStmt *S) {
474 if (!S)
475 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000476 for (const CapturedStmt::Capture &C : S->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000477 if (C.capturesVariable() && !C.capturesVariableByCopy()) {
478 const ValueDecl *VD = C.getCapturedVar();
479 markAsEscaped(VD);
480 if (isa<OMPCapturedExprDecl>(VD))
481 VisitValueDecl(VD);
482 }
483 }
484 }
485 void VisitLambdaExpr(const LambdaExpr *E) {
486 if (!E)
487 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000488 for (const LambdaCapture &C : E->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000489 if (C.capturesVariable()) {
490 if (C.getCaptureKind() == LCK_ByRef) {
491 const ValueDecl *VD = C.getCapturedVar();
492 markAsEscaped(VD);
493 if (E->isInitCapture(&C) || isa<OMPCapturedExprDecl>(VD))
494 VisitValueDecl(VD);
495 }
496 }
497 }
498 }
499 void VisitBlockExpr(const BlockExpr *E) {
500 if (!E)
501 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000502 for (const BlockDecl::Capture &C : E->getBlockDecl()->captures()) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000503 if (C.isByRef()) {
504 const VarDecl *VD = C.getVariable();
505 markAsEscaped(VD);
506 if (isa<OMPCapturedExprDecl>(VD) || VD->isInitCapture())
507 VisitValueDecl(VD);
508 }
509 }
510 }
511 void VisitCallExpr(const CallExpr *E) {
512 if (!E)
513 return;
514 for (const Expr *Arg : E->arguments()) {
515 if (!Arg)
516 continue;
517 if (Arg->isLValue()) {
518 const bool SavedAllEscaped = AllEscaped;
519 AllEscaped = true;
520 Visit(Arg);
521 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000522 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000523 Visit(Arg);
Alexey Bataev9ff80832018-04-16 20:16:21 +0000524 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000525 }
526 Visit(E->getCallee());
527 }
528 void VisitDeclRefExpr(const DeclRefExpr *E) {
529 if (!E)
530 return;
531 const ValueDecl *VD = E->getDecl();
532 if (AllEscaped)
533 markAsEscaped(VD);
534 if (isa<OMPCapturedExprDecl>(VD))
535 VisitValueDecl(VD);
536 else if (const auto *VarD = dyn_cast<VarDecl>(VD))
537 if (VarD->isInitCapture())
538 VisitValueDecl(VD);
539 }
540 void VisitUnaryOperator(const UnaryOperator *E) {
541 if (!E)
542 return;
543 if (E->getOpcode() == UO_AddrOf) {
544 const bool SavedAllEscaped = AllEscaped;
545 AllEscaped = true;
546 Visit(E->getSubExpr());
547 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000548 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000549 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000550 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000551 }
552 void VisitImplicitCastExpr(const ImplicitCastExpr *E) {
553 if (!E)
554 return;
555 if (E->getCastKind() == CK_ArrayToPointerDecay) {
556 const bool SavedAllEscaped = AllEscaped;
557 AllEscaped = true;
558 Visit(E->getSubExpr());
559 AllEscaped = SavedAllEscaped;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000560 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000561 Visit(E->getSubExpr());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000562 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000563 }
564 void VisitExpr(const Expr *E) {
565 if (!E)
566 return;
567 bool SavedAllEscaped = AllEscaped;
568 if (!E->isLValue())
569 AllEscaped = false;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000570 for (const Stmt *Child : E->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000571 if (Child)
572 Visit(Child);
573 AllEscaped = SavedAllEscaped;
574 }
575 void VisitStmt(const Stmt *S) {
576 if (!S)
577 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +0000578 for (const Stmt *Child : S->children())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000579 if (Child)
580 Visit(Child);
581 }
582
Alexey Bataevc99042b2018-03-15 18:10:54 +0000583 /// Returns the record that handles all the escaped local variables and used
584 /// instead of their original storage.
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000585 const RecordDecl *getGlobalizedRecord(bool IsInTTDRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000586 if (!GlobalizedRD)
Alexey Bataev4ac58d12018-10-12 20:19:59 +0000587 buildRecordForGlobalizedVars(IsInTTDRegion);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000588 return GlobalizedRD;
589 }
590
Alexey Bataevc99042b2018-03-15 18:10:54 +0000591 /// Returns the field in the globalized record for the escaped variable.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000592 const FieldDecl *getFieldForGlobalizedVar(const ValueDecl *VD) const {
593 assert(GlobalizedRD &&
594 "Record for globalized variables must be generated already.");
595 auto I = MappedDeclsFields.find(VD);
596 if (I == MappedDeclsFields.end())
597 return nullptr;
598 return I->getSecond();
599 }
600
Alexey Bataevc99042b2018-03-15 18:10:54 +0000601 /// Returns the list of the escaped local variables/parameters.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000602 ArrayRef<const ValueDecl *> getEscapedDecls() const {
603 return EscapedDecls.getArrayRef();
604 }
Alexey Bataevc99042b2018-03-15 18:10:54 +0000605
606 /// Checks if the escaped local variable is actually a parameter passed by
607 /// value.
608 const llvm::SmallPtrSetImpl<const Decl *> &getEscapedParameters() const {
609 return EscapedParameters;
610 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000611
612 /// Returns the list of the escaped variables with the variably modified
613 /// types.
614 ArrayRef<const ValueDecl *> getEscapedVariableLengthDecls() const {
615 return EscapedVariableLengthDecls.getArrayRef();
616 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +0000617};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000618} // anonymous namespace
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000619
620/// Get the GPU warp size.
621static llvm::Value *getNVPTXWarpSize(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_warpsize),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000625 "nvptx_warp_size");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000626}
627
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000628/// Get the id of the current thread on the GPU.
629static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000630 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000631 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000632 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000633 "nvptx_tid");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000634}
635
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +0000636/// Get the id of the warp in the block.
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 *getNVPTXWarpID(CodeGenFunction &CGF) {
640 CGBuilderTy &Bld = CGF.Builder;
641 return Bld.CreateAShr(getNVPTXThreadID(CGF), LaneIDBits, "nvptx_warp_id");
642}
643
644/// Get the id of the current lane in the Warp.
645/// We assume that the warp size is 32, which is always the case
646/// on the NVPTX device, to generate more efficient code.
647static llvm::Value *getNVPTXLaneID(CodeGenFunction &CGF) {
648 CGBuilderTy &Bld = CGF.Builder;
649 return Bld.CreateAnd(getNVPTXThreadID(CGF), Bld.getInt32(LaneIDMask),
650 "nvptx_lane_id");
651}
652
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000653/// Get the maximum number of threads in a block of the GPU.
654static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) {
Alexey Bataev3c595a62017-08-14 15:01:03 +0000655 return CGF.EmitRuntimeCall(
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000656 llvm::Intrinsic::getDeclaration(
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000657 &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x),
Alexey Bataev3c595a62017-08-14 15:01:03 +0000658 "nvptx_num_threads");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000659}
660
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000661/// Get the value of the thread_limit clause in the teams directive.
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000662/// For the 'generic' execution mode, the runtime encodes thread_limit in
663/// the launch parameters, always starting thread_limit+warpSize threads per
664/// CTA. The threads in the last warp are reserved for master execution.
665/// For the 'spmd' execution mode, all threads in a CTA are part of the team.
666static llvm::Value *getThreadLimit(CodeGenFunction &CGF,
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000667 bool IsInSPMDExecutionMode = false) {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000668 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev4065b9a2018-06-21 20:26:33 +0000669 return IsInSPMDExecutionMode
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000670 ? getNVPTXNumThreads(CGF)
Alexey Bataeve290ec02018-04-06 16:03:36 +0000671 : Bld.CreateNUWSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF),
672 "thread_limit");
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +0000673}
674
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000675/// Get the thread id of the OMP master thread.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000676/// The master thread id is the first thread (lane) of the last warp in the
677/// GPU block. Warp size is assumed to be some power of 2.
678/// Thread id is 0 indexed.
679/// E.g: If NumThreads is 33, master id is 32.
680/// If NumThreads is 64, master id is 32.
681/// If NumThreads is 1024, master id is 992.
Arpith Chacko Jacobccf2f732017-01-03 20:19:56 +0000682static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000683 CGBuilderTy &Bld = CGF.Builder;
684 llvm::Value *NumThreads = getNVPTXNumThreads(CGF);
685
686 // We assume that the warp size is a power of 2.
Alexey Bataeve290ec02018-04-06 16:03:36 +0000687 llvm::Value *Mask = Bld.CreateNUWSub(getNVPTXWarpSize(CGF), Bld.getInt32(1));
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000688
Alexey Bataeve290ec02018-04-06 16:03:36 +0000689 return Bld.CreateAnd(Bld.CreateNUWSub(NumThreads, Bld.getInt32(1)),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000690 Bld.CreateNot(Mask), "master_tid");
691}
692
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000693CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState(
Alexey Bataev7cae94e2018-01-04 19:45:16 +0000694 CodeGenModule &CGM, SourceLocation Loc)
Alexey Bataev9ff80832018-04-16 20:16:21 +0000695 : WorkerFn(nullptr), CGFI(CGM.getTypes().arrangeNullaryFunction()),
696 Loc(Loc) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000697 createWorkerFunction(CGM);
Vasileios Kalintirise5c09592016-03-22 10:41:20 +0000698}
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000699
700void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction(
701 CodeGenModule &CGM) {
702 // Create an worker function with no arguments.
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000703
704 WorkerFn = llvm::Function::Create(
Alexey Bataev9ff80832018-04-16 20:16:21 +0000705 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataevaee93892018-01-08 20:09:47 +0000706 /*placeholder=*/"_worker", &CGM.getModule());
Alexey Bataev9ff80832018-04-16 20:16:21 +0000707 CGM.SetInternalFunctionAttributes(GlobalDecl(), WorkerFn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +0000708 WorkerFn->setDoesNotRecurse();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +0000709}
710
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000711CGOpenMPRuntimeNVPTX::ExecutionMode
712CGOpenMPRuntimeNVPTX::getExecutionMode() const {
713 return CurrentExecutionMode;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000714}
715
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000716static CGOpenMPRuntimeNVPTX::DataSharingMode
717getDataSharingMode(CodeGenModule &CGM) {
718 return CGM.getLangOpts().OpenMPCUDAMode ? CGOpenMPRuntimeNVPTX::CUDA
719 : CGOpenMPRuntimeNVPTX::Generic;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +0000720}
721
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000722/// Check for inner (nested) SPMD construct, if any
723static bool hasNestedSPMDDirective(ASTContext &Ctx,
724 const OMPExecutableDirective &D) {
725 const auto *CS = D.getInnermostCapturedStmt();
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000726 const auto *Body =
727 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000728 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000729
Alexey Bataev5c427362019-04-10 19:11:33 +0000730 if (const auto *NestedDir =
731 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000732 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000733 switch (D.getDirectiveKind()) {
734 case OMPD_target:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000735 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000736 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000737 if (DKind == OMPD_teams) {
738 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
739 /*IgnoreCaptured=*/true);
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000740 if (!Body)
741 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000742 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
743 if (const auto *NND =
744 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000745 DKind = NND->getDirectiveKind();
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000746 if (isOpenMPParallelDirective(DKind))
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000747 return true;
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000748 }
749 }
750 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000751 case OMPD_target_teams:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000752 return isOpenMPParallelDirective(DKind);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000753 case OMPD_target_simd:
754 case OMPD_target_parallel:
755 case OMPD_target_parallel_for:
756 case OMPD_target_parallel_for_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000757 case OMPD_target_teams_distribute:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000758 case OMPD_target_teams_distribute_simd:
759 case OMPD_target_teams_distribute_parallel_for:
760 case OMPD_target_teams_distribute_parallel_for_simd:
761 case OMPD_parallel:
762 case OMPD_for:
763 case OMPD_parallel_for:
764 case OMPD_parallel_sections:
765 case OMPD_for_simd:
766 case OMPD_parallel_for_simd:
767 case OMPD_cancel:
768 case OMPD_cancellation_point:
769 case OMPD_ordered:
770 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000771 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000772 case OMPD_task:
773 case OMPD_simd:
774 case OMPD_sections:
775 case OMPD_section:
776 case OMPD_single:
777 case OMPD_master:
778 case OMPD_critical:
779 case OMPD_taskyield:
780 case OMPD_barrier:
781 case OMPD_taskwait:
782 case OMPD_taskgroup:
783 case OMPD_atomic:
784 case OMPD_flush:
785 case OMPD_teams:
786 case OMPD_target_data:
787 case OMPD_target_exit_data:
788 case OMPD_target_enter_data:
789 case OMPD_distribute:
790 case OMPD_distribute_simd:
791 case OMPD_distribute_parallel_for:
792 case OMPD_distribute_parallel_for_simd:
793 case OMPD_teams_distribute:
794 case OMPD_teams_distribute_simd:
795 case OMPD_teams_distribute_parallel_for:
796 case OMPD_teams_distribute_parallel_for_simd:
797 case OMPD_target_update:
798 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000799 case OMPD_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000800 case OMPD_declare_target:
801 case OMPD_end_declare_target:
802 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000803 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000804 case OMPD_taskloop:
805 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000806 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000807 case OMPD_unknown:
808 llvm_unreachable("Unexpected directive.");
809 }
810 }
811
812 return false;
813}
814
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000815static bool supportsSPMDExecutionMode(ASTContext &Ctx,
816 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000817 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
818 switch (DirectiveKind) {
819 case OMPD_target:
820 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000821 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000822 case OMPD_target_parallel:
823 case OMPD_target_parallel_for:
824 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000825 case OMPD_target_teams_distribute_parallel_for:
826 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000827 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000828 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000829 return true;
830 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000831 return false;
832 case OMPD_parallel:
833 case OMPD_for:
834 case OMPD_parallel_for:
835 case OMPD_parallel_sections:
836 case OMPD_for_simd:
837 case OMPD_parallel_for_simd:
838 case OMPD_cancel:
839 case OMPD_cancellation_point:
840 case OMPD_ordered:
841 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000842 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000843 case OMPD_task:
844 case OMPD_simd:
845 case OMPD_sections:
846 case OMPD_section:
847 case OMPD_single:
848 case OMPD_master:
849 case OMPD_critical:
850 case OMPD_taskyield:
851 case OMPD_barrier:
852 case OMPD_taskwait:
853 case OMPD_taskgroup:
854 case OMPD_atomic:
855 case OMPD_flush:
856 case OMPD_teams:
857 case OMPD_target_data:
858 case OMPD_target_exit_data:
859 case OMPD_target_enter_data:
860 case OMPD_distribute:
861 case OMPD_distribute_simd:
862 case OMPD_distribute_parallel_for:
863 case OMPD_distribute_parallel_for_simd:
864 case OMPD_teams_distribute:
865 case OMPD_teams_distribute_simd:
866 case OMPD_teams_distribute_parallel_for:
867 case OMPD_teams_distribute_parallel_for_simd:
868 case OMPD_target_update:
869 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000870 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000871 case OMPD_declare_target:
872 case OMPD_end_declare_target:
873 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000874 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000875 case OMPD_taskloop:
876 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000877 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000878 case OMPD_unknown:
879 break;
880 }
881 llvm_unreachable(
882 "Unknown programming model for OpenMP directive on NVPTX target.");
883}
884
885/// Check if the directive is loops based and has schedule clause at all or has
886/// static scheduling.
887static bool hasStaticScheduling(const OMPExecutableDirective &D) {
888 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
889 isOpenMPLoopDirective(D.getDirectiveKind()) &&
890 "Expected loop-based directive.");
891 return !D.hasClausesOfKind<OMPOrderedClause>() &&
892 (!D.hasClausesOfKind<OMPScheduleClause>() ||
893 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
894 [](const OMPScheduleClause *C) {
895 return C->getScheduleKind() == OMPC_SCHEDULE_static;
896 }));
897}
898
899/// Check for inner (nested) lightweight runtime construct, if any
900static bool hasNestedLightweightDirective(ASTContext &Ctx,
901 const OMPExecutableDirective &D) {
902 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
903 const auto *CS = D.getInnermostCapturedStmt();
904 const auto *Body =
905 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000906 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000907
Alexey Bataev5c427362019-04-10 19:11:33 +0000908 if (const auto *NestedDir =
909 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000910 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
911 switch (D.getDirectiveKind()) {
912 case OMPD_target:
913 if (isOpenMPParallelDirective(DKind) &&
914 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
915 hasStaticScheduling(*NestedDir))
916 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000917 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
918 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000919 if (DKind == OMPD_parallel) {
920 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
921 /*IgnoreCaptured=*/true);
922 if (!Body)
923 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000924 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
925 if (const auto *NND =
926 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000927 DKind = NND->getDirectiveKind();
928 if (isOpenMPWorksharingDirective(DKind) &&
929 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
930 return true;
931 }
932 } else if (DKind == OMPD_teams) {
933 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
934 /*IgnoreCaptured=*/true);
935 if (!Body)
936 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000937 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
938 if (const auto *NND =
939 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000940 DKind = NND->getDirectiveKind();
941 if (isOpenMPParallelDirective(DKind) &&
942 isOpenMPWorksharingDirective(DKind) &&
943 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
944 return true;
945 if (DKind == OMPD_parallel) {
946 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
947 /*IgnoreCaptured=*/true);
948 if (!Body)
949 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000950 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
951 if (const auto *NND =
952 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000953 DKind = NND->getDirectiveKind();
954 if (isOpenMPWorksharingDirective(DKind) &&
955 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
956 return true;
957 }
958 }
959 }
960 }
961 return false;
962 case OMPD_target_teams:
963 if (isOpenMPParallelDirective(DKind) &&
964 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
965 hasStaticScheduling(*NestedDir))
966 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000967 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
968 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000969 if (DKind == OMPD_parallel) {
970 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
971 /*IgnoreCaptured=*/true);
972 if (!Body)
973 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000974 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
975 if (const auto *NND =
976 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000977 DKind = NND->getDirectiveKind();
978 if (isOpenMPWorksharingDirective(DKind) &&
979 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
980 return true;
981 }
982 }
983 return false;
984 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000985 if (DKind == OMPD_simd)
986 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000987 return isOpenMPWorksharingDirective(DKind) &&
988 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
989 case OMPD_target_teams_distribute:
990 case OMPD_target_simd:
991 case OMPD_target_parallel_for:
992 case OMPD_target_parallel_for_simd:
993 case OMPD_target_teams_distribute_simd:
994 case OMPD_target_teams_distribute_parallel_for:
995 case OMPD_target_teams_distribute_parallel_for_simd:
996 case OMPD_parallel:
997 case OMPD_for:
998 case OMPD_parallel_for:
999 case OMPD_parallel_sections:
1000 case OMPD_for_simd:
1001 case OMPD_parallel_for_simd:
1002 case OMPD_cancel:
1003 case OMPD_cancellation_point:
1004 case OMPD_ordered:
1005 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001006 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001007 case OMPD_task:
1008 case OMPD_simd:
1009 case OMPD_sections:
1010 case OMPD_section:
1011 case OMPD_single:
1012 case OMPD_master:
1013 case OMPD_critical:
1014 case OMPD_taskyield:
1015 case OMPD_barrier:
1016 case OMPD_taskwait:
1017 case OMPD_taskgroup:
1018 case OMPD_atomic:
1019 case OMPD_flush:
1020 case OMPD_teams:
1021 case OMPD_target_data:
1022 case OMPD_target_exit_data:
1023 case OMPD_target_enter_data:
1024 case OMPD_distribute:
1025 case OMPD_distribute_simd:
1026 case OMPD_distribute_parallel_for:
1027 case OMPD_distribute_parallel_for_simd:
1028 case OMPD_teams_distribute:
1029 case OMPD_teams_distribute_simd:
1030 case OMPD_teams_distribute_parallel_for:
1031 case OMPD_teams_distribute_parallel_for_simd:
1032 case OMPD_target_update:
1033 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001034 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001035 case OMPD_declare_target:
1036 case OMPD_end_declare_target:
1037 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001038 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001039 case OMPD_taskloop:
1040 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001041 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001042 case OMPD_unknown:
1043 llvm_unreachable("Unexpected directive.");
1044 }
1045 }
1046
1047 return false;
1048}
1049
1050/// Checks if the construct supports lightweight runtime. It must be SPMD
1051/// construct + inner loop-based construct with static scheduling.
1052static bool supportsLightweightRuntime(ASTContext &Ctx,
1053 const OMPExecutableDirective &D) {
1054 if (!supportsSPMDExecutionMode(Ctx, D))
1055 return false;
1056 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1057 switch (DirectiveKind) {
1058 case OMPD_target:
1059 case OMPD_target_teams:
1060 case OMPD_target_parallel:
1061 return hasNestedLightweightDirective(Ctx, D);
1062 case OMPD_target_parallel_for:
1063 case OMPD_target_parallel_for_simd:
1064 case OMPD_target_teams_distribute_parallel_for:
1065 case OMPD_target_teams_distribute_parallel_for_simd:
1066 // (Last|First)-privates must be shared in parallel region.
1067 return hasStaticScheduling(D);
1068 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001069 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001070 return true;
1071 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001072 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001073 case OMPD_parallel:
1074 case OMPD_for:
1075 case OMPD_parallel_for:
1076 case OMPD_parallel_sections:
1077 case OMPD_for_simd:
1078 case OMPD_parallel_for_simd:
1079 case OMPD_cancel:
1080 case OMPD_cancellation_point:
1081 case OMPD_ordered:
1082 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001083 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001084 case OMPD_task:
1085 case OMPD_simd:
1086 case OMPD_sections:
1087 case OMPD_section:
1088 case OMPD_single:
1089 case OMPD_master:
1090 case OMPD_critical:
1091 case OMPD_taskyield:
1092 case OMPD_barrier:
1093 case OMPD_taskwait:
1094 case OMPD_taskgroup:
1095 case OMPD_atomic:
1096 case OMPD_flush:
1097 case OMPD_teams:
1098 case OMPD_target_data:
1099 case OMPD_target_exit_data:
1100 case OMPD_target_enter_data:
1101 case OMPD_distribute:
1102 case OMPD_distribute_simd:
1103 case OMPD_distribute_parallel_for:
1104 case OMPD_distribute_parallel_for_simd:
1105 case OMPD_teams_distribute:
1106 case OMPD_teams_distribute_simd:
1107 case OMPD_teams_distribute_parallel_for:
1108 case OMPD_teams_distribute_parallel_for_simd:
1109 case OMPD_target_update:
1110 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001111 case OMPD_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001112 case OMPD_declare_target:
1113 case OMPD_end_declare_target:
1114 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001115 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001116 case OMPD_taskloop:
1117 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001118 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001119 case OMPD_unknown:
1120 break;
1121 }
1122 llvm_unreachable(
1123 "Unknown programming model for OpenMP directive on NVPTX target.");
1124}
1125
1126void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001127 StringRef ParentName,
1128 llvm::Function *&OutlinedFn,
1129 llvm::Constant *&OutlinedFnID,
1130 bool IsOffloadEntry,
1131 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001132 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001133 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001134 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001135 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001136 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001137
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001138 // Emit target region as a standalone region.
1139 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001140 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1141 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001142
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001143 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001144 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001145 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001146 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001147 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001148 auto &RT =
1149 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001150 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1151 // Skip target region initialization.
1152 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001153 }
1154 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001155 auto &RT =
1156 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001157 RT.clearLocThreadIdInsertPt(CGF);
1158 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001159 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001160 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001161 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001162 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001163 // Reserve place for the globalized memory.
1164 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001165 if (!KernelStaticGlobalized) {
1166 KernelStaticGlobalized = new llvm::GlobalVariable(
1167 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1168 llvm::GlobalValue::InternalLinkage,
1169 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1170 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1171 llvm::GlobalValue::NotThreadLocal,
1172 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1173 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001174 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1175 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001176 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001177
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 // Now change the name of the worker function to correspond to this target
1179 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001180 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001181
1182 // Create the worker function
1183 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001184}
1185
1186// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001187void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001188 EntryFunctionState &EST,
1189 WorkerFunctionState &WST) {
1190 CGBuilderTy &Bld = CGF.Builder;
1191
1192 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1193 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1194 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1195 EST.ExitBB = CGF.createBasicBlock(".exit");
1196
Alexey Bataev9ff80832018-04-16 20:16:21 +00001197 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001198 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1199 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1200
1201 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001202 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001203 CGF.EmitBranch(EST.ExitBB);
1204
1205 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001206 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001207 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1208 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1209
1210 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001211 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001212 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001213 // First action in sequential region:
1214 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001215 // TODO: Optimize runtime initialization and pass in correct value.
1216 llvm::Value *Args[] = {getThreadLimit(CGF),
1217 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001218 CGF.EmitRuntimeCall(
1219 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001220
1221 // For data sharing, we need to initialize the stack.
1222 CGF.EmitRuntimeCall(
1223 createNVPTXRuntimeFunction(
1224 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1225
Alexey Bataevc99042b2018-03-15 18:10:54 +00001226 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001227}
1228
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001229void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001230 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001231 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001232 if (!CGF.HaveInsertPoint())
1233 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001234
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001235 emitGenericVarsEpilog(CGF);
1236
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001237 if (!EST.ExitBB)
1238 EST.ExitBB = CGF.createBasicBlock(".exit");
1239
1240 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1241 CGF.EmitBranch(TerminateBB);
1242
1243 CGF.EmitBlock(TerminateBB);
1244 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001245 // TODO: Optimize runtime initialization and pass in correct value.
1246 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001247 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001248 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001249 // Barrier to terminate worker threads.
1250 syncCTAThreads(CGF);
1251 // Master thread jumps to exit point.
1252 CGF.EmitBranch(EST.ExitBB);
1253
1254 CGF.EmitBlock(EST.ExitBB);
1255 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001256}
1257
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001258void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001259 StringRef ParentName,
1260 llvm::Function *&OutlinedFn,
1261 llvm::Constant *&OutlinedFnID,
1262 bool IsOffloadEntry,
1263 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001264 ExecutionRuntimeModesRAII ModeRAII(
1265 CurrentExecutionMode, RequiresFullRuntime,
1266 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1267 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001268 EntryFunctionState EST;
1269
1270 // Emit target region as a standalone region.
1271 class NVPTXPrePostActionTy : public PrePostActionTy {
1272 CGOpenMPRuntimeNVPTX &RT;
1273 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1274 const OMPExecutableDirective &D;
1275
1276 public:
1277 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1278 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1279 const OMPExecutableDirective &D)
1280 : RT(RT), EST(EST), D(D) {}
1281 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001282 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001283 // Skip target region initialization.
1284 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001285 }
1286 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001287 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001288 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001289 }
1290 } Action(*this, EST, D);
1291 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001292 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001293 // Reserve place for the globalized memory.
1294 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001295 if (!KernelStaticGlobalized) {
1296 KernelStaticGlobalized = new llvm::GlobalVariable(
1297 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1298 llvm::GlobalValue::InternalLinkage,
1299 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1300 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1301 llvm::GlobalValue::NotThreadLocal,
1302 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1303 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001304 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1305 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001306 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001307}
1308
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001309void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001310 CodeGenFunction &CGF, EntryFunctionState &EST,
1311 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001312 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001313
1314 // Setup BBs in entry function.
1315 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1316 EST.ExitBB = CGF.createBasicBlock(".exit");
1317
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001318 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1319 /*RequiresOMPRuntime=*/
1320 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1321 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001322 CGF.EmitRuntimeCall(
1323 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001324
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001325 if (RequiresFullRuntime) {
1326 // For data sharing, we need to initialize the stack.
1327 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1328 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1329 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001330
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001331 CGF.EmitBranch(ExecuteBB);
1332
1333 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001334
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001335 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001336}
1337
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001338void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001339 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001340 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001341 if (!CGF.HaveInsertPoint())
1342 return;
1343
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344 if (!EST.ExitBB)
1345 EST.ExitBB = CGF.createBasicBlock(".exit");
1346
1347 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1348 CGF.EmitBranch(OMPDeInitBB);
1349
1350 CGF.EmitBlock(OMPDeInitBB);
1351 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001352 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1353 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001354 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001355 createNVPTXRuntimeFunction(
1356 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001357 CGF.EmitBranch(EST.ExitBB);
1358
1359 CGF.EmitBlock(EST.ExitBB);
1360 EST.ExitBB = nullptr;
1361}
1362
1363// Create a unique global variable to indicate the execution mode of this target
1364// region. The execution mode is either 'generic', or 'spmd' depending on the
1365// target directive. This variable is picked up by the offload library to setup
1366// the device appropriately before kernel launch. If the execution mode is
1367// 'generic', the runtime reserves one warp for the master, otherwise, all
1368// warps participate in parallel work.
1369static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001370 bool Mode) {
1371 auto *GVMode =
1372 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1373 llvm::GlobalValue::WeakAnyLinkage,
1374 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1375 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001376 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001377}
1378
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001379void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001380 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001381
1382 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001383 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001384 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001385 emitWorkerLoop(CGF, WST);
1386 CGF.FinishFunction();
1387}
1388
1389void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1390 WorkerFunctionState &WST) {
1391 //
1392 // The workers enter this loop and wait for parallel work from the master.
1393 // When the master encounters a parallel region it sets up the work + variable
1394 // arguments, and wakes up the workers. The workers first check to see if
1395 // they are required for the parallel region, i.e., within the # of requested
1396 // parallel threads. The activated workers load the variable arguments and
1397 // execute the parallel work.
1398 //
1399
1400 CGBuilderTy &Bld = CGF.Builder;
1401
1402 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1403 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1404 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1405 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1406 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1407 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1408
1409 CGF.EmitBranch(AwaitBB);
1410
1411 // Workers wait for work from master.
1412 CGF.EmitBlock(AwaitBB);
1413 // Wait for parallel work
1414 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001415
1416 Address WorkFn =
1417 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1418 Address ExecStatus =
1419 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1420 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1421 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1422
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001423 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001424 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001425 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001426 llvm::Value *Ret = CGF.EmitRuntimeCall(
1427 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1428 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001429
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001430 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001431 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1432 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001433 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1434
1435 // Activate requested workers.
1436 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001437 llvm::Value *IsActive =
1438 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1439 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001440
1441 // Signal start of parallel region.
1442 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001443 // Skip initialization.
1444 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001445
1446 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001447 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001448 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001449 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001450
1451 llvm::Value *WorkFnMatch =
1452 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1453
1454 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1455 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1456 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1457
1458 // Execute this outlined function.
1459 CGF.EmitBlock(ExecuteFNBB);
1460
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001461 // Insert call to work function via shared wrapper. The shared
1462 // wrapper takes two arguments:
1463 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001464 // - the thread ID;
1465 emitCall(CGF, WST.Loc, W,
1466 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001467
1468 // Go to end of parallel region.
1469 CGF.EmitBranch(TerminateBB);
1470
1471 CGF.EmitBlock(CheckNextBB);
1472 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001473 // Default case: call to outlined function through pointer if the target
1474 // region makes a declare target call that may contain an orphaned parallel
1475 // directive.
1476 auto *ParallelFnTy =
1477 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001478 /*isVarArg=*/false);
1479 llvm::Value *WorkFnCast =
1480 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001481 // Insert call to work function via shared wrapper. The shared
1482 // wrapper takes two arguments:
1483 // - the parallelism level;
1484 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001485 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001486 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1487 // Go to end of parallel region.
1488 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001489
1490 // Signal end of parallel region.
1491 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001492 CGF.EmitRuntimeCall(
1493 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1494 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001495 CGF.EmitBranch(BarrierBB);
1496
1497 // All active and inactive workers wait at a barrier after parallel region.
1498 CGF.EmitBlock(BarrierBB);
1499 // Barrier after parallel region.
1500 syncCTAThreads(CGF);
1501 CGF.EmitBranch(AwaitBB);
1502
1503 // Exit target region.
1504 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001505 // Skip initialization.
1506 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001507}
1508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001509/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001510/// implementation. Specialized for the NVPTX device.
1511/// \param Function OpenMP runtime function.
1512/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001513llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001514CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001515 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001516 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1517 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001518 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1519 // RequiresOMPRuntime);
1520 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001521 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001522 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1523 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1524 break;
1525 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001526 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001527 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1528 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001529 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001530 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001531 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1532 break;
1533 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001534 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1535 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001536 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001537 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001538 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001539 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1540 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1541 break;
1542 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001543 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1544 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1545 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001546 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001549 break;
1550 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001551 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1552 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001553 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001554 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001555 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001556 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1558 break;
1559 }
1560 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001561 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1562 /// int16_t IsOMPRuntimeInitialized);
1563 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001564 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001565 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001566 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1568 break;
1569 }
1570 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1571 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001572 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001573 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1575 break;
1576 }
1577 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1578 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1579 // global_tid);
1580 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001581 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1584 break;
1585 }
1586 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1587 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1588 // global_tid);
1589 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001590 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001591 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1593 break;
1594 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001595 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1596 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1597 // int16_t lane_offset, int16_t warp_size);
1598 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001599 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001600 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1602 break;
1603 }
1604 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1605 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1606 // int16_t lane_offset, int16_t warp_size);
1607 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001608 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001609 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1611 break;
1612 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001613 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001614 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1615 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1616 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1617 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1618 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001619 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1620 CGM.Int16Ty, CGM.Int16Ty};
1621 auto *ShuffleReduceFnTy =
1622 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1623 /*isVarArg=*/false);
1624 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1625 auto *InterWarpCopyFnTy =
1626 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1627 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001628 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1629 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001630 CGM.Int32Ty,
1631 CGM.SizeTy,
1632 CGM.VoidPtrTy,
1633 ShuffleReduceFnTy->getPointerTo(),
1634 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001635 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001636 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1637 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001638 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001639 break;
1640 }
1641 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1642 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1643 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001644 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001645 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1646 RTLFn = CGM.CreateRuntimeFunction(
1647 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1648 break;
1649 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001650 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1651 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1652 // global_tid, void *global_buffer, int32_t num_of_records, void*
1653 // reduce_data,
1654 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1655 // lane_offset, int16_t shortCircuit),
1656 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1657 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1658 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1659 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1660 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1661 // *buffer, int idx, void *reduce_data));
1662 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1663 CGM.Int16Ty, CGM.Int16Ty};
1664 auto *ShuffleReduceFnTy =
1665 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1666 /*isVarArg=*/false);
1667 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1668 auto *InterWarpCopyFnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1670 /*isVarArg=*/false);
1671 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1672 CGM.VoidPtrTy};
1673 auto *GlobalListFnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1675 /*isVarArg=*/false);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1677 CGM.Int32Ty,
1678 CGM.VoidPtrTy,
1679 CGM.Int32Ty,
1680 CGM.VoidPtrTy,
1681 ShuffleReduceFnTy->getPointerTo(),
1682 InterWarpCopyFnTy->getPointerTo(),
1683 GlobalListFnTy->getPointerTo(),
1684 GlobalListFnTy->getPointerTo(),
1685 GlobalListFnTy->getPointerTo(),
1686 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001687 auto *FnTy =
1688 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1689 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001690 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001691 break;
1692 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001693 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1694 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001695 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001696 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1697 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1698 break;
1699 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001700 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1701 /// Build void __kmpc_data_sharing_init_stack_spmd();
1702 auto *FnTy =
1703 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001704 RTLFn =
1705 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001706 break;
1707 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001708 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1709 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001710 // int16_t UseSharedMemory);
1711 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001712 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001713 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001715 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001716 break;
1717 }
1718 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1719 // Build void __kmpc_data_sharing_pop_stack(void *a);
1720 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001721 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001722 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1723 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1724 /*Name=*/"__kmpc_data_sharing_pop_stack");
1725 break;
1726 }
1727 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1728 /// Build void __kmpc_begin_sharing_variables(void ***args,
1729 /// size_t n_args);
1730 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001731 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1734 break;
1735 }
1736 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1737 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001738 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001739 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1740 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1741 break;
1742 }
1743 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1744 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1745 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001746 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001747 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1749 break;
1750 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001751 case OMPRTL_NVPTX__kmpc_parallel_level: {
1752 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1753 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1754 auto *FnTy =
1755 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1757 break;
1758 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001759 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1760 // Build int8_t __kmpc_is_spmd_exec_mode();
1761 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1763 break;
1764 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001765 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001766 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1767 // const void *buf, size_t size, int16_t is_shared, const void **res);
1768 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1769 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001770 auto *FnTy =
1771 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1773 break;
1774 }
1775 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001776 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1777 // int16_t is_shared);
1778 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001779 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001781 RTLFn =
1782 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1783 break;
1784 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001785 case OMPRTL__kmpc_barrier: {
1786 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1787 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1788 auto *FnTy =
1789 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1790 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001791 cast<llvm::Function>(RTLFn.getCallee())
1792 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001793 break;
1794 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001795 case OMPRTL__kmpc_barrier_simple_spmd: {
1796 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1797 // global_tid);
1798 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1799 auto *FnTy =
1800 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1801 RTLFn =
1802 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001803 cast<llvm::Function>(RTLFn.getCallee())
1804 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001805 break;
1806 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001807 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1808 // Build int32_t __kmpc_warp_active_thread_mask(void);
1809 auto *FnTy =
1810 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1811 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1812 break;
1813 }
1814 case OMPRTL_NVPTX__kmpc_syncwarp: {
1815 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1816 auto *FnTy =
1817 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1818 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
1819 break;
1820 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001821 }
1822 return RTLFn;
1823}
1824
1825void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1826 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001827 uint64_t Size, int32_t,
1828 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001829 // TODO: Add support for global variables on the device after declare target
1830 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001831 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001832 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001833 llvm::Module &M = CGM.getModule();
1834 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001835
1836 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001837 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001838
1839 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001840 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001841 llvm::ConstantAsMetadata::get(
1842 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1843 // Append metadata to nvvm.annotations
1844 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1845}
1846
1847void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1848 const OMPExecutableDirective &D, StringRef ParentName,
1849 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001850 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001851 if (!IsOffloadEntry) // Nothing to do.
1852 return;
1853
1854 assert(!ParentName.empty() && "Invalid target region parent name!");
1855
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001856 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001857 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001858 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001859 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001860 else
1861 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1862 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001863
1864 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001865}
1866
Alexey Bataevceeaa482018-11-21 21:04:34 +00001867namespace {
1868LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1869/// Enum for accesseing the reserved_2 field of the ident_t struct.
1870enum ModeFlagsTy : unsigned {
1871 /// Bit set to 1 when in SPMD mode.
1872 KMP_IDENT_SPMD_MODE = 0x01,
1873 /// Bit set to 1 when a simplified runtime is used.
1874 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1875 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1876};
1877
1878/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1879static const ModeFlagsTy UndefinedMode =
1880 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1881} // anonymous namespace
1882
1883unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001884 switch (getExecutionMode()) {
1885 case EM_SPMD:
1886 if (requiresFullRuntime())
1887 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1888 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1889 case EM_NonSPMD:
1890 assert(requiresFullRuntime() && "Expected full runtime.");
1891 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1892 case EM_Unknown:
1893 return UndefinedMode;
1894 }
1895 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001896}
1897
Alexey Bataevc2cd2d42019-10-10 17:28:10 +00001898bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1899 const GlobalDecl &OldGD,
1900 llvm::GlobalValue *OrigAddr,
1901 bool IsForDefinition) {
1902 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1903 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1904 if (NewFD->isDefined()) {
1905 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1906 return true;
1907 }
1908 return false;
1909}
1910
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001911CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001912 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001913 if (!CGM.getLangOpts().OpenMPIsDevice)
1914 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001915}
Carlo Bertollic6872252016-04-04 15:55:02 +00001916
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001917void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1918 OpenMPProcBindClauseKind ProcBind,
1919 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001920 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001921 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001922 return;
1923
1924 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1925}
1926
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001927void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1928 llvm::Value *NumThreads,
1929 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001930 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001931 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001932 return;
1933
1934 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1935}
1936
Carlo Bertollic6872252016-04-04 15:55:02 +00001937void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1938 const Expr *NumTeams,
1939 const Expr *ThreadLimit,
1940 SourceLocation Loc) {}
1941
James Y Knight9871db02019-02-05 16:42:33 +00001942llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001943 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1944 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001945 // Emit target region as a standalone region.
1946 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001947 bool &IsInParallelRegion;
1948 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001949
1950 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001951 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1952 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001954 PrevIsInParallelRegion = IsInParallelRegion;
1955 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001956 }
1957 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001959 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001960 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001961 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001962 bool PrevIsInTTDRegion = IsInTTDRegion;
1963 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001964 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1965 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001966 auto *OutlinedFun =
1967 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1968 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001969 if (CGM.getLangOpts().Optimize) {
1970 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1971 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1972 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1973 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001974 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001975 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001976 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1977 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001978 llvm::Function *WrapperFun =
1979 createParallelDataSharingWrapper(OutlinedFun, D);
1980 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1981 }
1982
1983 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001984}
1985
Alexey Bataev2adecff2018-09-21 14:22:53 +00001986/// Get list of lastprivate variables from the teams distribute ... or
1987/// teams {distribute ...} directives.
1988static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001989getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001990 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1991 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1992 "expected teams directive.");
1993 const OMPExecutableDirective *Dir = &D;
1994 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001995 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001996 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001997 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
1998 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001999 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002000 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2001 Dir = nullptr;
2002 }
2003 }
2004 if (!Dir)
2005 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002006 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002007 for (const Expr *E : C->getVarRefs())
2008 Vars.push_back(getPrivateItem(E));
2009 }
2010}
2011
2012/// Get list of reduction variables from the teams ... directives.
2013static void
2014getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2015 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2016 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2017 "expected teams directive.");
2018 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2019 for (const Expr *E : C->privates())
2020 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002021 }
2022}
2023
James Y Knight9871db02019-02-05 16:42:33 +00002024llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002025 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2026 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002027 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002028
Alexey Bataev2adecff2018-09-21 14:22:53 +00002029 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002030 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002031 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002032 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002033 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2034 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002035 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002036 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2037 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002038 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002039 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002040 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002041 }
2042 } else if (!LastPrivatesReductions.empty()) {
2043 assert(!TeamAndReductions.first &&
2044 "Previous team declaration is not expected.");
2045 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2046 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002047 }
2048
Alexey Bataevc99042b2018-03-15 18:10:54 +00002049 // Emit target region as a standalone region.
2050 class NVPTXPrePostActionTy : public PrePostActionTy {
2051 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002052 const RecordDecl *GlobalizedRD;
2053 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2054 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002055
2056 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002057 NVPTXPrePostActionTy(
2058 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2059 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2060 &MappedDeclsFields)
2061 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2062 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002063 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002064 auto &Rt =
2065 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2066 if (GlobalizedRD) {
2067 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2068 I->getSecond().GlobalRecord = GlobalizedRD;
2069 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002070 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002071 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2072 for (const auto &Pair : MappedDeclsFields) {
2073 assert(Pair.getFirst()->isCanonicalDecl() &&
2074 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002075 Data.insert(std::make_pair(Pair.getFirst(),
2076 MappedVarData(Pair.getSecond(),
2077 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002078 }
2079 }
2080 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002081 }
2082 void Exit(CodeGenFunction &CGF) override {
2083 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2084 .emitGenericVarsEpilog(CGF);
2085 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002086 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2087 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002088 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002089 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002090 if (CGM.getLangOpts().Optimize) {
2091 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2092 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2093 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2094 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002095
2096 return OutlinedFun;
2097}
2098
Alexey Bataevc99042b2018-03-15 18:10:54 +00002099void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002100 SourceLocation Loc,
2101 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002102 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2103 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002104 return;
2105
Alexey Bataevc99042b2018-03-15 18:10:54 +00002106 CGBuilderTy &Bld = CGF.Builder;
2107
2108 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2109 if (I == FunctionGlobalizedDecls.end())
2110 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002111 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002112 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002113 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002114
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002115 // Recover pointer to this function's global record. The runtime will
2116 // handle the specifics of the allocation of the memory.
2117 // Use actual memory size of the record including the padding
2118 // for alignment purposes.
2119 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002120 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002121 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002122 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002123 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002124
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002125 llvm::PointerType *GlobalRecPtrTy =
2126 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002127 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002128 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002129 if (!IsInTTDRegion &&
2130 (WithSPMDCheck ||
2131 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002132 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2133 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2134 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002135 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2136 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2137 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2138 llvm::Value *PL = CGF.EmitRuntimeCall(
2139 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2140 {RTLoc, ThreadID});
2141 IsTTD = Bld.CreateIsNull(PL);
2142 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002143 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2144 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2145 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2146 // There is no need to emit line number for unconditional branch.
2147 (void)ApplyDebugLocation::CreateEmpty(CGF);
2148 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002149 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2150 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002151 CGF.EmitBranch(ExitBB);
2152 // There is no need to emit line number for unconditional branch.
2153 (void)ApplyDebugLocation::CreateEmpty(CGF);
2154 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002155 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2156 if (const RecordDecl *SecGlobalizedVarsRecord =
2157 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2158 SecGlobalRecTy =
2159 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2160
2161 // Recover pointer to this function's global record. The runtime will
2162 // handle the specifics of the allocation of the memory.
2163 // Use actual memory size of the record including the padding
2164 // for alignment purposes.
2165 unsigned Alignment =
2166 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2167 unsigned GlobalRecordSize =
2168 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2169 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2170 Size = Bld.CreateSelect(
2171 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2172 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002173 // TODO: allow the usage of shared memory to be controlled by
2174 // the user, for now, default to global.
2175 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002176 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002177 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2178 createNVPTXRuntimeFunction(
2179 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2180 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002181 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002182 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002183 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002184 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002185 /*NumReservedValues=*/2, "_select_stack");
2186 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2187 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2188 GlobalRecCastAddr = Phi;
2189 I->getSecond().GlobalRecordAddr = Phi;
2190 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002191 } else if (IsInTTDRegion) {
2192 assert(GlobalizedRecords.back().Records.size() < 2 &&
2193 "Expected less than 2 globalized records: one for target and one "
2194 "for teams.");
2195 unsigned Offset = 0;
2196 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2197 QualType RDTy = CGM.getContext().getRecordType(RD);
2198 unsigned Alignment =
2199 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2200 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2201 Offset =
2202 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2203 }
2204 unsigned Alignment =
2205 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2206 Offset = llvm::alignTo(Offset, Alignment);
2207 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2208 ++GlobalizedRecords.back().RegionCounter;
2209 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002210 assert(KernelStaticGlobalized &&
2211 "Kernel static pointer must be initialized already.");
2212 auto *UseSharedMemory = new llvm::GlobalVariable(
2213 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2214 llvm::GlobalValue::InternalLinkage, nullptr,
2215 "_openmp_static_kernel$is_shared");
2216 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2217 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2218 /*DestWidth=*/16, /*Signed=*/0);
2219 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2220 Address(UseSharedMemory,
2221 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2222 /*Volatile=*/false, Int16Ty, Loc);
2223 auto *StaticGlobalized = new llvm::GlobalVariable(
2224 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002225 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002226 auto *RecSize = new llvm::GlobalVariable(
2227 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2228 llvm::GlobalValue::InternalLinkage, nullptr,
2229 "_openmp_static_kernel$size");
2230 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2231 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002232 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002233 CGM.getContext().getSizeType(), Loc);
2234 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2235 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002236 llvm::Value *GlobalRecordSizeArg[] = {
2237 llvm::ConstantInt::get(
2238 CGM.Int16Ty,
2239 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2240 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002241 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2242 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2243 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002244 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002245 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002246 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2247 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002248 }
2249 assert(KernelStaticGlobalized && "Global address must be set already.");
2250 Address FrameAddr = CGF.EmitLoadOfPointer(
2251 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2252 CGM.getContext()
2253 .getPointerType(CGM.getContext().VoidPtrTy)
2254 .castAs<PointerType>());
2255 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002256 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002257 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2258 I->getSecond().IsInSPMDModeFlag = nullptr;
2259 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2260 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002261 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002262 // TODO: allow the usage of shared memory to be controlled by
2263 // the user, for now, default to global.
2264 llvm::Value *GlobalRecordSizeArg[] = {
2265 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2266 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002267 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2268 createNVPTXRuntimeFunction(
2269 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2270 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002271 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002272 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002273 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2274 I->getSecond().IsInSPMDModeFlag = nullptr;
2275 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002276 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002277 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002278
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002279 // Emit the "global alloca" which is a GEP from the global declaration
2280 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002281 LValue SecBase;
2282 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2283 if (IsTTD) {
2284 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2285 llvm::PointerType *SecGlobalRecPtrTy =
2286 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2287 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2288 Bld.CreatePointerBitCastOrAddrSpaceCast(
2289 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2290 SecGlobalRecTy);
2291 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002292 for (auto &Rec : I->getSecond().LocalVarData) {
2293 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2294 llvm::Value *ParValue;
2295 if (EscapedParam) {
2296 const auto *VD = cast<VarDecl>(Rec.first);
2297 LValue ParLVal =
2298 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2299 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2300 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002301 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2302 // Emit VarAddr basing on lane-id if required.
2303 QualType VarTy;
2304 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 VarTy = Rec.second.FD->getType();
2306 } else {
2307 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2308 VarAddr.getAddress().getPointer(),
2309 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002310 VarTy =
2311 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002312 VarAddr = CGF.MakeAddrLValue(
2313 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2314 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002315 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002316 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002317 if (!IsInTTDRegion &&
2318 (WithSPMDCheck ||
2319 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002320 assert(I->getSecond().IsInSPMDModeFlag &&
2321 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002322 if (IsTTD) {
2323 assert(SecIt->second.IsOnePerTeam &&
2324 "Secondary glob data must be one per team.");
2325 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2326 VarAddr.setAddress(
2327 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2328 VarAddr.getPointer()),
2329 VarAddr.getAlignment()));
2330 Rec.second.PrivateAddr = VarAddr.getAddress();
2331 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002332 Address GlobalPtr = Rec.second.PrivateAddr;
2333 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2334 Rec.second.PrivateAddr = Address(
2335 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2336 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2337 LocalAddr.getAlignment());
2338 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002339 if (EscapedParam) {
2340 const auto *VD = cast<VarDecl>(Rec.first);
2341 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2342 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2343 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002344 if (IsTTD)
2345 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002346 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002347 }
2348 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2349 // Recover pointer to this function's global record. The runtime will
2350 // handle the specifics of the allocation of the memory.
2351 // Use actual memory size of the record including the padding
2352 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002353 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002354 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2355 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2356 Size = Bld.CreateNUWAdd(
2357 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2358 llvm::Value *AlignVal =
2359 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2360 Size = Bld.CreateUDiv(Size, AlignVal);
2361 Size = Bld.CreateNUWMul(Size, AlignVal);
2362 // TODO: allow the usage of shared memory to be controlled by
2363 // the user, for now, default to global.
2364 llvm::Value *GlobalRecordSizeArg[] = {
2365 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2366 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002367 createNVPTXRuntimeFunction(
2368 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002369 GlobalRecordSizeArg);
2370 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2371 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2372 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2373 CGM.getContext().getDeclAlign(VD),
2374 AlignmentSource::Decl);
2375 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2376 Base.getAddress());
2377 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002378 }
2379 I->getSecond().MappedParams->apply(CGF);
2380}
2381
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002382void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2383 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002384 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2385 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002386 return;
2387
Alexey Bataevc99042b2018-03-15 18:10:54 +00002388 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002389 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002390 I->getSecond().MappedParams->restore(CGF);
2391 if (!CGF.HaveInsertPoint())
2392 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002393 for (llvm::Value *Addr :
2394 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2395 CGF.EmitRuntimeCall(
2396 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2397 Addr);
2398 }
2399 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002400 if (!IsInTTDRegion &&
2401 (WithSPMDCheck ||
2402 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002403 CGBuilderTy &Bld = CGF.Builder;
2404 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2405 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2406 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2407 // There is no need to emit line number for unconditional branch.
2408 (void)ApplyDebugLocation::CreateEmpty(CGF);
2409 CGF.EmitBlock(NonSPMDBB);
2410 CGF.EmitRuntimeCall(
2411 createNVPTXRuntimeFunction(
2412 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2413 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2414 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002415 } else if (IsInTTDRegion) {
2416 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2417 "region counter must be > 0.");
2418 --GlobalizedRecords.back().RegionCounter;
2419 // Emit the restore function only in the target region.
2420 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002421 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2422 /*DestWidth=*/16, /*Signed=*/0);
2423 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2424 Address(GlobalizedRecords.back().UseSharedMemory,
2425 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2426 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002427 llvm::Value *Args[] = {
2428 llvm::ConstantInt::get(
2429 CGM.Int16Ty,
2430 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2431 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002432 CGF.EmitRuntimeCall(
2433 createNVPTXRuntimeFunction(
2434 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002435 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002436 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002437 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002438 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2439 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2440 I->getSecond().GlobalRecordAddr);
2441 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002442 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002443 }
2444}
2445
Carlo Bertollic6872252016-04-04 15:55:02 +00002446void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2447 const OMPExecutableDirective &D,
2448 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002449 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002450 ArrayRef<llvm::Value *> CapturedVars) {
2451 if (!CGF.HaveInsertPoint())
2452 return;
2453
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002454 Address ZeroAddr = CGF.CreateMemTemp(
2455 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2456 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002457 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2458 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002459 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002460 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2461 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002462 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002463}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002464
2465void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002466 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002467 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2468 if (!CGF.HaveInsertPoint())
2469 return;
2470
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002471 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002472 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002473 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002474 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002475}
2476
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002477void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002478 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2479 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2480 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002481
2482 // Force inline this outlined function at its call site.
2483 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2484
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002485 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2486 /*DestWidth=*/32, /*Signed=*/1),
2487 ".zero.addr");
2488 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002489 // ThreadId for serialized parallels is 0.
2490 Address ThreadIDAddr = ZeroAddr;
2491 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002492 CodeGenFunction &CGF, PrePostActionTy &Action) {
2493 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002494
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002495 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2496 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2497 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2498 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2499 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2500 };
2501 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2502 PrePostActionTy &) {
2503
2504 RegionCodeGenTy RCG(CodeGen);
2505 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2506 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2507 llvm::Value *Args[] = {RTLoc, ThreadID};
2508
2509 NVPTXActionTy Action(
2510 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2511 Args,
2512 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2513 Args);
2514 RCG.setAction(Action);
2515 RCG(CGF);
2516 };
2517
2518 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2519 PrePostActionTy &Action) {
2520 CGBuilderTy &Bld = CGF.Builder;
2521 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2522 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002523 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2524
2525 // Prepare for parallel region. Indicate the outlined function.
2526 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002527 CGF.EmitRuntimeCall(
2528 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2529 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002530
2531 // Create a private scope that will globalize the arguments
2532 // passed from the outside of the target region.
2533 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2534
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002535 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002536 if (!CapturedVars.empty()) {
2537 // Prepare for parallel region. Indicate the outlined function.
2538 Address SharedArgs =
2539 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2540 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2541
2542 llvm::Value *DataSharingArgs[] = {
2543 SharedArgsPtr,
2544 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2545 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2546 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2547 DataSharingArgs);
2548
2549 // Store variable address in a list of references to pass to workers.
2550 unsigned Idx = 0;
2551 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002552 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2553 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2554 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002555 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002556 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002557 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002558 if (V->getType()->isIntegerTy())
2559 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2560 else
2561 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002562 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2563 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002564 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002565 }
2566 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002567
2568 // Activate workers. This barrier is used by the master to signal
2569 // work for the workers.
2570 syncCTAThreads(CGF);
2571
2572 // OpenMP [2.5, Parallel Construct, p.49]
2573 // There is an implied barrier at the end of a parallel region. After the
2574 // end of a parallel region, only the master thread of the team resumes
2575 // execution of the enclosing task region.
2576 //
2577 // The master waits at this barrier until all workers are done.
2578 syncCTAThreads(CGF);
2579
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002580 if (!CapturedVars.empty())
2581 CGF.EmitRuntimeCall(
2582 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2583
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002584 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002585 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002586 };
2587
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002588 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2589 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002590 if (IsInParallelRegion) {
2591 SeqGen(CGF, Action);
2592 } else if (IsInTargetMasterThreadRegion) {
2593 L0ParallelGen(CGF, Action);
2594 } else {
2595 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002596 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002597 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002598 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002599 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002600 // }
2601 CGBuilderTy &Bld = CGF.Builder;
2602 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002603 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2604 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002605 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002606 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2607 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002608 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002609 // There is no need to emit line number for unconditional branch.
2610 (void)ApplyDebugLocation::CreateEmpty(CGF);
2611 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002612 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2613 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2614 llvm::Value *PL = CGF.EmitRuntimeCall(
2615 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2616 {RTLoc, ThreadID});
2617 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002618 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002619 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002620 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002621 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002622 // There is no need to emit line number for unconditional branch.
2623 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002624 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002625 L0ParallelGen(CGF, Action);
2626 CGF.EmitBranch(ExitBB);
2627 // There is no need to emit line number for unconditional branch.
2628 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002629 // Emit the continuation block for code after the if.
2630 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2631 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002632 };
2633
Alexey Bataev9ff80832018-04-16 20:16:21 +00002634 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002635 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002636 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002637 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002638 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002639 ThenRCG(CGF);
2640 }
2641}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002642
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002643void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002644 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002645 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2646 // Just call the outlined function to execute the parallel region.
2647 // OutlinedFn(&GTid, &zero, CapturedStruct);
2648 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002649 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002650
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002651 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2652 /*DestWidth=*/32, /*Signed=*/1),
2653 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002654 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002655 // ThreadId for serialized parallels is 0.
2656 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002657 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002658 &ThreadIDAddr](CodeGenFunction &CGF,
2659 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002660 Action.Enter(CGF);
2661
2662 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2663 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2664 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2665 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2666 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2667 };
2668 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2669 PrePostActionTy &) {
2670
2671 RegionCodeGenTy RCG(CodeGen);
2672 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2673 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2674 llvm::Value *Args[] = {RTLoc, ThreadID};
2675
2676 NVPTXActionTy Action(
2677 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2678 Args,
2679 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2680 Args);
2681 RCG.setAction(Action);
2682 RCG(CGF);
2683 };
2684
2685 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002686 // In the worker need to use the real thread id.
2687 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002688 RegionCodeGenTy RCG(CodeGen);
2689 RCG(CGF);
2690 } else {
2691 // If we are not in the target region, it is definitely L2 parallelism or
2692 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2693 // need to check for orphaned directives.
2694 RegionCodeGenTy RCG(SeqGen);
2695 RCG(CGF);
2696 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002697}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002698
Alexey Bataeva3924b52019-01-03 16:25:35 +00002699void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2700 // Always emit simple barriers!
2701 if (!CGF.HaveInsertPoint())
2702 return;
2703 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2704 // This function does not use parameters, so we can emit just default values.
2705 llvm::Value *Args[] = {
2706 llvm::ConstantPointerNull::get(
2707 cast<llvm::PointerType>(getIdentTyPointerTy())),
2708 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002709 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002710 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002711 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002712}
2713
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002714void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2715 SourceLocation Loc,
2716 OpenMPDirectiveKind Kind, bool,
2717 bool) {
2718 // Always emit simple barriers!
2719 if (!CGF.HaveInsertPoint())
2720 return;
2721 // Build call __kmpc_cancel_barrier(loc, thread_id);
2722 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2723 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2724 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002725 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2726 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2727 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002728}
2729
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002730void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2731 CodeGenFunction &CGF, StringRef CriticalName,
2732 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2733 const Expr *Hint) {
2734 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2735 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2736 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2737 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2738 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2739
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002740 // Get the mask of active threads in the warp.
2741 llvm::Value *Mask = CGF.EmitRuntimeCall(
2742 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002743 // Fetch team-local id of the thread.
2744 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2745
2746 // Get the width of the team.
2747 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2748
2749 // Initialize the counter variable for the loop.
2750 QualType Int32Ty =
2751 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2752 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2753 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2754 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2755 /*isInit=*/true);
2756
2757 // Block checks if loop counter exceeds upper bound.
2758 CGF.EmitBlock(LoopBB);
2759 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2760 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2761 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2762
2763 // Block tests which single thread should execute region, and which threads
2764 // should go straight to synchronisation point.
2765 CGF.EmitBlock(TestBB);
2766 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2767 llvm::Value *CmpThreadToCounter =
2768 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2769 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2770
2771 // Block emits the body of the critical region.
2772 CGF.EmitBlock(BodyBB);
2773
2774 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002775 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2776 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002777
2778 // After the body surrounded by the critical region, the single executing
2779 // thread will jump to the synchronisation point.
2780 // Block waits for all threads in current team to finish then increments the
2781 // counter variable and returns to the loop.
2782 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002783 // Reconverge active threads in the warp.
2784 (void)CGF.EmitRuntimeCall(
2785 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002786
2787 llvm::Value *IncCounterVal =
2788 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2789 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2790 CGF.EmitBranch(LoopBB);
2791
2792 // Block that is reached when all threads in the team complete the region.
2793 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2794}
2795
Alexey Bataevb2575932018-01-04 20:18:55 +00002796/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002797static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2798 QualType ValTy, QualType CastTy,
2799 SourceLocation Loc) {
2800 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2801 "Cast type must sized.");
2802 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2803 "Val type must sized.");
2804 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2805 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002806 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002807 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2808 CGF.getContext().getTypeSizeInChars(CastTy))
2809 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2810 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2811 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2812 CastTy->hasSignedIntegerRepresentation());
2813 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002814 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2815 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002816 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2817 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002818}
2819
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002820/// This function creates calls to one of two shuffle functions to copy
2821/// variables between lanes in a warp.
2822static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002823 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002824 QualType ElemType,
2825 llvm::Value *Offset,
2826 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002827 CodeGenModule &CGM = CGF.CGM;
2828 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002829 CGOpenMPRuntimeNVPTX &RT =
2830 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2831
Alexey Bataeva453f362018-03-19 17:53:56 +00002832 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2833 assert(Size.getQuantity() <= 8 &&
2834 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002835
Alexey Bataeva453f362018-03-19 17:53:56 +00002836 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002837 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2838 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2839
2840 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002841 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2842 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2843 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002844 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002845 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002846
Alexey Bataev9ff80832018-04-16 20:16:21 +00002847 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2848 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002849
Alexey Bataeva453f362018-03-19 17:53:56 +00002850 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002851}
2852
Alexey Bataev12c62902018-06-22 19:10:38 +00002853static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2854 Address DestAddr, QualType ElemType,
2855 llvm::Value *Offset, SourceLocation Loc) {
2856 CGBuilderTy &Bld = CGF.Builder;
2857
2858 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2859 // Create the loop over the big sized data.
2860 // ptr = (void*)Elem;
2861 // ptrEnd = (void*) Elem + 1;
2862 // Step = 8;
2863 // while (ptr + Step < ptrEnd)
2864 // shuffle((int64_t)*ptr);
2865 // Step = 4;
2866 // while (ptr + Step < ptrEnd)
2867 // shuffle((int32_t)*ptr);
2868 // ...
2869 Address ElemPtr = DestAddr;
2870 Address Ptr = SrcAddr;
2871 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002872 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002873 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2874 if (Size < CharUnits::fromQuantity(IntSize))
2875 continue;
2876 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2877 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2878 /*Signed=*/1);
2879 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2880 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2881 ElemPtr =
2882 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2883 if (Size.getQuantity() / IntSize > 1) {
2884 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2885 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2886 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2887 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2888 CGF.EmitBlock(PreCondBB);
2889 llvm::PHINode *PhiSrc =
2890 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2891 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2892 llvm::PHINode *PhiDest =
2893 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2894 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2895 Ptr = Address(PhiSrc, Ptr.getAlignment());
2896 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2897 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2898 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2899 Ptr.getPointer(), CGF.VoidPtrTy));
2900 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2901 ThenBB, ExitBB);
2902 CGF.EmitBlock(ThenBB);
2903 llvm::Value *Res = createRuntimeShuffleFunction(
2904 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2905 IntType, Offset, Loc);
2906 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002907 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2908 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002909 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2910 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002911 CGF.EmitBranch(PreCondBB);
2912 CGF.EmitBlock(ExitBB);
2913 } else {
2914 llvm::Value *Res = createRuntimeShuffleFunction(
2915 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2916 IntType, Offset, Loc);
2917 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002918 Ptr = Bld.CreateConstGEP(Ptr, 1);
2919 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002920 }
2921 Size = Size % IntSize;
2922 }
2923}
2924
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002925namespace {
2926enum CopyAction : unsigned {
2927 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2928 // the warp using shuffle instructions.
2929 RemoteLaneToThread,
2930 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2931 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002932 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2933 ThreadToScratchpad,
2934 // ScratchpadToThread: Copy from a scratchpad array in global memory
2935 // containing team-reduced data to a thread's stack.
2936 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937};
2938} // namespace
2939
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002940struct CopyOptionsTy {
2941 llvm::Value *RemoteLaneOffset;
2942 llvm::Value *ScratchpadIndex;
2943 llvm::Value *ScratchpadWidth;
2944};
2945
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002946/// Emit instructions to copy a Reduce list, which contains partially
2947/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002948static void emitReductionListCopy(
2949 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2950 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2951 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002952
Alexey Bataev9ff80832018-04-16 20:16:21 +00002953 CodeGenModule &CGM = CGF.CGM;
2954 ASTContext &C = CGM.getContext();
2955 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002956
Alexey Bataev9ff80832018-04-16 20:16:21 +00002957 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2958 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2959 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002960
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002961 // Iterates, element-by-element, through the source Reduce list and
2962 // make a copy.
2963 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002964 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002965 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002966 Address SrcElementAddr = Address::invalid();
2967 Address DestElementAddr = Address::invalid();
2968 Address DestElementPtrAddr = Address::invalid();
2969 // Should we shuffle in an element from a remote lane?
2970 bool ShuffleInElement = false;
2971 // Set to true to update the pointer in the dest Reduce list to a
2972 // newly created element.
2973 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002974 // Increment the src or dest pointer to the scratchpad, for each
2975 // new element.
2976 bool IncrScratchpadSrc = false;
2977 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002978
2979 switch (Action) {
2980 case RemoteLaneToThread: {
2981 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002982 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002983 SrcElementAddr = CGF.EmitLoadOfPointer(
2984 SrcElementPtrAddr,
2985 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002986
2987 // Step 1.2: Create a temporary to store the element in the destination
2988 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002989 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990 DestElementAddr =
2991 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2992 ShuffleInElement = true;
2993 UpdateDestListPtr = true;
2994 break;
2995 }
2996 case ThreadCopy: {
2997 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002998 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002999 SrcElementAddr = CGF.EmitLoadOfPointer(
3000 SrcElementPtrAddr,
3001 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003002
3003 // Step 1.2: Get the address for dest element. The destination
3004 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003005 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003006 DestElementAddr = CGF.EmitLoadOfPointer(
3007 DestElementPtrAddr,
3008 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003009 break;
3010 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003011 case ThreadToScratchpad: {
3012 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003013 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003014 SrcElementAddr = CGF.EmitLoadOfPointer(
3015 SrcElementPtrAddr,
3016 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003017
3018 // Step 1.2: Get the address for dest element:
3019 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003020 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003021 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003022 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003023 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003024 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003025 ScratchPadElemAbsolutePtrVal =
3026 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003027 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3028 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003029 IncrScratchpadDest = true;
3030 break;
3031 }
3032 case ScratchpadToThread: {
3033 // Step 1.1: Get the address for the src element in the scratchpad.
3034 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003035 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003036 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003037 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003038 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003039 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003040 ScratchPadElemAbsolutePtrVal =
3041 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3042 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3043 C.getTypeAlignInChars(Private->getType()));
3044 IncrScratchpadSrc = true;
3045
3046 // Step 1.2: Create a temporary to store the element in the destination
3047 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003048 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003049 DestElementAddr =
3050 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3051 UpdateDestListPtr = true;
3052 break;
3053 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003054 }
3055
3056 // Regardless of src and dest of copy, we emit the load of src
3057 // element as this is required in all directions
3058 SrcElementAddr = Bld.CreateElementBitCast(
3059 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003060 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3061 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003062
3063 // Now that all active lanes have read the element in the
3064 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003065 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003066 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3067 RemoteLaneOffset, Private->getExprLoc());
3068 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003069 switch (CGF.getEvaluationKind(Private->getType())) {
3070 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003071 llvm::Value *Elem =
3072 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3073 Private->getType(), Private->getExprLoc());
3074 // Store the source element value to the dest element address.
3075 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3076 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003077 break;
3078 }
3079 case TEK_Complex: {
3080 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3081 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3082 Private->getExprLoc());
3083 CGF.EmitStoreOfComplex(
3084 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3085 /*isInit=*/false);
3086 break;
3087 }
3088 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003089 CGF.EmitAggregateCopy(
3090 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3091 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3092 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003093 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003094 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003095 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003096
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003097 // Step 3.1: Modify reference in dest Reduce list as needed.
3098 // Modifying the reference in Reduce list to point to the newly
3099 // created element. The element is live in the current function
3100 // scope and that of functions it invokes (i.e., reduce_function).
3101 // RemoteReduceData[i] = (void*)&RemoteElem
3102 if (UpdateDestListPtr) {
3103 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3104 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3105 DestElementPtrAddr, /*Volatile=*/false,
3106 C.VoidPtrTy);
3107 }
3108
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003109 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3110 // address of the next element in scratchpad memory, unless we're currently
3111 // processing the last one. Memory alignment is also taken care of here.
3112 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3113 llvm::Value *ScratchpadBasePtr =
3114 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003115 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3116 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003117 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003118 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003119
3120 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003121 ScratchpadBasePtr = Bld.CreateNUWSub(
3122 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3123 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003124 ScratchpadBasePtr,
3125 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003126 ScratchpadBasePtr = Bld.CreateNUWAdd(
3127 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3128 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003129 ScratchpadBasePtr,
3130 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3131
3132 if (IncrScratchpadDest)
3133 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3134 else /* IncrScratchpadSrc = true */
3135 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3136 }
3137
Alexey Bataev9ff80832018-04-16 20:16:21 +00003138 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003139 }
3140}
3141
3142/// This function emits a helper that gathers Reduce lists from the first
3143/// lane of every active warp to lanes in the first warp.
3144///
3145/// void inter_warp_copy_func(void* reduce_data, num_warps)
3146/// shared smem[warp_size];
3147/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003148/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003149/// If (I am the first lane in each warp)
3150/// Copy my local D to smem[warp_id]
3151/// sync
3152/// if (I am the first warp)
3153/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003154static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3155 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003156 QualType ReductionArrayTy,
3157 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003158 ASTContext &C = CGM.getContext();
3159 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003160
3161 // ReduceList: thread local Reduce list.
3162 // At the stage of the computation when this function is called, partially
3163 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003164 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3165 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166 // NumWarps: number of warps active in the parallel region. This could
3167 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003168 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003169 C.getIntTypeForBitwidth(32, /* Signed */ true),
3170 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003171 FunctionArgList Args;
3172 Args.push_back(&ReduceListArg);
3173 Args.push_back(&NumWarpsArg);
3174
Alexey Bataev9ff80832018-04-16 20:16:21 +00003175 const CGFunctionInfo &CGFI =
3176 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003177 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3178 llvm::GlobalValue::InternalLinkage,
3179 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003180 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003181 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003182 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003183 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003184
Alexey Bataev9ff80832018-04-16 20:16:21 +00003185 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003186
3187 // This array is used as a medium to transfer, one reduce element at a time,
3188 // the data from the first lane of every warp to lanes in the first warp
3189 // in order to perform the final step of a reduction in a parallel region
3190 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3191 // for reduced latency, as well as to have a distinct copy for concurrently
3192 // executing target regions. The array is declared with common linkage so
3193 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003194 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003195 "__openmp_nvptx_data_transfer_temporary_storage";
3196 llvm::GlobalVariable *TransferMedium =
3197 M.getGlobalVariable(TransferMediumName);
3198 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003199 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3201 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003202 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003203 llvm::Constant::getNullValue(Ty), TransferMediumName,
3204 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3205 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003206 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207 }
3208
3209 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003210 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003211 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003212 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003213 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003214 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003215
3216 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3217 Address LocalReduceList(
3218 Bld.CreatePointerBitCastOrAddrSpaceCast(
3219 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003220 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003221 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3222 CGF.getPointerAlign());
3223
3224 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003225 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003226 //
3227 // Warp master copies reduce element to transfer medium in __shared__
3228 // memory.
3229 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003230 unsigned RealTySize =
3231 C.getTypeSizeInChars(Private->getType())
3232 .alignTo(C.getTypeAlignInChars(Private->getType()))
3233 .getQuantity();
3234 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3235 unsigned NumIters = RealTySize / TySize;
3236 if (NumIters == 0)
3237 continue;
3238 QualType CType = C.getIntTypeForBitwidth(
3239 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3240 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3241 CharUnits Align = CharUnits::fromQuantity(TySize);
3242 llvm::Value *Cnt = nullptr;
3243 Address CntAddr = Address::invalid();
3244 llvm::BasicBlock *PrecondBB = nullptr;
3245 llvm::BasicBlock *ExitBB = nullptr;
3246 if (NumIters > 1) {
3247 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3248 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3249 /*Volatile=*/false, C.IntTy);
3250 PrecondBB = CGF.createBasicBlock("precond");
3251 ExitBB = CGF.createBasicBlock("exit");
3252 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3253 // There is no need to emit line number for unconditional branch.
3254 (void)ApplyDebugLocation::CreateEmpty(CGF);
3255 CGF.EmitBlock(PrecondBB);
3256 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3257 llvm::Value *Cmp =
3258 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3259 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3260 CGF.EmitBlock(BodyBB);
3261 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003262 // kmpc_barrier.
3263 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3264 /*EmitChecks=*/false,
3265 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003266 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3267 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3268 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003269
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003270 // if (lane_id == 0)
3271 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3272 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3273 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003274
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003275 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003276 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003277 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3278 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3279 // elemptr = ((CopyType*)(elemptrptr)) + I
3280 Address ElemPtr = Address(ElemPtrPtr, Align);
3281 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3282 if (NumIters > 1) {
3283 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3284 ElemPtr.getAlignment());
3285 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 // Get pointer to location in transfer medium.
3288 // MediumPtr = &medium[warp_id]
3289 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3290 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3291 Address MediumPtr(MediumPtrVal, Align);
3292 // Casting to actual data type.
3293 // MediumPtr = (CopyType*)MediumPtrAddr;
3294 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003295
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003296 // elem = *elemptr
3297 //*MediumPtr = elem
3298 llvm::Value *Elem =
3299 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003300 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003301 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003302
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003303 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003304
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003305 CGF.EmitBlock(ElseBB);
3306 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003309
Alexey Bataevae51b962018-12-14 21:00:58 +00003310 // kmpc_barrier.
3311 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3312 /*EmitChecks=*/false,
3313 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003314
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003315 //
3316 // Warp 0 copies reduce element from transfer medium.
3317 //
3318 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3319 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3320 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003321
Alexey Bataevae51b962018-12-14 21:00:58 +00003322 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3323 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3324 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3325
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003326 // Up to 32 threads in warp 0 are active.
3327 llvm::Value *IsActiveThread =
3328 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3329 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003330
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003331 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003332
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003333 // SrcMediumPtr = &medium[tid]
3334 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3335 TransferMedium,
3336 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3337 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3338 // SrcMediumVal = *SrcMediumPtr;
3339 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003340
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003341 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003342 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003343 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3344 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3345 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3346 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3347 if (NumIters > 1) {
3348 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3349 TargetElemPtr.getAlignment());
3350 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003351
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003352 // *TargetElemPtr = SrcMediumVal;
3353 llvm::Value *SrcMediumValue =
3354 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003355 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003356 CType);
3357 Bld.CreateBr(W0MergeBB);
3358
3359 CGF.EmitBlock(W0ElseBB);
3360 Bld.CreateBr(W0MergeBB);
3361
3362 CGF.EmitBlock(W0MergeBB);
3363
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003364 if (NumIters > 1) {
3365 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3366 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3367 CGF.EmitBranch(PrecondBB);
3368 (void)ApplyDebugLocation::CreateEmpty(CGF);
3369 CGF.EmitBlock(ExitBB);
3370 }
3371 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003372 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003373 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003374 }
3375
3376 CGF.FinishFunction();
3377 return Fn;
3378}
3379
3380/// Emit a helper that reduces data across two OpenMP threads (lanes)
3381/// in the same warp. It uses shuffle instructions to copy over data from
3382/// a remote lane's stack. The reduction algorithm performed is specified
3383/// by the fourth parameter.
3384///
3385/// Algorithm Versions.
3386/// Full Warp Reduce (argument value 0):
3387/// This algorithm assumes that all 32 lanes are active and gathers
3388/// data from these 32 lanes, producing a single resultant value.
3389/// Contiguous Partial Warp Reduce (argument value 1):
3390/// This algorithm assumes that only a *contiguous* subset of lanes
3391/// are active. This happens for the last warp in a parallel region
3392/// when the user specified num_threads is not an integer multiple of
3393/// 32. This contiguous subset always starts with the zeroth lane.
3394/// Partial Warp Reduce (argument value 2):
3395/// This algorithm gathers data from any number of lanes at any position.
3396/// All reduced values are stored in the lowest possible lane. The set
3397/// of problems every algorithm addresses is a super set of those
3398/// addressable by algorithms with a lower version number. Overhead
3399/// increases as algorithm version increases.
3400///
3401/// Terminology
3402/// Reduce element:
3403/// Reduce element refers to the individual data field with primitive
3404/// data types to be combined and reduced across threads.
3405/// Reduce list:
3406/// Reduce list refers to a collection of local, thread-private
3407/// reduce elements.
3408/// Remote Reduce list:
3409/// Remote Reduce list refers to a collection of remote (relative to
3410/// the current thread) reduce elements.
3411///
3412/// We distinguish between three states of threads that are important to
3413/// the implementation of this function.
3414/// Alive threads:
3415/// Threads in a warp executing the SIMT instruction, as distinguished from
3416/// threads that are inactive due to divergent control flow.
3417/// Active threads:
3418/// The minimal set of threads that has to be alive upon entry to this
3419/// function. The computation is correct iff active threads are alive.
3420/// Some threads are alive but they are not active because they do not
3421/// contribute to the computation in any useful manner. Turning them off
3422/// may introduce control flow overheads without any tangible benefits.
3423/// Effective threads:
3424/// In order to comply with the argument requirements of the shuffle
3425/// function, we must keep all lanes holding data alive. But at most
3426/// half of them perform value aggregation; we refer to this half of
3427/// threads as effective. The other half is simply handing off their
3428/// data.
3429///
3430/// Procedure
3431/// Value shuffle:
3432/// In this step active threads transfer data from higher lane positions
3433/// in the warp to lower lane positions, creating Remote Reduce list.
3434/// Value aggregation:
3435/// In this step, effective threads combine their thread local Reduce list
3436/// with Remote Reduce list and store the result in the thread local
3437/// Reduce list.
3438/// Value copy:
3439/// In this step, we deal with the assumption made by algorithm 2
3440/// (i.e. contiguity assumption). When we have an odd number of lanes
3441/// active, say 2k+1, only k threads will be effective and therefore k
3442/// new values will be produced. However, the Reduce list owned by the
3443/// (2k+1)th thread is ignored in the value aggregation. Therefore
3444/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3445/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003446static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003447 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003448 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003449 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003450
3451 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003452 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3453 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003454 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003455 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3456 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003457 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003458 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3459 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003460 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003461 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3462 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003463 FunctionArgList Args;
3464 Args.push_back(&ReduceListArg);
3465 Args.push_back(&LaneIDArg);
3466 Args.push_back(&RemoteLaneOffsetArg);
3467 Args.push_back(&AlgoVerArg);
3468
Alexey Bataev9ff80832018-04-16 20:16:21 +00003469 const CGFunctionInfo &CGFI =
3470 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003471 auto *Fn = llvm::Function::Create(
3472 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3473 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003474 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003475 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003476 if (CGM.getLangOpts().Optimize) {
3477 Fn->removeFnAttr(llvm::Attribute::NoInline);
3478 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3479 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3480 }
3481
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 =
Richard Smith772e2662019-10-04 01:25:59 +00004286 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
Alexey Bataev8061acd2019-02-20 16:36:22 +00004287 /*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(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004315 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4316 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004317 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);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004441 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4442 PointeeTy.isConstant(CGM.getContext())) {
4443 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4444 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004445 }
4446 }
4447 ArgType = CGM.getContext().getPointerType(PointeeTy);
4448 QC.addRestrict();
4449 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004450 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004451 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004452 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004453 return ImplicitParamDecl::Create(
4454 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4455 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004456 return ParmVarDecl::Create(
4457 CGM.getContext(),
4458 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004459 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004460 NativeParam->getIdentifier(), ArgType,
4461 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004462}
4463
4464Address
4465CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4466 const VarDecl *NativeParam,
4467 const VarDecl *TargetParam) const {
4468 assert(NativeParam != TargetParam &&
4469 NativeParam->getType()->isReferenceType() &&
4470 "Native arg must not be the same as target arg.");
4471 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4472 QualType NativeParamType = NativeParam->getType();
4473 QualifierCollector QC;
4474 const Type *NonQualTy = QC.strip(NativeParamType);
4475 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4476 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004477 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004478 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004479 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004480 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004481 // First cast to generic.
4482 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4483 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4484 /*AddrSpace=*/0));
4485 // Cast from generic to native address space.
4486 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4487 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4488 NativePointeeAddrSpace));
4489 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4490 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004491 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004492 return NativeParamAddr;
4493}
4494
4495void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004496 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004497 ArrayRef<llvm::Value *> Args) const {
4498 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004499 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004500 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004501 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004502 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4503 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4504 break;
4505 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004506 llvm::Type *TargetType = FnType->getParamType(I);
4507 llvm::Value *NativeArg = Args[I];
4508 if (!TargetType->isPointerTy()) {
4509 TargetArgs.emplace_back(NativeArg);
4510 continue;
4511 }
4512 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004513 NativeArg,
4514 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004515 TargetArgs.emplace_back(
4516 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4517 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004518 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004519}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004520
4521/// Emit function which wraps the outline parallel region
4522/// and controls the arguments which are passed to this function.
4523/// The wrapper ensures that the outlined function is called
4524/// with the correct arguments when data is shared.
4525llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4526 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4527 ASTContext &Ctx = CGM.getContext();
4528 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4529
4530 // Create a function that takes as argument the source thread.
4531 FunctionArgList WrapperArgs;
4532 QualType Int16QTy =
4533 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4534 QualType Int32QTy =
4535 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004536 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004537 /*Id=*/nullptr, Int16QTy,
4538 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004539 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004540 /*Id=*/nullptr, Int32QTy,
4541 ImplicitParamDecl::Other);
4542 WrapperArgs.emplace_back(&ParallelLevelArg);
4543 WrapperArgs.emplace_back(&WrapperArg);
4544
Alexey Bataev9ff80832018-04-16 20:16:21 +00004545 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004546 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4547
4548 auto *Fn = llvm::Function::Create(
4549 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004550 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004551 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004552 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004553 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004554
4555 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4556 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004557 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004558
4559 const auto *RD = CS.getCapturedRecordDecl();
4560 auto CurField = RD->field_begin();
4561
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004562 Address ZeroAddr = CGF.CreateMemTemp(
4563 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4564 /*Name*/ ".zero.addr");
4565 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004566 // Get the array of arguments.
4567 SmallVector<llvm::Value *, 8> Args;
4568
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004569 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4570 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004571
4572 CGBuilderTy &Bld = CGF.Builder;
4573 auto CI = CS.capture_begin();
4574
4575 // Use global memory for data sharing.
4576 // Handle passing of global args to workers.
4577 Address GlobalArgs =
4578 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4579 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4580 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4581 CGF.EmitRuntimeCall(
4582 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4583 DataSharingArgs);
4584
4585 // Retrieve the shared variables from the list of references returned
4586 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004587 Address SharedArgListAddress = Address::invalid();
4588 if (CS.capture_size() > 0 ||
4589 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4590 SharedArgListAddress = CGF.EmitLoadOfPointer(
4591 GlobalArgs, CGF.getContext()
4592 .getPointerType(CGF.getContext().getPointerType(
4593 CGF.getContext().VoidPtrTy))
4594 .castAs<PointerType>());
4595 }
4596 unsigned Idx = 0;
4597 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004598 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004599 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4600 Src, CGF.SizeTy->getPointerTo());
4601 llvm::Value *LB = CGF.EmitLoadOfScalar(
4602 TypedAddress,
4603 /*Volatile=*/false,
4604 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4605 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4606 Args.emplace_back(LB);
4607 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004608 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004609 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4610 Src, CGF.SizeTy->getPointerTo());
4611 llvm::Value *UB = CGF.EmitLoadOfScalar(
4612 TypedAddress,
4613 /*Volatile=*/false,
4614 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4615 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4616 Args.emplace_back(UB);
4617 ++Idx;
4618 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004619 if (CS.capture_size() > 0) {
4620 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004621 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4622 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004623 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004624 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004625 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4626 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4627 /*Volatile=*/false,
4628 CGFContext.getPointerType(ElemTy),
4629 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004630 if (CI->capturesVariableByCopy() &&
4631 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004632 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4633 CI->getLocation());
4634 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004635 Args.emplace_back(Arg);
4636 }
4637 }
4638
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004639 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004640 CGF.FinishFunction();
4641 return Fn;
4642}
4643
4644void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4645 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004646 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4647 return;
4648
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004649 assert(D && "Expected function or captured|block decl.");
4650 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4651 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004652 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4653 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004654 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004655 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004656 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4657 Body = FD->getBody();
4658 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4659 Body = BD->getBody();
4660 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4661 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004662 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004663 if (NeedToDelayGlobalization &&
4664 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4665 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004666 }
4667 if (!Body)
4668 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004669 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004670 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004671 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004672 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004673 TeamAndReductions.first = nullptr;
4674 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004675 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4676 VarChecker.getEscapedVariableLengthDecls();
4677 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004678 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004679 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4680 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004681 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004682 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4683 I->getSecond().EscapedParameters.insert(
4684 VarChecker.getEscapedParameters().begin(),
4685 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004686 I->getSecond().EscapedVariableLengthDecls.append(
4687 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004688 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004689 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004690 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004691 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004692 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004693 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004694 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004695 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004696 VarChecker.Visit(Body);
4697 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004698 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004699 I->getSecond().SecondaryLocalVarData.emplace();
4700 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4701 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4702 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4703 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004704 Data.insert(
4705 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004706 }
4707 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004708 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004709 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004710 struct GlobalizationScope final : EHScopeStack::Cleanup {
4711 GlobalizationScope() = default;
4712
4713 void Emit(CodeGenFunction &CGF, Flags flags) override {
4714 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004715 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004716 }
4717 };
4718 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004719 }
4720}
4721
4722Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4723 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004724 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4725 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4726 switch (A->getAllocatorType()) {
4727 // Use the default allocator here as by default local vars are
4728 // threadlocal.
4729 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4730 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004731 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4732 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004733 // Follow the user decision - use default allocation.
4734 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004735 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004736 // TODO: implement aupport for user-defined allocators.
4737 return Address::invalid();
4738 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4739 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4740 auto *GV = new llvm::GlobalVariable(
4741 CGM.getModule(), VarTy, /*isConstant=*/false,
4742 llvm::GlobalValue::InternalLinkage,
4743 llvm::Constant::getNullValue(VarTy), VD->getName(),
4744 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4745 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4746 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004747 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004748 return Address(GV, Align);
4749 }
4750 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4751 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4752 auto *GV = new llvm::GlobalVariable(
4753 CGM.getModule(), VarTy, /*isConstant=*/false,
4754 llvm::GlobalValue::InternalLinkage,
4755 llvm::Constant::getNullValue(VarTy), VD->getName(),
4756 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4757 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4758 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004759 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004760 return Address(GV, Align);
4761 }
4762 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4763 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4764 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4765 auto *GV = new llvm::GlobalVariable(
4766 CGM.getModule(), VarTy, /*isConstant=*/false,
4767 llvm::GlobalValue::InternalLinkage,
4768 llvm::Constant::getNullValue(VarTy), VD->getName());
4769 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004770 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004771 return Address(GV, Align);
4772 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004773 }
4774 }
4775
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004776 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4777 return Address::invalid();
4778
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004779 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004780 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4781 if (I == FunctionGlobalizedDecls.end())
4782 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004783 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004784 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004785 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004786 if (VD->hasAttrs()) {
4787 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4788 E(VD->attr_end());
4789 IT != E; ++IT) {
4790 auto VDI = I->getSecond().LocalVarData.find(
4791 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4792 ->getCanonicalDecl());
4793 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004794 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004795 }
4796 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004797
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004798 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004799}
4800
4801void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004802 FunctionGlobalizedDecls.erase(CGF.CurFn);
4803 CGOpenMPRuntime::functionFinished(CGF);
4804}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004805
4806void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4807 CodeGenFunction &CGF, const OMPLoopDirective &S,
4808 OpenMPDistScheduleClauseKind &ScheduleKind,
4809 llvm::Value *&Chunk) const {
4810 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4811 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4812 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4813 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4814 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004815 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004816 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004817 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4818 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004819}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004820
4821void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4822 CodeGenFunction &CGF, const OMPLoopDirective &S,
4823 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004824 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004825 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004826 // Chunk size is 1 in this case.
4827 llvm::APInt ChunkSize(32, 1);
4828 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4829 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4830 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004831}
Alexey Bataev60705422018-10-30 15:50:12 +00004832
4833void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4834 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4835 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4836 " Expected target-based directive.");
4837 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4838 for (const CapturedStmt::Capture &C : CS->captures()) {
4839 // Capture variables captured by reference in lambdas for target-based
4840 // directives.
4841 if (!C.capturesVariable())
4842 continue;
4843 const VarDecl *VD = C.getCapturedVar();
4844 const auto *RD = VD->getType()
4845 .getCanonicalType()
4846 .getNonReferenceType()
4847 ->getAsCXXRecordDecl();
4848 if (!RD || !RD->isLambda())
4849 continue;
4850 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4851 LValue VDLVal;
4852 if (VD->getType().getCanonicalType()->isReferenceType())
4853 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4854 else
4855 VDLVal = CGF.MakeAddrLValue(
4856 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4857 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4858 FieldDecl *ThisCapture = nullptr;
4859 RD->getCaptureFields(Captures, ThisCapture);
4860 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4861 LValue ThisLVal =
4862 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4863 llvm::Value *CXXThis = CGF.LoadCXXThis();
4864 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4865 }
4866 for (const LambdaCapture &LC : RD->captures()) {
4867 if (LC.getCaptureKind() != LCK_ByRef)
4868 continue;
4869 const VarDecl *VD = LC.getCapturedVar();
4870 if (!CS->capturesVariable(VD))
4871 continue;
4872 auto It = Captures.find(VD);
4873 assert(It != Captures.end() && "Found lambda capture without field.");
4874 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4875 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4876 if (VD->getType().getCanonicalType()->isReferenceType())
4877 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4878 VD->getType().getCanonicalType())
4879 .getAddress();
4880 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4881 }
4882 }
4883}
4884
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004885unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4886 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4887}
4888
Alexey Bataevc5687252019-03-21 19:35:27 +00004889bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4890 LangAS &AS) {
4891 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4892 return false;
4893 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4894 switch(A->getAllocatorType()) {
4895 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4896 // Not supported, fallback to the default mem space.
4897 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4898 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4899 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4900 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4901 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4902 AS = LangAS::Default;
4903 return true;
4904 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4905 AS = LangAS::cuda_constant;
4906 return true;
4907 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4908 AS = LangAS::cuda_shared;
4909 return true;
4910 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4911 llvm_unreachable("Expected predefined allocator for the variables with the "
4912 "static storage.");
4913 }
4914 return false;
4915}
4916
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004917// Get current CudaArch and ignore any unknown values
4918static CudaArch getCudaArch(CodeGenModule &CGM) {
4919 if (!CGM.getTarget().hasFeature("ptx"))
4920 return CudaArch::UNKNOWN;
4921 llvm::StringMap<bool> Features;
4922 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4923 CGM.getTarget().getTargetOpts().CPU,
4924 CGM.getTarget().getTargetOpts().Features);
4925 for (const auto &Feature : Features) {
4926 if (Feature.getValue()) {
4927 CudaArch Arch = StringToCudaArch(Feature.getKey());
4928 if (Arch != CudaArch::UNKNOWN)
4929 return Arch;
4930 }
4931 }
4932 return CudaArch::UNKNOWN;
4933}
4934
4935/// Check to see if target architecture supports unified addressing which is
4936/// a restriction for OpenMP requires clause "unified_shared_memory".
4937void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004938 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004939 for (const OMPClause *Clause : D->clauselists()) {
4940 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4941 switch (getCudaArch(CGM)) {
4942 case CudaArch::SM_20:
4943 case CudaArch::SM_21:
4944 case CudaArch::SM_30:
4945 case CudaArch::SM_32:
4946 case CudaArch::SM_35:
4947 case CudaArch::SM_37:
4948 case CudaArch::SM_50:
4949 case CudaArch::SM_52:
4950 case CudaArch::SM_53:
4951 case CudaArch::SM_60:
4952 case CudaArch::SM_61:
4953 case CudaArch::SM_62:
4954 CGM.Error(Clause->getBeginLoc(),
4955 "Target architecture does not support unified addressing");
4956 return;
4957 case CudaArch::SM_70:
4958 case CudaArch::SM_72:
4959 case CudaArch::SM_75:
4960 case CudaArch::GFX600:
4961 case CudaArch::GFX601:
4962 case CudaArch::GFX700:
4963 case CudaArch::GFX701:
4964 case CudaArch::GFX702:
4965 case CudaArch::GFX703:
4966 case CudaArch::GFX704:
4967 case CudaArch::GFX801:
4968 case CudaArch::GFX802:
4969 case CudaArch::GFX803:
4970 case CudaArch::GFX810:
4971 case CudaArch::GFX900:
4972 case CudaArch::GFX902:
4973 case CudaArch::GFX904:
4974 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004975 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004976 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004977 case CudaArch::GFX1010:
4978 case CudaArch::GFX1011:
4979 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004980 case CudaArch::UNKNOWN:
4981 break;
4982 case CudaArch::LAST:
4983 llvm_unreachable("Unexpected Cuda arch.");
4984 }
4985 }
4986 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004987 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004988}
4989
Alexey Bataeve4090182018-11-02 14:54:07 +00004990/// Get number of SMs and number of blocks per SM.
4991static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4992 std::pair<unsigned, unsigned> Data;
4993 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4994 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4995 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
4996 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
4997 if (Data.first && Data.second)
4998 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004999 switch (getCudaArch(CGM)) {
5000 case CudaArch::SM_20:
5001 case CudaArch::SM_21:
5002 case CudaArch::SM_30:
5003 case CudaArch::SM_32:
5004 case CudaArch::SM_35:
5005 case CudaArch::SM_37:
5006 case CudaArch::SM_50:
5007 case CudaArch::SM_52:
5008 case CudaArch::SM_53:
5009 return {16, 16};
5010 case CudaArch::SM_60:
5011 case CudaArch::SM_61:
5012 case CudaArch::SM_62:
5013 return {56, 32};
5014 case CudaArch::SM_70:
5015 case CudaArch::SM_72:
5016 case CudaArch::SM_75:
5017 return {84, 32};
5018 case CudaArch::GFX600:
5019 case CudaArch::GFX601:
5020 case CudaArch::GFX700:
5021 case CudaArch::GFX701:
5022 case CudaArch::GFX702:
5023 case CudaArch::GFX703:
5024 case CudaArch::GFX704:
5025 case CudaArch::GFX801:
5026 case CudaArch::GFX802:
5027 case CudaArch::GFX803:
5028 case CudaArch::GFX810:
5029 case CudaArch::GFX900:
5030 case CudaArch::GFX902:
5031 case CudaArch::GFX904:
5032 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005033 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005034 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005035 case CudaArch::GFX1010:
5036 case CudaArch::GFX1011:
5037 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005038 case CudaArch::UNKNOWN:
5039 break;
5040 case CudaArch::LAST:
5041 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005042 }
5043 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5044}
5045
5046void CGOpenMPRuntimeNVPTX::clear() {
5047 if (!GlobalizedRecords.empty()) {
5048 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005049 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5050 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005051 RecordDecl *StaticRD = C.buildImplicitRecord(
5052 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5053 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005054 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5055 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5056 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005057 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5058 if (Records.Records.empty())
5059 continue;
5060 unsigned Size = 0;
5061 unsigned RecAlignment = 0;
5062 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005063 QualType RDTy = C.getRecordType(RD);
5064 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005065 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005066 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005067 Size =
5068 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5069 }
5070 Size = llvm::alignTo(Size, RecAlignment);
5071 llvm::APInt ArySize(/*numBits=*/64, Size);
5072 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005073 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005074 const bool UseSharedMemory = Size <= SharedMemorySize;
5075 auto *Field =
5076 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5077 SourceLocation(), SourceLocation(), nullptr, SubTy,
5078 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5079 /*BW=*/nullptr, /*Mutable=*/false,
5080 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005081 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005082 if (UseSharedMemory) {
5083 SharedStaticRD->addDecl(Field);
5084 SharedRecs.push_back(&Records);
5085 } else {
5086 StaticRD->addDecl(Field);
5087 GlobalRecs.push_back(&Records);
5088 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005089 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005090 Records.UseSharedMemory->setInitializer(
5091 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5092 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005093 // Allocate SharedMemorySize buffer for the shared memory.
5094 // FIXME: nvlink does not handle weak linkage correctly (object with the
5095 // different size are reported as erroneous).
5096 // Restore this code as sson as nvlink is fixed.
5097 if (!SharedStaticRD->field_empty()) {
5098 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5099 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005100 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005101 auto *Field = FieldDecl::Create(
5102 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5103 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5104 /*BW=*/nullptr, /*Mutable=*/false,
5105 /*InitStyle=*/ICIS_NoInit);
5106 Field->setAccess(AS_public);
5107 SharedStaticRD->addDecl(Field);
5108 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005109 SharedStaticRD->completeDefinition();
5110 if (!SharedStaticRD->field_empty()) {
5111 QualType StaticTy = C.getRecordType(SharedStaticRD);
5112 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5113 auto *GV = new llvm::GlobalVariable(
5114 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005115 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005116 llvm::Constant::getNullValue(LLVMStaticTy),
5117 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5118 llvm::GlobalValue::NotThreadLocal,
5119 C.getTargetAddressSpace(LangAS::cuda_shared));
5120 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5121 GV, CGM.VoidPtrTy);
5122 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5123 Rec->Buffer->replaceAllUsesWith(Replacement);
5124 Rec->Buffer->eraseFromParent();
5125 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005126 }
5127 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005128 if (!StaticRD->field_empty()) {
5129 QualType StaticTy = C.getRecordType(StaticRD);
5130 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5131 llvm::APInt Size1(32, SMsBlockPerSM.second);
5132 QualType Arr1Ty =
Richard Smith772e2662019-10-04 01:25:59 +00005133 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005134 /*IndexTypeQuals=*/0);
5135 llvm::APInt Size2(32, SMsBlockPerSM.first);
Richard Smith772e2662019-10-04 01:25:59 +00005136 QualType Arr2Ty =
5137 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5138 /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005139 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005140 // FIXME: nvlink does not handle weak linkage correctly (object with the
5141 // different size are reported as erroneous).
5142 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005143 auto *GV = new llvm::GlobalVariable(
5144 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005145 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005146 llvm::Constant::getNullValue(LLVMArr2Ty),
5147 "_openmp_static_glob_rd_$_");
5148 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5149 GV, CGM.VoidPtrTy);
5150 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5151 Rec->Buffer->replaceAllUsesWith(Replacement);
5152 Rec->Buffer->eraseFromParent();
5153 }
5154 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005155 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005156 if (!TeamsReductions.empty()) {
5157 ASTContext &C = CGM.getContext();
5158 RecordDecl *StaticRD = C.buildImplicitRecord(
5159 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5160 StaticRD->startDefinition();
5161 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5162 QualType RecTy = C.getRecordType(TeamReductionRec);
5163 auto *Field = FieldDecl::Create(
5164 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5165 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5166 /*BW=*/nullptr, /*Mutable=*/false,
5167 /*InitStyle=*/ICIS_NoInit);
5168 Field->setAccess(AS_public);
5169 StaticRD->addDecl(Field);
5170 }
5171 StaticRD->completeDefinition();
5172 QualType StaticTy = C.getRecordType(StaticRD);
5173 llvm::Type *LLVMReductionsBufferTy =
5174 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005175 // FIXME: nvlink does not handle weak linkage correctly (object with the
5176 // different size are reported as erroneous).
5177 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005178 auto *GV = new llvm::GlobalVariable(
5179 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005180 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005181 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5182 "_openmp_teams_reductions_buffer_$_");
5183 KernelTeamsReductionPtr->setInitializer(
5184 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5185 CGM.VoidPtrTy));
5186 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005187 CGOpenMPRuntime::clear();
5188}