blob: e5ec3deac2c94b29183dac39a4ef45310adeff21 [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:
Alexey Bataevb8552ab2019-10-18 16:47:35 +0000807 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000808 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -0400809 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000810 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000811 case OMPD_unknown:
812 llvm_unreachable("Unexpected directive.");
813 }
814 }
815
816 return false;
817}
818
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000819static bool supportsSPMDExecutionMode(ASTContext &Ctx,
820 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000821 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
822 switch (DirectiveKind) {
823 case OMPD_target:
824 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000825 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000826 case OMPD_target_parallel:
827 case OMPD_target_parallel_for:
828 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000829 case OMPD_target_teams_distribute_parallel_for:
830 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000831 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000832 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000833 return true;
834 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000835 return false;
836 case OMPD_parallel:
837 case OMPD_for:
838 case OMPD_parallel_for:
839 case OMPD_parallel_sections:
840 case OMPD_for_simd:
841 case OMPD_parallel_for_simd:
842 case OMPD_cancel:
843 case OMPD_cancellation_point:
844 case OMPD_ordered:
845 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000846 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000847 case OMPD_task:
848 case OMPD_simd:
849 case OMPD_sections:
850 case OMPD_section:
851 case OMPD_single:
852 case OMPD_master:
853 case OMPD_critical:
854 case OMPD_taskyield:
855 case OMPD_barrier:
856 case OMPD_taskwait:
857 case OMPD_taskgroup:
858 case OMPD_atomic:
859 case OMPD_flush:
860 case OMPD_teams:
861 case OMPD_target_data:
862 case OMPD_target_exit_data:
863 case OMPD_target_enter_data:
864 case OMPD_distribute:
865 case OMPD_distribute_simd:
866 case OMPD_distribute_parallel_for:
867 case OMPD_distribute_parallel_for_simd:
868 case OMPD_teams_distribute:
869 case OMPD_teams_distribute_simd:
870 case OMPD_teams_distribute_parallel_for:
871 case OMPD_teams_distribute_parallel_for_simd:
872 case OMPD_target_update:
873 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000874 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000875 case OMPD_declare_target:
876 case OMPD_end_declare_target:
877 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000878 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000879 case OMPD_taskloop:
880 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000881 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +0000882 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000883 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -0400884 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +0000885 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000886 case OMPD_unknown:
887 break;
888 }
889 llvm_unreachable(
890 "Unknown programming model for OpenMP directive on NVPTX target.");
891}
892
893/// Check if the directive is loops based and has schedule clause at all or has
894/// static scheduling.
895static bool hasStaticScheduling(const OMPExecutableDirective &D) {
896 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
897 isOpenMPLoopDirective(D.getDirectiveKind()) &&
898 "Expected loop-based directive.");
899 return !D.hasClausesOfKind<OMPOrderedClause>() &&
900 (!D.hasClausesOfKind<OMPScheduleClause>() ||
901 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
902 [](const OMPScheduleClause *C) {
903 return C->getScheduleKind() == OMPC_SCHEDULE_static;
904 }));
905}
906
907/// Check for inner (nested) lightweight runtime construct, if any
908static bool hasNestedLightweightDirective(ASTContext &Ctx,
909 const OMPExecutableDirective &D) {
910 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
911 const auto *CS = D.getInnermostCapturedStmt();
912 const auto *Body =
913 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000914 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000915
Alexey Bataev5c427362019-04-10 19:11:33 +0000916 if (const auto *NestedDir =
917 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000918 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
919 switch (D.getDirectiveKind()) {
920 case OMPD_target:
921 if (isOpenMPParallelDirective(DKind) &&
922 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
923 hasStaticScheduling(*NestedDir))
924 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000925 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
926 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000927 if (DKind == OMPD_parallel) {
928 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
929 /*IgnoreCaptured=*/true);
930 if (!Body)
931 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000932 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
933 if (const auto *NND =
934 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000935 DKind = NND->getDirectiveKind();
936 if (isOpenMPWorksharingDirective(DKind) &&
937 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
938 return true;
939 }
940 } else if (DKind == OMPD_teams) {
941 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
942 /*IgnoreCaptured=*/true);
943 if (!Body)
944 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000945 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
946 if (const auto *NND =
947 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000948 DKind = NND->getDirectiveKind();
949 if (isOpenMPParallelDirective(DKind) &&
950 isOpenMPWorksharingDirective(DKind) &&
951 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
952 return true;
953 if (DKind == OMPD_parallel) {
954 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
955 /*IgnoreCaptured=*/true);
956 if (!Body)
957 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000958 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
959 if (const auto *NND =
960 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000961 DKind = NND->getDirectiveKind();
962 if (isOpenMPWorksharingDirective(DKind) &&
963 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
964 return true;
965 }
966 }
967 }
968 }
969 return false;
970 case OMPD_target_teams:
971 if (isOpenMPParallelDirective(DKind) &&
972 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
973 hasStaticScheduling(*NestedDir))
974 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000975 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
976 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000977 if (DKind == OMPD_parallel) {
978 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
979 /*IgnoreCaptured=*/true);
980 if (!Body)
981 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000982 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
983 if (const auto *NND =
984 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000985 DKind = NND->getDirectiveKind();
986 if (isOpenMPWorksharingDirective(DKind) &&
987 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
988 return true;
989 }
990 }
991 return false;
992 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000993 if (DKind == OMPD_simd)
994 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000995 return isOpenMPWorksharingDirective(DKind) &&
996 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
997 case OMPD_target_teams_distribute:
998 case OMPD_target_simd:
999 case OMPD_target_parallel_for:
1000 case OMPD_target_parallel_for_simd:
1001 case OMPD_target_teams_distribute_simd:
1002 case OMPD_target_teams_distribute_parallel_for:
1003 case OMPD_target_teams_distribute_parallel_for_simd:
1004 case OMPD_parallel:
1005 case OMPD_for:
1006 case OMPD_parallel_for:
1007 case OMPD_parallel_sections:
1008 case OMPD_for_simd:
1009 case OMPD_parallel_for_simd:
1010 case OMPD_cancel:
1011 case OMPD_cancellation_point:
1012 case OMPD_ordered:
1013 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001014 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001015 case OMPD_task:
1016 case OMPD_simd:
1017 case OMPD_sections:
1018 case OMPD_section:
1019 case OMPD_single:
1020 case OMPD_master:
1021 case OMPD_critical:
1022 case OMPD_taskyield:
1023 case OMPD_barrier:
1024 case OMPD_taskwait:
1025 case OMPD_taskgroup:
1026 case OMPD_atomic:
1027 case OMPD_flush:
1028 case OMPD_teams:
1029 case OMPD_target_data:
1030 case OMPD_target_exit_data:
1031 case OMPD_target_enter_data:
1032 case OMPD_distribute:
1033 case OMPD_distribute_simd:
1034 case OMPD_distribute_parallel_for:
1035 case OMPD_distribute_parallel_for_simd:
1036 case OMPD_teams_distribute:
1037 case OMPD_teams_distribute_simd:
1038 case OMPD_teams_distribute_parallel_for:
1039 case OMPD_teams_distribute_parallel_for_simd:
1040 case OMPD_target_update:
1041 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001042 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001043 case OMPD_declare_target:
1044 case OMPD_end_declare_target:
1045 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001046 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001047 case OMPD_taskloop:
1048 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001049 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00001050 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001051 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -04001052 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001053 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001054 case OMPD_unknown:
1055 llvm_unreachable("Unexpected directive.");
1056 }
1057 }
1058
1059 return false;
1060}
1061
1062/// Checks if the construct supports lightweight runtime. It must be SPMD
1063/// construct + inner loop-based construct with static scheduling.
1064static bool supportsLightweightRuntime(ASTContext &Ctx,
1065 const OMPExecutableDirective &D) {
1066 if (!supportsSPMDExecutionMode(Ctx, D))
1067 return false;
1068 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1069 switch (DirectiveKind) {
1070 case OMPD_target:
1071 case OMPD_target_teams:
1072 case OMPD_target_parallel:
1073 return hasNestedLightweightDirective(Ctx, D);
1074 case OMPD_target_parallel_for:
1075 case OMPD_target_parallel_for_simd:
1076 case OMPD_target_teams_distribute_parallel_for:
1077 case OMPD_target_teams_distribute_parallel_for_simd:
1078 // (Last|First)-privates must be shared in parallel region.
1079 return hasStaticScheduling(D);
1080 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001081 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001082 return true;
1083 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001084 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001085 case OMPD_parallel:
1086 case OMPD_for:
1087 case OMPD_parallel_for:
1088 case OMPD_parallel_sections:
1089 case OMPD_for_simd:
1090 case OMPD_parallel_for_simd:
1091 case OMPD_cancel:
1092 case OMPD_cancellation_point:
1093 case OMPD_ordered:
1094 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001095 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001096 case OMPD_task:
1097 case OMPD_simd:
1098 case OMPD_sections:
1099 case OMPD_section:
1100 case OMPD_single:
1101 case OMPD_master:
1102 case OMPD_critical:
1103 case OMPD_taskyield:
1104 case OMPD_barrier:
1105 case OMPD_taskwait:
1106 case OMPD_taskgroup:
1107 case OMPD_atomic:
1108 case OMPD_flush:
1109 case OMPD_teams:
1110 case OMPD_target_data:
1111 case OMPD_target_exit_data:
1112 case OMPD_target_enter_data:
1113 case OMPD_distribute:
1114 case OMPD_distribute_simd:
1115 case OMPD_distribute_parallel_for:
1116 case OMPD_distribute_parallel_for_simd:
1117 case OMPD_teams_distribute:
1118 case OMPD_teams_distribute_simd:
1119 case OMPD_teams_distribute_parallel_for:
1120 case OMPD_teams_distribute_parallel_for_simd:
1121 case OMPD_target_update:
1122 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001123 case OMPD_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001124 case OMPD_declare_target:
1125 case OMPD_end_declare_target:
1126 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001127 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001128 case OMPD_taskloop:
1129 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001130 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00001131 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001132 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -04001133 case OMPD_parallel_master_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00001134 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001135 case OMPD_unknown:
1136 break;
1137 }
1138 llvm_unreachable(
1139 "Unknown programming model for OpenMP directive on NVPTX target.");
1140}
1141
1142void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001143 StringRef ParentName,
1144 llvm::Function *&OutlinedFn,
1145 llvm::Constant *&OutlinedFnID,
1146 bool IsOffloadEntry,
1147 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001148 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001149 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001150 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001151 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001152 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001153
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001154 // Emit target region as a standalone region.
1155 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001156 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1157 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001158
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001159 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001160 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001161 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001162 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001163 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001164 auto &RT =
1165 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001166 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1167 // Skip target region initialization.
1168 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 }
1170 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001171 auto &RT =
1172 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001173 RT.clearLocThreadIdInsertPt(CGF);
1174 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001175 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001176 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001177 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001178 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001179 // Reserve place for the globalized memory.
1180 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001181 if (!KernelStaticGlobalized) {
1182 KernelStaticGlobalized = new llvm::GlobalVariable(
1183 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1184 llvm::GlobalValue::InternalLinkage,
1185 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1186 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1187 llvm::GlobalValue::NotThreadLocal,
1188 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1189 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001190 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1191 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001192 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001193
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001194 // Now change the name of the worker function to correspond to this target
1195 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001196 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001197
1198 // Create the worker function
1199 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001200}
1201
1202// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001203void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001204 EntryFunctionState &EST,
1205 WorkerFunctionState &WST) {
1206 CGBuilderTy &Bld = CGF.Builder;
1207
1208 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1209 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1210 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1211 EST.ExitBB = CGF.createBasicBlock(".exit");
1212
Alexey Bataev9ff80832018-04-16 20:16:21 +00001213 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001214 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1215 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1216
1217 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001218 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001219 CGF.EmitBranch(EST.ExitBB);
1220
1221 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001222 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001223 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1224 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1225
1226 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001227 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001228 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001229 // First action in sequential region:
1230 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001231 // TODO: Optimize runtime initialization and pass in correct value.
1232 llvm::Value *Args[] = {getThreadLimit(CGF),
1233 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001234 CGF.EmitRuntimeCall(
1235 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001236
1237 // For data sharing, we need to initialize the stack.
1238 CGF.EmitRuntimeCall(
1239 createNVPTXRuntimeFunction(
1240 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1241
Alexey Bataevc99042b2018-03-15 18:10:54 +00001242 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001243}
1244
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001245void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001246 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001247 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001248 if (!CGF.HaveInsertPoint())
1249 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001250
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001251 emitGenericVarsEpilog(CGF);
1252
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001253 if (!EST.ExitBB)
1254 EST.ExitBB = CGF.createBasicBlock(".exit");
1255
1256 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1257 CGF.EmitBranch(TerminateBB);
1258
1259 CGF.EmitBlock(TerminateBB);
1260 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001261 // TODO: Optimize runtime initialization and pass in correct value.
1262 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001263 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001264 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001265 // Barrier to terminate worker threads.
1266 syncCTAThreads(CGF);
1267 // Master thread jumps to exit point.
1268 CGF.EmitBranch(EST.ExitBB);
1269
1270 CGF.EmitBlock(EST.ExitBB);
1271 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001272}
1273
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001274void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001275 StringRef ParentName,
1276 llvm::Function *&OutlinedFn,
1277 llvm::Constant *&OutlinedFnID,
1278 bool IsOffloadEntry,
1279 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001280 ExecutionRuntimeModesRAII ModeRAII(
1281 CurrentExecutionMode, RequiresFullRuntime,
1282 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1283 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001284 EntryFunctionState EST;
1285
1286 // Emit target region as a standalone region.
1287 class NVPTXPrePostActionTy : public PrePostActionTy {
1288 CGOpenMPRuntimeNVPTX &RT;
1289 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1290 const OMPExecutableDirective &D;
1291
1292 public:
1293 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1294 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1295 const OMPExecutableDirective &D)
1296 : RT(RT), EST(EST), D(D) {}
1297 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001298 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001299 // Skip target region initialization.
1300 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001301 }
1302 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001303 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001304 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001305 }
1306 } Action(*this, EST, D);
1307 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001308 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001309 // Reserve place for the globalized memory.
1310 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001311 if (!KernelStaticGlobalized) {
1312 KernelStaticGlobalized = new llvm::GlobalVariable(
1313 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1314 llvm::GlobalValue::InternalLinkage,
1315 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1316 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1317 llvm::GlobalValue::NotThreadLocal,
1318 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1319 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001320 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1321 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001322 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001323}
1324
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001325void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001326 CodeGenFunction &CGF, EntryFunctionState &EST,
1327 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001328 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001329
1330 // Setup BBs in entry function.
1331 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1332 EST.ExitBB = CGF.createBasicBlock(".exit");
1333
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001334 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1335 /*RequiresOMPRuntime=*/
1336 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1337 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001338 CGF.EmitRuntimeCall(
1339 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001340
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001341 if (RequiresFullRuntime) {
1342 // For data sharing, we need to initialize the stack.
1343 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1344 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1345 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001346
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347 CGF.EmitBranch(ExecuteBB);
1348
1349 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001350
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001351 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001352}
1353
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001354void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001355 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001356 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001357 if (!CGF.HaveInsertPoint())
1358 return;
1359
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001360 if (!EST.ExitBB)
1361 EST.ExitBB = CGF.createBasicBlock(".exit");
1362
1363 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1364 CGF.EmitBranch(OMPDeInitBB);
1365
1366 CGF.EmitBlock(OMPDeInitBB);
1367 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001368 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1369 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001370 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001371 createNVPTXRuntimeFunction(
1372 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001373 CGF.EmitBranch(EST.ExitBB);
1374
1375 CGF.EmitBlock(EST.ExitBB);
1376 EST.ExitBB = nullptr;
1377}
1378
1379// Create a unique global variable to indicate the execution mode of this target
1380// region. The execution mode is either 'generic', or 'spmd' depending on the
1381// target directive. This variable is picked up by the offload library to setup
1382// the device appropriately before kernel launch. If the execution mode is
1383// 'generic', the runtime reserves one warp for the master, otherwise, all
1384// warps participate in parallel work.
1385static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001386 bool Mode) {
1387 auto *GVMode =
1388 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1389 llvm::GlobalValue::WeakAnyLinkage,
1390 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1391 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001392 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001393}
1394
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001395void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001396 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001397
1398 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001399 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001400 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001401 emitWorkerLoop(CGF, WST);
1402 CGF.FinishFunction();
1403}
1404
1405void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1406 WorkerFunctionState &WST) {
1407 //
1408 // The workers enter this loop and wait for parallel work from the master.
1409 // When the master encounters a parallel region it sets up the work + variable
1410 // arguments, and wakes up the workers. The workers first check to see if
1411 // they are required for the parallel region, i.e., within the # of requested
1412 // parallel threads. The activated workers load the variable arguments and
1413 // execute the parallel work.
1414 //
1415
1416 CGBuilderTy &Bld = CGF.Builder;
1417
1418 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1419 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1420 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1421 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1422 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1423 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1424
1425 CGF.EmitBranch(AwaitBB);
1426
1427 // Workers wait for work from master.
1428 CGF.EmitBlock(AwaitBB);
1429 // Wait for parallel work
1430 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001431
1432 Address WorkFn =
1433 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1434 Address ExecStatus =
1435 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1436 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1437 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1438
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001439 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001440 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001441 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001442 llvm::Value *Ret = CGF.EmitRuntimeCall(
1443 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1444 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001445
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001446 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001447 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1448 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001449 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1450
1451 // Activate requested workers.
1452 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001453 llvm::Value *IsActive =
1454 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1455 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001456
1457 // Signal start of parallel region.
1458 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001459 // Skip initialization.
1460 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001461
1462 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001463 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001464 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001465 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001466
1467 llvm::Value *WorkFnMatch =
1468 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1469
1470 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1471 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1472 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1473
1474 // Execute this outlined function.
1475 CGF.EmitBlock(ExecuteFNBB);
1476
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001477 // Insert call to work function via shared wrapper. The shared
1478 // wrapper takes two arguments:
1479 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001480 // - the thread ID;
1481 emitCall(CGF, WST.Loc, W,
1482 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001483
1484 // Go to end of parallel region.
1485 CGF.EmitBranch(TerminateBB);
1486
1487 CGF.EmitBlock(CheckNextBB);
1488 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001489 // Default case: call to outlined function through pointer if the target
1490 // region makes a declare target call that may contain an orphaned parallel
1491 // directive.
1492 auto *ParallelFnTy =
1493 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001494 /*isVarArg=*/false);
1495 llvm::Value *WorkFnCast =
1496 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001497 // Insert call to work function via shared wrapper. The shared
1498 // wrapper takes two arguments:
1499 // - the parallelism level;
1500 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001501 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001502 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1503 // Go to end of parallel region.
1504 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001505
1506 // Signal end of parallel region.
1507 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001508 CGF.EmitRuntimeCall(
1509 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1510 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001511 CGF.EmitBranch(BarrierBB);
1512
1513 // All active and inactive workers wait at a barrier after parallel region.
1514 CGF.EmitBlock(BarrierBB);
1515 // Barrier after parallel region.
1516 syncCTAThreads(CGF);
1517 CGF.EmitBranch(AwaitBB);
1518
1519 // Exit target region.
1520 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001521 // Skip initialization.
1522 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001523}
1524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001525/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001526/// implementation. Specialized for the NVPTX device.
1527/// \param Function OpenMP runtime function.
1528/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001529llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001530CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001531 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001532 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1533 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001534 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1535 // RequiresOMPRuntime);
1536 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001537 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001538 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1539 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1540 break;
1541 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001542 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001543 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1544 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001545 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001546 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001547 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1548 break;
1549 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001550 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1551 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001552 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001553 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001554 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001555 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1556 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1557 break;
1558 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001559 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1560 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1561 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001562 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001563 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1564 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001565 break;
1566 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001567 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1568 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001569 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001570 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001571 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001572 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1573 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1574 break;
1575 }
1576 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001577 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1578 /// int16_t IsOMPRuntimeInitialized);
1579 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001580 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001581 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001582 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1584 break;
1585 }
1586 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1587 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001588 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001589 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1590 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1591 break;
1592 }
1593 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1594 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1595 // global_tid);
1596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001597 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001598 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1599 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1600 break;
1601 }
1602 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1603 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1604 // global_tid);
1605 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001606 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001607 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1609 break;
1610 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001611 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1612 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1613 // int16_t lane_offset, int16_t warp_size);
1614 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001615 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001616 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1618 break;
1619 }
1620 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1621 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1622 // int16_t lane_offset, int16_t warp_size);
1623 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001624 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001625 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1626 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1627 break;
1628 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001629 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001630 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1631 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1632 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1633 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1634 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001635 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1636 CGM.Int16Ty, CGM.Int16Ty};
1637 auto *ShuffleReduceFnTy =
1638 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1639 /*isVarArg=*/false);
1640 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1641 auto *InterWarpCopyFnTy =
1642 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1643 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001644 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1645 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001646 CGM.Int32Ty,
1647 CGM.SizeTy,
1648 CGM.VoidPtrTy,
1649 ShuffleReduceFnTy->getPointerTo(),
1650 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001651 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001652 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1653 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001654 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001655 break;
1656 }
1657 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1658 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1659 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001660 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1662 RTLFn = CGM.CreateRuntimeFunction(
1663 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1664 break;
1665 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001666 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1667 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1668 // global_tid, void *global_buffer, int32_t num_of_records, void*
1669 // reduce_data,
1670 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1671 // lane_offset, int16_t shortCircuit),
1672 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1673 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1674 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1675 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1676 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1677 // *buffer, int idx, void *reduce_data));
1678 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1679 CGM.Int16Ty, CGM.Int16Ty};
1680 auto *ShuffleReduceFnTy =
1681 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1682 /*isVarArg=*/false);
1683 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1684 auto *InterWarpCopyFnTy =
1685 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1686 /*isVarArg=*/false);
1687 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1688 CGM.VoidPtrTy};
1689 auto *GlobalListFnTy =
1690 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1691 /*isVarArg=*/false);
1692 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1693 CGM.Int32Ty,
1694 CGM.VoidPtrTy,
1695 CGM.Int32Ty,
1696 CGM.VoidPtrTy,
1697 ShuffleReduceFnTy->getPointerTo(),
1698 InterWarpCopyFnTy->getPointerTo(),
1699 GlobalListFnTy->getPointerTo(),
1700 GlobalListFnTy->getPointerTo(),
1701 GlobalListFnTy->getPointerTo(),
1702 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001703 auto *FnTy =
1704 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1705 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001706 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001707 break;
1708 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001709 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1710 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001711 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001712 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1713 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1714 break;
1715 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001716 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1717 /// Build void __kmpc_data_sharing_init_stack_spmd();
1718 auto *FnTy =
1719 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001720 RTLFn =
1721 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001722 break;
1723 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001724 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1725 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001726 // int16_t UseSharedMemory);
1727 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001728 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001729 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1730 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001731 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001732 break;
1733 }
1734 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1735 // Build void __kmpc_data_sharing_pop_stack(void *a);
1736 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001737 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001738 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1740 /*Name=*/"__kmpc_data_sharing_pop_stack");
1741 break;
1742 }
1743 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1744 /// Build void __kmpc_begin_sharing_variables(void ***args,
1745 /// size_t n_args);
1746 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001747 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001748 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1749 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1750 break;
1751 }
1752 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1753 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001754 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001755 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1757 break;
1758 }
1759 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1760 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1761 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001762 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1765 break;
1766 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001767 case OMPRTL_NVPTX__kmpc_parallel_level: {
1768 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1770 auto *FnTy =
1771 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1772 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1773 break;
1774 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001775 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1776 // Build int8_t __kmpc_is_spmd_exec_mode();
1777 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1778 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1779 break;
1780 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001781 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001782 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1783 // const void *buf, size_t size, int16_t is_shared, const void **res);
1784 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1785 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001786 auto *FnTy =
1787 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1788 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1789 break;
1790 }
1791 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001792 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1793 // int16_t is_shared);
1794 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001795 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001797 RTLFn =
1798 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1799 break;
1800 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001801 case OMPRTL__kmpc_barrier: {
1802 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1803 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1804 auto *FnTy =
1805 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Matt Arsenault40ab8ae2019-10-27 14:17:40 -07001806 RTLFn =
1807 CGM.CreateConvergentRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001808 break;
1809 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001810 case OMPRTL__kmpc_barrier_simple_spmd: {
1811 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1812 // global_tid);
1813 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1814 auto *FnTy =
1815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Matt Arsenault40ab8ae2019-10-27 14:17:40 -07001816 RTLFn = CGM.CreateConvergentRuntimeFunction(
1817 FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
Alexey Bataeva3924b52019-01-03 16:25:35 +00001818 break;
1819 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001820 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1821 // Build int32_t __kmpc_warp_active_thread_mask(void);
1822 auto *FnTy =
1823 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
Matt Arsenault56a503b2019-10-27 15:09:49 -07001824 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001825 break;
1826 }
1827 case OMPRTL_NVPTX__kmpc_syncwarp: {
1828 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1829 auto *FnTy =
1830 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
Matt Arsenault56a503b2019-10-27 15:09:49 -07001831 RTLFn = CGM.CreateConvergentRuntimeFunction(FnTy, "__kmpc_syncwarp");
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001832 break;
1833 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001834 }
1835 return RTLFn;
1836}
1837
1838void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1839 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001840 uint64_t Size, int32_t,
1841 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001842 // TODO: Add support for global variables on the device after declare target
1843 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001844 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001845 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001846 llvm::Module &M = CGM.getModule();
1847 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001848
1849 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001850 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001851
1852 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001853 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001854 llvm::ConstantAsMetadata::get(
1855 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1856 // Append metadata to nvvm.annotations
1857 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1858}
1859
1860void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1861 const OMPExecutableDirective &D, StringRef ParentName,
1862 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001863 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001864 if (!IsOffloadEntry) // Nothing to do.
1865 return;
1866
1867 assert(!ParentName.empty() && "Invalid target region parent name!");
1868
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001869 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001870 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001871 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001872 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001873 else
1874 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1875 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001876
1877 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001878}
1879
Alexey Bataevceeaa482018-11-21 21:04:34 +00001880namespace {
1881LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1882/// Enum for accesseing the reserved_2 field of the ident_t struct.
1883enum ModeFlagsTy : unsigned {
1884 /// Bit set to 1 when in SPMD mode.
1885 KMP_IDENT_SPMD_MODE = 0x01,
1886 /// Bit set to 1 when a simplified runtime is used.
1887 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1888 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1889};
1890
1891/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1892static const ModeFlagsTy UndefinedMode =
1893 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1894} // anonymous namespace
1895
1896unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001897 switch (getExecutionMode()) {
1898 case EM_SPMD:
1899 if (requiresFullRuntime())
1900 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1901 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1902 case EM_NonSPMD:
1903 assert(requiresFullRuntime() && "Expected full runtime.");
1904 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1905 case EM_Unknown:
1906 return UndefinedMode;
1907 }
1908 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001909}
1910
Alexey Bataevc2cd2d42019-10-10 17:28:10 +00001911bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1912 const GlobalDecl &OldGD,
1913 llvm::GlobalValue *OrigAddr,
1914 bool IsForDefinition) {
1915 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1916 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1917 if (NewFD->isDefined()) {
1918 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1919 return true;
1920 }
1921 return false;
1922}
1923
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001924CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001925 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001926 if (!CGM.getLangOpts().OpenMPIsDevice)
1927 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001928}
Carlo Bertollic6872252016-04-04 15:55:02 +00001929
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001930void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1931 OpenMPProcBindClauseKind ProcBind,
1932 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001933 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001934 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001935 return;
1936
1937 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1938}
1939
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001940void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1941 llvm::Value *NumThreads,
1942 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001943 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001944 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001945 return;
1946
1947 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1948}
1949
Carlo Bertollic6872252016-04-04 15:55:02 +00001950void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1951 const Expr *NumTeams,
1952 const Expr *ThreadLimit,
1953 SourceLocation Loc) {}
1954
James Y Knight9871db02019-02-05 16:42:33 +00001955llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001956 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1957 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001958 // Emit target region as a standalone region.
1959 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001960 bool &IsInParallelRegion;
1961 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001962
1963 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001964 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1965 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001966 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001967 PrevIsInParallelRegion = IsInParallelRegion;
1968 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969 }
1970 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001971 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001972 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001973 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001974 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001975 bool PrevIsInTTDRegion = IsInTTDRegion;
1976 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001977 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1978 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001979 auto *OutlinedFun =
1980 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1981 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001982 if (CGM.getLangOpts().Optimize) {
1983 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1984 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1985 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1986 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001987 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001988 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001989 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1990 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001991 llvm::Function *WrapperFun =
1992 createParallelDataSharingWrapper(OutlinedFun, D);
1993 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1994 }
1995
1996 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001997}
1998
Alexey Bataev2adecff2018-09-21 14:22:53 +00001999/// Get list of lastprivate variables from the teams distribute ... or
2000/// teams {distribute ...} directives.
2001static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002002getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002003 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2004 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2005 "expected teams directive.");
2006 const OMPExecutableDirective *Dir = &D;
2007 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002008 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002009 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002010 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2011 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002012 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002013 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2014 Dir = nullptr;
2015 }
2016 }
2017 if (!Dir)
2018 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002019 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002020 for (const Expr *E : C->getVarRefs())
2021 Vars.push_back(getPrivateItem(E));
2022 }
2023}
2024
2025/// Get list of reduction variables from the teams ... directives.
2026static void
2027getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2028 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2029 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2030 "expected teams directive.");
2031 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2032 for (const Expr *E : C->privates())
2033 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002034 }
2035}
2036
James Y Knight9871db02019-02-05 16:42:33 +00002037llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002038 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2039 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002040 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002041
Alexey Bataev2adecff2018-09-21 14:22:53 +00002042 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002043 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002044 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002045 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002046 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2047 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002048 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002049 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2050 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002051 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002052 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002053 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002054 }
2055 } else if (!LastPrivatesReductions.empty()) {
2056 assert(!TeamAndReductions.first &&
2057 "Previous team declaration is not expected.");
2058 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2059 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002060 }
2061
Alexey Bataevc99042b2018-03-15 18:10:54 +00002062 // Emit target region as a standalone region.
2063 class NVPTXPrePostActionTy : public PrePostActionTy {
2064 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002065 const RecordDecl *GlobalizedRD;
2066 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2067 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002068
2069 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002070 NVPTXPrePostActionTy(
2071 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2072 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2073 &MappedDeclsFields)
2074 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2075 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002076 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002077 auto &Rt =
2078 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2079 if (GlobalizedRD) {
2080 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2081 I->getSecond().GlobalRecord = GlobalizedRD;
2082 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002083 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002084 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2085 for (const auto &Pair : MappedDeclsFields) {
2086 assert(Pair.getFirst()->isCanonicalDecl() &&
2087 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002088 Data.insert(std::make_pair(Pair.getFirst(),
2089 MappedVarData(Pair.getSecond(),
2090 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002091 }
2092 }
2093 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002094 }
2095 void Exit(CodeGenFunction &CGF) override {
2096 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2097 .emitGenericVarsEpilog(CGF);
2098 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002099 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2100 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002101 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002102 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002103 if (CGM.getLangOpts().Optimize) {
2104 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2105 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2106 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2107 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002108
2109 return OutlinedFun;
2110}
2111
Alexey Bataevc99042b2018-03-15 18:10:54 +00002112void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002113 SourceLocation Loc,
2114 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002115 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2116 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002117 return;
2118
Alexey Bataevc99042b2018-03-15 18:10:54 +00002119 CGBuilderTy &Bld = CGF.Builder;
2120
2121 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2122 if (I == FunctionGlobalizedDecls.end())
2123 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002124 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002125 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002126 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002127
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002128 // Recover pointer to this function's global record. The runtime will
2129 // handle the specifics of the allocation of the memory.
2130 // Use actual memory size of the record including the padding
2131 // for alignment purposes.
2132 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002133 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002134 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002135 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002136 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002137
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002138 llvm::PointerType *GlobalRecPtrTy =
2139 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002141 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002142 if (!IsInTTDRegion &&
2143 (WithSPMDCheck ||
2144 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002145 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2146 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2147 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002148 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2149 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2150 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2151 llvm::Value *PL = CGF.EmitRuntimeCall(
2152 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2153 {RTLoc, ThreadID});
2154 IsTTD = Bld.CreateIsNull(PL);
2155 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002156 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2157 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2158 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2159 // There is no need to emit line number for unconditional branch.
2160 (void)ApplyDebugLocation::CreateEmpty(CGF);
2161 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002162 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2163 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002164 CGF.EmitBranch(ExitBB);
2165 // There is no need to emit line number for unconditional branch.
2166 (void)ApplyDebugLocation::CreateEmpty(CGF);
2167 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002168 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2169 if (const RecordDecl *SecGlobalizedVarsRecord =
2170 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2171 SecGlobalRecTy =
2172 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2173
2174 // Recover pointer to this function's global record. The runtime will
2175 // handle the specifics of the allocation of the memory.
2176 // Use actual memory size of the record including the padding
2177 // for alignment purposes.
2178 unsigned Alignment =
2179 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2180 unsigned GlobalRecordSize =
2181 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2182 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2183 Size = Bld.CreateSelect(
2184 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2185 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002186 // TODO: allow the usage of shared memory to be controlled by
2187 // the user, for now, default to global.
2188 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002189 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002190 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2191 createNVPTXRuntimeFunction(
2192 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2193 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002194 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002195 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002196 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002197 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002198 /*NumReservedValues=*/2, "_select_stack");
2199 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2200 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2201 GlobalRecCastAddr = Phi;
2202 I->getSecond().GlobalRecordAddr = Phi;
2203 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002204 } else if (IsInTTDRegion) {
2205 assert(GlobalizedRecords.back().Records.size() < 2 &&
2206 "Expected less than 2 globalized records: one for target and one "
2207 "for teams.");
2208 unsigned Offset = 0;
2209 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2210 QualType RDTy = CGM.getContext().getRecordType(RD);
2211 unsigned Alignment =
2212 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2213 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2214 Offset =
2215 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2216 }
2217 unsigned Alignment =
2218 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2219 Offset = llvm::alignTo(Offset, Alignment);
2220 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2221 ++GlobalizedRecords.back().RegionCounter;
2222 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002223 assert(KernelStaticGlobalized &&
2224 "Kernel static pointer must be initialized already.");
2225 auto *UseSharedMemory = new llvm::GlobalVariable(
2226 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2227 llvm::GlobalValue::InternalLinkage, nullptr,
2228 "_openmp_static_kernel$is_shared");
2229 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2230 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2231 /*DestWidth=*/16, /*Signed=*/0);
2232 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2233 Address(UseSharedMemory,
2234 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2235 /*Volatile=*/false, Int16Ty, Loc);
2236 auto *StaticGlobalized = new llvm::GlobalVariable(
2237 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002238 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002239 auto *RecSize = new llvm::GlobalVariable(
2240 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2241 llvm::GlobalValue::InternalLinkage, nullptr,
2242 "_openmp_static_kernel$size");
2243 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2244 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002245 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002246 CGM.getContext().getSizeType(), Loc);
2247 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2248 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002249 llvm::Value *GlobalRecordSizeArg[] = {
2250 llvm::ConstantInt::get(
2251 CGM.Int16Ty,
2252 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2253 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002254 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2255 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2256 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002257 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002258 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002259 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2260 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002261 }
2262 assert(KernelStaticGlobalized && "Global address must be set already.");
2263 Address FrameAddr = CGF.EmitLoadOfPointer(
2264 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2265 CGM.getContext()
2266 .getPointerType(CGM.getContext().VoidPtrTy)
2267 .castAs<PointerType>());
2268 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002269 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002270 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2271 I->getSecond().IsInSPMDModeFlag = nullptr;
2272 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2273 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002274 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002275 // TODO: allow the usage of shared memory to be controlled by
2276 // the user, for now, default to global.
2277 llvm::Value *GlobalRecordSizeArg[] = {
2278 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2279 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002280 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2281 createNVPTXRuntimeFunction(
2282 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2283 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002284 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002285 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002286 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2287 I->getSecond().IsInSPMDModeFlag = nullptr;
2288 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002289 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002290 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002291
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002292 // Emit the "global alloca" which is a GEP from the global declaration
2293 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002294 LValue SecBase;
2295 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2296 if (IsTTD) {
2297 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2298 llvm::PointerType *SecGlobalRecPtrTy =
2299 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2300 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2301 Bld.CreatePointerBitCastOrAddrSpaceCast(
2302 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2303 SecGlobalRecTy);
2304 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002305 for (auto &Rec : I->getSecond().LocalVarData) {
2306 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2307 llvm::Value *ParValue;
2308 if (EscapedParam) {
2309 const auto *VD = cast<VarDecl>(Rec.first);
2310 LValue ParLVal =
2311 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2312 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2313 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002314 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2315 // Emit VarAddr basing on lane-id if required.
2316 QualType VarTy;
2317 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002318 VarTy = Rec.second.FD->getType();
2319 } else {
2320 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002321 VarAddr.getAddress(CGF).getPointer(),
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002322 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002323 VarTy =
2324 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002325 VarAddr = CGF.MakeAddrLValue(
2326 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2327 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002328 }
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002329 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
Alexey Bataeve4090182018-11-02 14:54:07 +00002330 if (!IsInTTDRegion &&
2331 (WithSPMDCheck ||
2332 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002333 assert(I->getSecond().IsInSPMDModeFlag &&
2334 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002335 if (IsTTD) {
2336 assert(SecIt->second.IsOnePerTeam &&
2337 "Secondary glob data must be one per team.");
2338 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2339 VarAddr.setAddress(
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002340 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(CGF),
2341 VarAddr.getPointer(CGF)),
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002342 VarAddr.getAlignment()));
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002343 Rec.second.PrivateAddr = VarAddr.getAddress(CGF);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002344 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002345 Address GlobalPtr = Rec.second.PrivateAddr;
2346 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2347 Rec.second.PrivateAddr = Address(
2348 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2349 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2350 LocalAddr.getAlignment());
2351 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002352 if (EscapedParam) {
2353 const auto *VD = cast<VarDecl>(Rec.first);
2354 CGF.EmitStoreOfScalar(ParValue, VarAddr);
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002355 I->getSecond().MappedParams->setVarAddr(CGF, VD,
2356 VarAddr.getAddress(CGF));
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002357 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002358 if (IsTTD)
2359 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002360 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002361 }
2362 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2363 // Recover pointer to this function's global record. The runtime will
2364 // handle the specifics of the allocation of the memory.
2365 // Use actual memory size of the record including the padding
2366 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002367 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002368 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2369 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2370 Size = Bld.CreateNUWAdd(
2371 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2372 llvm::Value *AlignVal =
2373 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2374 Size = Bld.CreateUDiv(Size, AlignVal);
2375 Size = Bld.CreateNUWMul(Size, AlignVal);
2376 // TODO: allow the usage of shared memory to be controlled by
2377 // the user, for now, default to global.
2378 llvm::Value *GlobalRecordSizeArg[] = {
2379 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2380 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002381 createNVPTXRuntimeFunction(
2382 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002383 GlobalRecordSizeArg);
2384 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2385 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2386 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2387 CGM.getContext().getDeclAlign(VD),
2388 AlignmentSource::Decl);
2389 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08002390 Base.getAddress(CGF));
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002391 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002392 }
2393 I->getSecond().MappedParams->apply(CGF);
2394}
2395
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002396void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2397 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002398 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2399 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002400 return;
2401
Alexey Bataevc99042b2018-03-15 18:10:54 +00002402 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002403 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002404 I->getSecond().MappedParams->restore(CGF);
2405 if (!CGF.HaveInsertPoint())
2406 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002407 for (llvm::Value *Addr :
2408 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2409 CGF.EmitRuntimeCall(
2410 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2411 Addr);
2412 }
2413 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002414 if (!IsInTTDRegion &&
2415 (WithSPMDCheck ||
2416 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002417 CGBuilderTy &Bld = CGF.Builder;
2418 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2419 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2420 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2421 // There is no need to emit line number for unconditional branch.
2422 (void)ApplyDebugLocation::CreateEmpty(CGF);
2423 CGF.EmitBlock(NonSPMDBB);
2424 CGF.EmitRuntimeCall(
2425 createNVPTXRuntimeFunction(
2426 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2427 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2428 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002429 } else if (IsInTTDRegion) {
2430 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2431 "region counter must be > 0.");
2432 --GlobalizedRecords.back().RegionCounter;
2433 // Emit the restore function only in the target region.
2434 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002435 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2436 /*DestWidth=*/16, /*Signed=*/0);
2437 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2438 Address(GlobalizedRecords.back().UseSharedMemory,
2439 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2440 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002441 llvm::Value *Args[] = {
2442 llvm::ConstantInt::get(
2443 CGM.Int16Ty,
2444 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2445 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002446 CGF.EmitRuntimeCall(
2447 createNVPTXRuntimeFunction(
2448 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002449 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002450 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002451 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002452 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2453 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2454 I->getSecond().GlobalRecordAddr);
2455 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002456 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002457 }
2458}
2459
Carlo Bertollic6872252016-04-04 15:55:02 +00002460void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2461 const OMPExecutableDirective &D,
2462 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002463 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002464 ArrayRef<llvm::Value *> CapturedVars) {
2465 if (!CGF.HaveInsertPoint())
2466 return;
2467
Alexey Bataevf89cf212019-10-16 16:59:01 +00002468 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2469 /*Name=*/".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002470 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2471 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002472 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002473 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2474 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002475 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002476}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002477
2478void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002479 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002480 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2481 if (!CGF.HaveInsertPoint())
2482 return;
2483
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002484 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002485 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002486 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002487 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002488}
2489
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002490void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002491 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2492 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2493 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002494
2495 // Force inline this outlined function at its call site.
2496 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2497
Alexey Bataevf89cf212019-10-16 16:59:01 +00002498 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2499 /*Name=*/".zero.addr");
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002500 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002501 // ThreadId for serialized parallels is 0.
2502 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002503 auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002504 CodeGenFunction &CGF, PrePostActionTy &Action) {
2505 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002506
Alexey Bataevf89cf212019-10-16 16:59:01 +00002507 Address ZeroAddr =
2508 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2509 /*Name=*/".bound.zero.addr");
2510 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002511 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2512 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2513 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2514 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2515 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2516 };
2517 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2518 PrePostActionTy &) {
2519
2520 RegionCodeGenTy RCG(CodeGen);
2521 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2522 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2523 llvm::Value *Args[] = {RTLoc, ThreadID};
2524
2525 NVPTXActionTy Action(
2526 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2527 Args,
2528 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2529 Args);
2530 RCG.setAction(Action);
2531 RCG(CGF);
2532 };
2533
2534 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2535 PrePostActionTy &Action) {
2536 CGBuilderTy &Bld = CGF.Builder;
2537 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2538 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002539 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2540
2541 // Prepare for parallel region. Indicate the outlined function.
2542 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002543 CGF.EmitRuntimeCall(
2544 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2545 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002546
2547 // Create a private scope that will globalize the arguments
2548 // passed from the outside of the target region.
2549 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2550
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002551 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002552 if (!CapturedVars.empty()) {
2553 // Prepare for parallel region. Indicate the outlined function.
2554 Address SharedArgs =
2555 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2556 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2557
2558 llvm::Value *DataSharingArgs[] = {
2559 SharedArgsPtr,
2560 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2561 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2562 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2563 DataSharingArgs);
2564
2565 // Store variable address in a list of references to pass to workers.
2566 unsigned Idx = 0;
2567 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002568 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2569 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2570 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002571 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002572 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002573 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002574 if (V->getType()->isIntegerTy())
2575 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2576 else
2577 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002578 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2579 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002580 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002581 }
2582 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002583
2584 // Activate workers. This barrier is used by the master to signal
2585 // work for the workers.
2586 syncCTAThreads(CGF);
2587
2588 // OpenMP [2.5, Parallel Construct, p.49]
2589 // There is an implied barrier at the end of a parallel region. After the
2590 // end of a parallel region, only the master thread of the team resumes
2591 // execution of the enclosing task region.
2592 //
2593 // The master waits at this barrier until all workers are done.
2594 syncCTAThreads(CGF);
2595
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002596 if (!CapturedVars.empty())
2597 CGF.EmitRuntimeCall(
2598 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2599
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002600 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002601 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002602 };
2603
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002604 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2605 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002606 if (IsInParallelRegion) {
2607 SeqGen(CGF, Action);
2608 } else if (IsInTargetMasterThreadRegion) {
2609 L0ParallelGen(CGF, Action);
2610 } else {
2611 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002612 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002613 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002614 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002615 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002616 // }
2617 CGBuilderTy &Bld = CGF.Builder;
2618 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002619 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2620 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002621 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002622 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2623 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002624 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002625 // There is no need to emit line number for unconditional branch.
2626 (void)ApplyDebugLocation::CreateEmpty(CGF);
2627 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002628 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2629 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2630 llvm::Value *PL = CGF.EmitRuntimeCall(
2631 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2632 {RTLoc, ThreadID});
2633 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002634 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002635 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002636 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002637 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002638 // There is no need to emit line number for unconditional branch.
2639 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002640 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002641 L0ParallelGen(CGF, Action);
2642 CGF.EmitBranch(ExitBB);
2643 // There is no need to emit line number for unconditional branch.
2644 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002645 // Emit the continuation block for code after the if.
2646 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2647 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002648 };
2649
Alexey Bataev9ff80832018-04-16 20:16:21 +00002650 if (IfCond) {
Alexey Bataev1d943ae2019-11-19 12:12:23 -05002651 emitIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002652 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002653 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002654 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002655 ThenRCG(CGF);
2656 }
2657}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002658
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002659void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002660 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002661 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2662 // Just call the outlined function to execute the parallel region.
2663 // OutlinedFn(&GTid, &zero, CapturedStruct);
2664 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002665 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002666
Alexey Bataevf89cf212019-10-16 16:59:01 +00002667 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2668 /*Name=*/".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002669 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002670 // ThreadId for serialized parallels is 0.
2671 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002672 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2673 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002674 Action.Enter(CGF);
2675
Alexey Bataevf89cf212019-10-16 16:59:01 +00002676 Address ZeroAddr =
2677 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2678 /*Name=*/".bound.zero.addr");
2679 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002680 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2681 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2682 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2683 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2684 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2685 };
2686 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2687 PrePostActionTy &) {
2688
2689 RegionCodeGenTy RCG(CodeGen);
2690 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2691 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2692 llvm::Value *Args[] = {RTLoc, ThreadID};
2693
2694 NVPTXActionTy Action(
2695 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2696 Args,
2697 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2698 Args);
2699 RCG.setAction(Action);
2700 RCG(CGF);
2701 };
2702
2703 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002704 // In the worker need to use the real thread id.
2705 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002706 RegionCodeGenTy RCG(CodeGen);
2707 RCG(CGF);
2708 } else {
2709 // If we are not in the target region, it is definitely L2 parallelism or
2710 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2711 // need to check for orphaned directives.
2712 RegionCodeGenTy RCG(SeqGen);
2713 RCG(CGF);
2714 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002715}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002716
Alexey Bataeva3924b52019-01-03 16:25:35 +00002717void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2718 // Always emit simple barriers!
2719 if (!CGF.HaveInsertPoint())
2720 return;
2721 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2722 // This function does not use parameters, so we can emit just default values.
2723 llvm::Value *Args[] = {
2724 llvm::ConstantPointerNull::get(
2725 cast<llvm::PointerType>(getIdentTyPointerTy())),
2726 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002727 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002728 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002729 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002730}
2731
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002732void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2733 SourceLocation Loc,
2734 OpenMPDirectiveKind Kind, bool,
2735 bool) {
2736 // Always emit simple barriers!
2737 if (!CGF.HaveInsertPoint())
2738 return;
2739 // Build call __kmpc_cancel_barrier(loc, thread_id);
2740 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2741 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2742 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002743 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2744 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2745 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002746}
2747
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002748void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2749 CodeGenFunction &CGF, StringRef CriticalName,
2750 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2751 const Expr *Hint) {
2752 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2753 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2754 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2755 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2756 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2757
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002758 // Get the mask of active threads in the warp.
2759 llvm::Value *Mask = CGF.EmitRuntimeCall(
2760 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002761 // Fetch team-local id of the thread.
2762 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2763
2764 // Get the width of the team.
2765 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2766
2767 // Initialize the counter variable for the loop.
2768 QualType Int32Ty =
2769 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2770 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2771 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2772 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2773 /*isInit=*/true);
2774
2775 // Block checks if loop counter exceeds upper bound.
2776 CGF.EmitBlock(LoopBB);
2777 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2778 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2779 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2780
2781 // Block tests which single thread should execute region, and which threads
2782 // should go straight to synchronisation point.
2783 CGF.EmitBlock(TestBB);
2784 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2785 llvm::Value *CmpThreadToCounter =
2786 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2787 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2788
2789 // Block emits the body of the critical region.
2790 CGF.EmitBlock(BodyBB);
2791
2792 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002793 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2794 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002795
2796 // After the body surrounded by the critical region, the single executing
2797 // thread will jump to the synchronisation point.
2798 // Block waits for all threads in current team to finish then increments the
2799 // counter variable and returns to the loop.
2800 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002801 // Reconverge active threads in the warp.
2802 (void)CGF.EmitRuntimeCall(
2803 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002804
2805 llvm::Value *IncCounterVal =
2806 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2807 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2808 CGF.EmitBranch(LoopBB);
2809
2810 // Block that is reached when all threads in the team complete the region.
2811 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2812}
2813
Alexey Bataevb2575932018-01-04 20:18:55 +00002814/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002815static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2816 QualType ValTy, QualType CastTy,
2817 SourceLocation Loc) {
2818 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2819 "Cast type must sized.");
2820 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2821 "Val type must sized.");
2822 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2823 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002824 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002825 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2826 CGF.getContext().getTypeSizeInChars(CastTy))
2827 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2828 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2829 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2830 CastTy->hasSignedIntegerRepresentation());
2831 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002832 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2833 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002834 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2835 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002836}
2837
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002838/// This function creates calls to one of two shuffle functions to copy
2839/// variables between lanes in a warp.
2840static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002841 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002842 QualType ElemType,
2843 llvm::Value *Offset,
2844 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002845 CodeGenModule &CGM = CGF.CGM;
2846 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002847 CGOpenMPRuntimeNVPTX &RT =
2848 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2849
Alexey Bataeva453f362018-03-19 17:53:56 +00002850 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2851 assert(Size.getQuantity() <= 8 &&
2852 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002853
Alexey Bataeva453f362018-03-19 17:53:56 +00002854 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002855 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2856 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2857
2858 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002859 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2860 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2861 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002862 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002863 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002864
Alexey Bataev9ff80832018-04-16 20:16:21 +00002865 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2866 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002867
Alexey Bataeva453f362018-03-19 17:53:56 +00002868 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002869}
2870
Alexey Bataev12c62902018-06-22 19:10:38 +00002871static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2872 Address DestAddr, QualType ElemType,
2873 llvm::Value *Offset, SourceLocation Loc) {
2874 CGBuilderTy &Bld = CGF.Builder;
2875
2876 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2877 // Create the loop over the big sized data.
2878 // ptr = (void*)Elem;
2879 // ptrEnd = (void*) Elem + 1;
2880 // Step = 8;
2881 // while (ptr + Step < ptrEnd)
2882 // shuffle((int64_t)*ptr);
2883 // Step = 4;
2884 // while (ptr + Step < ptrEnd)
2885 // shuffle((int32_t)*ptr);
2886 // ...
2887 Address ElemPtr = DestAddr;
2888 Address Ptr = SrcAddr;
2889 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002890 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002891 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2892 if (Size < CharUnits::fromQuantity(IntSize))
2893 continue;
2894 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2895 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2896 /*Signed=*/1);
2897 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2898 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2899 ElemPtr =
2900 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2901 if (Size.getQuantity() / IntSize > 1) {
2902 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2903 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2904 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2905 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2906 CGF.EmitBlock(PreCondBB);
2907 llvm::PHINode *PhiSrc =
2908 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2909 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2910 llvm::PHINode *PhiDest =
2911 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2912 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2913 Ptr = Address(PhiSrc, Ptr.getAlignment());
2914 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2915 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2916 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2917 Ptr.getPointer(), CGF.VoidPtrTy));
2918 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2919 ThenBB, ExitBB);
2920 CGF.EmitBlock(ThenBB);
2921 llvm::Value *Res = createRuntimeShuffleFunction(
2922 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2923 IntType, Offset, Loc);
2924 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002925 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2926 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002927 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2928 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002929 CGF.EmitBranch(PreCondBB);
2930 CGF.EmitBlock(ExitBB);
2931 } else {
2932 llvm::Value *Res = createRuntimeShuffleFunction(
2933 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2934 IntType, Offset, Loc);
2935 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002936 Ptr = Bld.CreateConstGEP(Ptr, 1);
2937 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002938 }
2939 Size = Size % IntSize;
2940 }
2941}
2942
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002943namespace {
2944enum CopyAction : unsigned {
2945 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2946 // the warp using shuffle instructions.
2947 RemoteLaneToThread,
2948 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2949 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002950 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2951 ThreadToScratchpad,
2952 // ScratchpadToThread: Copy from a scratchpad array in global memory
2953 // containing team-reduced data to a thread's stack.
2954 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002955};
2956} // namespace
2957
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002958struct CopyOptionsTy {
2959 llvm::Value *RemoteLaneOffset;
2960 llvm::Value *ScratchpadIndex;
2961 llvm::Value *ScratchpadWidth;
2962};
2963
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002964/// Emit instructions to copy a Reduce list, which contains partially
2965/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002966static void emitReductionListCopy(
2967 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2968 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2969 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002970
Alexey Bataev9ff80832018-04-16 20:16:21 +00002971 CodeGenModule &CGM = CGF.CGM;
2972 ASTContext &C = CGM.getContext();
2973 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002974
Alexey Bataev9ff80832018-04-16 20:16:21 +00002975 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2976 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2977 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002978
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002979 // Iterates, element-by-element, through the source Reduce list and
2980 // make a copy.
2981 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002982 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002983 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002984 Address SrcElementAddr = Address::invalid();
2985 Address DestElementAddr = Address::invalid();
2986 Address DestElementPtrAddr = Address::invalid();
2987 // Should we shuffle in an element from a remote lane?
2988 bool ShuffleInElement = false;
2989 // Set to true to update the pointer in the dest Reduce list to a
2990 // newly created element.
2991 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002992 // Increment the src or dest pointer to the scratchpad, for each
2993 // new element.
2994 bool IncrScratchpadSrc = false;
2995 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002996
2997 switch (Action) {
2998 case RemoteLaneToThread: {
2999 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003000 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003001 SrcElementAddr = CGF.EmitLoadOfPointer(
3002 SrcElementPtrAddr,
3003 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003004
3005 // Step 1.2: Create a temporary to store the element in the destination
3006 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003007 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003008 DestElementAddr =
3009 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3010 ShuffleInElement = true;
3011 UpdateDestListPtr = true;
3012 break;
3013 }
3014 case ThreadCopy: {
3015 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003016 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003017 SrcElementAddr = CGF.EmitLoadOfPointer(
3018 SrcElementPtrAddr,
3019 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003020
3021 // Step 1.2: Get the address for dest element. The destination
3022 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003023 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003024 DestElementAddr = CGF.EmitLoadOfPointer(
3025 DestElementPtrAddr,
3026 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003027 break;
3028 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003029 case ThreadToScratchpad: {
3030 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003031 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003032 SrcElementAddr = CGF.EmitLoadOfPointer(
3033 SrcElementPtrAddr,
3034 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003035
3036 // Step 1.2: Get the address for dest element:
3037 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003038 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003039 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003040 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003041 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003042 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003043 ScratchPadElemAbsolutePtrVal =
3044 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003045 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3046 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003047 IncrScratchpadDest = true;
3048 break;
3049 }
3050 case ScratchpadToThread: {
3051 // Step 1.1: Get the address for the src element in the scratchpad.
3052 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003053 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003054 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003055 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003056 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003057 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003058 ScratchPadElemAbsolutePtrVal =
3059 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3060 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3061 C.getTypeAlignInChars(Private->getType()));
3062 IncrScratchpadSrc = true;
3063
3064 // Step 1.2: Create a temporary to store the element in the destination
3065 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003066 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003067 DestElementAddr =
3068 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3069 UpdateDestListPtr = true;
3070 break;
3071 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003072 }
3073
3074 // Regardless of src and dest of copy, we emit the load of src
3075 // element as this is required in all directions
3076 SrcElementAddr = Bld.CreateElementBitCast(
3077 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003078 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3079 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003080
3081 // Now that all active lanes have read the element in the
3082 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003083 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003084 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3085 RemoteLaneOffset, Private->getExprLoc());
3086 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003087 switch (CGF.getEvaluationKind(Private->getType())) {
3088 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003089 llvm::Value *Elem =
3090 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3091 Private->getType(), Private->getExprLoc());
3092 // Store the source element value to the dest element address.
3093 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3094 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003095 break;
3096 }
3097 case TEK_Complex: {
3098 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3099 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3100 Private->getExprLoc());
3101 CGF.EmitStoreOfComplex(
3102 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3103 /*isInit=*/false);
3104 break;
3105 }
3106 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003107 CGF.EmitAggregateCopy(
3108 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3109 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3110 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003111 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003112 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003113 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003114
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003115 // Step 3.1: Modify reference in dest Reduce list as needed.
3116 // Modifying the reference in Reduce list to point to the newly
3117 // created element. The element is live in the current function
3118 // scope and that of functions it invokes (i.e., reduce_function).
3119 // RemoteReduceData[i] = (void*)&RemoteElem
3120 if (UpdateDestListPtr) {
3121 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3122 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3123 DestElementPtrAddr, /*Volatile=*/false,
3124 C.VoidPtrTy);
3125 }
3126
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003127 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3128 // address of the next element in scratchpad memory, unless we're currently
3129 // processing the last one. Memory alignment is also taken care of here.
3130 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3131 llvm::Value *ScratchpadBasePtr =
3132 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003133 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3134 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003135 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003136 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003137
3138 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003139 ScratchpadBasePtr = Bld.CreateNUWSub(
3140 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3141 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003142 ScratchpadBasePtr,
3143 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003144 ScratchpadBasePtr = Bld.CreateNUWAdd(
3145 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3146 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003147 ScratchpadBasePtr,
3148 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3149
3150 if (IncrScratchpadDest)
3151 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3152 else /* IncrScratchpadSrc = true */
3153 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3154 }
3155
Alexey Bataev9ff80832018-04-16 20:16:21 +00003156 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003157 }
3158}
3159
3160/// This function emits a helper that gathers Reduce lists from the first
3161/// lane of every active warp to lanes in the first warp.
3162///
3163/// void inter_warp_copy_func(void* reduce_data, num_warps)
3164/// shared smem[warp_size];
3165/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003166/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003167/// If (I am the first lane in each warp)
3168/// Copy my local D to smem[warp_id]
3169/// sync
3170/// if (I am the first warp)
3171/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3173 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003174 QualType ReductionArrayTy,
3175 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003176 ASTContext &C = CGM.getContext();
3177 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178
3179 // ReduceList: thread local Reduce list.
3180 // At the stage of the computation when this function is called, partially
3181 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003182 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3183 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003184 // NumWarps: number of warps active in the parallel region. This could
3185 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003186 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003187 C.getIntTypeForBitwidth(32, /* Signed */ true),
3188 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003189 FunctionArgList Args;
3190 Args.push_back(&ReduceListArg);
3191 Args.push_back(&NumWarpsArg);
3192
Alexey Bataev9ff80832018-04-16 20:16:21 +00003193 const CGFunctionInfo &CGFI =
3194 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003195 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3196 llvm::GlobalValue::InternalLinkage,
3197 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003198 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003199 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003200 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003201 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003202
Alexey Bataev9ff80832018-04-16 20:16:21 +00003203 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003204
3205 // This array is used as a medium to transfer, one reduce element at a time,
3206 // the data from the first lane of every warp to lanes in the first warp
3207 // in order to perform the final step of a reduction in a parallel region
3208 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3209 // for reduced latency, as well as to have a distinct copy for concurrently
3210 // executing target regions. The array is declared with common linkage so
3211 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003212 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003213 "__openmp_nvptx_data_transfer_temporary_storage";
3214 llvm::GlobalVariable *TransferMedium =
3215 M.getGlobalVariable(TransferMediumName);
3216 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003217 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003218 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3219 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003220 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003221 llvm::Constant::getNullValue(Ty), TransferMediumName,
3222 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3223 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003224 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003225 }
3226
3227 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003228 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003229 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003230 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003231 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003232 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003233
3234 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3235 Address LocalReduceList(
3236 Bld.CreatePointerBitCastOrAddrSpaceCast(
3237 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003238 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003239 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3240 CGF.getPointerAlign());
3241
3242 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003243 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003244 //
3245 // Warp master copies reduce element to transfer medium in __shared__
3246 // memory.
3247 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003248 unsigned RealTySize =
3249 C.getTypeSizeInChars(Private->getType())
3250 .alignTo(C.getTypeAlignInChars(Private->getType()))
3251 .getQuantity();
3252 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3253 unsigned NumIters = RealTySize / TySize;
3254 if (NumIters == 0)
3255 continue;
3256 QualType CType = C.getIntTypeForBitwidth(
3257 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3258 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3259 CharUnits Align = CharUnits::fromQuantity(TySize);
3260 llvm::Value *Cnt = nullptr;
3261 Address CntAddr = Address::invalid();
3262 llvm::BasicBlock *PrecondBB = nullptr;
3263 llvm::BasicBlock *ExitBB = nullptr;
3264 if (NumIters > 1) {
3265 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3266 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3267 /*Volatile=*/false, C.IntTy);
3268 PrecondBB = CGF.createBasicBlock("precond");
3269 ExitBB = CGF.createBasicBlock("exit");
3270 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3271 // There is no need to emit line number for unconditional branch.
3272 (void)ApplyDebugLocation::CreateEmpty(CGF);
3273 CGF.EmitBlock(PrecondBB);
3274 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3275 llvm::Value *Cmp =
3276 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3277 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3278 CGF.EmitBlock(BodyBB);
3279 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003280 // kmpc_barrier.
3281 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3282 /*EmitChecks=*/false,
3283 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003284 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3285 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3286 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003287
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003288 // if (lane_id == 0)
3289 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3290 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3291 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003292
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003293 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003294 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003295 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3296 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3297 // elemptr = ((CopyType*)(elemptrptr)) + I
3298 Address ElemPtr = Address(ElemPtrPtr, Align);
3299 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3300 if (NumIters > 1) {
3301 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3302 ElemPtr.getAlignment());
3303 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003304
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003305 // Get pointer to location in transfer medium.
3306 // MediumPtr = &medium[warp_id]
3307 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3308 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3309 Address MediumPtr(MediumPtrVal, Align);
3310 // Casting to actual data type.
3311 // MediumPtr = (CopyType*)MediumPtrAddr;
3312 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003313
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003314 // elem = *elemptr
3315 //*MediumPtr = elem
3316 llvm::Value *Elem =
3317 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003318 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003319 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003320
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003321 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003322
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003323 CGF.EmitBlock(ElseBB);
3324 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003325
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003326 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003327
Alexey Bataevae51b962018-12-14 21:00:58 +00003328 // kmpc_barrier.
3329 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3330 /*EmitChecks=*/false,
3331 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003332
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003333 //
3334 // Warp 0 copies reduce element from transfer medium.
3335 //
3336 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3337 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3338 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003339
Alexey Bataevae51b962018-12-14 21:00:58 +00003340 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3341 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3342 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3343
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003344 // Up to 32 threads in warp 0 are active.
3345 llvm::Value *IsActiveThread =
3346 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3347 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003348
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003349 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003350
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003351 // SrcMediumPtr = &medium[tid]
3352 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3353 TransferMedium,
3354 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3355 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3356 // SrcMediumVal = *SrcMediumPtr;
3357 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003358
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003359 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003360 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003361 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3362 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3363 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3364 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3365 if (NumIters > 1) {
3366 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3367 TargetElemPtr.getAlignment());
3368 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003369
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003370 // *TargetElemPtr = SrcMediumVal;
3371 llvm::Value *SrcMediumValue =
3372 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003373 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003374 CType);
3375 Bld.CreateBr(W0MergeBB);
3376
3377 CGF.EmitBlock(W0ElseBB);
3378 Bld.CreateBr(W0MergeBB);
3379
3380 CGF.EmitBlock(W0MergeBB);
3381
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003382 if (NumIters > 1) {
3383 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3384 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3385 CGF.EmitBranch(PrecondBB);
3386 (void)ApplyDebugLocation::CreateEmpty(CGF);
3387 CGF.EmitBlock(ExitBB);
3388 }
3389 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003390 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003391 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003392 }
3393
3394 CGF.FinishFunction();
3395 return Fn;
3396}
3397
3398/// Emit a helper that reduces data across two OpenMP threads (lanes)
3399/// in the same warp. It uses shuffle instructions to copy over data from
3400/// a remote lane's stack. The reduction algorithm performed is specified
3401/// by the fourth parameter.
3402///
3403/// Algorithm Versions.
3404/// Full Warp Reduce (argument value 0):
3405/// This algorithm assumes that all 32 lanes are active and gathers
3406/// data from these 32 lanes, producing a single resultant value.
3407/// Contiguous Partial Warp Reduce (argument value 1):
3408/// This algorithm assumes that only a *contiguous* subset of lanes
3409/// are active. This happens for the last warp in a parallel region
3410/// when the user specified num_threads is not an integer multiple of
3411/// 32. This contiguous subset always starts with the zeroth lane.
3412/// Partial Warp Reduce (argument value 2):
3413/// This algorithm gathers data from any number of lanes at any position.
3414/// All reduced values are stored in the lowest possible lane. The set
3415/// of problems every algorithm addresses is a super set of those
3416/// addressable by algorithms with a lower version number. Overhead
3417/// increases as algorithm version increases.
3418///
3419/// Terminology
3420/// Reduce element:
3421/// Reduce element refers to the individual data field with primitive
3422/// data types to be combined and reduced across threads.
3423/// Reduce list:
3424/// Reduce list refers to a collection of local, thread-private
3425/// reduce elements.
3426/// Remote Reduce list:
3427/// Remote Reduce list refers to a collection of remote (relative to
3428/// the current thread) reduce elements.
3429///
3430/// We distinguish between three states of threads that are important to
3431/// the implementation of this function.
3432/// Alive threads:
3433/// Threads in a warp executing the SIMT instruction, as distinguished from
3434/// threads that are inactive due to divergent control flow.
3435/// Active threads:
3436/// The minimal set of threads that has to be alive upon entry to this
3437/// function. The computation is correct iff active threads are alive.
3438/// Some threads are alive but they are not active because they do not
3439/// contribute to the computation in any useful manner. Turning them off
3440/// may introduce control flow overheads without any tangible benefits.
3441/// Effective threads:
3442/// In order to comply with the argument requirements of the shuffle
3443/// function, we must keep all lanes holding data alive. But at most
3444/// half of them perform value aggregation; we refer to this half of
3445/// threads as effective. The other half is simply handing off their
3446/// data.
3447///
3448/// Procedure
3449/// Value shuffle:
3450/// In this step active threads transfer data from higher lane positions
3451/// in the warp to lower lane positions, creating Remote Reduce list.
3452/// Value aggregation:
3453/// In this step, effective threads combine their thread local Reduce list
3454/// with Remote Reduce list and store the result in the thread local
3455/// Reduce list.
3456/// Value copy:
3457/// In this step, we deal with the assumption made by algorithm 2
3458/// (i.e. contiguity assumption). When we have an odd number of lanes
3459/// active, say 2k+1, only k threads will be effective and therefore k
3460/// new values will be produced. However, the Reduce list owned by the
3461/// (2k+1)th thread is ignored in the value aggregation. Therefore
3462/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3463/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003464static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003465 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003466 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003467 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003468
3469 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003470 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3471 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003472 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003473 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3474 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003475 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003476 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3477 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003478 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003479 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3480 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003481 FunctionArgList Args;
3482 Args.push_back(&ReduceListArg);
3483 Args.push_back(&LaneIDArg);
3484 Args.push_back(&RemoteLaneOffsetArg);
3485 Args.push_back(&AlgoVerArg);
3486
Alexey Bataev9ff80832018-04-16 20:16:21 +00003487 const CGFunctionInfo &CGFI =
3488 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003489 auto *Fn = llvm::Function::Create(
3490 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3491 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003492 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003493 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003494 if (CGM.getLangOpts().Optimize) {
3495 Fn->removeFnAttr(llvm::Attribute::NoInline);
3496 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3497 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3498 }
3499
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003500 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003501 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003502
Alexey Bataev9ff80832018-04-16 20:16:21 +00003503 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003504
3505 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3506 Address LocalReduceList(
3507 Bld.CreatePointerBitCastOrAddrSpaceCast(
3508 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3509 C.VoidPtrTy, SourceLocation()),
3510 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3511 CGF.getPointerAlign());
3512
3513 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3514 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3515 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3516
3517 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3518 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3519 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3520
3521 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3522 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3523 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3524
3525 // Create a local thread-private variable to host the Reduce list
3526 // from a remote lane.
3527 Address RemoteReduceList =
3528 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3529
3530 // This loop iterates through the list of reduce elements and copies,
3531 // element by element, from a remote lane in the warp to RemoteReduceList,
3532 // hosted on the thread's stack.
3533 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3534 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003535 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3536 /*ScratchpadIndex=*/nullptr,
3537 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003538
3539 // The actions to be performed on the Remote Reduce list is dependent
3540 // on the algorithm version.
3541 //
3542 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3543 // LaneId % 2 == 0 && Offset > 0):
3544 // do the reduction value aggregation
3545 //
3546 // The thread local variable Reduce list is mutated in place to host the
3547 // reduced data, which is the aggregated value produced from local and
3548 // remote lanes.
3549 //
3550 // Note that AlgoVer is expected to be a constant integer known at compile
3551 // time.
3552 // When AlgoVer==0, the first conjunction evaluates to true, making
3553 // the entire predicate true during compile time.
3554 // When AlgoVer==1, the second conjunction has only the second part to be
3555 // evaluated during runtime. Other conjunctions evaluates to false
3556 // during compile time.
3557 // When AlgoVer==2, the third conjunction has only the second part to be
3558 // evaluated during runtime. Other conjunctions evaluates to false
3559 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003560 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003561
Alexey Bataev9ff80832018-04-16 20:16:21 +00003562 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3563 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003564 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3565
Alexey Bataev9ff80832018-04-16 20:16:21 +00003566 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3567 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3568 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003569 CondAlgo2 = Bld.CreateAnd(
3570 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3571
Alexey Bataev9ff80832018-04-16 20:16:21 +00003572 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003573 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3574
3575 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3576 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3577 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3578 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3579
3580 CGF.EmitBlock(ThenBB);
3581 // reduce_function(LocalReduceList, RemoteReduceList)
3582 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3583 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3584 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3585 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003586 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3587 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003588 Bld.CreateBr(MergeBB);
3589
3590 CGF.EmitBlock(ElseBB);
3591 Bld.CreateBr(MergeBB);
3592
3593 CGF.EmitBlock(MergeBB);
3594
3595 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3596 // Reduce list.
3597 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003598 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003599 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3600
3601 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3602 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3603 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3604 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3605
3606 CGF.EmitBlock(CpyThenBB);
3607 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3608 RemoteReduceList, LocalReduceList);
3609 Bld.CreateBr(CpyMergeBB);
3610
3611 CGF.EmitBlock(CpyElseBB);
3612 Bld.CreateBr(CpyMergeBB);
3613
3614 CGF.EmitBlock(CpyMergeBB);
3615
3616 CGF.FinishFunction();
3617 return Fn;
3618}
3619
Alexey Bataev8061acd2019-02-20 16:36:22 +00003620/// This function emits a helper that copies all the reduction variables from
3621/// the team into the provided global buffer for the reduction variables.
3622///
3623/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3624/// For all data entries D in reduce_data:
3625/// Copy local D to buffer.D[Idx]
3626static llvm::Value *emitListToGlobalCopyFunction(
3627 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3628 QualType ReductionArrayTy, SourceLocation Loc,
3629 const RecordDecl *TeamReductionRec,
3630 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3631 &VarFieldMap) {
3632 ASTContext &C = CGM.getContext();
3633
3634 // Buffer: global reduction buffer.
3635 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3636 C.VoidPtrTy, ImplicitParamDecl::Other);
3637 // Idx: index of the buffer.
3638 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3639 ImplicitParamDecl::Other);
3640 // ReduceList: thread local Reduce list.
3641 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3642 C.VoidPtrTy, ImplicitParamDecl::Other);
3643 FunctionArgList Args;
3644 Args.push_back(&BufferArg);
3645 Args.push_back(&IdxArg);
3646 Args.push_back(&ReduceListArg);
3647
3648 const CGFunctionInfo &CGFI =
3649 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3650 auto *Fn = llvm::Function::Create(
3651 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3652 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3653 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3654 Fn->setDoesNotRecurse();
3655 CodeGenFunction CGF(CGM);
3656 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3657
3658 CGBuilderTy &Bld = CGF.Builder;
3659
3660 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3661 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3662 Address LocalReduceList(
3663 Bld.CreatePointerBitCastOrAddrSpaceCast(
3664 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3665 C.VoidPtrTy, Loc),
3666 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3667 CGF.getPointerAlign());
3668 QualType StaticTy = C.getRecordType(TeamReductionRec);
3669 llvm::Type *LLVMReductionsBufferTy =
3670 CGM.getTypes().ConvertTypeForMem(StaticTy);
3671 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3672 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3673 LLVMReductionsBufferTy->getPointerTo());
3674 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3675 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3676 /*Volatile=*/false, C.IntTy,
3677 Loc)};
3678 unsigned Idx = 0;
3679 for (const Expr *Private : Privates) {
3680 // Reduce element = LocalReduceList[i]
3681 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3682 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3683 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3684 // elemptr = ((CopyType*)(elemptrptr)) + I
3685 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3686 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3687 Address ElemPtr =
3688 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3689 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3690 // Global = Buffer.VD[Idx];
3691 const FieldDecl *FD = VarFieldMap.lookup(VD);
3692 LValue GlobLVal = CGF.EmitLValueForField(
3693 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08003694 llvm::Value *BufferPtr =
3695 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003696 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3697 switch (CGF.getEvaluationKind(Private->getType())) {
3698 case TEK_Scalar: {
3699 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3700 Private->getType(), Loc);
3701 CGF.EmitStoreOfScalar(V, GlobLVal);
3702 break;
3703 }
3704 case TEK_Complex: {
3705 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3706 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3707 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3708 break;
3709 }
3710 case TEK_Aggregate:
3711 CGF.EmitAggregateCopy(GlobLVal,
3712 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3713 Private->getType(), AggValueSlot::DoesNotOverlap);
3714 break;
3715 }
3716 ++Idx;
3717 }
3718
3719 CGF.FinishFunction();
3720 return Fn;
3721}
3722
3723/// This function emits a helper that reduces all the reduction variables from
3724/// the team into the provided global buffer for the reduction variables.
3725///
3726/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3727/// void *GlobPtrs[];
3728/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3729/// ...
3730/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3731/// reduce_function(GlobPtrs, reduce_data);
3732static llvm::Value *emitListToGlobalReduceFunction(
3733 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3734 QualType ReductionArrayTy, SourceLocation Loc,
3735 const RecordDecl *TeamReductionRec,
3736 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3737 &VarFieldMap,
3738 llvm::Function *ReduceFn) {
3739 ASTContext &C = CGM.getContext();
3740
3741 // Buffer: global reduction buffer.
3742 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3743 C.VoidPtrTy, ImplicitParamDecl::Other);
3744 // Idx: index of the buffer.
3745 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3746 ImplicitParamDecl::Other);
3747 // ReduceList: thread local Reduce list.
3748 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3749 C.VoidPtrTy, ImplicitParamDecl::Other);
3750 FunctionArgList Args;
3751 Args.push_back(&BufferArg);
3752 Args.push_back(&IdxArg);
3753 Args.push_back(&ReduceListArg);
3754
3755 const CGFunctionInfo &CGFI =
3756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3757 auto *Fn = llvm::Function::Create(
3758 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3759 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3760 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3761 Fn->setDoesNotRecurse();
3762 CodeGenFunction CGF(CGM);
3763 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3764
3765 CGBuilderTy &Bld = CGF.Builder;
3766
3767 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3768 QualType StaticTy = C.getRecordType(TeamReductionRec);
3769 llvm::Type *LLVMReductionsBufferTy =
3770 CGM.getTypes().ConvertTypeForMem(StaticTy);
3771 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3772 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3773 LLVMReductionsBufferTy->getPointerTo());
3774
3775 // 1. Build a list of reduction variables.
3776 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3777 Address ReductionList =
3778 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3779 auto IPriv = Privates.begin();
3780 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3781 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3782 /*Volatile=*/false, C.IntTy,
3783 Loc)};
3784 unsigned Idx = 0;
3785 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3786 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3787 // Global = Buffer.VD[Idx];
3788 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3789 const FieldDecl *FD = VarFieldMap.lookup(VD);
3790 LValue GlobLVal = CGF.EmitLValueForField(
3791 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08003792 llvm::Value *BufferPtr =
3793 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003794 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3795 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3796 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3797 // Store array size.
3798 ++Idx;
3799 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3800 llvm::Value *Size = CGF.Builder.CreateIntCast(
3801 CGF.getVLASize(
3802 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3803 .NumElts,
3804 CGF.SizeTy, /*isSigned=*/false);
3805 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3806 Elem);
3807 }
3808 }
3809
3810 // Call reduce_function(GlobalReduceList, ReduceList)
3811 llvm::Value *GlobalReduceList =
3812 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3813 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3814 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3815 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3816 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3817 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3818 CGF.FinishFunction();
3819 return Fn;
3820}
3821
3822/// This function emits a helper that copies all the reduction variables from
3823/// the team into the provided global buffer for the reduction variables.
3824///
3825/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3826/// For all data entries D in reduce_data:
3827/// Copy buffer.D[Idx] to local D;
3828static llvm::Value *emitGlobalToListCopyFunction(
3829 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3830 QualType ReductionArrayTy, SourceLocation Loc,
3831 const RecordDecl *TeamReductionRec,
3832 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3833 &VarFieldMap) {
3834 ASTContext &C = CGM.getContext();
3835
3836 // Buffer: global reduction buffer.
3837 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3838 C.VoidPtrTy, ImplicitParamDecl::Other);
3839 // Idx: index of the buffer.
3840 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3841 ImplicitParamDecl::Other);
3842 // ReduceList: thread local Reduce list.
3843 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3844 C.VoidPtrTy, ImplicitParamDecl::Other);
3845 FunctionArgList Args;
3846 Args.push_back(&BufferArg);
3847 Args.push_back(&IdxArg);
3848 Args.push_back(&ReduceListArg);
3849
3850 const CGFunctionInfo &CGFI =
3851 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3852 auto *Fn = llvm::Function::Create(
3853 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3854 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3855 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3856 Fn->setDoesNotRecurse();
3857 CodeGenFunction CGF(CGM);
3858 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3859
3860 CGBuilderTy &Bld = CGF.Builder;
3861
3862 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3863 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3864 Address LocalReduceList(
3865 Bld.CreatePointerBitCastOrAddrSpaceCast(
3866 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3867 C.VoidPtrTy, Loc),
3868 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3869 CGF.getPointerAlign());
3870 QualType StaticTy = C.getRecordType(TeamReductionRec);
3871 llvm::Type *LLVMReductionsBufferTy =
3872 CGM.getTypes().ConvertTypeForMem(StaticTy);
3873 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3874 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3875 LLVMReductionsBufferTy->getPointerTo());
3876
3877 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3878 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3879 /*Volatile=*/false, C.IntTy,
3880 Loc)};
3881 unsigned Idx = 0;
3882 for (const Expr *Private : Privates) {
3883 // Reduce element = LocalReduceList[i]
3884 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3885 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3886 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3887 // elemptr = ((CopyType*)(elemptrptr)) + I
3888 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3889 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3890 Address ElemPtr =
3891 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3892 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3893 // Global = Buffer.VD[Idx];
3894 const FieldDecl *FD = VarFieldMap.lookup(VD);
3895 LValue GlobLVal = CGF.EmitLValueForField(
3896 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08003897 llvm::Value *BufferPtr =
3898 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003899 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3900 switch (CGF.getEvaluationKind(Private->getType())) {
3901 case TEK_Scalar: {
3902 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3903 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3904 break;
3905 }
3906 case TEK_Complex: {
3907 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3908 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3909 /*isInit=*/false);
3910 break;
3911 }
3912 case TEK_Aggregate:
3913 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3914 GlobLVal, Private->getType(),
3915 AggValueSlot::DoesNotOverlap);
3916 break;
3917 }
3918 ++Idx;
3919 }
3920
3921 CGF.FinishFunction();
3922 return Fn;
3923}
3924
3925/// This function emits a helper that reduces all the reduction variables from
3926/// the team into the provided global buffer for the reduction variables.
3927///
3928/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3929/// void *GlobPtrs[];
3930/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3931/// ...
3932/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3933/// reduce_function(reduce_data, GlobPtrs);
3934static llvm::Value *emitGlobalToListReduceFunction(
3935 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3936 QualType ReductionArrayTy, SourceLocation Loc,
3937 const RecordDecl *TeamReductionRec,
3938 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3939 &VarFieldMap,
3940 llvm::Function *ReduceFn) {
3941 ASTContext &C = CGM.getContext();
3942
3943 // Buffer: global reduction buffer.
3944 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3945 C.VoidPtrTy, ImplicitParamDecl::Other);
3946 // Idx: index of the buffer.
3947 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3948 ImplicitParamDecl::Other);
3949 // ReduceList: thread local Reduce list.
3950 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3951 C.VoidPtrTy, ImplicitParamDecl::Other);
3952 FunctionArgList Args;
3953 Args.push_back(&BufferArg);
3954 Args.push_back(&IdxArg);
3955 Args.push_back(&ReduceListArg);
3956
3957 const CGFunctionInfo &CGFI =
3958 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3959 auto *Fn = llvm::Function::Create(
3960 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3961 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3962 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3963 Fn->setDoesNotRecurse();
3964 CodeGenFunction CGF(CGM);
3965 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3966
3967 CGBuilderTy &Bld = CGF.Builder;
3968
3969 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3970 QualType StaticTy = C.getRecordType(TeamReductionRec);
3971 llvm::Type *LLVMReductionsBufferTy =
3972 CGM.getTypes().ConvertTypeForMem(StaticTy);
3973 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3974 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3975 LLVMReductionsBufferTy->getPointerTo());
3976
3977 // 1. Build a list of reduction variables.
3978 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3979 Address ReductionList =
3980 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3981 auto IPriv = Privates.begin();
3982 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3983 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3984 /*Volatile=*/false, C.IntTy,
3985 Loc)};
3986 unsigned Idx = 0;
3987 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3988 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3989 // Global = Buffer.VD[Idx];
3990 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3991 const FieldDecl *FD = VarFieldMap.lookup(VD);
3992 LValue GlobLVal = CGF.EmitLValueForField(
3993 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08003994 llvm::Value *BufferPtr =
3995 Bld.CreateInBoundsGEP(GlobLVal.getPointer(CGF), Idxs);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003996 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3997 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3998 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3999 // Store array size.
4000 ++Idx;
4001 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4002 llvm::Value *Size = CGF.Builder.CreateIntCast(
4003 CGF.getVLASize(
4004 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4005 .NumElts,
4006 CGF.SizeTy, /*isSigned=*/false);
4007 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4008 Elem);
4009 }
4010 }
4011
4012 // Call reduce_function(ReduceList, GlobalReduceList)
4013 llvm::Value *GlobalReduceList =
4014 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
4015 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
4016 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
4017 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4018 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4019 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4020 CGF.FinishFunction();
4021 return Fn;
4022}
4023
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004024///
4025/// Design of OpenMP reductions on the GPU
4026///
4027/// Consider a typical OpenMP program with one or more reduction
4028/// clauses:
4029///
4030/// float foo;
4031/// double bar;
4032/// #pragma omp target teams distribute parallel for \
4033/// reduction(+:foo) reduction(*:bar)
4034/// for (int i = 0; i < N; i++) {
4035/// foo += A[i]; bar *= B[i];
4036/// }
4037///
4038/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4039/// all teams. In our OpenMP implementation on the NVPTX device an
4040/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4041/// within a team are mapped to CUDA threads within a threadblock.
4042/// Our goal is to efficiently aggregate values across all OpenMP
4043/// threads such that:
4044///
4045/// - the compiler and runtime are logically concise, and
4046/// - the reduction is performed efficiently in a hierarchical
4047/// manner as follows: within OpenMP threads in the same warp,
4048/// across warps in a threadblock, and finally across teams on
4049/// the NVPTX device.
4050///
4051/// Introduction to Decoupling
4052///
4053/// We would like to decouple the compiler and the runtime so that the
4054/// latter is ignorant of the reduction variables (number, data types)
4055/// and the reduction operators. This allows a simpler interface
4056/// and implementation while still attaining good performance.
4057///
4058/// Pseudocode for the aforementioned OpenMP program generated by the
4059/// compiler is as follows:
4060///
4061/// 1. Create private copies of reduction variables on each OpenMP
4062/// thread: 'foo_private', 'bar_private'
4063/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4064/// to it and writes the result in 'foo_private' and 'bar_private'
4065/// respectively.
4066/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4067/// and store the result on the team master:
4068///
Alexey Bataev8e009032019-01-04 17:25:09 +00004069/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004070/// reduceData, shuffleReduceFn, interWarpCpyFn)
4071///
4072/// where:
4073/// struct ReduceData {
4074/// double *foo;
4075/// double *bar;
4076/// } reduceData
4077/// reduceData.foo = &foo_private
4078/// reduceData.bar = &bar_private
4079///
4080/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4081/// auxiliary functions generated by the compiler that operate on
4082/// variables of type 'ReduceData'. They aid the runtime perform
4083/// algorithmic steps in a data agnostic manner.
4084///
4085/// 'shuffleReduceFn' is a pointer to a function that reduces data
4086/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4087/// same warp. It takes the following arguments as input:
4088///
4089/// a. variable of type 'ReduceData' on the calling lane,
4090/// b. its lane_id,
4091/// c. an offset relative to the current lane_id to generate a
4092/// remote_lane_id. The remote lane contains the second
4093/// variable of type 'ReduceData' that is to be reduced.
4094/// d. an algorithm version parameter determining which reduction
4095/// algorithm to use.
4096///
4097/// 'shuffleReduceFn' retrieves data from the remote lane using
4098/// efficient GPU shuffle intrinsics and reduces, using the
4099/// algorithm specified by the 4th parameter, the two operands
4100/// element-wise. The result is written to the first operand.
4101///
4102/// Different reduction algorithms are implemented in different
4103/// runtime functions, all calling 'shuffleReduceFn' to perform
4104/// the essential reduction step. Therefore, based on the 4th
4105/// parameter, this function behaves slightly differently to
4106/// cooperate with the runtime to ensure correctness under
4107/// different circumstances.
4108///
4109/// 'InterWarpCpyFn' is a pointer to a function that transfers
4110/// reduced variables across warps. It tunnels, through CUDA
4111/// shared memory, the thread-private data of type 'ReduceData'
4112/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004113/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4114/// The last team writes the global reduced value to memory.
4115///
4116/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4117/// reduceData, shuffleReduceFn, interWarpCpyFn,
4118/// scratchpadCopyFn, loadAndReduceFn)
4119///
4120/// 'scratchpadCopyFn' is a helper that stores reduced
4121/// data from the team master to a scratchpad array in
4122/// global memory.
4123///
4124/// 'loadAndReduceFn' is a helper that loads data from
4125/// the scratchpad array and reduces it with the input
4126/// operand.
4127///
4128/// These compiler generated functions hide address
4129/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004130/// 5. if ret == 1:
4131/// The team master of the last team stores the reduced
4132/// result to the globals in memory.
4133/// foo += reduceData.foo; bar *= reduceData.bar
4134///
4135///
4136/// Warp Reduction Algorithms
4137///
4138/// On the warp level, we have three algorithms implemented in the
4139/// OpenMP runtime depending on the number of active lanes:
4140///
4141/// Full Warp Reduction
4142///
4143/// The reduce algorithm within a warp where all lanes are active
4144/// is implemented in the runtime as follows:
4145///
4146/// full_warp_reduce(void *reduce_data,
4147/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4148/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4149/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4150/// }
4151///
4152/// The algorithm completes in log(2, WARPSIZE) steps.
4153///
4154/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4155/// not used therefore we save instructions by not retrieving lane_id
4156/// from the corresponding special registers. The 4th parameter, which
4157/// represents the version of the algorithm being used, is set to 0 to
4158/// signify full warp reduction.
4159///
4160/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4161///
4162/// #reduce_elem refers to an element in the local lane's data structure
4163/// #remote_elem is retrieved from a remote lane
4164/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4165/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4166///
4167/// Contiguous Partial Warp Reduction
4168///
4169/// This reduce algorithm is used within a warp where only the first
4170/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4171/// number of OpenMP threads in a parallel region is not a multiple of
4172/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4173///
4174/// void
4175/// contiguous_partial_reduce(void *reduce_data,
4176/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4177/// int size, int lane_id) {
4178/// int curr_size;
4179/// int offset;
4180/// curr_size = size;
4181/// mask = curr_size/2;
4182/// while (offset>0) {
4183/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4184/// curr_size = (curr_size+1)/2;
4185/// offset = curr_size/2;
4186/// }
4187/// }
4188///
4189/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4190///
4191/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4192/// if (lane_id < offset)
4193/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4194/// else
4195/// reduce_elem = remote_elem
4196///
4197/// This algorithm assumes that the data to be reduced are located in a
4198/// contiguous subset of lanes starting from the first. When there is
4199/// an odd number of active lanes, the data in the last lane is not
4200/// aggregated with any other lane's dat but is instead copied over.
4201///
4202/// Dispersed Partial Warp Reduction
4203///
4204/// This algorithm is used within a warp when any discontiguous subset of
4205/// lanes are active. It is used to implement the reduction operation
4206/// across lanes in an OpenMP simd region or in a nested parallel region.
4207///
4208/// void
4209/// dispersed_partial_reduce(void *reduce_data,
4210/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4211/// int size, remote_id;
4212/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4213/// do {
4214/// remote_id = next_active_lane_id_right_after_me();
4215/// # the above function returns 0 of no active lane
4216/// # is present right after the current lane.
4217/// size = number_of_active_lanes_in_this_warp();
4218/// logical_lane_id /= 2;
4219/// ShuffleReduceFn(reduce_data, logical_lane_id,
4220/// remote_id-1-threadIdx.x, 2);
4221/// } while (logical_lane_id % 2 == 0 && size > 1);
4222/// }
4223///
4224/// There is no assumption made about the initial state of the reduction.
4225/// Any number of lanes (>=1) could be active at any position. The reduction
4226/// result is returned in the first active lane.
4227///
4228/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4229///
4230/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4231/// if (lane_id % 2 == 0 && offset > 0)
4232/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4233/// else
4234/// reduce_elem = remote_elem
4235///
4236///
4237/// Intra-Team Reduction
4238///
4239/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004240/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004241/// threads in a team. It first reduces within a warp using the
4242/// aforementioned algorithms. We then proceed to gather all such
4243/// reduced values at the first warp.
4244///
4245/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4246/// data from each of the "warp master" (zeroth lane of each warp, where
4247/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4248/// a mathematical sense) the problem of reduction across warp masters in
4249/// a block to the problem of warp reduction.
4250///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004251///
4252/// Inter-Team Reduction
4253///
4254/// Once a team has reduced its data to a single value, it is stored in
4255/// a global scratchpad array. Since each team has a distinct slot, this
4256/// can be done without locking.
4257///
4258/// The last team to write to the scratchpad array proceeds to reduce the
4259/// scratchpad array. One or more workers in the last team use the helper
4260/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4261/// the k'th worker reduces every k'th element.
4262///
Alexey Bataev8e009032019-01-04 17:25:09 +00004263/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004264/// reduce across workers and compute a globally reduced value.
4265///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004266void CGOpenMPRuntimeNVPTX::emitReduction(
4267 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4268 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4269 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4270 if (!CGF.HaveInsertPoint())
4271 return;
4272
4273 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004274#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004275 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004276#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004277
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004278 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004279 assert(!TeamsReduction && !ParallelReduction &&
4280 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004281 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4282 ReductionOps, Options);
4283 return;
4284 }
4285
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004286 assert((TeamsReduction || ParallelReduction) &&
4287 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004288
Alexey Bataeva1166022018-11-27 21:24:54 +00004289 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004290 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004291 // or
4292 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004293 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004294 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004295
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004296 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004297 ASTContext &C = CGM.getContext();
4298 // 1. Build a list of reduction variables.
4299 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4300 auto Size = RHSExprs.size();
4301 for (const Expr *E : Privates) {
4302 if (E->getType()->isVariablyModifiedType())
4303 // Reserve place for array size.
4304 ++Size;
4305 }
4306 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4307 QualType ReductionArrayTy =
Richard Smith772e2662019-10-04 01:25:59 +00004308 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
Alexey Bataev8061acd2019-02-20 16:36:22 +00004309 /*IndexTypeQuals=*/0);
4310 Address ReductionList =
4311 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4312 auto IPriv = Privates.begin();
4313 unsigned Idx = 0;
4314 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4315 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4316 CGF.Builder.CreateStore(
4317 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08004318 CGF.EmitLValue(RHSExprs[I]).getPointer(CGF), CGF.VoidPtrTy),
Alexey Bataev8061acd2019-02-20 16:36:22 +00004319 Elem);
4320 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4321 // Store array size.
4322 ++Idx;
4323 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4324 llvm::Value *Size = CGF.Builder.CreateIntCast(
4325 CGF.getVLASize(
4326 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4327 .NumElts,
4328 CGF.SizeTy, /*isSigned=*/false);
4329 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4330 Elem);
4331 }
4332 }
4333
4334 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4335 ReductionList.getPointer(), CGF.VoidPtrTy);
4336 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004337 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4338 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004339 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4340 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4341 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4342 llvm::Value *InterWarpCopyFn =
4343 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4344
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004345 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004346 llvm::Value *Args[] = {RTLoc,
4347 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004348 CGF.Builder.getInt32(RHSExprs.size()),
4349 ReductionArrayTySize,
4350 RL,
4351 ShuffleAndReduceFn,
4352 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004353
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004354 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004355 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004356 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4357 Args);
4358 } else {
4359 assert(TeamsReduction && "expected teams reduction.");
4360 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4361 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4362 int Cnt = 0;
4363 for (const Expr *DRE : Privates) {
4364 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4365 ++Cnt;
4366 }
4367 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4368 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4369 C.getLangOpts().OpenMPCUDAReductionBufNum);
4370 TeamsReductions.push_back(TeamReductionRec);
4371 if (!KernelTeamsReductionPtr) {
4372 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4373 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4374 llvm::GlobalValue::InternalLinkage, nullptr,
4375 "_openmp_teams_reductions_buffer_$_$ptr");
4376 }
4377 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4378 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4379 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4380 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4381 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4382 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4383 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4384 ReductionFn);
4385 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4386 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4387 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4388 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4389 ReductionFn);
4390
4391 llvm::Value *Args[] = {
4392 RTLoc,
4393 ThreadId,
4394 GlobalBufferPtr,
4395 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4396 RL,
4397 ShuffleAndReduceFn,
4398 InterWarpCopyFn,
4399 GlobalToBufferCpyFn,
4400 GlobalToBufferRedFn,
4401 BufferToGlobalCpyFn,
4402 BufferToGlobalRedFn};
4403
4404 Res = CGF.EmitRuntimeCall(
4405 createNVPTXRuntimeFunction(
4406 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004407 Args);
4408 }
4409
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004410 // 5. Build if (res == 1)
4411 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4412 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4413 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4414 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4415 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004416
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004417 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004418 // thread in each team.
4419 // __kmpc_end_reduce{_nowait}(<gtid>);
4420 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004421 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004422
4423 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004424 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004425 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4426 auto IPriv = Privates.begin();
4427 auto ILHS = LHSExprs.begin();
4428 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004429 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004430 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4431 cast<DeclRefExpr>(*IRHS));
4432 ++IPriv;
4433 ++ILHS;
4434 ++IRHS;
4435 }
4436 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004437 llvm::Value *EndArgs[] = {ThreadId};
4438 RegionCodeGenTy RCG(CodeGen);
4439 NVPTXActionTy Action(
4440 nullptr, llvm::None,
4441 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4442 EndArgs);
4443 RCG.setAction(Action);
4444 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004445 // There is no need to emit line number for unconditional branch.
4446 (void)ApplyDebugLocation::CreateEmpty(CGF);
4447 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004448}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004449
4450const VarDecl *
4451CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4452 const VarDecl *NativeParam) const {
4453 if (!NativeParam->getType()->isReferenceType())
4454 return NativeParam;
4455 QualType ArgType = NativeParam->getType();
4456 QualifierCollector QC;
4457 const Type *NonQualTy = QC.strip(ArgType);
4458 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4459 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4460 if (Attr->getCaptureKind() == OMPC_map) {
4461 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4462 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004463 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4464 PointeeTy.isConstant(CGM.getContext())) {
4465 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4466 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004467 }
4468 }
4469 ArgType = CGM.getContext().getPointerType(PointeeTy);
4470 QC.addRestrict();
4471 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004472 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004473 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004474 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004475 return ImplicitParamDecl::Create(
4476 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4477 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004478 return ParmVarDecl::Create(
4479 CGM.getContext(),
4480 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004481 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004482 NativeParam->getIdentifier(), ArgType,
4483 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004484}
4485
4486Address
4487CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4488 const VarDecl *NativeParam,
4489 const VarDecl *TargetParam) const {
4490 assert(NativeParam != TargetParam &&
4491 NativeParam->getType()->isReferenceType() &&
4492 "Native arg must not be the same as target arg.");
4493 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4494 QualType NativeParamType = NativeParam->getType();
4495 QualifierCollector QC;
4496 const Type *NonQualTy = QC.strip(NativeParamType);
4497 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4498 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004499 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004500 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004501 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004502 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004503 // First cast to generic.
4504 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4505 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4506 /*AddrSpace=*/0));
4507 // Cast from generic to native address space.
4508 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4509 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4510 NativePointeeAddrSpace));
4511 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4512 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004513 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004514 return NativeParamAddr;
4515}
4516
4517void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004518 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004519 ArrayRef<llvm::Value *> Args) const {
4520 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004521 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004522 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004523 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004524 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4525 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4526 break;
4527 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004528 llvm::Type *TargetType = FnType->getParamType(I);
4529 llvm::Value *NativeArg = Args[I];
4530 if (!TargetType->isPointerTy()) {
4531 TargetArgs.emplace_back(NativeArg);
4532 continue;
4533 }
4534 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004535 NativeArg,
4536 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004537 TargetArgs.emplace_back(
4538 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4539 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004540 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004541}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004542
4543/// Emit function which wraps the outline parallel region
4544/// and controls the arguments which are passed to this function.
4545/// The wrapper ensures that the outlined function is called
4546/// with the correct arguments when data is shared.
4547llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4548 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4549 ASTContext &Ctx = CGM.getContext();
4550 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4551
4552 // Create a function that takes as argument the source thread.
4553 FunctionArgList WrapperArgs;
4554 QualType Int16QTy =
4555 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4556 QualType Int32QTy =
4557 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004558 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004559 /*Id=*/nullptr, Int16QTy,
4560 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004561 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004562 /*Id=*/nullptr, Int32QTy,
4563 ImplicitParamDecl::Other);
4564 WrapperArgs.emplace_back(&ParallelLevelArg);
4565 WrapperArgs.emplace_back(&WrapperArg);
4566
Alexey Bataev9ff80832018-04-16 20:16:21 +00004567 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004568 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4569
4570 auto *Fn = llvm::Function::Create(
4571 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004572 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004573 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004574 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004575 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004576
4577 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4578 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004579 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004580
4581 const auto *RD = CS.getCapturedRecordDecl();
4582 auto CurField = RD->field_begin();
4583
Alexey Bataevf89cf212019-10-16 16:59:01 +00004584 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4585 /*Name=*/".zero.addr");
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004586 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004587 // Get the array of arguments.
4588 SmallVector<llvm::Value *, 8> Args;
4589
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004590 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4591 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004592
4593 CGBuilderTy &Bld = CGF.Builder;
4594 auto CI = CS.capture_begin();
4595
4596 // Use global memory for data sharing.
4597 // Handle passing of global args to workers.
4598 Address GlobalArgs =
4599 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4600 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4601 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4602 CGF.EmitRuntimeCall(
4603 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4604 DataSharingArgs);
4605
4606 // Retrieve the shared variables from the list of references returned
4607 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004608 Address SharedArgListAddress = Address::invalid();
4609 if (CS.capture_size() > 0 ||
4610 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4611 SharedArgListAddress = CGF.EmitLoadOfPointer(
4612 GlobalArgs, CGF.getContext()
4613 .getPointerType(CGF.getContext().getPointerType(
4614 CGF.getContext().VoidPtrTy))
4615 .castAs<PointerType>());
4616 }
4617 unsigned Idx = 0;
4618 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004619 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004620 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4621 Src, CGF.SizeTy->getPointerTo());
4622 llvm::Value *LB = CGF.EmitLoadOfScalar(
4623 TypedAddress,
4624 /*Volatile=*/false,
4625 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4626 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4627 Args.emplace_back(LB);
4628 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004629 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004630 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4631 Src, CGF.SizeTy->getPointerTo());
4632 llvm::Value *UB = CGF.EmitLoadOfScalar(
4633 TypedAddress,
4634 /*Volatile=*/false,
4635 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4636 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4637 Args.emplace_back(UB);
4638 ++Idx;
4639 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004640 if (CS.capture_size() > 0) {
4641 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004642 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4643 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004644 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004645 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004646 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4647 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4648 /*Volatile=*/false,
4649 CGFContext.getPointerType(ElemTy),
4650 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004651 if (CI->capturesVariableByCopy() &&
4652 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004653 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4654 CI->getLocation());
4655 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004656 Args.emplace_back(Arg);
4657 }
4658 }
4659
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004660 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004661 CGF.FinishFunction();
4662 return Fn;
4663}
4664
4665void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4666 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004667 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4668 return;
4669
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004670 assert(D && "Expected function or captured|block decl.");
4671 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4672 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004673 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4674 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004675 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004676 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004677 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4678 Body = FD->getBody();
4679 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4680 Body = BD->getBody();
4681 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4682 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004683 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004684 if (NeedToDelayGlobalization &&
4685 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4686 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004687 }
4688 if (!Body)
4689 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004690 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004691 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004692 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004693 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004694 TeamAndReductions.first = nullptr;
4695 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004696 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4697 VarChecker.getEscapedVariableLengthDecls();
4698 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004699 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004700 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4701 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004702 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004703 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4704 I->getSecond().EscapedParameters.insert(
4705 VarChecker.getEscapedParameters().begin(),
4706 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004707 I->getSecond().EscapedVariableLengthDecls.append(
4708 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004709 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004710 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004711 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004712 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004713 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004714 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004715 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004716 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004717 VarChecker.Visit(Body);
4718 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004719 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004720 I->getSecond().SecondaryLocalVarData.emplace();
4721 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4722 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4723 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4724 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004725 Data.insert(
4726 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004727 }
4728 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004729 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004730 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004731 struct GlobalizationScope final : EHScopeStack::Cleanup {
4732 GlobalizationScope() = default;
4733
4734 void Emit(CodeGenFunction &CGF, Flags flags) override {
4735 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004736 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004737 }
4738 };
4739 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004740 }
4741}
4742
4743Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4744 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004745 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4746 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4747 switch (A->getAllocatorType()) {
4748 // Use the default allocator here as by default local vars are
4749 // threadlocal.
4750 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4751 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004752 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4753 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004754 // Follow the user decision - use default allocation.
4755 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004756 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004757 // TODO: implement aupport for user-defined allocators.
4758 return Address::invalid();
4759 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4760 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4761 auto *GV = new llvm::GlobalVariable(
4762 CGM.getModule(), VarTy, /*isConstant=*/false,
4763 llvm::GlobalValue::InternalLinkage,
4764 llvm::Constant::getNullValue(VarTy), VD->getName(),
4765 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4766 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4767 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004768 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004769 return Address(GV, Align);
4770 }
4771 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4772 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4773 auto *GV = new llvm::GlobalVariable(
4774 CGM.getModule(), VarTy, /*isConstant=*/false,
4775 llvm::GlobalValue::InternalLinkage,
4776 llvm::Constant::getNullValue(VarTy), VD->getName(),
4777 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4778 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4779 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004780 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004781 return Address(GV, Align);
4782 }
4783 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4784 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4785 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4786 auto *GV = new llvm::GlobalVariable(
4787 CGM.getModule(), VarTy, /*isConstant=*/false,
4788 llvm::GlobalValue::InternalLinkage,
4789 llvm::Constant::getNullValue(VarTy), VD->getName());
4790 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004791 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004792 return Address(GV, Align);
4793 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004794 }
4795 }
4796
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004797 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4798 return Address::invalid();
4799
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004800 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004801 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4802 if (I == FunctionGlobalizedDecls.end())
4803 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004804 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004805 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004806 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004807 if (VD->hasAttrs()) {
4808 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4809 E(VD->attr_end());
4810 IT != E; ++IT) {
4811 auto VDI = I->getSecond().LocalVarData.find(
4812 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4813 ->getCanonicalDecl());
4814 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004815 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004816 }
4817 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004818
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004819 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004820}
4821
4822void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004823 FunctionGlobalizedDecls.erase(CGF.CurFn);
4824 CGOpenMPRuntime::functionFinished(CGF);
4825}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004826
4827void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4828 CodeGenFunction &CGF, const OMPLoopDirective &S,
4829 OpenMPDistScheduleClauseKind &ScheduleKind,
4830 llvm::Value *&Chunk) const {
4831 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4832 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4833 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4834 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4835 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004836 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004837 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004838 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4839 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004840}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004841
4842void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4843 CodeGenFunction &CGF, const OMPLoopDirective &S,
4844 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004845 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004846 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004847 // Chunk size is 1 in this case.
4848 llvm::APInt ChunkSize(32, 1);
4849 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4850 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4851 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004852}
Alexey Bataev60705422018-10-30 15:50:12 +00004853
4854void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4855 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4856 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4857 " Expected target-based directive.");
4858 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4859 for (const CapturedStmt::Capture &C : CS->captures()) {
4860 // Capture variables captured by reference in lambdas for target-based
4861 // directives.
4862 if (!C.capturesVariable())
4863 continue;
4864 const VarDecl *VD = C.getCapturedVar();
4865 const auto *RD = VD->getType()
4866 .getCanonicalType()
4867 .getNonReferenceType()
4868 ->getAsCXXRecordDecl();
4869 if (!RD || !RD->isLambda())
4870 continue;
4871 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4872 LValue VDLVal;
4873 if (VD->getType().getCanonicalType()->isReferenceType())
4874 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4875 else
4876 VDLVal = CGF.MakeAddrLValue(
4877 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4878 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4879 FieldDecl *ThisCapture = nullptr;
4880 RD->getCaptureFields(Captures, ThisCapture);
4881 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4882 LValue ThisLVal =
4883 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4884 llvm::Value *CXXThis = CGF.LoadCXXThis();
4885 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4886 }
4887 for (const LambdaCapture &LC : RD->captures()) {
4888 if (LC.getCaptureKind() != LCK_ByRef)
4889 continue;
4890 const VarDecl *VD = LC.getCapturedVar();
4891 if (!CS->capturesVariable(VD))
4892 continue;
4893 auto It = Captures.find(VD);
4894 assert(It != Captures.end() && "Found lambda capture without field.");
4895 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4896 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4897 if (VD->getType().getCanonicalType()->isReferenceType())
4898 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4899 VD->getType().getCanonicalType())
Akira Hatanaka8a5b7c32019-12-03 11:24:46 -08004900 .getAddress(CGF);
Alexey Bataev60705422018-10-30 15:50:12 +00004901 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4902 }
4903 }
4904}
4905
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004906unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4907 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4908}
4909
Alexey Bataevc5687252019-03-21 19:35:27 +00004910bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4911 LangAS &AS) {
4912 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4913 return false;
4914 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4915 switch(A->getAllocatorType()) {
4916 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4917 // Not supported, fallback to the default mem space.
4918 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4919 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4920 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4921 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4922 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4923 AS = LangAS::Default;
4924 return true;
4925 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4926 AS = LangAS::cuda_constant;
4927 return true;
4928 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4929 AS = LangAS::cuda_shared;
4930 return true;
4931 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4932 llvm_unreachable("Expected predefined allocator for the variables with the "
4933 "static storage.");
4934 }
4935 return false;
4936}
4937
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004938// Get current CudaArch and ignore any unknown values
4939static CudaArch getCudaArch(CodeGenModule &CGM) {
4940 if (!CGM.getTarget().hasFeature("ptx"))
4941 return CudaArch::UNKNOWN;
4942 llvm::StringMap<bool> Features;
4943 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4944 CGM.getTarget().getTargetOpts().CPU,
4945 CGM.getTarget().getTargetOpts().Features);
4946 for (const auto &Feature : Features) {
4947 if (Feature.getValue()) {
4948 CudaArch Arch = StringToCudaArch(Feature.getKey());
4949 if (Arch != CudaArch::UNKNOWN)
4950 return Arch;
4951 }
4952 }
4953 return CudaArch::UNKNOWN;
4954}
4955
4956/// Check to see if target architecture supports unified addressing which is
4957/// a restriction for OpenMP requires clause "unified_shared_memory".
4958void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004959 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004960 for (const OMPClause *Clause : D->clauselists()) {
4961 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
Alexey Bataev7b710a42019-11-05 10:10:50 -05004962 CudaArch Arch = getCudaArch(CGM);
4963 switch (Arch) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004964 case CudaArch::SM_20:
4965 case CudaArch::SM_21:
4966 case CudaArch::SM_30:
4967 case CudaArch::SM_32:
4968 case CudaArch::SM_35:
4969 case CudaArch::SM_37:
4970 case CudaArch::SM_50:
4971 case CudaArch::SM_52:
4972 case CudaArch::SM_53:
4973 case CudaArch::SM_60:
4974 case CudaArch::SM_61:
Alexey Bataev7b710a42019-11-05 10:10:50 -05004975 case CudaArch::SM_62: {
4976 SmallString<256> Buffer;
4977 llvm::raw_svector_ostream Out(Buffer);
4978 Out << "Target architecture " << CudaArchToString(Arch)
4979 << " does not support unified addressing";
4980 CGM.Error(Clause->getBeginLoc(), Out.str());
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004981 return;
Alexey Bataev7b710a42019-11-05 10:10:50 -05004982 }
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004983 case CudaArch::SM_70:
4984 case CudaArch::SM_72:
4985 case CudaArch::SM_75:
4986 case CudaArch::GFX600:
4987 case CudaArch::GFX601:
4988 case CudaArch::GFX700:
4989 case CudaArch::GFX701:
4990 case CudaArch::GFX702:
4991 case CudaArch::GFX703:
4992 case CudaArch::GFX704:
4993 case CudaArch::GFX801:
4994 case CudaArch::GFX802:
4995 case CudaArch::GFX803:
4996 case CudaArch::GFX810:
4997 case CudaArch::GFX900:
4998 case CudaArch::GFX902:
4999 case CudaArch::GFX904:
5000 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005001 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005002 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005003 case CudaArch::GFX1010:
5004 case CudaArch::GFX1011:
5005 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005006 case CudaArch::UNKNOWN:
5007 break;
5008 case CudaArch::LAST:
5009 llvm_unreachable("Unexpected Cuda arch.");
5010 }
5011 }
5012 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00005013 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005014}
5015
Alexey Bataeve4090182018-11-02 14:54:07 +00005016/// Get number of SMs and number of blocks per SM.
5017static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
5018 std::pair<unsigned, unsigned> Data;
5019 if (CGM.getLangOpts().OpenMPCUDANumSMs)
5020 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
5021 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5022 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5023 if (Data.first && Data.second)
5024 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005025 switch (getCudaArch(CGM)) {
5026 case CudaArch::SM_20:
5027 case CudaArch::SM_21:
5028 case CudaArch::SM_30:
5029 case CudaArch::SM_32:
5030 case CudaArch::SM_35:
5031 case CudaArch::SM_37:
5032 case CudaArch::SM_50:
5033 case CudaArch::SM_52:
5034 case CudaArch::SM_53:
5035 return {16, 16};
5036 case CudaArch::SM_60:
5037 case CudaArch::SM_61:
5038 case CudaArch::SM_62:
5039 return {56, 32};
5040 case CudaArch::SM_70:
5041 case CudaArch::SM_72:
5042 case CudaArch::SM_75:
5043 return {84, 32};
5044 case CudaArch::GFX600:
5045 case CudaArch::GFX601:
5046 case CudaArch::GFX700:
5047 case CudaArch::GFX701:
5048 case CudaArch::GFX702:
5049 case CudaArch::GFX703:
5050 case CudaArch::GFX704:
5051 case CudaArch::GFX801:
5052 case CudaArch::GFX802:
5053 case CudaArch::GFX803:
5054 case CudaArch::GFX810:
5055 case CudaArch::GFX900:
5056 case CudaArch::GFX902:
5057 case CudaArch::GFX904:
5058 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005059 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005060 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005061 case CudaArch::GFX1010:
5062 case CudaArch::GFX1011:
5063 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005064 case CudaArch::UNKNOWN:
5065 break;
5066 case CudaArch::LAST:
5067 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005068 }
5069 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5070}
5071
5072void CGOpenMPRuntimeNVPTX::clear() {
5073 if (!GlobalizedRecords.empty()) {
5074 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005075 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5076 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005077 RecordDecl *StaticRD = C.buildImplicitRecord(
5078 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5079 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005080 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5081 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5082 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005083 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5084 if (Records.Records.empty())
5085 continue;
5086 unsigned Size = 0;
5087 unsigned RecAlignment = 0;
5088 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005089 QualType RDTy = C.getRecordType(RD);
5090 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005091 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005092 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005093 Size =
5094 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5095 }
5096 Size = llvm::alignTo(Size, RecAlignment);
5097 llvm::APInt ArySize(/*numBits=*/64, Size);
5098 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005099 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005100 const bool UseSharedMemory = Size <= SharedMemorySize;
5101 auto *Field =
5102 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5103 SourceLocation(), SourceLocation(), nullptr, SubTy,
5104 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5105 /*BW=*/nullptr, /*Mutable=*/false,
5106 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005107 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005108 if (UseSharedMemory) {
5109 SharedStaticRD->addDecl(Field);
5110 SharedRecs.push_back(&Records);
5111 } else {
5112 StaticRD->addDecl(Field);
5113 GlobalRecs.push_back(&Records);
5114 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005115 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005116 Records.UseSharedMemory->setInitializer(
5117 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5118 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005119 // Allocate SharedMemorySize buffer for the shared memory.
5120 // FIXME: nvlink does not handle weak linkage correctly (object with the
5121 // different size are reported as erroneous).
5122 // Restore this code as sson as nvlink is fixed.
5123 if (!SharedStaticRD->field_empty()) {
5124 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5125 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005126 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005127 auto *Field = FieldDecl::Create(
5128 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5129 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5130 /*BW=*/nullptr, /*Mutable=*/false,
5131 /*InitStyle=*/ICIS_NoInit);
5132 Field->setAccess(AS_public);
5133 SharedStaticRD->addDecl(Field);
5134 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005135 SharedStaticRD->completeDefinition();
5136 if (!SharedStaticRD->field_empty()) {
5137 QualType StaticTy = C.getRecordType(SharedStaticRD);
5138 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5139 auto *GV = new llvm::GlobalVariable(
5140 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005141 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005142 llvm::Constant::getNullValue(LLVMStaticTy),
5143 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5144 llvm::GlobalValue::NotThreadLocal,
5145 C.getTargetAddressSpace(LangAS::cuda_shared));
5146 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5147 GV, CGM.VoidPtrTy);
5148 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5149 Rec->Buffer->replaceAllUsesWith(Replacement);
5150 Rec->Buffer->eraseFromParent();
5151 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005152 }
5153 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005154 if (!StaticRD->field_empty()) {
5155 QualType StaticTy = C.getRecordType(StaticRD);
5156 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5157 llvm::APInt Size1(32, SMsBlockPerSM.second);
5158 QualType Arr1Ty =
Richard Smith772e2662019-10-04 01:25:59 +00005159 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005160 /*IndexTypeQuals=*/0);
5161 llvm::APInt Size2(32, SMsBlockPerSM.first);
Richard Smith772e2662019-10-04 01:25:59 +00005162 QualType Arr2Ty =
5163 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5164 /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005165 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005166 // FIXME: nvlink does not handle weak linkage correctly (object with the
5167 // different size are reported as erroneous).
5168 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005169 auto *GV = new llvm::GlobalVariable(
5170 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005171 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005172 llvm::Constant::getNullValue(LLVMArr2Ty),
5173 "_openmp_static_glob_rd_$_");
5174 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5175 GV, CGM.VoidPtrTy);
5176 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5177 Rec->Buffer->replaceAllUsesWith(Replacement);
5178 Rec->Buffer->eraseFromParent();
5179 }
5180 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005181 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005182 if (!TeamsReductions.empty()) {
5183 ASTContext &C = CGM.getContext();
5184 RecordDecl *StaticRD = C.buildImplicitRecord(
5185 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5186 StaticRD->startDefinition();
5187 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5188 QualType RecTy = C.getRecordType(TeamReductionRec);
5189 auto *Field = FieldDecl::Create(
5190 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5191 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5192 /*BW=*/nullptr, /*Mutable=*/false,
5193 /*InitStyle=*/ICIS_NoInit);
5194 Field->setAccess(AS_public);
5195 StaticRD->addDecl(Field);
5196 }
5197 StaticRD->completeDefinition();
5198 QualType StaticTy = C.getRecordType(StaticRD);
5199 llvm::Type *LLVMReductionsBufferTy =
5200 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005201 // FIXME: nvlink does not handle weak linkage correctly (object with the
5202 // different size are reported as erroneous).
5203 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005204 auto *GV = new llvm::GlobalVariable(
5205 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005206 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005207 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5208 "_openmp_teams_reductions_buffer_$_");
5209 KernelTeamsReductionPtr->setInitializer(
5210 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5211 CGM.VoidPtrTy));
5212 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005213 CGOpenMPRuntime::clear();
5214}