blob: a5be9aabc56321579379190988207cc7f5920825 [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:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000806 case OMPD_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +0000807 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000808 case OMPD_unknown:
809 llvm_unreachable("Unexpected directive.");
810 }
811 }
812
813 return false;
814}
815
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000816static bool supportsSPMDExecutionMode(ASTContext &Ctx,
817 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000818 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
819 switch (DirectiveKind) {
820 case OMPD_target:
821 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000822 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000823 case OMPD_target_parallel:
824 case OMPD_target_parallel_for:
825 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000826 case OMPD_target_teams_distribute_parallel_for:
827 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000828 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000829 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000830 return true;
831 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000832 return false;
833 case OMPD_parallel:
834 case OMPD_for:
835 case OMPD_parallel_for:
836 case OMPD_parallel_sections:
837 case OMPD_for_simd:
838 case OMPD_parallel_for_simd:
839 case OMPD_cancel:
840 case OMPD_cancellation_point:
841 case OMPD_ordered:
842 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000843 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000844 case OMPD_task:
845 case OMPD_simd:
846 case OMPD_sections:
847 case OMPD_section:
848 case OMPD_single:
849 case OMPD_master:
850 case OMPD_critical:
851 case OMPD_taskyield:
852 case OMPD_barrier:
853 case OMPD_taskwait:
854 case OMPD_taskgroup:
855 case OMPD_atomic:
856 case OMPD_flush:
857 case OMPD_teams:
858 case OMPD_target_data:
859 case OMPD_target_exit_data:
860 case OMPD_target_enter_data:
861 case OMPD_distribute:
862 case OMPD_distribute_simd:
863 case OMPD_distribute_parallel_for:
864 case OMPD_distribute_parallel_for_simd:
865 case OMPD_teams_distribute:
866 case OMPD_teams_distribute_simd:
867 case OMPD_teams_distribute_parallel_for:
868 case OMPD_teams_distribute_parallel_for_simd:
869 case OMPD_target_update:
870 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000871 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000872 case OMPD_declare_target:
873 case OMPD_end_declare_target:
874 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000875 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000876 case OMPD_taskloop:
877 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000878 case OMPD_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +0000879 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000880 case OMPD_unknown:
881 break;
882 }
883 llvm_unreachable(
884 "Unknown programming model for OpenMP directive on NVPTX target.");
885}
886
887/// Check if the directive is loops based and has schedule clause at all or has
888/// static scheduling.
889static bool hasStaticScheduling(const OMPExecutableDirective &D) {
890 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
891 isOpenMPLoopDirective(D.getDirectiveKind()) &&
892 "Expected loop-based directive.");
893 return !D.hasClausesOfKind<OMPOrderedClause>() &&
894 (!D.hasClausesOfKind<OMPScheduleClause>() ||
895 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
896 [](const OMPScheduleClause *C) {
897 return C->getScheduleKind() == OMPC_SCHEDULE_static;
898 }));
899}
900
901/// Check for inner (nested) lightweight runtime construct, if any
902static bool hasNestedLightweightDirective(ASTContext &Ctx,
903 const OMPExecutableDirective &D) {
904 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
905 const auto *CS = D.getInnermostCapturedStmt();
906 const auto *Body =
907 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000908 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000909
Alexey Bataev5c427362019-04-10 19:11:33 +0000910 if (const auto *NestedDir =
911 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000912 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
913 switch (D.getDirectiveKind()) {
914 case OMPD_target:
915 if (isOpenMPParallelDirective(DKind) &&
916 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
917 hasStaticScheduling(*NestedDir))
918 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000919 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
920 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000921 if (DKind == OMPD_parallel) {
922 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
923 /*IgnoreCaptured=*/true);
924 if (!Body)
925 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000926 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
927 if (const auto *NND =
928 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000929 DKind = NND->getDirectiveKind();
930 if (isOpenMPWorksharingDirective(DKind) &&
931 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
932 return true;
933 }
934 } else if (DKind == OMPD_teams) {
935 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
936 /*IgnoreCaptured=*/true);
937 if (!Body)
938 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000939 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
940 if (const auto *NND =
941 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000942 DKind = NND->getDirectiveKind();
943 if (isOpenMPParallelDirective(DKind) &&
944 isOpenMPWorksharingDirective(DKind) &&
945 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
946 return true;
947 if (DKind == OMPD_parallel) {
948 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
949 /*IgnoreCaptured=*/true);
950 if (!Body)
951 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000952 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
953 if (const auto *NND =
954 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000955 DKind = NND->getDirectiveKind();
956 if (isOpenMPWorksharingDirective(DKind) &&
957 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
958 return true;
959 }
960 }
961 }
962 }
963 return false;
964 case OMPD_target_teams:
965 if (isOpenMPParallelDirective(DKind) &&
966 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
967 hasStaticScheduling(*NestedDir))
968 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000969 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
970 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000971 if (DKind == OMPD_parallel) {
972 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
973 /*IgnoreCaptured=*/true);
974 if (!Body)
975 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000976 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
977 if (const auto *NND =
978 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000979 DKind = NND->getDirectiveKind();
980 if (isOpenMPWorksharingDirective(DKind) &&
981 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
982 return true;
983 }
984 }
985 return false;
986 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000987 if (DKind == OMPD_simd)
988 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000989 return isOpenMPWorksharingDirective(DKind) &&
990 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
991 case OMPD_target_teams_distribute:
992 case OMPD_target_simd:
993 case OMPD_target_parallel_for:
994 case OMPD_target_parallel_for_simd:
995 case OMPD_target_teams_distribute_simd:
996 case OMPD_target_teams_distribute_parallel_for:
997 case OMPD_target_teams_distribute_parallel_for_simd:
998 case OMPD_parallel:
999 case OMPD_for:
1000 case OMPD_parallel_for:
1001 case OMPD_parallel_sections:
1002 case OMPD_for_simd:
1003 case OMPD_parallel_for_simd:
1004 case OMPD_cancel:
1005 case OMPD_cancellation_point:
1006 case OMPD_ordered:
1007 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001008 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001009 case OMPD_task:
1010 case OMPD_simd:
1011 case OMPD_sections:
1012 case OMPD_section:
1013 case OMPD_single:
1014 case OMPD_master:
1015 case OMPD_critical:
1016 case OMPD_taskyield:
1017 case OMPD_barrier:
1018 case OMPD_taskwait:
1019 case OMPD_taskgroup:
1020 case OMPD_atomic:
1021 case OMPD_flush:
1022 case OMPD_teams:
1023 case OMPD_target_data:
1024 case OMPD_target_exit_data:
1025 case OMPD_target_enter_data:
1026 case OMPD_distribute:
1027 case OMPD_distribute_simd:
1028 case OMPD_distribute_parallel_for:
1029 case OMPD_distribute_parallel_for_simd:
1030 case OMPD_teams_distribute:
1031 case OMPD_teams_distribute_simd:
1032 case OMPD_teams_distribute_parallel_for:
1033 case OMPD_teams_distribute_parallel_for_simd:
1034 case OMPD_target_update:
1035 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001036 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001037 case OMPD_declare_target:
1038 case OMPD_end_declare_target:
1039 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001040 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001041 case OMPD_taskloop:
1042 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001043 case OMPD_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +00001044 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001045 case OMPD_unknown:
1046 llvm_unreachable("Unexpected directive.");
1047 }
1048 }
1049
1050 return false;
1051}
1052
1053/// Checks if the construct supports lightweight runtime. It must be SPMD
1054/// construct + inner loop-based construct with static scheduling.
1055static bool supportsLightweightRuntime(ASTContext &Ctx,
1056 const OMPExecutableDirective &D) {
1057 if (!supportsSPMDExecutionMode(Ctx, D))
1058 return false;
1059 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1060 switch (DirectiveKind) {
1061 case OMPD_target:
1062 case OMPD_target_teams:
1063 case OMPD_target_parallel:
1064 return hasNestedLightweightDirective(Ctx, D);
1065 case OMPD_target_parallel_for:
1066 case OMPD_target_parallel_for_simd:
1067 case OMPD_target_teams_distribute_parallel_for:
1068 case OMPD_target_teams_distribute_parallel_for_simd:
1069 // (Last|First)-privates must be shared in parallel region.
1070 return hasStaticScheduling(D);
1071 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001072 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001073 return true;
1074 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001075 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001076 case OMPD_parallel:
1077 case OMPD_for:
1078 case OMPD_parallel_for:
1079 case OMPD_parallel_sections:
1080 case OMPD_for_simd:
1081 case OMPD_parallel_for_simd:
1082 case OMPD_cancel:
1083 case OMPD_cancellation_point:
1084 case OMPD_ordered:
1085 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001086 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001087 case OMPD_task:
1088 case OMPD_simd:
1089 case OMPD_sections:
1090 case OMPD_section:
1091 case OMPD_single:
1092 case OMPD_master:
1093 case OMPD_critical:
1094 case OMPD_taskyield:
1095 case OMPD_barrier:
1096 case OMPD_taskwait:
1097 case OMPD_taskgroup:
1098 case OMPD_atomic:
1099 case OMPD_flush:
1100 case OMPD_teams:
1101 case OMPD_target_data:
1102 case OMPD_target_exit_data:
1103 case OMPD_target_enter_data:
1104 case OMPD_distribute:
1105 case OMPD_distribute_simd:
1106 case OMPD_distribute_parallel_for:
1107 case OMPD_distribute_parallel_for_simd:
1108 case OMPD_teams_distribute:
1109 case OMPD_teams_distribute_simd:
1110 case OMPD_teams_distribute_parallel_for:
1111 case OMPD_teams_distribute_parallel_for_simd:
1112 case OMPD_target_update:
1113 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001114 case OMPD_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001115 case OMPD_declare_target:
1116 case OMPD_end_declare_target:
1117 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001118 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001119 case OMPD_taskloop:
1120 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001121 case OMPD_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +00001122 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001123 case OMPD_unknown:
1124 break;
1125 }
1126 llvm_unreachable(
1127 "Unknown programming model for OpenMP directive on NVPTX target.");
1128}
1129
1130void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001131 StringRef ParentName,
1132 llvm::Function *&OutlinedFn,
1133 llvm::Constant *&OutlinedFnID,
1134 bool IsOffloadEntry,
1135 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001136 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001137 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001138 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001139 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001140 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001141
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001142 // Emit target region as a standalone region.
1143 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001144 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1145 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001146
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001147 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001148 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001149 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001150 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001152 auto &RT =
1153 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001154 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1155 // Skip target region initialization.
1156 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001157 }
1158 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001159 auto &RT =
1160 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001161 RT.clearLocThreadIdInsertPt(CGF);
1162 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001163 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001164 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001165 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001166 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001167 // Reserve place for the globalized memory.
1168 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001169 if (!KernelStaticGlobalized) {
1170 KernelStaticGlobalized = new llvm::GlobalVariable(
1171 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1172 llvm::GlobalValue::InternalLinkage,
1173 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1174 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1175 llvm::GlobalValue::NotThreadLocal,
1176 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1177 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001178 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1179 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001180 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001181
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 // Now change the name of the worker function to correspond to this target
1183 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001184 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001185
1186 // Create the worker function
1187 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001188}
1189
1190// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001191void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192 EntryFunctionState &EST,
1193 WorkerFunctionState &WST) {
1194 CGBuilderTy &Bld = CGF.Builder;
1195
1196 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1197 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1198 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1199 EST.ExitBB = CGF.createBasicBlock(".exit");
1200
Alexey Bataev9ff80832018-04-16 20:16:21 +00001201 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001202 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1203 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1204
1205 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001206 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001207 CGF.EmitBranch(EST.ExitBB);
1208
1209 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001210 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1212 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1213
1214 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001215 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001216 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001217 // First action in sequential region:
1218 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001219 // TODO: Optimize runtime initialization and pass in correct value.
1220 llvm::Value *Args[] = {getThreadLimit(CGF),
1221 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001222 CGF.EmitRuntimeCall(
1223 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001224
1225 // For data sharing, we need to initialize the stack.
1226 CGF.EmitRuntimeCall(
1227 createNVPTXRuntimeFunction(
1228 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1229
Alexey Bataevc99042b2018-03-15 18:10:54 +00001230 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001231}
1232
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001233void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001234 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001235 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001236 if (!CGF.HaveInsertPoint())
1237 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001238
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001239 emitGenericVarsEpilog(CGF);
1240
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001241 if (!EST.ExitBB)
1242 EST.ExitBB = CGF.createBasicBlock(".exit");
1243
1244 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1245 CGF.EmitBranch(TerminateBB);
1246
1247 CGF.EmitBlock(TerminateBB);
1248 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001249 // TODO: Optimize runtime initialization and pass in correct value.
1250 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001251 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001252 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001253 // Barrier to terminate worker threads.
1254 syncCTAThreads(CGF);
1255 // Master thread jumps to exit point.
1256 CGF.EmitBranch(EST.ExitBB);
1257
1258 CGF.EmitBlock(EST.ExitBB);
1259 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001260}
1261
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001262void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001263 StringRef ParentName,
1264 llvm::Function *&OutlinedFn,
1265 llvm::Constant *&OutlinedFnID,
1266 bool IsOffloadEntry,
1267 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001268 ExecutionRuntimeModesRAII ModeRAII(
1269 CurrentExecutionMode, RequiresFullRuntime,
1270 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1271 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001272 EntryFunctionState EST;
1273
1274 // Emit target region as a standalone region.
1275 class NVPTXPrePostActionTy : public PrePostActionTy {
1276 CGOpenMPRuntimeNVPTX &RT;
1277 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1278 const OMPExecutableDirective &D;
1279
1280 public:
1281 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1282 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1283 const OMPExecutableDirective &D)
1284 : RT(RT), EST(EST), D(D) {}
1285 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001286 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001287 // Skip target region initialization.
1288 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001289 }
1290 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001291 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001292 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001293 }
1294 } Action(*this, EST, D);
1295 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001296 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001297 // Reserve place for the globalized memory.
1298 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001299 if (!KernelStaticGlobalized) {
1300 KernelStaticGlobalized = new llvm::GlobalVariable(
1301 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1302 llvm::GlobalValue::InternalLinkage,
1303 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1304 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1305 llvm::GlobalValue::NotThreadLocal,
1306 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1307 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001308 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1309 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001310 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001311}
1312
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001313void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001314 CodeGenFunction &CGF, EntryFunctionState &EST,
1315 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001316 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001317
1318 // Setup BBs in entry function.
1319 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1320 EST.ExitBB = CGF.createBasicBlock(".exit");
1321
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001322 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1323 /*RequiresOMPRuntime=*/
1324 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1325 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326 CGF.EmitRuntimeCall(
1327 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001328
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001329 if (RequiresFullRuntime) {
1330 // For data sharing, we need to initialize the stack.
1331 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1332 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1333 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001334
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001335 CGF.EmitBranch(ExecuteBB);
1336
1337 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001338
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001339 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001340}
1341
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001342void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001343 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001344 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001345 if (!CGF.HaveInsertPoint())
1346 return;
1347
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001348 if (!EST.ExitBB)
1349 EST.ExitBB = CGF.createBasicBlock(".exit");
1350
1351 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1352 CGF.EmitBranch(OMPDeInitBB);
1353
1354 CGF.EmitBlock(OMPDeInitBB);
1355 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001356 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1357 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001358 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001359 createNVPTXRuntimeFunction(
1360 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001361 CGF.EmitBranch(EST.ExitBB);
1362
1363 CGF.EmitBlock(EST.ExitBB);
1364 EST.ExitBB = nullptr;
1365}
1366
1367// Create a unique global variable to indicate the execution mode of this target
1368// region. The execution mode is either 'generic', or 'spmd' depending on the
1369// target directive. This variable is picked up by the offload library to setup
1370// the device appropriately before kernel launch. If the execution mode is
1371// 'generic', the runtime reserves one warp for the master, otherwise, all
1372// warps participate in parallel work.
1373static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001374 bool Mode) {
1375 auto *GVMode =
1376 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1377 llvm::GlobalValue::WeakAnyLinkage,
1378 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1379 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001380 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001381}
1382
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001383void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001384 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001385
1386 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001387 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001388 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001389 emitWorkerLoop(CGF, WST);
1390 CGF.FinishFunction();
1391}
1392
1393void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1394 WorkerFunctionState &WST) {
1395 //
1396 // The workers enter this loop and wait for parallel work from the master.
1397 // When the master encounters a parallel region it sets up the work + variable
1398 // arguments, and wakes up the workers. The workers first check to see if
1399 // they are required for the parallel region, i.e., within the # of requested
1400 // parallel threads. The activated workers load the variable arguments and
1401 // execute the parallel work.
1402 //
1403
1404 CGBuilderTy &Bld = CGF.Builder;
1405
1406 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1407 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1408 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1409 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1410 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1411 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1412
1413 CGF.EmitBranch(AwaitBB);
1414
1415 // Workers wait for work from master.
1416 CGF.EmitBlock(AwaitBB);
1417 // Wait for parallel work
1418 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001419
1420 Address WorkFn =
1421 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1422 Address ExecStatus =
1423 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1424 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1425 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1426
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001427 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001428 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001429 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001430 llvm::Value *Ret = CGF.EmitRuntimeCall(
1431 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1432 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001433
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001434 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001435 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1436 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001437 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1438
1439 // Activate requested workers.
1440 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001441 llvm::Value *IsActive =
1442 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1443 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001444
1445 // Signal start of parallel region.
1446 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001447 // Skip initialization.
1448 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001449
1450 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001451 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001452 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001453 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001454
1455 llvm::Value *WorkFnMatch =
1456 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1457
1458 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1459 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1460 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1461
1462 // Execute this outlined function.
1463 CGF.EmitBlock(ExecuteFNBB);
1464
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001465 // Insert call to work function via shared wrapper. The shared
1466 // wrapper takes two arguments:
1467 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001468 // - the thread ID;
1469 emitCall(CGF, WST.Loc, W,
1470 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001471
1472 // Go to end of parallel region.
1473 CGF.EmitBranch(TerminateBB);
1474
1475 CGF.EmitBlock(CheckNextBB);
1476 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001477 // Default case: call to outlined function through pointer if the target
1478 // region makes a declare target call that may contain an orphaned parallel
1479 // directive.
1480 auto *ParallelFnTy =
1481 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001482 /*isVarArg=*/false);
1483 llvm::Value *WorkFnCast =
1484 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001485 // Insert call to work function via shared wrapper. The shared
1486 // wrapper takes two arguments:
1487 // - the parallelism level;
1488 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001489 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001490 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1491 // Go to end of parallel region.
1492 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001493
1494 // Signal end of parallel region.
1495 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001496 CGF.EmitRuntimeCall(
1497 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1498 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001499 CGF.EmitBranch(BarrierBB);
1500
1501 // All active and inactive workers wait at a barrier after parallel region.
1502 CGF.EmitBlock(BarrierBB);
1503 // Barrier after parallel region.
1504 syncCTAThreads(CGF);
1505 CGF.EmitBranch(AwaitBB);
1506
1507 // Exit target region.
1508 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001509 // Skip initialization.
1510 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001511}
1512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001513/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001514/// implementation. Specialized for the NVPTX device.
1515/// \param Function OpenMP runtime function.
1516/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001517llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001518CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001519 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001520 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1521 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001522 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1523 // RequiresOMPRuntime);
1524 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001525 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1527 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1528 break;
1529 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001530 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001531 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1532 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001533 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001534 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001535 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1536 break;
1537 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001538 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1539 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001540 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001541 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001542 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1545 break;
1546 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001547 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1548 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1549 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001550 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001551 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1552 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001553 break;
1554 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001555 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1556 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001557 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001558 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001559 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001560 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1561 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1562 break;
1563 }
1564 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001565 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1566 /// int16_t IsOMPRuntimeInitialized);
1567 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001568 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001569 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001570 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1572 break;
1573 }
1574 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1575 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001576 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001577 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1579 break;
1580 }
1581 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1582 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1583 // global_tid);
1584 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001585 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001586 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1588 break;
1589 }
1590 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1591 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1592 // global_tid);
1593 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001594 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001595 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1596 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1597 break;
1598 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001599 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1600 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1601 // int16_t lane_offset, int16_t warp_size);
1602 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001603 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001604 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1606 break;
1607 }
1608 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1609 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1610 // int16_t lane_offset, int16_t warp_size);
1611 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001612 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001613 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1614 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1615 break;
1616 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001617 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001618 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1619 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1620 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1621 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1622 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001623 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1624 CGM.Int16Ty, CGM.Int16Ty};
1625 auto *ShuffleReduceFnTy =
1626 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1627 /*isVarArg=*/false);
1628 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1629 auto *InterWarpCopyFnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1631 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001632 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1633 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001634 CGM.Int32Ty,
1635 CGM.SizeTy,
1636 CGM.VoidPtrTy,
1637 ShuffleReduceFnTy->getPointerTo(),
1638 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001639 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001640 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1641 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001642 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001643 break;
1644 }
1645 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1646 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1647 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001648 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001649 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1650 RTLFn = CGM.CreateRuntimeFunction(
1651 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1652 break;
1653 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001654 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1655 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1656 // global_tid, void *global_buffer, int32_t num_of_records, void*
1657 // reduce_data,
1658 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1659 // lane_offset, int16_t shortCircuit),
1660 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1661 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1662 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1663 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1664 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1665 // *buffer, int idx, void *reduce_data));
1666 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1667 CGM.Int16Ty, CGM.Int16Ty};
1668 auto *ShuffleReduceFnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1670 /*isVarArg=*/false);
1671 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1672 auto *InterWarpCopyFnTy =
1673 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1674 /*isVarArg=*/false);
1675 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1676 CGM.VoidPtrTy};
1677 auto *GlobalListFnTy =
1678 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1679 /*isVarArg=*/false);
1680 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1681 CGM.Int32Ty,
1682 CGM.VoidPtrTy,
1683 CGM.Int32Ty,
1684 CGM.VoidPtrTy,
1685 ShuffleReduceFnTy->getPointerTo(),
1686 InterWarpCopyFnTy->getPointerTo(),
1687 GlobalListFnTy->getPointerTo(),
1688 GlobalListFnTy->getPointerTo(),
1689 GlobalListFnTy->getPointerTo(),
1690 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001691 auto *FnTy =
1692 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1693 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001694 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001695 break;
1696 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001697 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1698 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001699 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001700 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1701 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1702 break;
1703 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001704 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1705 /// Build void __kmpc_data_sharing_init_stack_spmd();
1706 auto *FnTy =
1707 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001708 RTLFn =
1709 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001710 break;
1711 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001712 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1713 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001714 // int16_t UseSharedMemory);
1715 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001716 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001717 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1718 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001719 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001720 break;
1721 }
1722 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1723 // Build void __kmpc_data_sharing_pop_stack(void *a);
1724 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001725 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001726 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1728 /*Name=*/"__kmpc_data_sharing_pop_stack");
1729 break;
1730 }
1731 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1732 /// Build void __kmpc_begin_sharing_variables(void ***args,
1733 /// size_t n_args);
1734 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001735 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001736 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1738 break;
1739 }
1740 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1741 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001742 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001743 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1745 break;
1746 }
1747 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1748 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1749 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001750 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001751 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1753 break;
1754 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001755 case OMPRTL_NVPTX__kmpc_parallel_level: {
1756 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1758 auto *FnTy =
1759 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1761 break;
1762 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001763 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1764 // Build int8_t __kmpc_is_spmd_exec_mode();
1765 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1766 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1767 break;
1768 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001769 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001770 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1771 // const void *buf, size_t size, int16_t is_shared, const void **res);
1772 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1773 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001774 auto *FnTy =
1775 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1776 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1777 break;
1778 }
1779 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001780 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1781 // int16_t is_shared);
1782 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001783 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001785 RTLFn =
1786 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1787 break;
1788 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001789 case OMPRTL__kmpc_barrier: {
1790 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1792 auto *FnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001795 cast<llvm::Function>(RTLFn.getCallee())
1796 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001797 break;
1798 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001799 case OMPRTL__kmpc_barrier_simple_spmd: {
1800 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1801 // global_tid);
1802 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1803 auto *FnTy =
1804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1805 RTLFn =
1806 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001807 cast<llvm::Function>(RTLFn.getCallee())
1808 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001809 break;
1810 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001811 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1812 // Build int32_t __kmpc_warp_active_thread_mask(void);
1813 auto *FnTy =
1814 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1815 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1816 break;
1817 }
1818 case OMPRTL_NVPTX__kmpc_syncwarp: {
1819 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1820 auto *FnTy =
1821 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1822 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
1823 break;
1824 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001825 }
1826 return RTLFn;
1827}
1828
1829void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1830 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001831 uint64_t Size, int32_t,
1832 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001833 // TODO: Add support for global variables on the device after declare target
1834 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001835 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001836 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001837 llvm::Module &M = CGM.getModule();
1838 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001839
1840 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001841 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001842
1843 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001844 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001845 llvm::ConstantAsMetadata::get(
1846 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1847 // Append metadata to nvvm.annotations
1848 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1849}
1850
1851void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1852 const OMPExecutableDirective &D, StringRef ParentName,
1853 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001854 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001855 if (!IsOffloadEntry) // Nothing to do.
1856 return;
1857
1858 assert(!ParentName.empty() && "Invalid target region parent name!");
1859
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001860 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001861 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001862 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001863 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001864 else
1865 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1866 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001867
1868 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001869}
1870
Alexey Bataevceeaa482018-11-21 21:04:34 +00001871namespace {
1872LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1873/// Enum for accesseing the reserved_2 field of the ident_t struct.
1874enum ModeFlagsTy : unsigned {
1875 /// Bit set to 1 when in SPMD mode.
1876 KMP_IDENT_SPMD_MODE = 0x01,
1877 /// Bit set to 1 when a simplified runtime is used.
1878 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1879 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1880};
1881
1882/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1883static const ModeFlagsTy UndefinedMode =
1884 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1885} // anonymous namespace
1886
1887unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001888 switch (getExecutionMode()) {
1889 case EM_SPMD:
1890 if (requiresFullRuntime())
1891 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1892 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1893 case EM_NonSPMD:
1894 assert(requiresFullRuntime() && "Expected full runtime.");
1895 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1896 case EM_Unknown:
1897 return UndefinedMode;
1898 }
1899 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001900}
1901
Alexey Bataevc2cd2d42019-10-10 17:28:10 +00001902bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1903 const GlobalDecl &OldGD,
1904 llvm::GlobalValue *OrigAddr,
1905 bool IsForDefinition) {
1906 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1907 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1908 if (NewFD->isDefined()) {
1909 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1910 return true;
1911 }
1912 return false;
1913}
1914
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001915CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001916 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001917 if (!CGM.getLangOpts().OpenMPIsDevice)
1918 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001919}
Carlo Bertollic6872252016-04-04 15:55:02 +00001920
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001921void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1922 OpenMPProcBindClauseKind ProcBind,
1923 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001924 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001925 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001926 return;
1927
1928 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1929}
1930
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001931void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1932 llvm::Value *NumThreads,
1933 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001934 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001935 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001936 return;
1937
1938 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1939}
1940
Carlo Bertollic6872252016-04-04 15:55:02 +00001941void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1942 const Expr *NumTeams,
1943 const Expr *ThreadLimit,
1944 SourceLocation Loc) {}
1945
James Y Knight9871db02019-02-05 16:42:33 +00001946llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001947 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1948 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001949 // Emit target region as a standalone region.
1950 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001951 bool &IsInParallelRegion;
1952 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953
1954 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001955 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1956 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001957 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001958 PrevIsInParallelRegion = IsInParallelRegion;
1959 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001960 }
1961 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001962 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001963 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001964 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001965 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001966 bool PrevIsInTTDRegion = IsInTTDRegion;
1967 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001968 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1969 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001970 auto *OutlinedFun =
1971 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1972 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001973 if (CGM.getLangOpts().Optimize) {
1974 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1975 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1976 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1977 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001978 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001979 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001980 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1981 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001982 llvm::Function *WrapperFun =
1983 createParallelDataSharingWrapper(OutlinedFun, D);
1984 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1985 }
1986
1987 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001988}
1989
Alexey Bataev2adecff2018-09-21 14:22:53 +00001990/// Get list of lastprivate variables from the teams distribute ... or
1991/// teams {distribute ...} directives.
1992static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001993getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001994 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1995 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
1996 "expected teams directive.");
1997 const OMPExecutableDirective *Dir = &D;
1998 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00001999 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002000 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002001 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2002 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002003 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002004 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2005 Dir = nullptr;
2006 }
2007 }
2008 if (!Dir)
2009 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002010 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002011 for (const Expr *E : C->getVarRefs())
2012 Vars.push_back(getPrivateItem(E));
2013 }
2014}
2015
2016/// Get list of reduction variables from the teams ... directives.
2017static void
2018getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2019 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2020 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2021 "expected teams directive.");
2022 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2023 for (const Expr *E : C->privates())
2024 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002025 }
2026}
2027
James Y Knight9871db02019-02-05 16:42:33 +00002028llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002029 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2030 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002031 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002032
Alexey Bataev2adecff2018-09-21 14:22:53 +00002033 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002034 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002035 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002036 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002037 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2038 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002039 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002040 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2041 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002042 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002043 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002044 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002045 }
2046 } else if (!LastPrivatesReductions.empty()) {
2047 assert(!TeamAndReductions.first &&
2048 "Previous team declaration is not expected.");
2049 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2050 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002051 }
2052
Alexey Bataevc99042b2018-03-15 18:10:54 +00002053 // Emit target region as a standalone region.
2054 class NVPTXPrePostActionTy : public PrePostActionTy {
2055 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002056 const RecordDecl *GlobalizedRD;
2057 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2058 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002059
2060 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002061 NVPTXPrePostActionTy(
2062 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2063 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2064 &MappedDeclsFields)
2065 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2066 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002067 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002068 auto &Rt =
2069 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2070 if (GlobalizedRD) {
2071 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2072 I->getSecond().GlobalRecord = GlobalizedRD;
2073 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002074 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002075 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2076 for (const auto &Pair : MappedDeclsFields) {
2077 assert(Pair.getFirst()->isCanonicalDecl() &&
2078 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002079 Data.insert(std::make_pair(Pair.getFirst(),
2080 MappedVarData(Pair.getSecond(),
2081 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002082 }
2083 }
2084 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002085 }
2086 void Exit(CodeGenFunction &CGF) override {
2087 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2088 .emitGenericVarsEpilog(CGF);
2089 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002090 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2091 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002092 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002093 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002094 if (CGM.getLangOpts().Optimize) {
2095 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2096 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2097 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2098 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002099
2100 return OutlinedFun;
2101}
2102
Alexey Bataevc99042b2018-03-15 18:10:54 +00002103void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002104 SourceLocation Loc,
2105 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002106 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2107 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002108 return;
2109
Alexey Bataevc99042b2018-03-15 18:10:54 +00002110 CGBuilderTy &Bld = CGF.Builder;
2111
2112 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2113 if (I == FunctionGlobalizedDecls.end())
2114 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002115 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002116 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002117 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002118
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002119 // Recover pointer to this function's global record. The runtime will
2120 // handle the specifics of the allocation of the memory.
2121 // Use actual memory size of the record including the padding
2122 // for alignment purposes.
2123 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002124 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002125 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002126 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002127 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002128
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002129 llvm::PointerType *GlobalRecPtrTy =
2130 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002131 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002132 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002133 if (!IsInTTDRegion &&
2134 (WithSPMDCheck ||
2135 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002136 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2137 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2138 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002139 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2140 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2141 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2142 llvm::Value *PL = CGF.EmitRuntimeCall(
2143 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2144 {RTLoc, ThreadID});
2145 IsTTD = Bld.CreateIsNull(PL);
2146 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002147 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2148 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2149 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2150 // There is no need to emit line number for unconditional branch.
2151 (void)ApplyDebugLocation::CreateEmpty(CGF);
2152 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002153 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2154 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002155 CGF.EmitBranch(ExitBB);
2156 // There is no need to emit line number for unconditional branch.
2157 (void)ApplyDebugLocation::CreateEmpty(CGF);
2158 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002159 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2160 if (const RecordDecl *SecGlobalizedVarsRecord =
2161 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2162 SecGlobalRecTy =
2163 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2164
2165 // Recover pointer to this function's global record. The runtime will
2166 // handle the specifics of the allocation of the memory.
2167 // Use actual memory size of the record including the padding
2168 // for alignment purposes.
2169 unsigned Alignment =
2170 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2171 unsigned GlobalRecordSize =
2172 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2173 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2174 Size = Bld.CreateSelect(
2175 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2176 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002177 // TODO: allow the usage of shared memory to be controlled by
2178 // the user, for now, default to global.
2179 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002180 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002181 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2182 createNVPTXRuntimeFunction(
2183 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2184 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002185 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002186 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002187 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002188 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002189 /*NumReservedValues=*/2, "_select_stack");
2190 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2191 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2192 GlobalRecCastAddr = Phi;
2193 I->getSecond().GlobalRecordAddr = Phi;
2194 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002195 } else if (IsInTTDRegion) {
2196 assert(GlobalizedRecords.back().Records.size() < 2 &&
2197 "Expected less than 2 globalized records: one for target and one "
2198 "for teams.");
2199 unsigned Offset = 0;
2200 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2201 QualType RDTy = CGM.getContext().getRecordType(RD);
2202 unsigned Alignment =
2203 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2204 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2205 Offset =
2206 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2207 }
2208 unsigned Alignment =
2209 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2210 Offset = llvm::alignTo(Offset, Alignment);
2211 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2212 ++GlobalizedRecords.back().RegionCounter;
2213 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002214 assert(KernelStaticGlobalized &&
2215 "Kernel static pointer must be initialized already.");
2216 auto *UseSharedMemory = new llvm::GlobalVariable(
2217 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2218 llvm::GlobalValue::InternalLinkage, nullptr,
2219 "_openmp_static_kernel$is_shared");
2220 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2221 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2222 /*DestWidth=*/16, /*Signed=*/0);
2223 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2224 Address(UseSharedMemory,
2225 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2226 /*Volatile=*/false, Int16Ty, Loc);
2227 auto *StaticGlobalized = new llvm::GlobalVariable(
2228 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002229 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002230 auto *RecSize = new llvm::GlobalVariable(
2231 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2232 llvm::GlobalValue::InternalLinkage, nullptr,
2233 "_openmp_static_kernel$size");
2234 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2235 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002236 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002237 CGM.getContext().getSizeType(), Loc);
2238 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2239 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002240 llvm::Value *GlobalRecordSizeArg[] = {
2241 llvm::ConstantInt::get(
2242 CGM.Int16Ty,
2243 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2244 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002245 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2246 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2247 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002248 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002249 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002250 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2251 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002252 }
2253 assert(KernelStaticGlobalized && "Global address must be set already.");
2254 Address FrameAddr = CGF.EmitLoadOfPointer(
2255 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2256 CGM.getContext()
2257 .getPointerType(CGM.getContext().VoidPtrTy)
2258 .castAs<PointerType>());
2259 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002260 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002261 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2262 I->getSecond().IsInSPMDModeFlag = nullptr;
2263 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2264 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002265 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002266 // TODO: allow the usage of shared memory to be controlled by
2267 // the user, for now, default to global.
2268 llvm::Value *GlobalRecordSizeArg[] = {
2269 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2270 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002271 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2272 createNVPTXRuntimeFunction(
2273 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2274 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002275 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002276 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002277 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2278 I->getSecond().IsInSPMDModeFlag = nullptr;
2279 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002280 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002281 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002282
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002283 // Emit the "global alloca" which is a GEP from the global declaration
2284 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002285 LValue SecBase;
2286 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2287 if (IsTTD) {
2288 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2289 llvm::PointerType *SecGlobalRecPtrTy =
2290 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2291 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2292 Bld.CreatePointerBitCastOrAddrSpaceCast(
2293 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2294 SecGlobalRecTy);
2295 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002296 for (auto &Rec : I->getSecond().LocalVarData) {
2297 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2298 llvm::Value *ParValue;
2299 if (EscapedParam) {
2300 const auto *VD = cast<VarDecl>(Rec.first);
2301 LValue ParLVal =
2302 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2303 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2304 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002305 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2306 // Emit VarAddr basing on lane-id if required.
2307 QualType VarTy;
2308 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002309 VarTy = Rec.second.FD->getType();
2310 } else {
2311 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2312 VarAddr.getAddress().getPointer(),
2313 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002314 VarTy =
2315 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002316 VarAddr = CGF.MakeAddrLValue(
2317 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2318 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002319 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002320 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002321 if (!IsInTTDRegion &&
2322 (WithSPMDCheck ||
2323 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002324 assert(I->getSecond().IsInSPMDModeFlag &&
2325 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002326 if (IsTTD) {
2327 assert(SecIt->second.IsOnePerTeam &&
2328 "Secondary glob data must be one per team.");
2329 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2330 VarAddr.setAddress(
2331 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2332 VarAddr.getPointer()),
2333 VarAddr.getAlignment()));
2334 Rec.second.PrivateAddr = VarAddr.getAddress();
2335 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002336 Address GlobalPtr = Rec.second.PrivateAddr;
2337 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2338 Rec.second.PrivateAddr = Address(
2339 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2340 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2341 LocalAddr.getAlignment());
2342 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002343 if (EscapedParam) {
2344 const auto *VD = cast<VarDecl>(Rec.first);
2345 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2346 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2347 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002348 if (IsTTD)
2349 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002350 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002351 }
2352 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2353 // Recover pointer to this function's global record. The runtime will
2354 // handle the specifics of the allocation of the memory.
2355 // Use actual memory size of the record including the padding
2356 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002357 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002358 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2359 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2360 Size = Bld.CreateNUWAdd(
2361 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2362 llvm::Value *AlignVal =
2363 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2364 Size = Bld.CreateUDiv(Size, AlignVal);
2365 Size = Bld.CreateNUWMul(Size, AlignVal);
2366 // TODO: allow the usage of shared memory to be controlled by
2367 // the user, for now, default to global.
2368 llvm::Value *GlobalRecordSizeArg[] = {
2369 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2370 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002371 createNVPTXRuntimeFunction(
2372 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002373 GlobalRecordSizeArg);
2374 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2375 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2376 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2377 CGM.getContext().getDeclAlign(VD),
2378 AlignmentSource::Decl);
2379 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2380 Base.getAddress());
2381 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002382 }
2383 I->getSecond().MappedParams->apply(CGF);
2384}
2385
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002386void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2387 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002388 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2389 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002390 return;
2391
Alexey Bataevc99042b2018-03-15 18:10:54 +00002392 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002393 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002394 I->getSecond().MappedParams->restore(CGF);
2395 if (!CGF.HaveInsertPoint())
2396 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002397 for (llvm::Value *Addr :
2398 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2399 CGF.EmitRuntimeCall(
2400 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2401 Addr);
2402 }
2403 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002404 if (!IsInTTDRegion &&
2405 (WithSPMDCheck ||
2406 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002407 CGBuilderTy &Bld = CGF.Builder;
2408 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2409 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2410 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2411 // There is no need to emit line number for unconditional branch.
2412 (void)ApplyDebugLocation::CreateEmpty(CGF);
2413 CGF.EmitBlock(NonSPMDBB);
2414 CGF.EmitRuntimeCall(
2415 createNVPTXRuntimeFunction(
2416 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2417 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2418 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002419 } else if (IsInTTDRegion) {
2420 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2421 "region counter must be > 0.");
2422 --GlobalizedRecords.back().RegionCounter;
2423 // Emit the restore function only in the target region.
2424 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002425 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2426 /*DestWidth=*/16, /*Signed=*/0);
2427 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2428 Address(GlobalizedRecords.back().UseSharedMemory,
2429 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2430 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002431 llvm::Value *Args[] = {
2432 llvm::ConstantInt::get(
2433 CGM.Int16Ty,
2434 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2435 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002436 CGF.EmitRuntimeCall(
2437 createNVPTXRuntimeFunction(
2438 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002439 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002440 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002441 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002442 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2443 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2444 I->getSecond().GlobalRecordAddr);
2445 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002446 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002447 }
2448}
2449
Carlo Bertollic6872252016-04-04 15:55:02 +00002450void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2451 const OMPExecutableDirective &D,
2452 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002453 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002454 ArrayRef<llvm::Value *> CapturedVars) {
2455 if (!CGF.HaveInsertPoint())
2456 return;
2457
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002458 Address ZeroAddr = CGF.CreateMemTemp(
2459 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
2460 /*Name*/ ".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002461 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2462 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002463 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002464 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2465 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002466 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002467}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002468
2469void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002470 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002471 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2472 if (!CGF.HaveInsertPoint())
2473 return;
2474
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002475 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002476 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002477 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002478 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002479}
2480
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002481void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002482 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2483 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2484 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002485
2486 // Force inline this outlined function at its call site.
2487 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2488
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002489 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2490 /*DestWidth=*/32, /*Signed=*/1),
2491 ".zero.addr");
2492 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002493 // ThreadId for serialized parallels is 0.
2494 Address ThreadIDAddr = ZeroAddr;
2495 auto &&CodeGen = [this, Fn, CapturedVars, Loc, ZeroAddr, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002496 CodeGenFunction &CGF, PrePostActionTy &Action) {
2497 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002498
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002499 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2500 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2501 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2502 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2503 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2504 };
2505 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2506 PrePostActionTy &) {
2507
2508 RegionCodeGenTy RCG(CodeGen);
2509 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2510 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2511 llvm::Value *Args[] = {RTLoc, ThreadID};
2512
2513 NVPTXActionTy Action(
2514 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2515 Args,
2516 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2517 Args);
2518 RCG.setAction(Action);
2519 RCG(CGF);
2520 };
2521
2522 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2523 PrePostActionTy &Action) {
2524 CGBuilderTy &Bld = CGF.Builder;
2525 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2526 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002527 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2528
2529 // Prepare for parallel region. Indicate the outlined function.
2530 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002531 CGF.EmitRuntimeCall(
2532 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2533 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002534
2535 // Create a private scope that will globalize the arguments
2536 // passed from the outside of the target region.
2537 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2538
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002539 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002540 if (!CapturedVars.empty()) {
2541 // Prepare for parallel region. Indicate the outlined function.
2542 Address SharedArgs =
2543 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2544 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2545
2546 llvm::Value *DataSharingArgs[] = {
2547 SharedArgsPtr,
2548 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2549 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2550 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2551 DataSharingArgs);
2552
2553 // Store variable address in a list of references to pass to workers.
2554 unsigned Idx = 0;
2555 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002556 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2557 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2558 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002559 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002560 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002561 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002562 if (V->getType()->isIntegerTy())
2563 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2564 else
2565 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002566 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2567 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002568 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002569 }
2570 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002571
2572 // Activate workers. This barrier is used by the master to signal
2573 // work for the workers.
2574 syncCTAThreads(CGF);
2575
2576 // OpenMP [2.5, Parallel Construct, p.49]
2577 // There is an implied barrier at the end of a parallel region. After the
2578 // end of a parallel region, only the master thread of the team resumes
2579 // execution of the enclosing task region.
2580 //
2581 // The master waits at this barrier until all workers are done.
2582 syncCTAThreads(CGF);
2583
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002584 if (!CapturedVars.empty())
2585 CGF.EmitRuntimeCall(
2586 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2587
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002588 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002589 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002590 };
2591
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002592 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2593 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002594 if (IsInParallelRegion) {
2595 SeqGen(CGF, Action);
2596 } else if (IsInTargetMasterThreadRegion) {
2597 L0ParallelGen(CGF, Action);
2598 } else {
2599 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002600 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002601 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002602 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002603 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002604 // }
2605 CGBuilderTy &Bld = CGF.Builder;
2606 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002607 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2608 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002609 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002610 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2611 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002613 // There is no need to emit line number for unconditional branch.
2614 (void)ApplyDebugLocation::CreateEmpty(CGF);
2615 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2617 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2618 llvm::Value *PL = CGF.EmitRuntimeCall(
2619 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2620 {RTLoc, ThreadID});
2621 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002622 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002623 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002624 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002625 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002626 // There is no need to emit line number for unconditional branch.
2627 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002628 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002629 L0ParallelGen(CGF, Action);
2630 CGF.EmitBranch(ExitBB);
2631 // There is no need to emit line number for unconditional branch.
2632 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002633 // Emit the continuation block for code after the if.
2634 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2635 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002636 };
2637
Alexey Bataev9ff80832018-04-16 20:16:21 +00002638 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002639 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002640 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002641 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002642 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002643 ThenRCG(CGF);
2644 }
2645}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002646
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002647void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002648 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002649 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2650 // Just call the outlined function to execute the parallel region.
2651 // OutlinedFn(&GTid, &zero, CapturedStruct);
2652 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002653 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002654
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002655 Address ZeroAddr = CGF.CreateMemTemp(CGF.getContext().getIntTypeForBitwidth(
2656 /*DestWidth=*/32, /*Signed=*/1),
2657 ".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002658 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002659 // ThreadId for serialized parallels is 0.
2660 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002661 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, ZeroAddr,
Alexey Bataev8521ff62018-07-25 20:03:01 +00002662 &ThreadIDAddr](CodeGenFunction &CGF,
2663 PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002664 Action.Enter(CGF);
2665
2666 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2667 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2668 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2669 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2670 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2671 };
2672 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2673 PrePostActionTy &) {
2674
2675 RegionCodeGenTy RCG(CodeGen);
2676 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2677 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2678 llvm::Value *Args[] = {RTLoc, ThreadID};
2679
2680 NVPTXActionTy Action(
2681 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2682 Args,
2683 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2684 Args);
2685 RCG.setAction(Action);
2686 RCG(CGF);
2687 };
2688
2689 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002690 // In the worker need to use the real thread id.
2691 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002692 RegionCodeGenTy RCG(CodeGen);
2693 RCG(CGF);
2694 } else {
2695 // If we are not in the target region, it is definitely L2 parallelism or
2696 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2697 // need to check for orphaned directives.
2698 RegionCodeGenTy RCG(SeqGen);
2699 RCG(CGF);
2700 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002701}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002702
Alexey Bataeva3924b52019-01-03 16:25:35 +00002703void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2704 // Always emit simple barriers!
2705 if (!CGF.HaveInsertPoint())
2706 return;
2707 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2708 // This function does not use parameters, so we can emit just default values.
2709 llvm::Value *Args[] = {
2710 llvm::ConstantPointerNull::get(
2711 cast<llvm::PointerType>(getIdentTyPointerTy())),
2712 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002713 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002714 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002715 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002716}
2717
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002718void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2719 SourceLocation Loc,
2720 OpenMPDirectiveKind Kind, bool,
2721 bool) {
2722 // Always emit simple barriers!
2723 if (!CGF.HaveInsertPoint())
2724 return;
2725 // Build call __kmpc_cancel_barrier(loc, thread_id);
2726 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2727 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2728 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002729 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2730 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2731 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002732}
2733
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002734void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2735 CodeGenFunction &CGF, StringRef CriticalName,
2736 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2737 const Expr *Hint) {
2738 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2739 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2740 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2741 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2742 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2743
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002744 // Get the mask of active threads in the warp.
2745 llvm::Value *Mask = CGF.EmitRuntimeCall(
2746 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002747 // Fetch team-local id of the thread.
2748 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2749
2750 // Get the width of the team.
2751 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2752
2753 // Initialize the counter variable for the loop.
2754 QualType Int32Ty =
2755 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2756 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2757 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2758 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2759 /*isInit=*/true);
2760
2761 // Block checks if loop counter exceeds upper bound.
2762 CGF.EmitBlock(LoopBB);
2763 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2764 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2765 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2766
2767 // Block tests which single thread should execute region, and which threads
2768 // should go straight to synchronisation point.
2769 CGF.EmitBlock(TestBB);
2770 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2771 llvm::Value *CmpThreadToCounter =
2772 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2773 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2774
2775 // Block emits the body of the critical region.
2776 CGF.EmitBlock(BodyBB);
2777
2778 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002779 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2780 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002781
2782 // After the body surrounded by the critical region, the single executing
2783 // thread will jump to the synchronisation point.
2784 // Block waits for all threads in current team to finish then increments the
2785 // counter variable and returns to the loop.
2786 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002787 // Reconverge active threads in the warp.
2788 (void)CGF.EmitRuntimeCall(
2789 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002790
2791 llvm::Value *IncCounterVal =
2792 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2793 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2794 CGF.EmitBranch(LoopBB);
2795
2796 // Block that is reached when all threads in the team complete the region.
2797 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2798}
2799
Alexey Bataevb2575932018-01-04 20:18:55 +00002800/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002801static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2802 QualType ValTy, QualType CastTy,
2803 SourceLocation Loc) {
2804 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2805 "Cast type must sized.");
2806 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2807 "Val type must sized.");
2808 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2809 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002810 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002811 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2812 CGF.getContext().getTypeSizeInChars(CastTy))
2813 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2814 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2815 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2816 CastTy->hasSignedIntegerRepresentation());
2817 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002818 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2819 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002820 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2821 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002822}
2823
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002824/// This function creates calls to one of two shuffle functions to copy
2825/// variables between lanes in a warp.
2826static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002827 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002828 QualType ElemType,
2829 llvm::Value *Offset,
2830 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002831 CodeGenModule &CGM = CGF.CGM;
2832 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002833 CGOpenMPRuntimeNVPTX &RT =
2834 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2835
Alexey Bataeva453f362018-03-19 17:53:56 +00002836 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2837 assert(Size.getQuantity() <= 8 &&
2838 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002839
Alexey Bataeva453f362018-03-19 17:53:56 +00002840 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002841 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2842 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2843
2844 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002845 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2846 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2847 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002848 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002849 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002850
Alexey Bataev9ff80832018-04-16 20:16:21 +00002851 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2852 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002853
Alexey Bataeva453f362018-03-19 17:53:56 +00002854 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002855}
2856
Alexey Bataev12c62902018-06-22 19:10:38 +00002857static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2858 Address DestAddr, QualType ElemType,
2859 llvm::Value *Offset, SourceLocation Loc) {
2860 CGBuilderTy &Bld = CGF.Builder;
2861
2862 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2863 // Create the loop over the big sized data.
2864 // ptr = (void*)Elem;
2865 // ptrEnd = (void*) Elem + 1;
2866 // Step = 8;
2867 // while (ptr + Step < ptrEnd)
2868 // shuffle((int64_t)*ptr);
2869 // Step = 4;
2870 // while (ptr + Step < ptrEnd)
2871 // shuffle((int32_t)*ptr);
2872 // ...
2873 Address ElemPtr = DestAddr;
2874 Address Ptr = SrcAddr;
2875 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002876 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002877 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2878 if (Size < CharUnits::fromQuantity(IntSize))
2879 continue;
2880 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2881 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2882 /*Signed=*/1);
2883 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2884 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2885 ElemPtr =
2886 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2887 if (Size.getQuantity() / IntSize > 1) {
2888 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2889 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2890 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2891 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2892 CGF.EmitBlock(PreCondBB);
2893 llvm::PHINode *PhiSrc =
2894 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2895 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2896 llvm::PHINode *PhiDest =
2897 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2898 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2899 Ptr = Address(PhiSrc, Ptr.getAlignment());
2900 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2901 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2902 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2903 Ptr.getPointer(), CGF.VoidPtrTy));
2904 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2905 ThenBB, ExitBB);
2906 CGF.EmitBlock(ThenBB);
2907 llvm::Value *Res = createRuntimeShuffleFunction(
2908 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2909 IntType, Offset, Loc);
2910 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002911 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2912 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002913 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2914 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002915 CGF.EmitBranch(PreCondBB);
2916 CGF.EmitBlock(ExitBB);
2917 } else {
2918 llvm::Value *Res = createRuntimeShuffleFunction(
2919 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2920 IntType, Offset, Loc);
2921 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002922 Ptr = Bld.CreateConstGEP(Ptr, 1);
2923 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002924 }
2925 Size = Size % IntSize;
2926 }
2927}
2928
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002929namespace {
2930enum CopyAction : unsigned {
2931 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2932 // the warp using shuffle instructions.
2933 RemoteLaneToThread,
2934 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2935 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002936 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2937 ThreadToScratchpad,
2938 // ScratchpadToThread: Copy from a scratchpad array in global memory
2939 // containing team-reduced data to a thread's stack.
2940 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002941};
2942} // namespace
2943
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002944struct CopyOptionsTy {
2945 llvm::Value *RemoteLaneOffset;
2946 llvm::Value *ScratchpadIndex;
2947 llvm::Value *ScratchpadWidth;
2948};
2949
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002950/// Emit instructions to copy a Reduce list, which contains partially
2951/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002952static void emitReductionListCopy(
2953 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2954 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2955 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002956
Alexey Bataev9ff80832018-04-16 20:16:21 +00002957 CodeGenModule &CGM = CGF.CGM;
2958 ASTContext &C = CGM.getContext();
2959 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002960
Alexey Bataev9ff80832018-04-16 20:16:21 +00002961 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2962 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2963 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002964
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002965 // Iterates, element-by-element, through the source Reduce list and
2966 // make a copy.
2967 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002968 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002969 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002970 Address SrcElementAddr = Address::invalid();
2971 Address DestElementAddr = Address::invalid();
2972 Address DestElementPtrAddr = Address::invalid();
2973 // Should we shuffle in an element from a remote lane?
2974 bool ShuffleInElement = false;
2975 // Set to true to update the pointer in the dest Reduce list to a
2976 // newly created element.
2977 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002978 // Increment the src or dest pointer to the scratchpad, for each
2979 // new element.
2980 bool IncrScratchpadSrc = false;
2981 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002982
2983 switch (Action) {
2984 case RemoteLaneToThread: {
2985 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002986 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002987 SrcElementAddr = CGF.EmitLoadOfPointer(
2988 SrcElementPtrAddr,
2989 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990
2991 // Step 1.2: Create a temporary to store the element in the destination
2992 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002993 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002994 DestElementAddr =
2995 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
2996 ShuffleInElement = true;
2997 UpdateDestListPtr = true;
2998 break;
2999 }
3000 case ThreadCopy: {
3001 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003002 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003003 SrcElementAddr = CGF.EmitLoadOfPointer(
3004 SrcElementPtrAddr,
3005 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003006
3007 // Step 1.2: Get the address for dest element. The destination
3008 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003009 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003010 DestElementAddr = CGF.EmitLoadOfPointer(
3011 DestElementPtrAddr,
3012 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003013 break;
3014 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003015 case ThreadToScratchpad: {
3016 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003017 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003018 SrcElementAddr = CGF.EmitLoadOfPointer(
3019 SrcElementPtrAddr,
3020 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003021
3022 // Step 1.2: Get the address for dest element:
3023 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003024 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003025 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003026 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003027 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003028 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003029 ScratchPadElemAbsolutePtrVal =
3030 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003031 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3032 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003033 IncrScratchpadDest = true;
3034 break;
3035 }
3036 case ScratchpadToThread: {
3037 // Step 1.1: Get the address for the src element in the scratchpad.
3038 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003039 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003040 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003041 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003042 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003043 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003044 ScratchPadElemAbsolutePtrVal =
3045 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3046 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3047 C.getTypeAlignInChars(Private->getType()));
3048 IncrScratchpadSrc = true;
3049
3050 // Step 1.2: Create a temporary to store the element in the destination
3051 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003052 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003053 DestElementAddr =
3054 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3055 UpdateDestListPtr = true;
3056 break;
3057 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003058 }
3059
3060 // Regardless of src and dest of copy, we emit the load of src
3061 // element as this is required in all directions
3062 SrcElementAddr = Bld.CreateElementBitCast(
3063 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003064 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3065 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003066
3067 // Now that all active lanes have read the element in the
3068 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003069 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003070 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3071 RemoteLaneOffset, Private->getExprLoc());
3072 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003073 switch (CGF.getEvaluationKind(Private->getType())) {
3074 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003075 llvm::Value *Elem =
3076 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3077 Private->getType(), Private->getExprLoc());
3078 // Store the source element value to the dest element address.
3079 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3080 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003081 break;
3082 }
3083 case TEK_Complex: {
3084 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3085 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3086 Private->getExprLoc());
3087 CGF.EmitStoreOfComplex(
3088 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3089 /*isInit=*/false);
3090 break;
3091 }
3092 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003093 CGF.EmitAggregateCopy(
3094 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3095 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3096 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003097 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003098 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003099 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003100
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003101 // Step 3.1: Modify reference in dest Reduce list as needed.
3102 // Modifying the reference in Reduce list to point to the newly
3103 // created element. The element is live in the current function
3104 // scope and that of functions it invokes (i.e., reduce_function).
3105 // RemoteReduceData[i] = (void*)&RemoteElem
3106 if (UpdateDestListPtr) {
3107 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3108 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3109 DestElementPtrAddr, /*Volatile=*/false,
3110 C.VoidPtrTy);
3111 }
3112
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003113 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3114 // address of the next element in scratchpad memory, unless we're currently
3115 // processing the last one. Memory alignment is also taken care of here.
3116 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3117 llvm::Value *ScratchpadBasePtr =
3118 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003119 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3120 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003121 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003122 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003123
3124 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003125 ScratchpadBasePtr = Bld.CreateNUWSub(
3126 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3127 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003128 ScratchpadBasePtr,
3129 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003130 ScratchpadBasePtr = Bld.CreateNUWAdd(
3131 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3132 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003133 ScratchpadBasePtr,
3134 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3135
3136 if (IncrScratchpadDest)
3137 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3138 else /* IncrScratchpadSrc = true */
3139 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3140 }
3141
Alexey Bataev9ff80832018-04-16 20:16:21 +00003142 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003143 }
3144}
3145
3146/// This function emits a helper that gathers Reduce lists from the first
3147/// lane of every active warp to lanes in the first warp.
3148///
3149/// void inter_warp_copy_func(void* reduce_data, num_warps)
3150/// shared smem[warp_size];
3151/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003152/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003153/// If (I am the first lane in each warp)
3154/// Copy my local D to smem[warp_id]
3155/// sync
3156/// if (I am the first warp)
3157/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003158static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3159 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003160 QualType ReductionArrayTy,
3161 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003162 ASTContext &C = CGM.getContext();
3163 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003164
3165 // ReduceList: thread local Reduce list.
3166 // At the stage of the computation when this function is called, partially
3167 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003168 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3169 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003170 // NumWarps: number of warps active in the parallel region. This could
3171 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003172 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003173 C.getIntTypeForBitwidth(32, /* Signed */ true),
3174 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003175 FunctionArgList Args;
3176 Args.push_back(&ReduceListArg);
3177 Args.push_back(&NumWarpsArg);
3178
Alexey Bataev9ff80832018-04-16 20:16:21 +00003179 const CGFunctionInfo &CGFI =
3180 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003181 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3182 llvm::GlobalValue::InternalLinkage,
3183 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003184 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003185 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003186 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003187 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003188
Alexey Bataev9ff80832018-04-16 20:16:21 +00003189 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003190
3191 // This array is used as a medium to transfer, one reduce element at a time,
3192 // the data from the first lane of every warp to lanes in the first warp
3193 // in order to perform the final step of a reduction in a parallel region
3194 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3195 // for reduced latency, as well as to have a distinct copy for concurrently
3196 // executing target regions. The array is declared with common linkage so
3197 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003198 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003199 "__openmp_nvptx_data_transfer_temporary_storage";
3200 llvm::GlobalVariable *TransferMedium =
3201 M.getGlobalVariable(TransferMediumName);
3202 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003203 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003204 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3205 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003206 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207 llvm::Constant::getNullValue(Ty), TransferMediumName,
3208 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3209 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003210 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003211 }
3212
3213 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003214 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003215 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003216 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003217 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003218 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003219
3220 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3221 Address LocalReduceList(
3222 Bld.CreatePointerBitCastOrAddrSpaceCast(
3223 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003224 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003225 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3226 CGF.getPointerAlign());
3227
3228 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003229 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003230 //
3231 // Warp master copies reduce element to transfer medium in __shared__
3232 // memory.
3233 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003234 unsigned RealTySize =
3235 C.getTypeSizeInChars(Private->getType())
3236 .alignTo(C.getTypeAlignInChars(Private->getType()))
3237 .getQuantity();
3238 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3239 unsigned NumIters = RealTySize / TySize;
3240 if (NumIters == 0)
3241 continue;
3242 QualType CType = C.getIntTypeForBitwidth(
3243 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3244 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3245 CharUnits Align = CharUnits::fromQuantity(TySize);
3246 llvm::Value *Cnt = nullptr;
3247 Address CntAddr = Address::invalid();
3248 llvm::BasicBlock *PrecondBB = nullptr;
3249 llvm::BasicBlock *ExitBB = nullptr;
3250 if (NumIters > 1) {
3251 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3252 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3253 /*Volatile=*/false, C.IntTy);
3254 PrecondBB = CGF.createBasicBlock("precond");
3255 ExitBB = CGF.createBasicBlock("exit");
3256 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3257 // There is no need to emit line number for unconditional branch.
3258 (void)ApplyDebugLocation::CreateEmpty(CGF);
3259 CGF.EmitBlock(PrecondBB);
3260 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3261 llvm::Value *Cmp =
3262 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3263 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3264 CGF.EmitBlock(BodyBB);
3265 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003266 // kmpc_barrier.
3267 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3268 /*EmitChecks=*/false,
3269 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003270 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3271 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3272 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003273
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003274 // if (lane_id == 0)
3275 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3276 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3277 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003278
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003279 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003280 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003281 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3282 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3283 // elemptr = ((CopyType*)(elemptrptr)) + I
3284 Address ElemPtr = Address(ElemPtrPtr, Align);
3285 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3286 if (NumIters > 1) {
3287 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3288 ElemPtr.getAlignment());
3289 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003290
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003291 // Get pointer to location in transfer medium.
3292 // MediumPtr = &medium[warp_id]
3293 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3294 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3295 Address MediumPtr(MediumPtrVal, Align);
3296 // Casting to actual data type.
3297 // MediumPtr = (CopyType*)MediumPtrAddr;
3298 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003299
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003300 // elem = *elemptr
3301 //*MediumPtr = elem
3302 llvm::Value *Elem =
3303 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003304 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003305 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003306
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003307 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003308
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003309 CGF.EmitBlock(ElseBB);
3310 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003311
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003312 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevae51b962018-12-14 21:00:58 +00003314 // kmpc_barrier.
3315 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3316 /*EmitChecks=*/false,
3317 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003318
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003319 //
3320 // Warp 0 copies reduce element from transfer medium.
3321 //
3322 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3323 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3324 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003325
Alexey Bataevae51b962018-12-14 21:00:58 +00003326 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3327 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3328 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3329
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003330 // Up to 32 threads in warp 0 are active.
3331 llvm::Value *IsActiveThread =
3332 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3333 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003334
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003335 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003336
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003337 // SrcMediumPtr = &medium[tid]
3338 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3339 TransferMedium,
3340 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3341 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3342 // SrcMediumVal = *SrcMediumPtr;
3343 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003344
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003345 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003346 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003347 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3348 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3349 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3350 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3351 if (NumIters > 1) {
3352 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3353 TargetElemPtr.getAlignment());
3354 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003355
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003356 // *TargetElemPtr = SrcMediumVal;
3357 llvm::Value *SrcMediumValue =
3358 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003359 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003360 CType);
3361 Bld.CreateBr(W0MergeBB);
3362
3363 CGF.EmitBlock(W0ElseBB);
3364 Bld.CreateBr(W0MergeBB);
3365
3366 CGF.EmitBlock(W0MergeBB);
3367
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003368 if (NumIters > 1) {
3369 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3370 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3371 CGF.EmitBranch(PrecondBB);
3372 (void)ApplyDebugLocation::CreateEmpty(CGF);
3373 CGF.EmitBlock(ExitBB);
3374 }
3375 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003376 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003377 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003378 }
3379
3380 CGF.FinishFunction();
3381 return Fn;
3382}
3383
3384/// Emit a helper that reduces data across two OpenMP threads (lanes)
3385/// in the same warp. It uses shuffle instructions to copy over data from
3386/// a remote lane's stack. The reduction algorithm performed is specified
3387/// by the fourth parameter.
3388///
3389/// Algorithm Versions.
3390/// Full Warp Reduce (argument value 0):
3391/// This algorithm assumes that all 32 lanes are active and gathers
3392/// data from these 32 lanes, producing a single resultant value.
3393/// Contiguous Partial Warp Reduce (argument value 1):
3394/// This algorithm assumes that only a *contiguous* subset of lanes
3395/// are active. This happens for the last warp in a parallel region
3396/// when the user specified num_threads is not an integer multiple of
3397/// 32. This contiguous subset always starts with the zeroth lane.
3398/// Partial Warp Reduce (argument value 2):
3399/// This algorithm gathers data from any number of lanes at any position.
3400/// All reduced values are stored in the lowest possible lane. The set
3401/// of problems every algorithm addresses is a super set of those
3402/// addressable by algorithms with a lower version number. Overhead
3403/// increases as algorithm version increases.
3404///
3405/// Terminology
3406/// Reduce element:
3407/// Reduce element refers to the individual data field with primitive
3408/// data types to be combined and reduced across threads.
3409/// Reduce list:
3410/// Reduce list refers to a collection of local, thread-private
3411/// reduce elements.
3412/// Remote Reduce list:
3413/// Remote Reduce list refers to a collection of remote (relative to
3414/// the current thread) reduce elements.
3415///
3416/// We distinguish between three states of threads that are important to
3417/// the implementation of this function.
3418/// Alive threads:
3419/// Threads in a warp executing the SIMT instruction, as distinguished from
3420/// threads that are inactive due to divergent control flow.
3421/// Active threads:
3422/// The minimal set of threads that has to be alive upon entry to this
3423/// function. The computation is correct iff active threads are alive.
3424/// Some threads are alive but they are not active because they do not
3425/// contribute to the computation in any useful manner. Turning them off
3426/// may introduce control flow overheads without any tangible benefits.
3427/// Effective threads:
3428/// In order to comply with the argument requirements of the shuffle
3429/// function, we must keep all lanes holding data alive. But at most
3430/// half of them perform value aggregation; we refer to this half of
3431/// threads as effective. The other half is simply handing off their
3432/// data.
3433///
3434/// Procedure
3435/// Value shuffle:
3436/// In this step active threads transfer data from higher lane positions
3437/// in the warp to lower lane positions, creating Remote Reduce list.
3438/// Value aggregation:
3439/// In this step, effective threads combine their thread local Reduce list
3440/// with Remote Reduce list and store the result in the thread local
3441/// Reduce list.
3442/// Value copy:
3443/// In this step, we deal with the assumption made by algorithm 2
3444/// (i.e. contiguity assumption). When we have an odd number of lanes
3445/// active, say 2k+1, only k threads will be effective and therefore k
3446/// new values will be produced. However, the Reduce list owned by the
3447/// (2k+1)th thread is ignored in the value aggregation. Therefore
3448/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3449/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003450static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003451 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003452 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003453 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003454
3455 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003456 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3457 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003458 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003459 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3460 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003461 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003462 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3463 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003464 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003465 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3466 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003467 FunctionArgList Args;
3468 Args.push_back(&ReduceListArg);
3469 Args.push_back(&LaneIDArg);
3470 Args.push_back(&RemoteLaneOffsetArg);
3471 Args.push_back(&AlgoVerArg);
3472
Alexey Bataev9ff80832018-04-16 20:16:21 +00003473 const CGFunctionInfo &CGFI =
3474 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003475 auto *Fn = llvm::Function::Create(
3476 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3477 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003478 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003479 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003480 if (CGM.getLangOpts().Optimize) {
3481 Fn->removeFnAttr(llvm::Attribute::NoInline);
3482 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3483 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3484 }
3485
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003486 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003487 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003488
Alexey Bataev9ff80832018-04-16 20:16:21 +00003489 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003490
3491 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3492 Address LocalReduceList(
3493 Bld.CreatePointerBitCastOrAddrSpaceCast(
3494 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3495 C.VoidPtrTy, SourceLocation()),
3496 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3497 CGF.getPointerAlign());
3498
3499 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3500 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3501 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3502
3503 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3504 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3505 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3506
3507 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3508 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3509 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3510
3511 // Create a local thread-private variable to host the Reduce list
3512 // from a remote lane.
3513 Address RemoteReduceList =
3514 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3515
3516 // This loop iterates through the list of reduce elements and copies,
3517 // element by element, from a remote lane in the warp to RemoteReduceList,
3518 // hosted on the thread's stack.
3519 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3520 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003521 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3522 /*ScratchpadIndex=*/nullptr,
3523 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003524
3525 // The actions to be performed on the Remote Reduce list is dependent
3526 // on the algorithm version.
3527 //
3528 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3529 // LaneId % 2 == 0 && Offset > 0):
3530 // do the reduction value aggregation
3531 //
3532 // The thread local variable Reduce list is mutated in place to host the
3533 // reduced data, which is the aggregated value produced from local and
3534 // remote lanes.
3535 //
3536 // Note that AlgoVer is expected to be a constant integer known at compile
3537 // time.
3538 // When AlgoVer==0, the first conjunction evaluates to true, making
3539 // the entire predicate true during compile time.
3540 // When AlgoVer==1, the second conjunction has only the second part to be
3541 // evaluated during runtime. Other conjunctions evaluates to false
3542 // during compile time.
3543 // When AlgoVer==2, the third conjunction has only the second part to be
3544 // evaluated during runtime. Other conjunctions evaluates to false
3545 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003546 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003547
Alexey Bataev9ff80832018-04-16 20:16:21 +00003548 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3549 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003550 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3551
Alexey Bataev9ff80832018-04-16 20:16:21 +00003552 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3553 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3554 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003555 CondAlgo2 = Bld.CreateAnd(
3556 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3557
Alexey Bataev9ff80832018-04-16 20:16:21 +00003558 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003559 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3560
3561 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3562 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3563 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3564 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3565
3566 CGF.EmitBlock(ThenBB);
3567 // reduce_function(LocalReduceList, RemoteReduceList)
3568 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3569 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3570 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3571 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003572 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3573 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003574 Bld.CreateBr(MergeBB);
3575
3576 CGF.EmitBlock(ElseBB);
3577 Bld.CreateBr(MergeBB);
3578
3579 CGF.EmitBlock(MergeBB);
3580
3581 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3582 // Reduce list.
3583 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003584 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003585 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3586
3587 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3588 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3589 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3590 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3591
3592 CGF.EmitBlock(CpyThenBB);
3593 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3594 RemoteReduceList, LocalReduceList);
3595 Bld.CreateBr(CpyMergeBB);
3596
3597 CGF.EmitBlock(CpyElseBB);
3598 Bld.CreateBr(CpyMergeBB);
3599
3600 CGF.EmitBlock(CpyMergeBB);
3601
3602 CGF.FinishFunction();
3603 return Fn;
3604}
3605
Alexey Bataev8061acd2019-02-20 16:36:22 +00003606/// This function emits a helper that copies all the reduction variables from
3607/// the team into the provided global buffer for the reduction variables.
3608///
3609/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3610/// For all data entries D in reduce_data:
3611/// Copy local D to buffer.D[Idx]
3612static llvm::Value *emitListToGlobalCopyFunction(
3613 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3614 QualType ReductionArrayTy, SourceLocation Loc,
3615 const RecordDecl *TeamReductionRec,
3616 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3617 &VarFieldMap) {
3618 ASTContext &C = CGM.getContext();
3619
3620 // Buffer: global reduction buffer.
3621 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3622 C.VoidPtrTy, ImplicitParamDecl::Other);
3623 // Idx: index of the buffer.
3624 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3625 ImplicitParamDecl::Other);
3626 // ReduceList: thread local Reduce list.
3627 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3628 C.VoidPtrTy, ImplicitParamDecl::Other);
3629 FunctionArgList Args;
3630 Args.push_back(&BufferArg);
3631 Args.push_back(&IdxArg);
3632 Args.push_back(&ReduceListArg);
3633
3634 const CGFunctionInfo &CGFI =
3635 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3636 auto *Fn = llvm::Function::Create(
3637 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3638 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3639 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3640 Fn->setDoesNotRecurse();
3641 CodeGenFunction CGF(CGM);
3642 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3643
3644 CGBuilderTy &Bld = CGF.Builder;
3645
3646 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3647 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3648 Address LocalReduceList(
3649 Bld.CreatePointerBitCastOrAddrSpaceCast(
3650 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3651 C.VoidPtrTy, Loc),
3652 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3653 CGF.getPointerAlign());
3654 QualType StaticTy = C.getRecordType(TeamReductionRec);
3655 llvm::Type *LLVMReductionsBufferTy =
3656 CGM.getTypes().ConvertTypeForMem(StaticTy);
3657 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3658 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3659 LLVMReductionsBufferTy->getPointerTo());
3660 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3661 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3662 /*Volatile=*/false, C.IntTy,
3663 Loc)};
3664 unsigned Idx = 0;
3665 for (const Expr *Private : Privates) {
3666 // Reduce element = LocalReduceList[i]
3667 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3668 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3669 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3670 // elemptr = ((CopyType*)(elemptrptr)) + I
3671 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3672 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3673 Address ElemPtr =
3674 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3675 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3676 // Global = Buffer.VD[Idx];
3677 const FieldDecl *FD = VarFieldMap.lookup(VD);
3678 LValue GlobLVal = CGF.EmitLValueForField(
3679 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3680 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3681 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3682 switch (CGF.getEvaluationKind(Private->getType())) {
3683 case TEK_Scalar: {
3684 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3685 Private->getType(), Loc);
3686 CGF.EmitStoreOfScalar(V, GlobLVal);
3687 break;
3688 }
3689 case TEK_Complex: {
3690 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3691 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3692 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3693 break;
3694 }
3695 case TEK_Aggregate:
3696 CGF.EmitAggregateCopy(GlobLVal,
3697 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3698 Private->getType(), AggValueSlot::DoesNotOverlap);
3699 break;
3700 }
3701 ++Idx;
3702 }
3703
3704 CGF.FinishFunction();
3705 return Fn;
3706}
3707
3708/// This function emits a helper that reduces all the reduction variables from
3709/// the team into the provided global buffer for the reduction variables.
3710///
3711/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3712/// void *GlobPtrs[];
3713/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3714/// ...
3715/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3716/// reduce_function(GlobPtrs, reduce_data);
3717static llvm::Value *emitListToGlobalReduceFunction(
3718 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3719 QualType ReductionArrayTy, SourceLocation Loc,
3720 const RecordDecl *TeamReductionRec,
3721 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3722 &VarFieldMap,
3723 llvm::Function *ReduceFn) {
3724 ASTContext &C = CGM.getContext();
3725
3726 // Buffer: global reduction buffer.
3727 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3728 C.VoidPtrTy, ImplicitParamDecl::Other);
3729 // Idx: index of the buffer.
3730 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3731 ImplicitParamDecl::Other);
3732 // ReduceList: thread local Reduce list.
3733 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3734 C.VoidPtrTy, ImplicitParamDecl::Other);
3735 FunctionArgList Args;
3736 Args.push_back(&BufferArg);
3737 Args.push_back(&IdxArg);
3738 Args.push_back(&ReduceListArg);
3739
3740 const CGFunctionInfo &CGFI =
3741 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3742 auto *Fn = llvm::Function::Create(
3743 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3744 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3745 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3746 Fn->setDoesNotRecurse();
3747 CodeGenFunction CGF(CGM);
3748 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3749
3750 CGBuilderTy &Bld = CGF.Builder;
3751
3752 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3753 QualType StaticTy = C.getRecordType(TeamReductionRec);
3754 llvm::Type *LLVMReductionsBufferTy =
3755 CGM.getTypes().ConvertTypeForMem(StaticTy);
3756 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3757 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3758 LLVMReductionsBufferTy->getPointerTo());
3759
3760 // 1. Build a list of reduction variables.
3761 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3762 Address ReductionList =
3763 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3764 auto IPriv = Privates.begin();
3765 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3766 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3767 /*Volatile=*/false, C.IntTy,
3768 Loc)};
3769 unsigned Idx = 0;
3770 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3771 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3772 // Global = Buffer.VD[Idx];
3773 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3774 const FieldDecl *FD = VarFieldMap.lookup(VD);
3775 LValue GlobLVal = CGF.EmitLValueForField(
3776 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3777 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3778 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3779 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3780 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3781 // Store array size.
3782 ++Idx;
3783 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3784 llvm::Value *Size = CGF.Builder.CreateIntCast(
3785 CGF.getVLASize(
3786 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3787 .NumElts,
3788 CGF.SizeTy, /*isSigned=*/false);
3789 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3790 Elem);
3791 }
3792 }
3793
3794 // Call reduce_function(GlobalReduceList, ReduceList)
3795 llvm::Value *GlobalReduceList =
3796 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3797 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3798 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3799 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3800 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3801 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3802 CGF.FinishFunction();
3803 return Fn;
3804}
3805
3806/// This function emits a helper that copies all the reduction variables from
3807/// the team into the provided global buffer for the reduction variables.
3808///
3809/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3810/// For all data entries D in reduce_data:
3811/// Copy buffer.D[Idx] to local D;
3812static llvm::Value *emitGlobalToListCopyFunction(
3813 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3814 QualType ReductionArrayTy, SourceLocation Loc,
3815 const RecordDecl *TeamReductionRec,
3816 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3817 &VarFieldMap) {
3818 ASTContext &C = CGM.getContext();
3819
3820 // Buffer: global reduction buffer.
3821 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3822 C.VoidPtrTy, ImplicitParamDecl::Other);
3823 // Idx: index of the buffer.
3824 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3825 ImplicitParamDecl::Other);
3826 // ReduceList: thread local Reduce list.
3827 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3828 C.VoidPtrTy, ImplicitParamDecl::Other);
3829 FunctionArgList Args;
3830 Args.push_back(&BufferArg);
3831 Args.push_back(&IdxArg);
3832 Args.push_back(&ReduceListArg);
3833
3834 const CGFunctionInfo &CGFI =
3835 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3836 auto *Fn = llvm::Function::Create(
3837 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3838 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3839 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3840 Fn->setDoesNotRecurse();
3841 CodeGenFunction CGF(CGM);
3842 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3843
3844 CGBuilderTy &Bld = CGF.Builder;
3845
3846 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3847 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3848 Address LocalReduceList(
3849 Bld.CreatePointerBitCastOrAddrSpaceCast(
3850 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3851 C.VoidPtrTy, Loc),
3852 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3853 CGF.getPointerAlign());
3854 QualType StaticTy = C.getRecordType(TeamReductionRec);
3855 llvm::Type *LLVMReductionsBufferTy =
3856 CGM.getTypes().ConvertTypeForMem(StaticTy);
3857 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3858 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3859 LLVMReductionsBufferTy->getPointerTo());
3860
3861 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3862 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3863 /*Volatile=*/false, C.IntTy,
3864 Loc)};
3865 unsigned Idx = 0;
3866 for (const Expr *Private : Privates) {
3867 // Reduce element = LocalReduceList[i]
3868 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3869 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3870 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3871 // elemptr = ((CopyType*)(elemptrptr)) + I
3872 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3873 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3874 Address ElemPtr =
3875 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3876 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3877 // Global = Buffer.VD[Idx];
3878 const FieldDecl *FD = VarFieldMap.lookup(VD);
3879 LValue GlobLVal = CGF.EmitLValueForField(
3880 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3881 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3882 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3883 switch (CGF.getEvaluationKind(Private->getType())) {
3884 case TEK_Scalar: {
3885 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3886 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3887 break;
3888 }
3889 case TEK_Complex: {
3890 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3891 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3892 /*isInit=*/false);
3893 break;
3894 }
3895 case TEK_Aggregate:
3896 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3897 GlobLVal, Private->getType(),
3898 AggValueSlot::DoesNotOverlap);
3899 break;
3900 }
3901 ++Idx;
3902 }
3903
3904 CGF.FinishFunction();
3905 return Fn;
3906}
3907
3908/// This function emits a helper that reduces all the reduction variables from
3909/// the team into the provided global buffer for the reduction variables.
3910///
3911/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3912/// void *GlobPtrs[];
3913/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3914/// ...
3915/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3916/// reduce_function(reduce_data, GlobPtrs);
3917static llvm::Value *emitGlobalToListReduceFunction(
3918 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3919 QualType ReductionArrayTy, SourceLocation Loc,
3920 const RecordDecl *TeamReductionRec,
3921 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3922 &VarFieldMap,
3923 llvm::Function *ReduceFn) {
3924 ASTContext &C = CGM.getContext();
3925
3926 // Buffer: global reduction buffer.
3927 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3928 C.VoidPtrTy, ImplicitParamDecl::Other);
3929 // Idx: index of the buffer.
3930 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3931 ImplicitParamDecl::Other);
3932 // ReduceList: thread local Reduce list.
3933 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3934 C.VoidPtrTy, ImplicitParamDecl::Other);
3935 FunctionArgList Args;
3936 Args.push_back(&BufferArg);
3937 Args.push_back(&IdxArg);
3938 Args.push_back(&ReduceListArg);
3939
3940 const CGFunctionInfo &CGFI =
3941 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3942 auto *Fn = llvm::Function::Create(
3943 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3944 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3945 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3946 Fn->setDoesNotRecurse();
3947 CodeGenFunction CGF(CGM);
3948 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3949
3950 CGBuilderTy &Bld = CGF.Builder;
3951
3952 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3953 QualType StaticTy = C.getRecordType(TeamReductionRec);
3954 llvm::Type *LLVMReductionsBufferTy =
3955 CGM.getTypes().ConvertTypeForMem(StaticTy);
3956 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3957 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3958 LLVMReductionsBufferTy->getPointerTo());
3959
3960 // 1. Build a list of reduction variables.
3961 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3962 Address ReductionList =
3963 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3964 auto IPriv = Privates.begin();
3965 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3966 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3967 /*Volatile=*/false, C.IntTy,
3968 Loc)};
3969 unsigned Idx = 0;
3970 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3971 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3972 // Global = Buffer.VD[Idx];
3973 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3974 const FieldDecl *FD = VarFieldMap.lookup(VD);
3975 LValue GlobLVal = CGF.EmitLValueForField(
3976 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3977 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3978 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3979 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3980 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3981 // Store array size.
3982 ++Idx;
3983 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3984 llvm::Value *Size = CGF.Builder.CreateIntCast(
3985 CGF.getVLASize(
3986 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3987 .NumElts,
3988 CGF.SizeTy, /*isSigned=*/false);
3989 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3990 Elem);
3991 }
3992 }
3993
3994 // Call reduce_function(ReduceList, GlobalReduceList)
3995 llvm::Value *GlobalReduceList =
3996 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3997 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3998 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3999 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4000 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4001 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4002 CGF.FinishFunction();
4003 return Fn;
4004}
4005
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004006///
4007/// Design of OpenMP reductions on the GPU
4008///
4009/// Consider a typical OpenMP program with one or more reduction
4010/// clauses:
4011///
4012/// float foo;
4013/// double bar;
4014/// #pragma omp target teams distribute parallel for \
4015/// reduction(+:foo) reduction(*:bar)
4016/// for (int i = 0; i < N; i++) {
4017/// foo += A[i]; bar *= B[i];
4018/// }
4019///
4020/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4021/// all teams. In our OpenMP implementation on the NVPTX device an
4022/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4023/// within a team are mapped to CUDA threads within a threadblock.
4024/// Our goal is to efficiently aggregate values across all OpenMP
4025/// threads such that:
4026///
4027/// - the compiler and runtime are logically concise, and
4028/// - the reduction is performed efficiently in a hierarchical
4029/// manner as follows: within OpenMP threads in the same warp,
4030/// across warps in a threadblock, and finally across teams on
4031/// the NVPTX device.
4032///
4033/// Introduction to Decoupling
4034///
4035/// We would like to decouple the compiler and the runtime so that the
4036/// latter is ignorant of the reduction variables (number, data types)
4037/// and the reduction operators. This allows a simpler interface
4038/// and implementation while still attaining good performance.
4039///
4040/// Pseudocode for the aforementioned OpenMP program generated by the
4041/// compiler is as follows:
4042///
4043/// 1. Create private copies of reduction variables on each OpenMP
4044/// thread: 'foo_private', 'bar_private'
4045/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4046/// to it and writes the result in 'foo_private' and 'bar_private'
4047/// respectively.
4048/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4049/// and store the result on the team master:
4050///
Alexey Bataev8e009032019-01-04 17:25:09 +00004051/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004052/// reduceData, shuffleReduceFn, interWarpCpyFn)
4053///
4054/// where:
4055/// struct ReduceData {
4056/// double *foo;
4057/// double *bar;
4058/// } reduceData
4059/// reduceData.foo = &foo_private
4060/// reduceData.bar = &bar_private
4061///
4062/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4063/// auxiliary functions generated by the compiler that operate on
4064/// variables of type 'ReduceData'. They aid the runtime perform
4065/// algorithmic steps in a data agnostic manner.
4066///
4067/// 'shuffleReduceFn' is a pointer to a function that reduces data
4068/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4069/// same warp. It takes the following arguments as input:
4070///
4071/// a. variable of type 'ReduceData' on the calling lane,
4072/// b. its lane_id,
4073/// c. an offset relative to the current lane_id to generate a
4074/// remote_lane_id. The remote lane contains the second
4075/// variable of type 'ReduceData' that is to be reduced.
4076/// d. an algorithm version parameter determining which reduction
4077/// algorithm to use.
4078///
4079/// 'shuffleReduceFn' retrieves data from the remote lane using
4080/// efficient GPU shuffle intrinsics and reduces, using the
4081/// algorithm specified by the 4th parameter, the two operands
4082/// element-wise. The result is written to the first operand.
4083///
4084/// Different reduction algorithms are implemented in different
4085/// runtime functions, all calling 'shuffleReduceFn' to perform
4086/// the essential reduction step. Therefore, based on the 4th
4087/// parameter, this function behaves slightly differently to
4088/// cooperate with the runtime to ensure correctness under
4089/// different circumstances.
4090///
4091/// 'InterWarpCpyFn' is a pointer to a function that transfers
4092/// reduced variables across warps. It tunnels, through CUDA
4093/// shared memory, the thread-private data of type 'ReduceData'
4094/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004095/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4096/// The last team writes the global reduced value to memory.
4097///
4098/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4099/// reduceData, shuffleReduceFn, interWarpCpyFn,
4100/// scratchpadCopyFn, loadAndReduceFn)
4101///
4102/// 'scratchpadCopyFn' is a helper that stores reduced
4103/// data from the team master to a scratchpad array in
4104/// global memory.
4105///
4106/// 'loadAndReduceFn' is a helper that loads data from
4107/// the scratchpad array and reduces it with the input
4108/// operand.
4109///
4110/// These compiler generated functions hide address
4111/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004112/// 5. if ret == 1:
4113/// The team master of the last team stores the reduced
4114/// result to the globals in memory.
4115/// foo += reduceData.foo; bar *= reduceData.bar
4116///
4117///
4118/// Warp Reduction Algorithms
4119///
4120/// On the warp level, we have three algorithms implemented in the
4121/// OpenMP runtime depending on the number of active lanes:
4122///
4123/// Full Warp Reduction
4124///
4125/// The reduce algorithm within a warp where all lanes are active
4126/// is implemented in the runtime as follows:
4127///
4128/// full_warp_reduce(void *reduce_data,
4129/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4130/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4131/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4132/// }
4133///
4134/// The algorithm completes in log(2, WARPSIZE) steps.
4135///
4136/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4137/// not used therefore we save instructions by not retrieving lane_id
4138/// from the corresponding special registers. The 4th parameter, which
4139/// represents the version of the algorithm being used, is set to 0 to
4140/// signify full warp reduction.
4141///
4142/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4143///
4144/// #reduce_elem refers to an element in the local lane's data structure
4145/// #remote_elem is retrieved from a remote lane
4146/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4147/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4148///
4149/// Contiguous Partial Warp Reduction
4150///
4151/// This reduce algorithm is used within a warp where only the first
4152/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4153/// number of OpenMP threads in a parallel region is not a multiple of
4154/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4155///
4156/// void
4157/// contiguous_partial_reduce(void *reduce_data,
4158/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4159/// int size, int lane_id) {
4160/// int curr_size;
4161/// int offset;
4162/// curr_size = size;
4163/// mask = curr_size/2;
4164/// while (offset>0) {
4165/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4166/// curr_size = (curr_size+1)/2;
4167/// offset = curr_size/2;
4168/// }
4169/// }
4170///
4171/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4172///
4173/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4174/// if (lane_id < offset)
4175/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4176/// else
4177/// reduce_elem = remote_elem
4178///
4179/// This algorithm assumes that the data to be reduced are located in a
4180/// contiguous subset of lanes starting from the first. When there is
4181/// an odd number of active lanes, the data in the last lane is not
4182/// aggregated with any other lane's dat but is instead copied over.
4183///
4184/// Dispersed Partial Warp Reduction
4185///
4186/// This algorithm is used within a warp when any discontiguous subset of
4187/// lanes are active. It is used to implement the reduction operation
4188/// across lanes in an OpenMP simd region or in a nested parallel region.
4189///
4190/// void
4191/// dispersed_partial_reduce(void *reduce_data,
4192/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4193/// int size, remote_id;
4194/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4195/// do {
4196/// remote_id = next_active_lane_id_right_after_me();
4197/// # the above function returns 0 of no active lane
4198/// # is present right after the current lane.
4199/// size = number_of_active_lanes_in_this_warp();
4200/// logical_lane_id /= 2;
4201/// ShuffleReduceFn(reduce_data, logical_lane_id,
4202/// remote_id-1-threadIdx.x, 2);
4203/// } while (logical_lane_id % 2 == 0 && size > 1);
4204/// }
4205///
4206/// There is no assumption made about the initial state of the reduction.
4207/// Any number of lanes (>=1) could be active at any position. The reduction
4208/// result is returned in the first active lane.
4209///
4210/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4211///
4212/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4213/// if (lane_id % 2 == 0 && offset > 0)
4214/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4215/// else
4216/// reduce_elem = remote_elem
4217///
4218///
4219/// Intra-Team Reduction
4220///
4221/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004222/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004223/// threads in a team. It first reduces within a warp using the
4224/// aforementioned algorithms. We then proceed to gather all such
4225/// reduced values at the first warp.
4226///
4227/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4228/// data from each of the "warp master" (zeroth lane of each warp, where
4229/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4230/// a mathematical sense) the problem of reduction across warp masters in
4231/// a block to the problem of warp reduction.
4232///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004233///
4234/// Inter-Team Reduction
4235///
4236/// Once a team has reduced its data to a single value, it is stored in
4237/// a global scratchpad array. Since each team has a distinct slot, this
4238/// can be done without locking.
4239///
4240/// The last team to write to the scratchpad array proceeds to reduce the
4241/// scratchpad array. One or more workers in the last team use the helper
4242/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4243/// the k'th worker reduces every k'th element.
4244///
Alexey Bataev8e009032019-01-04 17:25:09 +00004245/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004246/// reduce across workers and compute a globally reduced value.
4247///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004248void CGOpenMPRuntimeNVPTX::emitReduction(
4249 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4250 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4251 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4252 if (!CGF.HaveInsertPoint())
4253 return;
4254
4255 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004256#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004257 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004258#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004259
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004260 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004261 assert(!TeamsReduction && !ParallelReduction &&
4262 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004263 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4264 ReductionOps, Options);
4265 return;
4266 }
4267
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004268 assert((TeamsReduction || ParallelReduction) &&
4269 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004270
Alexey Bataeva1166022018-11-27 21:24:54 +00004271 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004272 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004273 // or
4274 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004275 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004276 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004277
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004278 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004279 ASTContext &C = CGM.getContext();
4280 // 1. Build a list of reduction variables.
4281 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4282 auto Size = RHSExprs.size();
4283 for (const Expr *E : Privates) {
4284 if (E->getType()->isVariablyModifiedType())
4285 // Reserve place for array size.
4286 ++Size;
4287 }
4288 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4289 QualType ReductionArrayTy =
Richard Smith772e2662019-10-04 01:25:59 +00004290 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
Alexey Bataev8061acd2019-02-20 16:36:22 +00004291 /*IndexTypeQuals=*/0);
4292 Address ReductionList =
4293 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4294 auto IPriv = Privates.begin();
4295 unsigned Idx = 0;
4296 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4297 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4298 CGF.Builder.CreateStore(
4299 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4300 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4301 Elem);
4302 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4303 // Store array size.
4304 ++Idx;
4305 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4306 llvm::Value *Size = CGF.Builder.CreateIntCast(
4307 CGF.getVLASize(
4308 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4309 .NumElts,
4310 CGF.SizeTy, /*isSigned=*/false);
4311 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4312 Elem);
4313 }
4314 }
4315
4316 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4317 ReductionList.getPointer(), CGF.VoidPtrTy);
4318 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004319 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4320 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004321 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4322 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4323 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4324 llvm::Value *InterWarpCopyFn =
4325 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4326
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004327 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004328 llvm::Value *Args[] = {RTLoc,
4329 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004330 CGF.Builder.getInt32(RHSExprs.size()),
4331 ReductionArrayTySize,
4332 RL,
4333 ShuffleAndReduceFn,
4334 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004335
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004336 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004337 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004338 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4339 Args);
4340 } else {
4341 assert(TeamsReduction && "expected teams reduction.");
4342 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4343 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4344 int Cnt = 0;
4345 for (const Expr *DRE : Privates) {
4346 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4347 ++Cnt;
4348 }
4349 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4350 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4351 C.getLangOpts().OpenMPCUDAReductionBufNum);
4352 TeamsReductions.push_back(TeamReductionRec);
4353 if (!KernelTeamsReductionPtr) {
4354 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4355 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4356 llvm::GlobalValue::InternalLinkage, nullptr,
4357 "_openmp_teams_reductions_buffer_$_$ptr");
4358 }
4359 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4360 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4361 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4362 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4363 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4364 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4365 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4366 ReductionFn);
4367 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4368 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4369 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4370 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4371 ReductionFn);
4372
4373 llvm::Value *Args[] = {
4374 RTLoc,
4375 ThreadId,
4376 GlobalBufferPtr,
4377 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4378 RL,
4379 ShuffleAndReduceFn,
4380 InterWarpCopyFn,
4381 GlobalToBufferCpyFn,
4382 GlobalToBufferRedFn,
4383 BufferToGlobalCpyFn,
4384 BufferToGlobalRedFn};
4385
4386 Res = CGF.EmitRuntimeCall(
4387 createNVPTXRuntimeFunction(
4388 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004389 Args);
4390 }
4391
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004392 // 5. Build if (res == 1)
4393 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4394 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4395 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4396 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4397 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004398
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004399 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004400 // thread in each team.
4401 // __kmpc_end_reduce{_nowait}(<gtid>);
4402 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004403 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004404
4405 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004406 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004407 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4408 auto IPriv = Privates.begin();
4409 auto ILHS = LHSExprs.begin();
4410 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004411 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004412 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4413 cast<DeclRefExpr>(*IRHS));
4414 ++IPriv;
4415 ++ILHS;
4416 ++IRHS;
4417 }
4418 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004419 llvm::Value *EndArgs[] = {ThreadId};
4420 RegionCodeGenTy RCG(CodeGen);
4421 NVPTXActionTy Action(
4422 nullptr, llvm::None,
4423 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4424 EndArgs);
4425 RCG.setAction(Action);
4426 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004427 // There is no need to emit line number for unconditional branch.
4428 (void)ApplyDebugLocation::CreateEmpty(CGF);
4429 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004430}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004431
4432const VarDecl *
4433CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4434 const VarDecl *NativeParam) const {
4435 if (!NativeParam->getType()->isReferenceType())
4436 return NativeParam;
4437 QualType ArgType = NativeParam->getType();
4438 QualifierCollector QC;
4439 const Type *NonQualTy = QC.strip(ArgType);
4440 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4441 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4442 if (Attr->getCaptureKind() == OMPC_map) {
4443 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4444 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004445 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4446 PointeeTy.isConstant(CGM.getContext())) {
4447 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4448 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004449 }
4450 }
4451 ArgType = CGM.getContext().getPointerType(PointeeTy);
4452 QC.addRestrict();
4453 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004454 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004455 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004456 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004457 return ImplicitParamDecl::Create(
4458 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4459 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004460 return ParmVarDecl::Create(
4461 CGM.getContext(),
4462 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004463 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004464 NativeParam->getIdentifier(), ArgType,
4465 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004466}
4467
4468Address
4469CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4470 const VarDecl *NativeParam,
4471 const VarDecl *TargetParam) const {
4472 assert(NativeParam != TargetParam &&
4473 NativeParam->getType()->isReferenceType() &&
4474 "Native arg must not be the same as target arg.");
4475 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4476 QualType NativeParamType = NativeParam->getType();
4477 QualifierCollector QC;
4478 const Type *NonQualTy = QC.strip(NativeParamType);
4479 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4480 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004481 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004482 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004483 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004484 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004485 // First cast to generic.
4486 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4487 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4488 /*AddrSpace=*/0));
4489 // Cast from generic to native address space.
4490 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4491 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4492 NativePointeeAddrSpace));
4493 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4494 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004495 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004496 return NativeParamAddr;
4497}
4498
4499void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004500 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004501 ArrayRef<llvm::Value *> Args) const {
4502 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004503 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004504 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004505 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004506 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4507 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4508 break;
4509 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004510 llvm::Type *TargetType = FnType->getParamType(I);
4511 llvm::Value *NativeArg = Args[I];
4512 if (!TargetType->isPointerTy()) {
4513 TargetArgs.emplace_back(NativeArg);
4514 continue;
4515 }
4516 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004517 NativeArg,
4518 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004519 TargetArgs.emplace_back(
4520 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4521 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004522 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004523}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004524
4525/// Emit function which wraps the outline parallel region
4526/// and controls the arguments which are passed to this function.
4527/// The wrapper ensures that the outlined function is called
4528/// with the correct arguments when data is shared.
4529llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4530 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4531 ASTContext &Ctx = CGM.getContext();
4532 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4533
4534 // Create a function that takes as argument the source thread.
4535 FunctionArgList WrapperArgs;
4536 QualType Int16QTy =
4537 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4538 QualType Int32QTy =
4539 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004540 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004541 /*Id=*/nullptr, Int16QTy,
4542 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004543 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004544 /*Id=*/nullptr, Int32QTy,
4545 ImplicitParamDecl::Other);
4546 WrapperArgs.emplace_back(&ParallelLevelArg);
4547 WrapperArgs.emplace_back(&WrapperArg);
4548
Alexey Bataev9ff80832018-04-16 20:16:21 +00004549 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004550 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4551
4552 auto *Fn = llvm::Function::Create(
4553 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004554 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004555 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004556 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004557 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004558
4559 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4560 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004561 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562
4563 const auto *RD = CS.getCapturedRecordDecl();
4564 auto CurField = RD->field_begin();
4565
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004566 Address ZeroAddr = CGF.CreateMemTemp(
4567 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1),
4568 /*Name*/ ".zero.addr");
4569 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004570 // Get the array of arguments.
4571 SmallVector<llvm::Value *, 8> Args;
4572
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004573 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4574 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004575
4576 CGBuilderTy &Bld = CGF.Builder;
4577 auto CI = CS.capture_begin();
4578
4579 // Use global memory for data sharing.
4580 // Handle passing of global args to workers.
4581 Address GlobalArgs =
4582 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4583 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4584 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4585 CGF.EmitRuntimeCall(
4586 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4587 DataSharingArgs);
4588
4589 // Retrieve the shared variables from the list of references returned
4590 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004591 Address SharedArgListAddress = Address::invalid();
4592 if (CS.capture_size() > 0 ||
4593 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4594 SharedArgListAddress = CGF.EmitLoadOfPointer(
4595 GlobalArgs, CGF.getContext()
4596 .getPointerType(CGF.getContext().getPointerType(
4597 CGF.getContext().VoidPtrTy))
4598 .castAs<PointerType>());
4599 }
4600 unsigned Idx = 0;
4601 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004602 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004603 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4604 Src, CGF.SizeTy->getPointerTo());
4605 llvm::Value *LB = CGF.EmitLoadOfScalar(
4606 TypedAddress,
4607 /*Volatile=*/false,
4608 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4609 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4610 Args.emplace_back(LB);
4611 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004612 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004613 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4614 Src, CGF.SizeTy->getPointerTo());
4615 llvm::Value *UB = CGF.EmitLoadOfScalar(
4616 TypedAddress,
4617 /*Volatile=*/false,
4618 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4619 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4620 Args.emplace_back(UB);
4621 ++Idx;
4622 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004623 if (CS.capture_size() > 0) {
4624 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004625 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4626 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004627 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004628 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004629 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4630 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4631 /*Volatile=*/false,
4632 CGFContext.getPointerType(ElemTy),
4633 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004634 if (CI->capturesVariableByCopy() &&
4635 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004636 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4637 CI->getLocation());
4638 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004639 Args.emplace_back(Arg);
4640 }
4641 }
4642
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004643 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004644 CGF.FinishFunction();
4645 return Fn;
4646}
4647
4648void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4649 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004650 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4651 return;
4652
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004653 assert(D && "Expected function or captured|block decl.");
4654 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4655 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004656 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4657 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004658 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004659 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004660 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4661 Body = FD->getBody();
4662 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4663 Body = BD->getBody();
4664 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4665 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004666 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004667 if (NeedToDelayGlobalization &&
4668 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4669 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004670 }
4671 if (!Body)
4672 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004673 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004674 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004675 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004676 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004677 TeamAndReductions.first = nullptr;
4678 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004679 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4680 VarChecker.getEscapedVariableLengthDecls();
4681 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004682 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004683 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4684 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004685 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004686 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4687 I->getSecond().EscapedParameters.insert(
4688 VarChecker.getEscapedParameters().begin(),
4689 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004690 I->getSecond().EscapedVariableLengthDecls.append(
4691 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004692 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004693 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004694 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004695 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004696 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004697 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004698 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004699 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004700 VarChecker.Visit(Body);
4701 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004702 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004703 I->getSecond().SecondaryLocalVarData.emplace();
4704 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4705 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4706 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4707 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004708 Data.insert(
4709 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004710 }
4711 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004712 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004713 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004714 struct GlobalizationScope final : EHScopeStack::Cleanup {
4715 GlobalizationScope() = default;
4716
4717 void Emit(CodeGenFunction &CGF, Flags flags) override {
4718 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004719 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004720 }
4721 };
4722 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004723 }
4724}
4725
4726Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4727 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004728 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4729 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4730 switch (A->getAllocatorType()) {
4731 // Use the default allocator here as by default local vars are
4732 // threadlocal.
4733 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4734 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004735 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4736 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004737 // Follow the user decision - use default allocation.
4738 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004739 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004740 // TODO: implement aupport for user-defined allocators.
4741 return Address::invalid();
4742 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4743 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4744 auto *GV = new llvm::GlobalVariable(
4745 CGM.getModule(), VarTy, /*isConstant=*/false,
4746 llvm::GlobalValue::InternalLinkage,
4747 llvm::Constant::getNullValue(VarTy), VD->getName(),
4748 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4749 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4750 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004751 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004752 return Address(GV, Align);
4753 }
4754 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4755 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4756 auto *GV = new llvm::GlobalVariable(
4757 CGM.getModule(), VarTy, /*isConstant=*/false,
4758 llvm::GlobalValue::InternalLinkage,
4759 llvm::Constant::getNullValue(VarTy), VD->getName(),
4760 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4761 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4762 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004763 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004764 return Address(GV, Align);
4765 }
4766 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4767 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4768 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4769 auto *GV = new llvm::GlobalVariable(
4770 CGM.getModule(), VarTy, /*isConstant=*/false,
4771 llvm::GlobalValue::InternalLinkage,
4772 llvm::Constant::getNullValue(VarTy), VD->getName());
4773 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004774 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004775 return Address(GV, Align);
4776 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004777 }
4778 }
4779
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004780 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4781 return Address::invalid();
4782
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004783 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004784 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4785 if (I == FunctionGlobalizedDecls.end())
4786 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004787 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004788 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004789 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004790 if (VD->hasAttrs()) {
4791 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4792 E(VD->attr_end());
4793 IT != E; ++IT) {
4794 auto VDI = I->getSecond().LocalVarData.find(
4795 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4796 ->getCanonicalDecl());
4797 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004798 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004799 }
4800 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004801
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004802 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004803}
4804
4805void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004806 FunctionGlobalizedDecls.erase(CGF.CurFn);
4807 CGOpenMPRuntime::functionFinished(CGF);
4808}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004809
4810void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4811 CodeGenFunction &CGF, const OMPLoopDirective &S,
4812 OpenMPDistScheduleClauseKind &ScheduleKind,
4813 llvm::Value *&Chunk) const {
4814 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4815 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4816 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4817 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4818 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004819 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004820 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004821 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4822 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004823}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004824
4825void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4826 CodeGenFunction &CGF, const OMPLoopDirective &S,
4827 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004828 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004829 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004830 // Chunk size is 1 in this case.
4831 llvm::APInt ChunkSize(32, 1);
4832 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4833 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4834 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004835}
Alexey Bataev60705422018-10-30 15:50:12 +00004836
4837void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4838 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4839 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4840 " Expected target-based directive.");
4841 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4842 for (const CapturedStmt::Capture &C : CS->captures()) {
4843 // Capture variables captured by reference in lambdas for target-based
4844 // directives.
4845 if (!C.capturesVariable())
4846 continue;
4847 const VarDecl *VD = C.getCapturedVar();
4848 const auto *RD = VD->getType()
4849 .getCanonicalType()
4850 .getNonReferenceType()
4851 ->getAsCXXRecordDecl();
4852 if (!RD || !RD->isLambda())
4853 continue;
4854 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4855 LValue VDLVal;
4856 if (VD->getType().getCanonicalType()->isReferenceType())
4857 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4858 else
4859 VDLVal = CGF.MakeAddrLValue(
4860 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4861 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4862 FieldDecl *ThisCapture = nullptr;
4863 RD->getCaptureFields(Captures, ThisCapture);
4864 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4865 LValue ThisLVal =
4866 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4867 llvm::Value *CXXThis = CGF.LoadCXXThis();
4868 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4869 }
4870 for (const LambdaCapture &LC : RD->captures()) {
4871 if (LC.getCaptureKind() != LCK_ByRef)
4872 continue;
4873 const VarDecl *VD = LC.getCapturedVar();
4874 if (!CS->capturesVariable(VD))
4875 continue;
4876 auto It = Captures.find(VD);
4877 assert(It != Captures.end() && "Found lambda capture without field.");
4878 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4879 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4880 if (VD->getType().getCanonicalType()->isReferenceType())
4881 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4882 VD->getType().getCanonicalType())
4883 .getAddress();
4884 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4885 }
4886 }
4887}
4888
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004889unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4890 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4891}
4892
Alexey Bataevc5687252019-03-21 19:35:27 +00004893bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4894 LangAS &AS) {
4895 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4896 return false;
4897 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4898 switch(A->getAllocatorType()) {
4899 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4900 // Not supported, fallback to the default mem space.
4901 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4902 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4903 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4904 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4905 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4906 AS = LangAS::Default;
4907 return true;
4908 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4909 AS = LangAS::cuda_constant;
4910 return true;
4911 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4912 AS = LangAS::cuda_shared;
4913 return true;
4914 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4915 llvm_unreachable("Expected predefined allocator for the variables with the "
4916 "static storage.");
4917 }
4918 return false;
4919}
4920
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004921// Get current CudaArch and ignore any unknown values
4922static CudaArch getCudaArch(CodeGenModule &CGM) {
4923 if (!CGM.getTarget().hasFeature("ptx"))
4924 return CudaArch::UNKNOWN;
4925 llvm::StringMap<bool> Features;
4926 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4927 CGM.getTarget().getTargetOpts().CPU,
4928 CGM.getTarget().getTargetOpts().Features);
4929 for (const auto &Feature : Features) {
4930 if (Feature.getValue()) {
4931 CudaArch Arch = StringToCudaArch(Feature.getKey());
4932 if (Arch != CudaArch::UNKNOWN)
4933 return Arch;
4934 }
4935 }
4936 return CudaArch::UNKNOWN;
4937}
4938
4939/// Check to see if target architecture supports unified addressing which is
4940/// a restriction for OpenMP requires clause "unified_shared_memory".
4941void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004942 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004943 for (const OMPClause *Clause : D->clauselists()) {
4944 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4945 switch (getCudaArch(CGM)) {
4946 case CudaArch::SM_20:
4947 case CudaArch::SM_21:
4948 case CudaArch::SM_30:
4949 case CudaArch::SM_32:
4950 case CudaArch::SM_35:
4951 case CudaArch::SM_37:
4952 case CudaArch::SM_50:
4953 case CudaArch::SM_52:
4954 case CudaArch::SM_53:
4955 case CudaArch::SM_60:
4956 case CudaArch::SM_61:
4957 case CudaArch::SM_62:
4958 CGM.Error(Clause->getBeginLoc(),
4959 "Target architecture does not support unified addressing");
4960 return;
4961 case CudaArch::SM_70:
4962 case CudaArch::SM_72:
4963 case CudaArch::SM_75:
4964 case CudaArch::GFX600:
4965 case CudaArch::GFX601:
4966 case CudaArch::GFX700:
4967 case CudaArch::GFX701:
4968 case CudaArch::GFX702:
4969 case CudaArch::GFX703:
4970 case CudaArch::GFX704:
4971 case CudaArch::GFX801:
4972 case CudaArch::GFX802:
4973 case CudaArch::GFX803:
4974 case CudaArch::GFX810:
4975 case CudaArch::GFX900:
4976 case CudaArch::GFX902:
4977 case CudaArch::GFX904:
4978 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004979 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004980 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004981 case CudaArch::GFX1010:
4982 case CudaArch::GFX1011:
4983 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004984 case CudaArch::UNKNOWN:
4985 break;
4986 case CudaArch::LAST:
4987 llvm_unreachable("Unexpected Cuda arch.");
4988 }
4989 }
4990 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004991 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004992}
4993
Alexey Bataeve4090182018-11-02 14:54:07 +00004994/// Get number of SMs and number of blocks per SM.
4995static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
4996 std::pair<unsigned, unsigned> Data;
4997 if (CGM.getLangOpts().OpenMPCUDANumSMs)
4998 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
4999 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5000 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5001 if (Data.first && Data.second)
5002 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005003 switch (getCudaArch(CGM)) {
5004 case CudaArch::SM_20:
5005 case CudaArch::SM_21:
5006 case CudaArch::SM_30:
5007 case CudaArch::SM_32:
5008 case CudaArch::SM_35:
5009 case CudaArch::SM_37:
5010 case CudaArch::SM_50:
5011 case CudaArch::SM_52:
5012 case CudaArch::SM_53:
5013 return {16, 16};
5014 case CudaArch::SM_60:
5015 case CudaArch::SM_61:
5016 case CudaArch::SM_62:
5017 return {56, 32};
5018 case CudaArch::SM_70:
5019 case CudaArch::SM_72:
5020 case CudaArch::SM_75:
5021 return {84, 32};
5022 case CudaArch::GFX600:
5023 case CudaArch::GFX601:
5024 case CudaArch::GFX700:
5025 case CudaArch::GFX701:
5026 case CudaArch::GFX702:
5027 case CudaArch::GFX703:
5028 case CudaArch::GFX704:
5029 case CudaArch::GFX801:
5030 case CudaArch::GFX802:
5031 case CudaArch::GFX803:
5032 case CudaArch::GFX810:
5033 case CudaArch::GFX900:
5034 case CudaArch::GFX902:
5035 case CudaArch::GFX904:
5036 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005037 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005038 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005039 case CudaArch::GFX1010:
5040 case CudaArch::GFX1011:
5041 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005042 case CudaArch::UNKNOWN:
5043 break;
5044 case CudaArch::LAST:
5045 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005046 }
5047 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5048}
5049
5050void CGOpenMPRuntimeNVPTX::clear() {
5051 if (!GlobalizedRecords.empty()) {
5052 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005053 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5054 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005055 RecordDecl *StaticRD = C.buildImplicitRecord(
5056 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5057 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005058 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5059 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5060 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005061 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5062 if (Records.Records.empty())
5063 continue;
5064 unsigned Size = 0;
5065 unsigned RecAlignment = 0;
5066 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005067 QualType RDTy = C.getRecordType(RD);
5068 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005069 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005070 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005071 Size =
5072 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5073 }
5074 Size = llvm::alignTo(Size, RecAlignment);
5075 llvm::APInt ArySize(/*numBits=*/64, Size);
5076 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005077 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005078 const bool UseSharedMemory = Size <= SharedMemorySize;
5079 auto *Field =
5080 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5081 SourceLocation(), SourceLocation(), nullptr, SubTy,
5082 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5083 /*BW=*/nullptr, /*Mutable=*/false,
5084 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005085 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005086 if (UseSharedMemory) {
5087 SharedStaticRD->addDecl(Field);
5088 SharedRecs.push_back(&Records);
5089 } else {
5090 StaticRD->addDecl(Field);
5091 GlobalRecs.push_back(&Records);
5092 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005093 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005094 Records.UseSharedMemory->setInitializer(
5095 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5096 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005097 // Allocate SharedMemorySize buffer for the shared memory.
5098 // FIXME: nvlink does not handle weak linkage correctly (object with the
5099 // different size are reported as erroneous).
5100 // Restore this code as sson as nvlink is fixed.
5101 if (!SharedStaticRD->field_empty()) {
5102 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5103 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005104 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005105 auto *Field = FieldDecl::Create(
5106 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5107 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5108 /*BW=*/nullptr, /*Mutable=*/false,
5109 /*InitStyle=*/ICIS_NoInit);
5110 Field->setAccess(AS_public);
5111 SharedStaticRD->addDecl(Field);
5112 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005113 SharedStaticRD->completeDefinition();
5114 if (!SharedStaticRD->field_empty()) {
5115 QualType StaticTy = C.getRecordType(SharedStaticRD);
5116 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5117 auto *GV = new llvm::GlobalVariable(
5118 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005119 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005120 llvm::Constant::getNullValue(LLVMStaticTy),
5121 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5122 llvm::GlobalValue::NotThreadLocal,
5123 C.getTargetAddressSpace(LangAS::cuda_shared));
5124 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5125 GV, CGM.VoidPtrTy);
5126 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5127 Rec->Buffer->replaceAllUsesWith(Replacement);
5128 Rec->Buffer->eraseFromParent();
5129 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005130 }
5131 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005132 if (!StaticRD->field_empty()) {
5133 QualType StaticTy = C.getRecordType(StaticRD);
5134 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5135 llvm::APInt Size1(32, SMsBlockPerSM.second);
5136 QualType Arr1Ty =
Richard Smith772e2662019-10-04 01:25:59 +00005137 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005138 /*IndexTypeQuals=*/0);
5139 llvm::APInt Size2(32, SMsBlockPerSM.first);
Richard Smith772e2662019-10-04 01:25:59 +00005140 QualType Arr2Ty =
5141 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5142 /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005143 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005144 // FIXME: nvlink does not handle weak linkage correctly (object with the
5145 // different size are reported as erroneous).
5146 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005147 auto *GV = new llvm::GlobalVariable(
5148 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005149 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005150 llvm::Constant::getNullValue(LLVMArr2Ty),
5151 "_openmp_static_glob_rd_$_");
5152 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5153 GV, CGM.VoidPtrTy);
5154 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5155 Rec->Buffer->replaceAllUsesWith(Replacement);
5156 Rec->Buffer->eraseFromParent();
5157 }
5158 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005159 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005160 if (!TeamsReductions.empty()) {
5161 ASTContext &C = CGM.getContext();
5162 RecordDecl *StaticRD = C.buildImplicitRecord(
5163 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5164 StaticRD->startDefinition();
5165 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5166 QualType RecTy = C.getRecordType(TeamReductionRec);
5167 auto *Field = FieldDecl::Create(
5168 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5169 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5170 /*BW=*/nullptr, /*Mutable=*/false,
5171 /*InitStyle=*/ICIS_NoInit);
5172 Field->setAccess(AS_public);
5173 StaticRD->addDecl(Field);
5174 }
5175 StaticRD->completeDefinition();
5176 QualType StaticTy = C.getRecordType(StaticRD);
5177 llvm::Type *LLVMReductionsBufferTy =
5178 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005179 // FIXME: nvlink does not handle weak linkage correctly (object with the
5180 // different size are reported as erroneous).
5181 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005182 auto *GV = new llvm::GlobalVariable(
5183 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005184 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005185 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5186 "_openmp_teams_reductions_buffer_$_");
5187 KernelTeamsReductionPtr->setInitializer(
5188 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5189 CGM.VoidPtrTy));
5190 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005191 CGOpenMPRuntime::clear();
5192}