blob: 291052109e87f5b5b6bcb56f817859ba329c1f8a [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 Bataev5bbcead2019-10-14 17:17:41 +0000807 case OMPD_parallel_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +0000808 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000809 case OMPD_unknown:
810 llvm_unreachable("Unexpected directive.");
811 }
812 }
813
814 return false;
815}
816
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000817static bool supportsSPMDExecutionMode(ASTContext &Ctx,
818 const OMPExecutableDirective &D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000819 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
820 switch (DirectiveKind) {
821 case OMPD_target:
822 case OMPD_target_teams:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000823 return hasNestedSPMDDirective(Ctx, D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000824 case OMPD_target_parallel:
825 case OMPD_target_parallel_for:
826 case OMPD_target_parallel_for_simd:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +0000827 case OMPD_target_teams_distribute_parallel_for:
828 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +0000829 case OMPD_target_simd:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000830 case OMPD_target_teams_distribute_simd:
Alexey Bataevdc9e7dc2019-04-17 16:53:08 +0000831 return true;
832 case OMPD_target_teams_distribute:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000833 return false;
834 case OMPD_parallel:
835 case OMPD_for:
836 case OMPD_parallel_for:
837 case OMPD_parallel_sections:
838 case OMPD_for_simd:
839 case OMPD_parallel_for_simd:
840 case OMPD_cancel:
841 case OMPD_cancellation_point:
842 case OMPD_ordered:
843 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000844 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000845 case OMPD_task:
846 case OMPD_simd:
847 case OMPD_sections:
848 case OMPD_section:
849 case OMPD_single:
850 case OMPD_master:
851 case OMPD_critical:
852 case OMPD_taskyield:
853 case OMPD_barrier:
854 case OMPD_taskwait:
855 case OMPD_taskgroup:
856 case OMPD_atomic:
857 case OMPD_flush:
858 case OMPD_teams:
859 case OMPD_target_data:
860 case OMPD_target_exit_data:
861 case OMPD_target_enter_data:
862 case OMPD_distribute:
863 case OMPD_distribute_simd:
864 case OMPD_distribute_parallel_for:
865 case OMPD_distribute_parallel_for_simd:
866 case OMPD_teams_distribute:
867 case OMPD_teams_distribute_simd:
868 case OMPD_teams_distribute_parallel_for:
869 case OMPD_teams_distribute_parallel_for_simd:
870 case OMPD_target_update:
871 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +0000872 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000873 case OMPD_declare_target:
874 case OMPD_end_declare_target:
875 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +0000876 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000877 case OMPD_taskloop:
878 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +0000879 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000880 case OMPD_parallel_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +0000881 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000882 case OMPD_unknown:
883 break;
884 }
885 llvm_unreachable(
886 "Unknown programming model for OpenMP directive on NVPTX target.");
887}
888
889/// Check if the directive is loops based and has schedule clause at all or has
890/// static scheduling.
891static bool hasStaticScheduling(const OMPExecutableDirective &D) {
892 assert(isOpenMPWorksharingDirective(D.getDirectiveKind()) &&
893 isOpenMPLoopDirective(D.getDirectiveKind()) &&
894 "Expected loop-based directive.");
895 return !D.hasClausesOfKind<OMPOrderedClause>() &&
896 (!D.hasClausesOfKind<OMPScheduleClause>() ||
897 llvm::any_of(D.getClausesOfKind<OMPScheduleClause>(),
898 [](const OMPScheduleClause *C) {
899 return C->getScheduleKind() == OMPC_SCHEDULE_static;
900 }));
901}
902
903/// Check for inner (nested) lightweight runtime construct, if any
904static bool hasNestedLightweightDirective(ASTContext &Ctx,
905 const OMPExecutableDirective &D) {
906 assert(supportsSPMDExecutionMode(Ctx, D) && "Expected SPMD mode directive.");
907 const auto *CS = D.getInnermostCapturedStmt();
908 const auto *Body =
909 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev5c427362019-04-10 19:11:33 +0000910 const Stmt *ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000911
Alexey Bataev5c427362019-04-10 19:11:33 +0000912 if (const auto *NestedDir =
913 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000914 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
915 switch (D.getDirectiveKind()) {
916 case OMPD_target:
917 if (isOpenMPParallelDirective(DKind) &&
918 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
919 hasStaticScheduling(*NestedDir))
920 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000921 if (DKind == OMPD_teams_distribute_simd || DKind == OMPD_simd)
922 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000923 if (DKind == OMPD_parallel) {
924 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
925 /*IgnoreCaptured=*/true);
926 if (!Body)
927 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000928 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
929 if (const auto *NND =
930 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000931 DKind = NND->getDirectiveKind();
932 if (isOpenMPWorksharingDirective(DKind) &&
933 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
934 return true;
935 }
936 } else if (DKind == OMPD_teams) {
937 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
938 /*IgnoreCaptured=*/true);
939 if (!Body)
940 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000941 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
942 if (const auto *NND =
943 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000944 DKind = NND->getDirectiveKind();
945 if (isOpenMPParallelDirective(DKind) &&
946 isOpenMPWorksharingDirective(DKind) &&
947 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
948 return true;
949 if (DKind == OMPD_parallel) {
950 Body = NND->getInnermostCapturedStmt()->IgnoreContainers(
951 /*IgnoreCaptured=*/true);
952 if (!Body)
953 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000954 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
955 if (const auto *NND =
956 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000957 DKind = NND->getDirectiveKind();
958 if (isOpenMPWorksharingDirective(DKind) &&
959 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
960 return true;
961 }
962 }
963 }
964 }
965 return false;
966 case OMPD_target_teams:
967 if (isOpenMPParallelDirective(DKind) &&
968 isOpenMPWorksharingDirective(DKind) && isOpenMPLoopDirective(DKind) &&
969 hasStaticScheduling(*NestedDir))
970 return true;
Alexey Bataev1472e322019-04-19 16:48:38 +0000971 if (DKind == OMPD_distribute_simd || DKind == OMPD_simd)
972 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000973 if (DKind == OMPD_parallel) {
974 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
975 /*IgnoreCaptured=*/true);
976 if (!Body)
977 return false;
Alexey Bataev5c427362019-04-10 19:11:33 +0000978 ChildStmt = CGOpenMPRuntime::getSingleCompoundChild(Ctx, Body);
979 if (const auto *NND =
980 dyn_cast_or_null<OMPExecutableDirective>(ChildStmt)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000981 DKind = NND->getDirectiveKind();
982 if (isOpenMPWorksharingDirective(DKind) &&
983 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NND))
984 return true;
985 }
986 }
987 return false;
988 case OMPD_target_parallel:
Alexey Bataev1472e322019-04-19 16:48:38 +0000989 if (DKind == OMPD_simd)
990 return true;
Alexey Bataev8d8e1232018-08-29 18:32:21 +0000991 return isOpenMPWorksharingDirective(DKind) &&
992 isOpenMPLoopDirective(DKind) && hasStaticScheduling(*NestedDir);
993 case OMPD_target_teams_distribute:
994 case OMPD_target_simd:
995 case OMPD_target_parallel_for:
996 case OMPD_target_parallel_for_simd:
997 case OMPD_target_teams_distribute_simd:
998 case OMPD_target_teams_distribute_parallel_for:
999 case OMPD_target_teams_distribute_parallel_for_simd:
1000 case OMPD_parallel:
1001 case OMPD_for:
1002 case OMPD_parallel_for:
1003 case OMPD_parallel_sections:
1004 case OMPD_for_simd:
1005 case OMPD_parallel_for_simd:
1006 case OMPD_cancel:
1007 case OMPD_cancellation_point:
1008 case OMPD_ordered:
1009 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001010 case OMPD_allocate:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001011 case OMPD_task:
1012 case OMPD_simd:
1013 case OMPD_sections:
1014 case OMPD_section:
1015 case OMPD_single:
1016 case OMPD_master:
1017 case OMPD_critical:
1018 case OMPD_taskyield:
1019 case OMPD_barrier:
1020 case OMPD_taskwait:
1021 case OMPD_taskgroup:
1022 case OMPD_atomic:
1023 case OMPD_flush:
1024 case OMPD_teams:
1025 case OMPD_target_data:
1026 case OMPD_target_exit_data:
1027 case OMPD_target_enter_data:
1028 case OMPD_distribute:
1029 case OMPD_distribute_simd:
1030 case OMPD_distribute_parallel_for:
1031 case OMPD_distribute_parallel_for_simd:
1032 case OMPD_teams_distribute:
1033 case OMPD_teams_distribute_simd:
1034 case OMPD_teams_distribute_parallel_for:
1035 case OMPD_teams_distribute_parallel_for_simd:
1036 case OMPD_target_update:
1037 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001038 case OMPD_declare_variant:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001039 case OMPD_declare_target:
1040 case OMPD_end_declare_target:
1041 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001042 case OMPD_declare_mapper:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001043 case OMPD_taskloop:
1044 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001045 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001046 case OMPD_parallel_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +00001047 case OMPD_requires:
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001048 case OMPD_unknown:
1049 llvm_unreachable("Unexpected directive.");
1050 }
1051 }
1052
1053 return false;
1054}
1055
1056/// Checks if the construct supports lightweight runtime. It must be SPMD
1057/// construct + inner loop-based construct with static scheduling.
1058static bool supportsLightweightRuntime(ASTContext &Ctx,
1059 const OMPExecutableDirective &D) {
1060 if (!supportsSPMDExecutionMode(Ctx, D))
1061 return false;
1062 OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind();
1063 switch (DirectiveKind) {
1064 case OMPD_target:
1065 case OMPD_target_teams:
1066 case OMPD_target_parallel:
1067 return hasNestedLightweightDirective(Ctx, D);
1068 case OMPD_target_parallel_for:
1069 case OMPD_target_parallel_for_simd:
1070 case OMPD_target_teams_distribute_parallel_for:
1071 case OMPD_target_teams_distribute_parallel_for_simd:
1072 // (Last|First)-privates must be shared in parallel region.
1073 return hasStaticScheduling(D);
1074 case OMPD_target_simd:
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001075 case OMPD_target_teams_distribute_simd:
Alexey Bataev1472e322019-04-19 16:48:38 +00001076 return true;
1077 case OMPD_target_teams_distribute:
Alexey Bataevdf093e72018-05-11 19:45:14 +00001078 return false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001079 case OMPD_parallel:
1080 case OMPD_for:
1081 case OMPD_parallel_for:
1082 case OMPD_parallel_sections:
1083 case OMPD_for_simd:
1084 case OMPD_parallel_for_simd:
1085 case OMPD_cancel:
1086 case OMPD_cancellation_point:
1087 case OMPD_ordered:
1088 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001089 case OMPD_allocate:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001090 case OMPD_task:
1091 case OMPD_simd:
1092 case OMPD_sections:
1093 case OMPD_section:
1094 case OMPD_single:
1095 case OMPD_master:
1096 case OMPD_critical:
1097 case OMPD_taskyield:
1098 case OMPD_barrier:
1099 case OMPD_taskwait:
1100 case OMPD_taskgroup:
1101 case OMPD_atomic:
1102 case OMPD_flush:
1103 case OMPD_teams:
1104 case OMPD_target_data:
1105 case OMPD_target_exit_data:
1106 case OMPD_target_enter_data:
1107 case OMPD_distribute:
1108 case OMPD_distribute_simd:
1109 case OMPD_distribute_parallel_for:
1110 case OMPD_distribute_parallel_for_simd:
1111 case OMPD_teams_distribute:
1112 case OMPD_teams_distribute_simd:
1113 case OMPD_teams_distribute_parallel_for:
1114 case OMPD_teams_distribute_parallel_for_simd:
1115 case OMPD_target_update:
1116 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +00001117 case OMPD_declare_variant:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001118 case OMPD_declare_target:
1119 case OMPD_end_declare_target:
1120 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00001121 case OMPD_declare_mapper:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001122 case OMPD_taskloop:
1123 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +00001124 case OMPD_master_taskloop:
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001125 case OMPD_parallel_master_taskloop:
Kelvin Li1408f912018-09-26 04:28:39 +00001126 case OMPD_requires:
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001127 case OMPD_unknown:
1128 break;
1129 }
1130 llvm_unreachable(
1131 "Unknown programming model for OpenMP directive on NVPTX target.");
1132}
1133
1134void CGOpenMPRuntimeNVPTX::emitNonSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001135 StringRef ParentName,
1136 llvm::Function *&OutlinedFn,
1137 llvm::Constant *&OutlinedFnID,
1138 bool IsOffloadEntry,
1139 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001140 ExecutionRuntimeModesRAII ModeRAII(CurrentExecutionMode);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001141 EntryFunctionState EST;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001142 WorkerFunctionState WST(CGM, D.getBeginLoc());
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001143 Work.clear();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001144 WrapperFunctionsMap.clear();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001145
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001146 // Emit target region as a standalone region.
1147 class NVPTXPrePostActionTy : public PrePostActionTy {
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001148 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1149 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001150
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001151 public:
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001152 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001153 CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST)
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001154 : EST(EST), WST(WST) {}
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001155 void Enter(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001156 auto &RT =
1157 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001158 RT.emitNonSPMDEntryHeader(CGF, EST, WST);
1159 // Skip target region initialization.
1160 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001161 }
1162 void Exit(CodeGenFunction &CGF) override {
Alexey Bataeve4090182018-11-02 14:54:07 +00001163 auto &RT =
1164 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
Alexey Bataev6bc27322018-10-05 15:27:47 +00001165 RT.clearLocThreadIdInsertPt(CGF);
1166 RT.emitNonSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001167 }
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001168 } Action(EST, WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001169 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001170 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001171 // Reserve place for the globalized memory.
1172 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001173 if (!KernelStaticGlobalized) {
1174 KernelStaticGlobalized = new llvm::GlobalVariable(
1175 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1176 llvm::GlobalValue::InternalLinkage,
1177 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1178 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1179 llvm::GlobalValue::NotThreadLocal,
1180 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1181 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001182 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1183 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001184 IsInTTDRegion = false;
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001185
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001186 // Now change the name of the worker function to correspond to this target
1187 // region's entry function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001188 WST.WorkerFn->setName(Twine(OutlinedFn->getName(), "_worker"));
Alexey Bataevaee93892018-01-08 20:09:47 +00001189
1190 // Create the worker function
1191 emitWorkerFunction(WST);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001192}
1193
1194// Setup NVPTX threads for master-worker OpenMP scheme.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001195void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryHeader(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001196 EntryFunctionState &EST,
1197 WorkerFunctionState &WST) {
1198 CGBuilderTy &Bld = CGF.Builder;
1199
1200 llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker");
1201 llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck");
1202 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
1203 EST.ExitBB = CGF.createBasicBlock(".exit");
1204
Alexey Bataev9ff80832018-04-16 20:16:21 +00001205 llvm::Value *IsWorker =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001206 Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF));
1207 Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB);
1208
1209 CGF.EmitBlock(WorkerBB);
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001210 emitCall(CGF, WST.Loc, WST.WorkerFn);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001211 CGF.EmitBranch(EST.ExitBB);
1212
1213 CGF.EmitBlock(MasterCheckBB);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001214 llvm::Value *IsMaster =
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001215 Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF));
1216 Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB);
1217
1218 CGF.EmitBlock(MasterBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001219 IsInTargetMasterThreadRegion = true;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001220 // SEQUENTIAL (MASTER) REGION START
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001221 // First action in sequential region:
1222 // Initialize the state of the OpenMP runtime library on the GPU.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001223 // TODO: Optimize runtime initialization and pass in correct value.
1224 llvm::Value *Args[] = {getThreadLimit(CGF),
1225 Bld.getInt16(/*RequiresOMPRuntime=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001226 CGF.EmitRuntimeCall(
1227 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001228
1229 // For data sharing, we need to initialize the stack.
1230 CGF.EmitRuntimeCall(
1231 createNVPTXRuntimeFunction(
1232 OMPRTL_NVPTX__kmpc_data_sharing_init_stack));
1233
Alexey Bataevc99042b2018-03-15 18:10:54 +00001234 emitGenericVarsProlog(CGF, WST.Loc);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001235}
1236
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001237void CGOpenMPRuntimeNVPTX::emitNonSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001238 EntryFunctionState &EST) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001239 IsInTargetMasterThreadRegion = false;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001240 if (!CGF.HaveInsertPoint())
1241 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001242
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001243 emitGenericVarsEpilog(CGF);
1244
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001245 if (!EST.ExitBB)
1246 EST.ExitBB = CGF.createBasicBlock(".exit");
1247
1248 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier");
1249 CGF.EmitBranch(TerminateBB);
1250
1251 CGF.EmitBlock(TerminateBB);
1252 // Signal termination condition.
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001253 // TODO: Optimize runtime initialization and pass in correct value.
1254 llvm::Value *Args[] = {CGF.Builder.getInt16(/*IsOMPRuntimeInitialized=*/1)};
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001255 CGF.EmitRuntimeCall(
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001256 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), Args);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001257 // Barrier to terminate worker threads.
1258 syncCTAThreads(CGF);
1259 // Master thread jumps to exit point.
1260 CGF.EmitBranch(EST.ExitBB);
1261
1262 CGF.EmitBlock(EST.ExitBB);
1263 EST.ExitBB = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001264}
1265
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001266void CGOpenMPRuntimeNVPTX::emitSPMDKernel(const OMPExecutableDirective &D,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001267 StringRef ParentName,
1268 llvm::Function *&OutlinedFn,
1269 llvm::Constant *&OutlinedFnID,
1270 bool IsOffloadEntry,
1271 const RegionCodeGenTy &CodeGen) {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001272 ExecutionRuntimeModesRAII ModeRAII(
1273 CurrentExecutionMode, RequiresFullRuntime,
1274 CGM.getLangOpts().OpenMPCUDAForceFullRuntime ||
1275 !supportsLightweightRuntime(CGM.getContext(), D));
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001276 EntryFunctionState EST;
1277
1278 // Emit target region as a standalone region.
1279 class NVPTXPrePostActionTy : public PrePostActionTy {
1280 CGOpenMPRuntimeNVPTX &RT;
1281 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST;
1282 const OMPExecutableDirective &D;
1283
1284 public:
1285 NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT,
1286 CGOpenMPRuntimeNVPTX::EntryFunctionState &EST,
1287 const OMPExecutableDirective &D)
1288 : RT(RT), EST(EST), D(D) {}
1289 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001290 RT.emitSPMDEntryHeader(CGF, EST, D);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001291 // Skip target region initialization.
1292 RT.setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001293 }
1294 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevfd006c42018-10-05 15:08:53 +00001295 RT.clearLocThreadIdInsertPt(CGF);
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001296 RT.emitSPMDEntryFooter(CGF, EST);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001297 }
1298 } Action(*this, EST, D);
1299 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001300 IsInTTDRegion = true;
Alexey Bataeve4090182018-11-02 14:54:07 +00001301 // Reserve place for the globalized memory.
1302 GlobalizedRecords.emplace_back();
Alexey Bataeve4090182018-11-02 14:54:07 +00001303 if (!KernelStaticGlobalized) {
1304 KernelStaticGlobalized = new llvm::GlobalVariable(
1305 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/false,
1306 llvm::GlobalValue::InternalLinkage,
1307 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
1308 "_openmp_kernel_static_glob_rd$ptr", /*InsertBefore=*/nullptr,
1309 llvm::GlobalValue::NotThreadLocal,
1310 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
1311 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001312 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
1313 IsOffloadEntry, CodeGen);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001314 IsInTTDRegion = false;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001315}
1316
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001317void CGOpenMPRuntimeNVPTX::emitSPMDEntryHeader(
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001318 CodeGenFunction &CGF, EntryFunctionState &EST,
1319 const OMPExecutableDirective &D) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001320 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001321
1322 // Setup BBs in entry function.
1323 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute");
1324 EST.ExitBB = CGF.createBasicBlock(".exit");
1325
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001326 llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSPMDExecutionMode=*/true),
1327 /*RequiresOMPRuntime=*/
1328 Bld.getInt16(RequiresFullRuntime ? 1 : 0),
1329 /*RequiresDataSharing=*/Bld.getInt16(0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001330 CGF.EmitRuntimeCall(
1331 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args);
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001332
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001333 if (RequiresFullRuntime) {
1334 // For data sharing, we need to initialize the stack.
1335 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
1336 OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd));
1337 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001338
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001339 CGF.EmitBranch(ExecuteBB);
1340
1341 CGF.EmitBlock(ExecuteBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001342
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001343 IsInTargetMasterThreadRegion = true;
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001344}
1345
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001346void CGOpenMPRuntimeNVPTX::emitSPMDEntryFooter(CodeGenFunction &CGF,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001347 EntryFunctionState &EST) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001348 IsInTargetMasterThreadRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001349 if (!CGF.HaveInsertPoint())
1350 return;
1351
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001352 if (!EST.ExitBB)
1353 EST.ExitBB = CGF.createBasicBlock(".exit");
1354
1355 llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit");
1356 CGF.EmitBranch(OMPDeInitBB);
1357
1358 CGF.EmitBlock(OMPDeInitBB);
1359 // DeInitialize the OMP state in the runtime; called by all active threads.
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001360 llvm::Value *Args[] = {/*RequiresOMPRuntime=*/
1361 CGF.Builder.getInt16(RequiresFullRuntime ? 1 : 0)};
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001362 CGF.EmitRuntimeCall(
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001363 createNVPTXRuntimeFunction(
1364 OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2), Args);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001365 CGF.EmitBranch(EST.ExitBB);
1366
1367 CGF.EmitBlock(EST.ExitBB);
1368 EST.ExitBB = nullptr;
1369}
1370
1371// Create a unique global variable to indicate the execution mode of this target
1372// region. The execution mode is either 'generic', or 'spmd' depending on the
1373// target directive. This variable is picked up by the offload library to setup
1374// the device appropriately before kernel launch. If the execution mode is
1375// 'generic', the runtime reserves one warp for the master, otherwise, all
1376// warps participate in parallel work.
1377static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001378 bool Mode) {
1379 auto *GVMode =
1380 new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1381 llvm::GlobalValue::WeakAnyLinkage,
1382 llvm::ConstantInt::get(CGM.Int8Ty, Mode ? 0 : 1),
1383 Twine(Name, "_exec_mode"));
Alexey Bataev9ff80832018-04-16 20:16:21 +00001384 CGM.addCompilerUsedGlobal(GVMode);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001385}
1386
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001387void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) {
Gheorghe-Teodor Berceaeb89b1d2017-11-21 15:54:54 +00001388 ASTContext &Ctx = CGM.getContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001389
1390 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001391 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, WST.CGFI, {},
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001392 WST.Loc, WST.Loc);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001393 emitWorkerLoop(CGF, WST);
1394 CGF.FinishFunction();
1395}
1396
1397void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF,
1398 WorkerFunctionState &WST) {
1399 //
1400 // The workers enter this loop and wait for parallel work from the master.
1401 // When the master encounters a parallel region it sets up the work + variable
1402 // arguments, and wakes up the workers. The workers first check to see if
1403 // they are required for the parallel region, i.e., within the # of requested
1404 // parallel threads. The activated workers load the variable arguments and
1405 // execute the parallel work.
1406 //
1407
1408 CGBuilderTy &Bld = CGF.Builder;
1409
1410 llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work");
1411 llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers");
1412 llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel");
1413 llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel");
1414 llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel");
1415 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
1416
1417 CGF.EmitBranch(AwaitBB);
1418
1419 // Workers wait for work from master.
1420 CGF.EmitBlock(AwaitBB);
1421 // Wait for parallel work
1422 syncCTAThreads(CGF);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001423
1424 Address WorkFn =
1425 CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn");
1426 Address ExecStatus =
1427 CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status");
1428 CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0));
1429 CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy));
1430
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001431 // TODO: Optimize runtime initialization and pass in correct value.
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001432 llvm::Value *Args[] = {WorkFn.getPointer(),
Jonas Hahnfeldfa059ba2017-12-27 10:39:56 +00001433 /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001434 llvm::Value *Ret = CGF.EmitRuntimeCall(
1435 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args);
1436 Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001437
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001438 // On termination condition (workid == 0), exit loop.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001439 llvm::Value *WorkID = Bld.CreateLoad(WorkFn);
1440 llvm::Value *ShouldTerminate = Bld.CreateIsNull(WorkID, "should_terminate");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001441 Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB);
1442
1443 // Activate requested workers.
1444 CGF.EmitBlock(SelectWorkersBB);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001445 llvm::Value *IsActive =
1446 Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active");
1447 Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001448
1449 // Signal start of parallel region.
1450 CGF.EmitBlock(ExecuteBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001451 // Skip initialization.
1452 setLocThreadIdInsertPt(CGF, /*AtCurrentPoint=*/true);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001453
1454 // Process work items: outlined parallel functions.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001455 for (llvm::Function *W : Work) {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001456 // Try to match this outlined function.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001457 llvm::Value *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001458
1459 llvm::Value *WorkFnMatch =
1460 Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match");
1461
1462 llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn");
1463 llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next");
1464 Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB);
1465
1466 // Execute this outlined function.
1467 CGF.EmitBlock(ExecuteFNBB);
1468
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001469 // Insert call to work function via shared wrapper. The shared
1470 // wrapper takes two arguments:
1471 // - the parallelism level;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00001472 // - the thread ID;
1473 emitCall(CGF, WST.Loc, W,
1474 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001475
1476 // Go to end of parallel region.
1477 CGF.EmitBranch(TerminateBB);
1478
1479 CGF.EmitBlock(CheckNextBB);
1480 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001481 // Default case: call to outlined function through pointer if the target
1482 // region makes a declare target call that may contain an orphaned parallel
1483 // directive.
1484 auto *ParallelFnTy =
1485 llvm::FunctionType::get(CGM.VoidTy, {CGM.Int16Ty, CGM.Int32Ty},
James Y Knight9871db02019-02-05 16:42:33 +00001486 /*isVarArg=*/false);
1487 llvm::Value *WorkFnCast =
1488 Bld.CreateBitCast(WorkID, ParallelFnTy->getPointerTo());
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001489 // Insert call to work function via shared wrapper. The shared
1490 // wrapper takes two arguments:
1491 // - the parallelism level;
1492 // - the thread ID;
James Y Knight9871db02019-02-05 16:42:33 +00001493 emitCall(CGF, WST.Loc, {ParallelFnTy, WorkFnCast},
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001494 {Bld.getInt16(/*ParallelLevel=*/0), getThreadID(CGF, WST.Loc)});
1495 // Go to end of parallel region.
1496 CGF.EmitBranch(TerminateBB);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001497
1498 // Signal end of parallel region.
1499 CGF.EmitBlock(TerminateBB);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001500 CGF.EmitRuntimeCall(
1501 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel),
1502 llvm::None);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001503 CGF.EmitBranch(BarrierBB);
1504
1505 // All active and inactive workers wait at a barrier after parallel region.
1506 CGF.EmitBlock(BarrierBB);
1507 // Barrier after parallel region.
1508 syncCTAThreads(CGF);
1509 CGF.EmitBranch(AwaitBB);
1510
1511 // Exit target region.
1512 CGF.EmitBlock(ExitBB);
Alexey Bataev3ce5d822018-11-29 21:21:32 +00001513 // Skip initialization.
1514 clearLocThreadIdInsertPt(CGF);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001515}
1516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001517/// Returns specified OpenMP runtime function for the current OpenMP
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001518/// implementation. Specialized for the NVPTX device.
1519/// \param Function OpenMP runtime function.
1520/// \return Specified function.
James Y Knight9871db02019-02-05 16:42:33 +00001521llvm::FunctionCallee
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001522CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) {
James Y Knight9871db02019-02-05 16:42:33 +00001523 llvm::FunctionCallee RTLFn = nullptr;
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001524 switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) {
1525 case OMPRTL_NVPTX__kmpc_kernel_init: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001526 // Build void __kmpc_kernel_init(kmp_int32 thread_limit, int16_t
1527 // RequiresOMPRuntime);
1528 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001529 auto *FnTy =
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001530 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1531 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init");
1532 break;
1533 }
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001534 case OMPRTL_NVPTX__kmpc_kernel_deinit: {
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001535 // Build void __kmpc_kernel_deinit(int16_t IsOMPRuntimeInitialized);
1536 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001537 auto *FnTy =
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001538 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Arpith Chacko Jacob406acdb2017-01-05 15:24:05 +00001539 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit");
1540 break;
1541 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001542 case OMPRTL_NVPTX__kmpc_spmd_kernel_init: {
1543 // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit,
Jonas Hahnfeld891c7fb2017-11-22 14:46:49 +00001544 // int16_t RequiresOMPRuntime, int16_t RequiresDataSharing);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001545 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001546 auto *FnTy =
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001547 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1548 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init");
1549 break;
1550 }
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001551 case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit_v2: {
1552 // Build void __kmpc_spmd_kernel_deinit_v2(int16_t RequiresOMPRuntime);
1553 llvm::Type *TypeParams[] = {CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001554 auto *FnTy =
Gheorghe-Teodor Bercea2b404702018-11-29 20:53:49 +00001555 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1556 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit_v2");
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001557 break;
1558 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001559 case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: {
1560 /// Build void __kmpc_kernel_prepare_parallel(
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001561 /// void *outlined_function, int16_t IsOMPRuntimeInitialized);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001562 llvm::Type *TypeParams[] = {CGM.Int8PtrTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001563 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001564 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1565 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel");
1566 break;
1567 }
1568 case OMPRTL_NVPTX__kmpc_kernel_parallel: {
Gheorghe-Teodor Bercea7d80da12018-03-07 21:59:50 +00001569 /// Build bool __kmpc_kernel_parallel(void **outlined_function,
1570 /// int16_t IsOMPRuntimeInitialized);
1571 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy, CGM.Int16Ty};
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001572 llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
Alexey Bataev9ff80832018-04-16 20:16:21 +00001573 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001574 llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false);
1575 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel");
1576 break;
1577 }
1578 case OMPRTL_NVPTX__kmpc_kernel_end_parallel: {
1579 /// Build void __kmpc_kernel_end_parallel();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001580 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001581 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel");
1583 break;
1584 }
1585 case OMPRTL_NVPTX__kmpc_serialized_parallel: {
1586 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1587 // global_tid);
1588 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001589 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001590 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1592 break;
1593 }
1594 case OMPRTL_NVPTX__kmpc_end_serialized_parallel: {
1595 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1596 // global_tid);
1597 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001598 auto *FnTy =
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001599 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1600 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1601 break;
1602 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001603 case OMPRTL_NVPTX__kmpc_shuffle_int32: {
1604 // Build int32_t __kmpc_shuffle_int32(int32_t element,
1605 // int16_t lane_offset, int16_t warp_size);
1606 llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001607 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001608 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1609 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int32");
1610 break;
1611 }
1612 case OMPRTL_NVPTX__kmpc_shuffle_int64: {
1613 // Build int64_t __kmpc_shuffle_int64(int64_t element,
1614 // int16_t lane_offset, int16_t warp_size);
1615 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001616 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001617 llvm::FunctionType::get(CGM.Int64Ty, TypeParams, /*isVarArg*/ false);
1618 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_shuffle_int64");
1619 break;
1620 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001621 case OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001622 // Build int32_t kmpc_nvptx_parallel_reduce_nowait_v2(ident_t *loc,
1623 // kmp_int32 global_tid, kmp_int32 num_vars, size_t reduce_size, void*
1624 // reduce_data, void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t
1625 // lane_id, int16_t lane_offset, int16_t Algorithm Version), void
1626 // (*kmp_InterWarpCopyFctPtr)(void* src, int warp_num));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001627 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1628 CGM.Int16Ty, CGM.Int16Ty};
1629 auto *ShuffleReduceFnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1631 /*isVarArg=*/false);
1632 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1633 auto *InterWarpCopyFnTy =
1634 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1635 /*isVarArg=*/false);
Alexey Bataev8e009032019-01-04 17:25:09 +00001636 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1637 CGM.Int32Ty,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001638 CGM.Int32Ty,
1639 CGM.SizeTy,
1640 CGM.VoidPtrTy,
1641 ShuffleReduceFnTy->getPointerTo(),
1642 InterWarpCopyFnTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001643 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001644 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1645 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8e009032019-01-04 17:25:09 +00001646 FnTy, /*Name=*/"__kmpc_nvptx_parallel_reduce_nowait_v2");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001647 break;
1648 }
1649 case OMPRTL_NVPTX__kmpc_end_reduce_nowait: {
1650 // Build __kmpc_end_reduce_nowait(kmp_int32 global_tid);
1651 llvm::Type *TypeParams[] = {CGM.Int32Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001652 auto *FnTy =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00001653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1654 RTLFn = CGM.CreateRuntimeFunction(
1655 FnTy, /*Name=*/"__kmpc_nvptx_end_reduce_nowait");
1656 break;
1657 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00001658 case OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2: {
1659 // Build int32_t __kmpc_nvptx_teams_reduce_nowait_v2(ident_t *loc, kmp_int32
1660 // global_tid, void *global_buffer, int32_t num_of_records, void*
1661 // reduce_data,
1662 // void (*kmp_ShuffleReductFctPtr)(void *rhsData, int16_t lane_id, int16_t
1663 // lane_offset, int16_t shortCircuit),
1664 // void (*kmp_InterWarpCopyFctPtr)(void* src, int32_t warp_num), void
1665 // (*kmp_ListToGlobalCpyFctPtr)(void *buffer, int idx, void *reduce_data),
1666 // void (*kmp_GlobalToListCpyFctPtr)(void *buffer, int idx,
1667 // void *reduce_data), void (*kmp_GlobalToListCpyPtrsFctPtr)(void *buffer,
1668 // int idx, void *reduce_data), void (*kmp_GlobalToListRedFctPtr)(void
1669 // *buffer, int idx, void *reduce_data));
1670 llvm::Type *ShuffleReduceTypeParams[] = {CGM.VoidPtrTy, CGM.Int16Ty,
1671 CGM.Int16Ty, CGM.Int16Ty};
1672 auto *ShuffleReduceFnTy =
1673 llvm::FunctionType::get(CGM.VoidTy, ShuffleReduceTypeParams,
1674 /*isVarArg=*/false);
1675 llvm::Type *InterWarpCopyTypeParams[] = {CGM.VoidPtrTy, CGM.Int32Ty};
1676 auto *InterWarpCopyFnTy =
1677 llvm::FunctionType::get(CGM.VoidTy, InterWarpCopyTypeParams,
1678 /*isVarArg=*/false);
1679 llvm::Type *GlobalListTypeParams[] = {CGM.VoidPtrTy, CGM.IntTy,
1680 CGM.VoidPtrTy};
1681 auto *GlobalListFnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, GlobalListTypeParams,
1683 /*isVarArg=*/false);
1684 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1685 CGM.Int32Ty,
1686 CGM.VoidPtrTy,
1687 CGM.Int32Ty,
1688 CGM.VoidPtrTy,
1689 ShuffleReduceFnTy->getPointerTo(),
1690 InterWarpCopyFnTy->getPointerTo(),
1691 GlobalListFnTy->getPointerTo(),
1692 GlobalListFnTy->getPointerTo(),
1693 GlobalListFnTy->getPointerTo(),
1694 GlobalListFnTy->getPointerTo()};
Alexey Bataeva1166022018-11-27 21:24:54 +00001695 auto *FnTy =
1696 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1697 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00001698 FnTy, /*Name=*/"__kmpc_nvptx_teams_reduce_nowait_v2");
Alexey Bataeva1166022018-11-27 21:24:54 +00001699 break;
1700 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001701 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack: {
1702 /// Build void __kmpc_data_sharing_init_stack();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001703 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001704 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1705 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack");
1706 break;
1707 }
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001708 case OMPRTL_NVPTX__kmpc_data_sharing_init_stack_spmd: {
1709 /// Build void __kmpc_data_sharing_init_stack_spmd();
1710 auto *FnTy =
1711 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00001712 RTLFn =
1713 CGM.CreateRuntimeFunction(FnTy, "__kmpc_data_sharing_init_stack_spmd");
Gheorghe-Teodor Berceaad4e5792018-07-13 16:18:24 +00001714 break;
1715 }
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001716 case OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack: {
1717 // Build void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001718 // int16_t UseSharedMemory);
1719 llvm::Type *TypeParams[] = {CGM.SizeTy, CGM.Int16Ty};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001720 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001721 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1722 RTLFn = CGM.CreateRuntimeFunction(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00001723 FnTy, /*Name=*/"__kmpc_data_sharing_coalesced_push_stack");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001724 break;
1725 }
1726 case OMPRTL_NVPTX__kmpc_data_sharing_pop_stack: {
1727 // Build void __kmpc_data_sharing_pop_stack(void *a);
1728 llvm::Type *TypeParams[] = {CGM.VoidPtrTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001729 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001730 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1731 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1732 /*Name=*/"__kmpc_data_sharing_pop_stack");
1733 break;
1734 }
1735 case OMPRTL_NVPTX__kmpc_begin_sharing_variables: {
1736 /// Build void __kmpc_begin_sharing_variables(void ***args,
1737 /// size_t n_args);
1738 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo(), CGM.SizeTy};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001739 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001740 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1741 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_begin_sharing_variables");
1742 break;
1743 }
1744 case OMPRTL_NVPTX__kmpc_end_sharing_variables: {
1745 /// Build void __kmpc_end_sharing_variables();
Alexey Bataev9ff80832018-04-16 20:16:21 +00001746 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001747 llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false);
1748 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_sharing_variables");
1749 break;
1750 }
1751 case OMPRTL_NVPTX__kmpc_get_shared_variables: {
1752 /// Build void __kmpc_get_shared_variables(void ***GlobalArgs);
1753 llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy->getPointerTo()};
Alexey Bataev9ff80832018-04-16 20:16:21 +00001754 auto *FnTy =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001755 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1756 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_shared_variables");
1757 break;
1758 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001759 case OMPRTL_NVPTX__kmpc_parallel_level: {
1760 // Build uint16_t __kmpc_parallel_level(ident_t *loc, kmp_int32 global_tid);
1761 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1762 auto *FnTy =
1763 llvm::FunctionType::get(CGM.Int16Ty, TypeParams, /*isVarArg*/ false);
1764 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_parallel_level");
1765 break;
1766 }
Alexey Bataev673110d2018-05-16 13:36:30 +00001767 case OMPRTL_NVPTX__kmpc_is_spmd_exec_mode: {
1768 // Build int8_t __kmpc_is_spmd_exec_mode();
1769 auto *FnTy = llvm::FunctionType::get(CGM.Int8Ty, /*isVarArg=*/false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_is_spmd_exec_mode");
1771 break;
1772 }
Alexey Bataeve4090182018-11-02 14:54:07 +00001773 case OMPRTL_NVPTX__kmpc_get_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001774 // Build void __kmpc_get_team_static_memory(int16_t isSPMDExecutionMode,
1775 // const void *buf, size_t size, int16_t is_shared, const void **res);
1776 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.VoidPtrTy, CGM.SizeTy,
1777 CGM.Int16Ty, CGM.VoidPtrPtrTy};
Alexey Bataeve4090182018-11-02 14:54:07 +00001778 auto *FnTy =
1779 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_get_team_static_memory");
1781 break;
1782 }
1783 case OMPRTL_NVPTX__kmpc_restore_team_static_memory: {
Alexey Bataev8e009032019-01-04 17:25:09 +00001784 // Build void __kmpc_restore_team_static_memory(int16_t isSPMDExecutionMode,
1785 // int16_t is_shared);
1786 llvm::Type *TypeParams[] = {CGM.Int16Ty, CGM.Int16Ty};
Alexey Bataeve4090182018-11-02 14:54:07 +00001787 auto *FnTy =
Alexey Bataev8e009032019-01-04 17:25:09 +00001788 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
Alexey Bataeve4090182018-11-02 14:54:07 +00001789 RTLFn =
1790 CGM.CreateRuntimeFunction(FnTy, "__kmpc_restore_team_static_memory");
1791 break;
1792 }
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001793 case OMPRTL__kmpc_barrier: {
1794 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
1795 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1796 auto *FnTy =
1797 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1798 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
James Y Knight9871db02019-02-05 16:42:33 +00001799 cast<llvm::Function>(RTLFn.getCallee())
1800 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataevc3028ca2018-12-04 15:03:25 +00001801 break;
1802 }
Alexey Bataeva3924b52019-01-03 16:25:35 +00001803 case OMPRTL__kmpc_barrier_simple_spmd: {
1804 // Build void __kmpc_barrier_simple_spmd(ident_t *loc, kmp_int32
1805 // global_tid);
1806 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1807 auto *FnTy =
1808 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1809 RTLFn =
1810 CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier_simple_spmd");
James Y Knight9871db02019-02-05 16:42:33 +00001811 cast<llvm::Function>(RTLFn.getCallee())
1812 ->addFnAttr(llvm::Attribute::Convergent);
Alexey Bataeva3924b52019-01-03 16:25:35 +00001813 break;
1814 }
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00001815 case OMPRTL_NVPTX__kmpc_warp_active_thread_mask: {
1816 // Build int32_t __kmpc_warp_active_thread_mask(void);
1817 auto *FnTy =
1818 llvm::FunctionType::get(CGM.Int32Ty, llvm::None, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_warp_active_thread_mask");
1820 break;
1821 }
1822 case OMPRTL_NVPTX__kmpc_syncwarp: {
1823 // Build void __kmpc_syncwarp(kmp_int32 Mask);
1824 auto *FnTy =
1825 llvm::FunctionType::get(CGM.VoidTy, CGM.Int32Ty, /*isVarArg=*/false);
1826 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_syncwarp");
1827 break;
1828 }
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001829 }
1830 return RTLFn;
1831}
1832
1833void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID,
1834 llvm::Constant *Addr,
Alexey Bataev03f270c2018-03-30 18:31:07 +00001835 uint64_t Size, int32_t,
1836 llvm::GlobalValue::LinkageTypes) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001837 // TODO: Add support for global variables on the device after declare target
1838 // support.
Alexey Bataev9ff80832018-04-16 20:16:21 +00001839 if (!isa<llvm::Function>(Addr))
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001840 return;
Alexey Bataev9ff80832018-04-16 20:16:21 +00001841 llvm::Module &M = CGM.getModule();
1842 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001843
1844 // Get "nvvm.annotations" metadata node
Alexey Bataev9ff80832018-04-16 20:16:21 +00001845 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001846
1847 llvm::Metadata *MDVals[] = {
Alexey Bataev9ff80832018-04-16 20:16:21 +00001848 llvm::ConstantAsMetadata::get(Addr), llvm::MDString::get(Ctx, "kernel"),
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001849 llvm::ConstantAsMetadata::get(
1850 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))};
1851 // Append metadata to nvvm.annotations
1852 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
1853}
1854
1855void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction(
1856 const OMPExecutableDirective &D, StringRef ParentName,
1857 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001858 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001859 if (!IsOffloadEntry) // Nothing to do.
1860 return;
1861
1862 assert(!ParentName.empty() && "Invalid target region parent name!");
1863
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001864 bool Mode = supportsSPMDExecutionMode(CGM.getContext(), D);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001865 if (Mode)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001866 emitSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001867 CodeGen);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001868 else
1869 emitNonSPMDKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry,
1870 CodeGen);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00001871
1872 setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001873}
1874
Alexey Bataevceeaa482018-11-21 21:04:34 +00001875namespace {
1876LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
1877/// Enum for accesseing the reserved_2 field of the ident_t struct.
1878enum ModeFlagsTy : unsigned {
1879 /// Bit set to 1 when in SPMD mode.
1880 KMP_IDENT_SPMD_MODE = 0x01,
1881 /// Bit set to 1 when a simplified runtime is used.
1882 KMP_IDENT_SIMPLE_RT_MODE = 0x02,
1883 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/KMP_IDENT_SIMPLE_RT_MODE)
1884};
1885
1886/// Special mode Undefined. Is the combination of Non-SPMD mode + SimpleRuntime.
1887static const ModeFlagsTy UndefinedMode =
1888 (~KMP_IDENT_SPMD_MODE) & KMP_IDENT_SIMPLE_RT_MODE;
1889} // anonymous namespace
1890
1891unsigned CGOpenMPRuntimeNVPTX::getDefaultLocationReserved2Flags() const {
Alexey Bataeve8ad4b72018-11-26 18:37:09 +00001892 switch (getExecutionMode()) {
1893 case EM_SPMD:
1894 if (requiresFullRuntime())
1895 return KMP_IDENT_SPMD_MODE & (~KMP_IDENT_SIMPLE_RT_MODE);
1896 return KMP_IDENT_SPMD_MODE | KMP_IDENT_SIMPLE_RT_MODE;
1897 case EM_NonSPMD:
1898 assert(requiresFullRuntime() && "Expected full runtime.");
1899 return (~KMP_IDENT_SPMD_MODE) & (~KMP_IDENT_SIMPLE_RT_MODE);
1900 case EM_Unknown:
1901 return UndefinedMode;
1902 }
1903 llvm_unreachable("Unknown flags are requested.");
Alexey Bataevceeaa482018-11-21 21:04:34 +00001904}
1905
Alexey Bataevc2cd2d42019-10-10 17:28:10 +00001906bool CGOpenMPRuntimeNVPTX::tryEmitDeclareVariant(const GlobalDecl &NewGD,
1907 const GlobalDecl &OldGD,
1908 llvm::GlobalValue *OrigAddr,
1909 bool IsForDefinition) {
1910 // Emit the function in OldGD with the body from NewGD, if NewGD is defined.
1911 auto *NewFD = cast<FunctionDecl>(NewGD.getDecl());
1912 if (NewFD->isDefined()) {
1913 CGM.emitOpenMPDeviceFunctionRedefinition(OldGD, NewGD, OrigAddr);
1914 return true;
1915 }
1916 return false;
1917}
1918
Samuel Antao45bfe4c2016-02-08 15:59:20 +00001919CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001920 : CGOpenMPRuntime(CGM, "_", "$") {
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001921 if (!CGM.getLangOpts().OpenMPIsDevice)
1922 llvm_unreachable("OpenMP NVPTX can only handle device code.");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00001923}
Carlo Bertollic6872252016-04-04 15:55:02 +00001924
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001925void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF,
1926 OpenMPProcBindClauseKind ProcBind,
1927 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001928 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001929 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacob2cd6eea2017-01-25 16:55:10 +00001930 return;
1931
1932 CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc);
1933}
1934
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001935void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF,
1936 llvm::Value *NumThreads,
1937 SourceLocation Loc) {
Alexey Bataev4065b9a2018-06-21 20:26:33 +00001938 // Do nothing in case of SPMD mode and L0 parallel.
Alexey Bataev2a3320a2018-05-15 18:01:01 +00001939 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Arpith Chacko Jacobe04da5d2017-01-25 01:18:34 +00001940 return;
1941
1942 CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc);
1943}
1944
Carlo Bertollic6872252016-04-04 15:55:02 +00001945void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF,
1946 const Expr *NumTeams,
1947 const Expr *ThreadLimit,
1948 SourceLocation Loc) {}
1949
James Y Knight9871db02019-02-05 16:42:33 +00001950llvm::Function *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001951 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1952 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00001953 // Emit target region as a standalone region.
1954 class NVPTXPrePostActionTy : public PrePostActionTy {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001955 bool &IsInParallelRegion;
1956 bool PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001957
1958 public:
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001959 NVPTXPrePostActionTy(bool &IsInParallelRegion)
1960 : IsInParallelRegion(IsInParallelRegion) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00001961 void Enter(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001962 PrevIsInParallelRegion = IsInParallelRegion;
1963 IsInParallelRegion = true;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001964 }
1965 void Exit(CodeGenFunction &CGF) override {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001966 IsInParallelRegion = PrevIsInParallelRegion;
Alexey Bataevc99042b2018-03-15 18:10:54 +00001967 }
Alexey Bataevb99dcb52018-07-09 17:43:58 +00001968 } Action(IsInParallelRegion);
Alexey Bataevc99042b2018-03-15 18:10:54 +00001969 CodeGen.setAction(Action);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001970 bool PrevIsInTTDRegion = IsInTTDRegion;
1971 IsInTTDRegion = false;
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001972 bool PrevIsInTargetMasterThreadRegion = IsInTargetMasterThreadRegion;
1973 IsInTargetMasterThreadRegion = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001974 auto *OutlinedFun =
1975 cast<llvm::Function>(CGOpenMPRuntime::emitParallelOutlinedFunction(
1976 D, ThreadIDVar, InnermostKind, CodeGen));
Alexey Bataev8c5555c2019-05-21 15:11:58 +00001977 if (CGM.getLangOpts().Optimize) {
1978 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
1979 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
1980 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
1981 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00001982 IsInTargetMasterThreadRegion = PrevIsInTargetMasterThreadRegion;
Alexey Bataev4ac58d12018-10-12 20:19:59 +00001983 IsInTTDRegion = PrevIsInTTDRegion;
Alexey Bataevbf5c8482018-05-10 18:32:08 +00001984 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD &&
1985 !IsInParallelRegion) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001986 llvm::Function *WrapperFun =
1987 createParallelDataSharingWrapper(OutlinedFun, D);
1988 WrapperFunctionsMap[OutlinedFun] = WrapperFun;
1989 }
1990
1991 return OutlinedFun;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001992}
1993
Alexey Bataev2adecff2018-09-21 14:22:53 +00001994/// Get list of lastprivate variables from the teams distribute ... or
1995/// teams {distribute ...} directives.
1996static void
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00001997getDistributeLastprivateVars(ASTContext &Ctx, const OMPExecutableDirective &D,
Alexey Bataev2adecff2018-09-21 14:22:53 +00001998 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
1999 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2000 "expected teams directive.");
2001 const OMPExecutableDirective *Dir = &D;
2002 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002003 if (const Stmt *S = CGOpenMPRuntime::getSingleCompoundChild(
Alexey Bataev8bcc69c2018-11-09 20:03:19 +00002004 Ctx,
Alexey Bataev2adecff2018-09-21 14:22:53 +00002005 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(
2006 /*IgnoreCaptured=*/true))) {
Alexey Bataev5c427362019-04-10 19:11:33 +00002007 Dir = dyn_cast_or_null<OMPExecutableDirective>(S);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002008 if (Dir && !isOpenMPDistributeDirective(Dir->getDirectiveKind()))
2009 Dir = nullptr;
2010 }
2011 }
2012 if (!Dir)
2013 return;
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002014 for (const auto *C : Dir->getClausesOfKind<OMPLastprivateClause>()) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002015 for (const Expr *E : C->getVarRefs())
2016 Vars.push_back(getPrivateItem(E));
2017 }
2018}
2019
2020/// Get list of reduction variables from the teams ... directives.
2021static void
2022getTeamsReductionVars(ASTContext &Ctx, const OMPExecutableDirective &D,
2023 llvm::SmallVectorImpl<const ValueDecl *> &Vars) {
2024 assert(isOpenMPTeamsDirective(D.getDirectiveKind()) &&
2025 "expected teams directive.");
2026 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) {
2027 for (const Expr *E : C->privates())
2028 Vars.push_back(getPrivateItem(E));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002029 }
2030}
2031
James Y Knight9871db02019-02-05 16:42:33 +00002032llvm::Function *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction(
Carlo Bertollic6872252016-04-04 15:55:02 +00002033 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
2034 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002035 SourceLocation Loc = D.getBeginLoc();
Carlo Bertollic6872252016-04-04 15:55:02 +00002036
Alexey Bataev2adecff2018-09-21 14:22:53 +00002037 const RecordDecl *GlobalizedRD = nullptr;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002038 llvm::SmallVector<const ValueDecl *, 4> LastPrivatesReductions;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002039 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> MappedDeclsFields;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002040 // Globalize team reductions variable unconditionally in all modes.
Alexey Bataev8061acd2019-02-20 16:36:22 +00002041 if (getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
2042 getTeamsReductionVars(CGM.getContext(), D, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002043 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002044 getDistributeLastprivateVars(CGM.getContext(), D, LastPrivatesReductions);
2045 if (!LastPrivatesReductions.empty()) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002046 GlobalizedRD = ::buildRecordForGlobalizedVars(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002047 CGM.getContext(), llvm::None, LastPrivatesReductions,
Alexey Bataev8061acd2019-02-20 16:36:22 +00002048 MappedDeclsFields, WarpSize);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002049 }
2050 } else if (!LastPrivatesReductions.empty()) {
2051 assert(!TeamAndReductions.first &&
2052 "Previous team declaration is not expected.");
2053 TeamAndReductions.first = D.getCapturedStmt(OMPD_teams)->getCapturedDecl();
2054 std::swap(TeamAndReductions.second, LastPrivatesReductions);
Alexey Bataev2adecff2018-09-21 14:22:53 +00002055 }
2056
Alexey Bataevc99042b2018-03-15 18:10:54 +00002057 // Emit target region as a standalone region.
2058 class NVPTXPrePostActionTy : public PrePostActionTy {
2059 SourceLocation &Loc;
Alexey Bataev2adecff2018-09-21 14:22:53 +00002060 const RecordDecl *GlobalizedRD;
2061 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2062 &MappedDeclsFields;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002063
2064 public:
Alexey Bataev2adecff2018-09-21 14:22:53 +00002065 NVPTXPrePostActionTy(
2066 SourceLocation &Loc, const RecordDecl *GlobalizedRD,
2067 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
2068 &MappedDeclsFields)
2069 : Loc(Loc), GlobalizedRD(GlobalizedRD),
2070 MappedDeclsFields(MappedDeclsFields) {}
Alexey Bataevc99042b2018-03-15 18:10:54 +00002071 void Enter(CodeGenFunction &CGF) override {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002072 auto &Rt =
2073 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime());
2074 if (GlobalizedRD) {
2075 auto I = Rt.FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
2076 I->getSecond().GlobalRecord = GlobalizedRD;
2077 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002078 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataev2adecff2018-09-21 14:22:53 +00002079 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
2080 for (const auto &Pair : MappedDeclsFields) {
2081 assert(Pair.getFirst()->isCanonicalDecl() &&
2082 "Expected canonical declaration");
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002083 Data.insert(std::make_pair(Pair.getFirst(),
2084 MappedVarData(Pair.getSecond(),
2085 /*IsOnePerTeam=*/true)));
Alexey Bataev2adecff2018-09-21 14:22:53 +00002086 }
2087 }
2088 Rt.emitGenericVarsProlog(CGF, Loc);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002089 }
2090 void Exit(CodeGenFunction &CGF) override {
2091 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
2092 .emitGenericVarsEpilog(CGF);
2093 }
Alexey Bataev2adecff2018-09-21 14:22:53 +00002094 } Action(Loc, GlobalizedRD, MappedDeclsFields);
2095 CodeGen.setAction(Action);
James Y Knight9871db02019-02-05 16:42:33 +00002096 llvm::Function *OutlinedFun = CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002097 D, ThreadIDVar, InnermostKind, CodeGen);
Alexey Bataev8c5555c2019-05-21 15:11:58 +00002098 if (CGM.getLangOpts().Optimize) {
2099 OutlinedFun->removeFnAttr(llvm::Attribute::NoInline);
2100 OutlinedFun->removeFnAttr(llvm::Attribute::OptimizeNone);
2101 OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline);
2102 }
Carlo Bertollic6872252016-04-04 15:55:02 +00002103
2104 return OutlinedFun;
2105}
2106
Alexey Bataevc99042b2018-03-15 18:10:54 +00002107void CGOpenMPRuntimeNVPTX::emitGenericVarsProlog(CodeGenFunction &CGF,
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002108 SourceLocation Loc,
2109 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002110 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2111 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002112 return;
2113
Alexey Bataevc99042b2018-03-15 18:10:54 +00002114 CGBuilderTy &Bld = CGF.Builder;
2115
2116 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
2117 if (I == FunctionGlobalizedDecls.end())
2118 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002119 if (const RecordDecl *GlobalizedVarsRecord = I->getSecond().GlobalRecord) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002120 QualType GlobalRecTy = CGM.getContext().getRecordType(GlobalizedVarsRecord);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002121 QualType SecGlobalRecTy;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002122
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002123 // Recover pointer to this function's global record. The runtime will
2124 // handle the specifics of the allocation of the memory.
2125 // Use actual memory size of the record including the padding
2126 // for alignment purposes.
2127 unsigned Alignment =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002128 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002129 unsigned GlobalRecordSize =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002130 CGM.getContext().getTypeSizeInChars(GlobalRecTy).getQuantity();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002131 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002132
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002133 llvm::PointerType *GlobalRecPtrTy =
2134 CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo();
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002135 llvm::Value *GlobalRecCastAddr;
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002136 llvm::Value *IsTTD = nullptr;
Alexey Bataeve4090182018-11-02 14:54:07 +00002137 if (!IsInTTDRegion &&
2138 (WithSPMDCheck ||
2139 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002140 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2141 llvm::BasicBlock *SPMDBB = CGF.createBasicBlock(".spmd");
2142 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002143 if (I->getSecond().SecondaryGlobalRecord.hasValue()) {
2144 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2145 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2146 llvm::Value *PL = CGF.EmitRuntimeCall(
2147 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2148 {RTLoc, ThreadID});
2149 IsTTD = Bld.CreateIsNull(PL);
2150 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002151 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2152 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
2153 Bld.CreateCondBr(IsSPMD, SPMDBB, NonSPMDBB);
2154 // There is no need to emit line number for unconditional branch.
2155 (void)ApplyDebugLocation::CreateEmpty(CGF);
2156 CGF.EmitBlock(SPMDBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002157 Address RecPtr = Address(llvm::ConstantPointerNull::get(GlobalRecPtrTy),
2158 CharUnits::fromQuantity(Alignment));
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002159 CGF.EmitBranch(ExitBB);
2160 // There is no need to emit line number for unconditional branch.
2161 (void)ApplyDebugLocation::CreateEmpty(CGF);
2162 CGF.EmitBlock(NonSPMDBB);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002163 llvm::Value *Size = llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize);
2164 if (const RecordDecl *SecGlobalizedVarsRecord =
2165 I->getSecond().SecondaryGlobalRecord.getValueOr(nullptr)) {
2166 SecGlobalRecTy =
2167 CGM.getContext().getRecordType(SecGlobalizedVarsRecord);
2168
2169 // Recover pointer to this function's global record. The runtime will
2170 // handle the specifics of the allocation of the memory.
2171 // Use actual memory size of the record including the padding
2172 // for alignment purposes.
2173 unsigned Alignment =
2174 CGM.getContext().getTypeAlignInChars(SecGlobalRecTy).getQuantity();
2175 unsigned GlobalRecordSize =
2176 CGM.getContext().getTypeSizeInChars(SecGlobalRecTy).getQuantity();
2177 GlobalRecordSize = llvm::alignTo(GlobalRecordSize, Alignment);
2178 Size = Bld.CreateSelect(
2179 IsTTD, llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize), Size);
2180 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002181 // TODO: allow the usage of shared memory to be controlled by
2182 // the user, for now, default to global.
2183 llvm::Value *GlobalRecordSizeArg[] = {
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002184 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002185 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2186 createNVPTXRuntimeFunction(
2187 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2188 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002189 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002190 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002191 CGF.EmitBlock(ExitBB);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002192 auto *Phi = Bld.CreatePHI(GlobalRecPtrTy,
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002193 /*NumReservedValues=*/2, "_select_stack");
2194 Phi->addIncoming(RecPtr.getPointer(), SPMDBB);
2195 Phi->addIncoming(GlobalRecCastAddr, NonSPMDBB);
2196 GlobalRecCastAddr = Phi;
2197 I->getSecond().GlobalRecordAddr = Phi;
2198 I->getSecond().IsInSPMDModeFlag = IsSPMD;
Alexey Bataeve4090182018-11-02 14:54:07 +00002199 } else if (IsInTTDRegion) {
2200 assert(GlobalizedRecords.back().Records.size() < 2 &&
2201 "Expected less than 2 globalized records: one for target and one "
2202 "for teams.");
2203 unsigned Offset = 0;
2204 for (const RecordDecl *RD : GlobalizedRecords.back().Records) {
2205 QualType RDTy = CGM.getContext().getRecordType(RD);
2206 unsigned Alignment =
2207 CGM.getContext().getTypeAlignInChars(RDTy).getQuantity();
2208 unsigned Size = CGM.getContext().getTypeSizeInChars(RDTy).getQuantity();
2209 Offset =
2210 llvm::alignTo(llvm::alignTo(Offset, Alignment) + Size, Alignment);
2211 }
2212 unsigned Alignment =
2213 CGM.getContext().getTypeAlignInChars(GlobalRecTy).getQuantity();
2214 Offset = llvm::alignTo(Offset, Alignment);
2215 GlobalizedRecords.back().Records.push_back(GlobalizedVarsRecord);
2216 ++GlobalizedRecords.back().RegionCounter;
2217 if (GlobalizedRecords.back().Records.size() == 1) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002218 assert(KernelStaticGlobalized &&
2219 "Kernel static pointer must be initialized already.");
2220 auto *UseSharedMemory = new llvm::GlobalVariable(
2221 CGM.getModule(), CGM.Int16Ty, /*isConstant=*/true,
2222 llvm::GlobalValue::InternalLinkage, nullptr,
2223 "_openmp_static_kernel$is_shared");
2224 UseSharedMemory->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2225 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2226 /*DestWidth=*/16, /*Signed=*/0);
2227 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2228 Address(UseSharedMemory,
2229 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2230 /*Volatile=*/false, Int16Ty, Loc);
2231 auto *StaticGlobalized = new llvm::GlobalVariable(
2232 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002233 llvm::GlobalValue::CommonLinkage, nullptr);
Alexey Bataeve4090182018-11-02 14:54:07 +00002234 auto *RecSize = new llvm::GlobalVariable(
2235 CGM.getModule(), CGM.SizeTy, /*isConstant=*/true,
2236 llvm::GlobalValue::InternalLinkage, nullptr,
2237 "_openmp_static_kernel$size");
2238 RecSize->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2239 llvm::Value *Ld = CGF.EmitLoadOfScalar(
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002240 Address(RecSize, CGM.getSizeAlign()), /*Volatile=*/false,
Alexey Bataeve4090182018-11-02 14:54:07 +00002241 CGM.getContext().getSizeType(), Loc);
2242 llvm::Value *ResAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2243 KernelStaticGlobalized, CGM.VoidPtrPtrTy);
Alexey Bataev8e009032019-01-04 17:25:09 +00002244 llvm::Value *GlobalRecordSizeArg[] = {
2245 llvm::ConstantInt::get(
2246 CGM.Int16Ty,
2247 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2248 StaticGlobalized, Ld, IsInSharedMemory, ResAddr};
Alexey Bataeve4090182018-11-02 14:54:07 +00002249 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2250 OMPRTL_NVPTX__kmpc_get_team_static_memory),
2251 GlobalRecordSizeArg);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002252 GlobalizedRecords.back().Buffer = StaticGlobalized;
Alexey Bataeve4090182018-11-02 14:54:07 +00002253 GlobalizedRecords.back().RecSize = RecSize;
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002254 GlobalizedRecords.back().UseSharedMemory = UseSharedMemory;
2255 GlobalizedRecords.back().Loc = Loc;
Alexey Bataeve4090182018-11-02 14:54:07 +00002256 }
2257 assert(KernelStaticGlobalized && "Global address must be set already.");
2258 Address FrameAddr = CGF.EmitLoadOfPointer(
2259 Address(KernelStaticGlobalized, CGM.getPointerAlign()),
2260 CGM.getContext()
2261 .getPointerType(CGM.getContext().VoidPtrTy)
2262 .castAs<PointerType>());
2263 llvm::Value *GlobalRecValue =
James Y Knight751fe282019-02-09 22:22:28 +00002264 Bld.CreateConstInBoundsGEP(FrameAddr, Offset).getPointer();
Alexey Bataeve4090182018-11-02 14:54:07 +00002265 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2266 I->getSecond().IsInSPMDModeFlag = nullptr;
2267 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2268 GlobalRecValue, CGF.ConvertTypeForMem(GlobalRecTy)->getPointerTo());
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002269 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002270 // TODO: allow the usage of shared memory to be controlled by
2271 // the user, for now, default to global.
2272 llvm::Value *GlobalRecordSizeArg[] = {
2273 llvm::ConstantInt::get(CGM.SizeTy, GlobalRecordSize),
2274 CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002275 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
2276 createNVPTXRuntimeFunction(
2277 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
2278 GlobalRecordSizeArg);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002279 GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002280 GlobalRecValue, GlobalRecPtrTy);
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002281 I->getSecond().GlobalRecordAddr = GlobalRecValue;
2282 I->getSecond().IsInSPMDModeFlag = nullptr;
2283 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002284 LValue Base =
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002285 CGF.MakeNaturalAlignPointeeAddrLValue(GlobalRecCastAddr, GlobalRecTy);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002286
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002287 // Emit the "global alloca" which is a GEP from the global declaration
2288 // record using the pointer returned by the runtime.
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002289 LValue SecBase;
2290 decltype(I->getSecond().LocalVarData)::const_iterator SecIt;
2291 if (IsTTD) {
2292 SecIt = I->getSecond().SecondaryLocalVarData->begin();
2293 llvm::PointerType *SecGlobalRecPtrTy =
2294 CGF.ConvertTypeForMem(SecGlobalRecTy)->getPointerTo();
2295 SecBase = CGF.MakeNaturalAlignPointeeAddrLValue(
2296 Bld.CreatePointerBitCastOrAddrSpaceCast(
2297 I->getSecond().GlobalRecordAddr, SecGlobalRecPtrTy),
2298 SecGlobalRecTy);
2299 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002300 for (auto &Rec : I->getSecond().LocalVarData) {
2301 bool EscapedParam = I->getSecond().EscapedParameters.count(Rec.first);
2302 llvm::Value *ParValue;
2303 if (EscapedParam) {
2304 const auto *VD = cast<VarDecl>(Rec.first);
2305 LValue ParLVal =
2306 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
2307 ParValue = CGF.EmitLoadOfScalar(ParLVal, Loc);
2308 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002309 LValue VarAddr = CGF.EmitLValueForField(Base, Rec.second.FD);
2310 // Emit VarAddr basing on lane-id if required.
2311 QualType VarTy;
2312 if (Rec.second.IsOnePerTeam) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002313 VarTy = Rec.second.FD->getType();
2314 } else {
2315 llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
2316 VarAddr.getAddress().getPointer(),
2317 {Bld.getInt32(0), getNVPTXLaneID(CGF)});
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002318 VarTy =
2319 Rec.second.FD->getType()->castAsArrayTypeUnsafe()->getElementType();
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002320 VarAddr = CGF.MakeAddrLValue(
2321 Address(Ptr, CGM.getContext().getDeclAlign(Rec.first)), VarTy,
2322 AlignmentSource::Decl);
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002323 }
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002324 Rec.second.PrivateAddr = VarAddr.getAddress();
Alexey Bataeve4090182018-11-02 14:54:07 +00002325 if (!IsInTTDRegion &&
2326 (WithSPMDCheck ||
2327 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002328 assert(I->getSecond().IsInSPMDModeFlag &&
2329 "Expected unknown execution mode or required SPMD check.");
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00002330 if (IsTTD) {
2331 assert(SecIt->second.IsOnePerTeam &&
2332 "Secondary glob data must be one per team.");
2333 LValue SecVarAddr = CGF.EmitLValueForField(SecBase, SecIt->second.FD);
2334 VarAddr.setAddress(
2335 Address(Bld.CreateSelect(IsTTD, SecVarAddr.getPointer(),
2336 VarAddr.getPointer()),
2337 VarAddr.getAlignment()));
2338 Rec.second.PrivateAddr = VarAddr.getAddress();
2339 }
Alexey Bataev9ea3c382018-10-09 14:49:00 +00002340 Address GlobalPtr = Rec.second.PrivateAddr;
2341 Address LocalAddr = CGF.CreateMemTemp(VarTy, Rec.second.FD->getName());
2342 Rec.second.PrivateAddr = Address(
2343 Bld.CreateSelect(I->getSecond().IsInSPMDModeFlag,
2344 LocalAddr.getPointer(), GlobalPtr.getPointer()),
2345 LocalAddr.getAlignment());
2346 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002347 if (EscapedParam) {
2348 const auto *VD = cast<VarDecl>(Rec.first);
2349 CGF.EmitStoreOfScalar(ParValue, VarAddr);
2350 I->getSecond().MappedParams->setVarAddr(CGF, VD, VarAddr.getAddress());
2351 }
Alexey Bataev93a38d62018-10-16 00:09:06 +00002352 if (IsTTD)
2353 ++SecIt;
Alexey Bataevc99042b2018-03-15 18:10:54 +00002354 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002355 }
2356 for (const ValueDecl *VD : I->getSecond().EscapedVariableLengthDecls) {
2357 // Recover pointer to this function's global record. The runtime will
2358 // handle the specifics of the allocation of the memory.
2359 // Use actual memory size of the record including the padding
2360 // for alignment purposes.
Alexey Bataev9ff80832018-04-16 20:16:21 +00002361 CGBuilderTy &Bld = CGF.Builder;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002362 llvm::Value *Size = CGF.getTypeSize(VD->getType());
2363 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2364 Size = Bld.CreateNUWAdd(
2365 Size, llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity() - 1));
2366 llvm::Value *AlignVal =
2367 llvm::ConstantInt::get(CGF.SizeTy, Align.getQuantity());
2368 Size = Bld.CreateUDiv(Size, AlignVal);
2369 Size = Bld.CreateNUWMul(Size, AlignVal);
2370 // TODO: allow the usage of shared memory to be controlled by
2371 // the user, for now, default to global.
2372 llvm::Value *GlobalRecordSizeArg[] = {
2373 Size, CGF.Builder.getInt16(/*UseSharedMemory=*/0)};
2374 llvm::Value *GlobalRecValue = CGF.EmitRuntimeCall(
Alexey Bataev1fc1f8e2018-11-02 16:08:31 +00002375 createNVPTXRuntimeFunction(
2376 OMPRTL_NVPTX__kmpc_data_sharing_coalesced_push_stack),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002377 GlobalRecordSizeArg);
2378 llvm::Value *GlobalRecCastAddr = Bld.CreatePointerBitCastOrAddrSpaceCast(
2379 GlobalRecValue, CGF.ConvertTypeForMem(VD->getType())->getPointerTo());
2380 LValue Base = CGF.MakeAddrLValue(GlobalRecCastAddr, VD->getType(),
2381 CGM.getContext().getDeclAlign(VD),
2382 AlignmentSource::Decl);
2383 I->getSecond().MappedParams->setVarAddr(CGF, cast<VarDecl>(VD),
2384 Base.getAddress());
2385 I->getSecond().EscapedVariableLengthDeclsAddrs.emplace_back(GlobalRecValue);
Alexey Bataevc99042b2018-03-15 18:10:54 +00002386 }
2387 I->getSecond().MappedParams->apply(CGF);
2388}
2389
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002390void CGOpenMPRuntimeNVPTX::emitGenericVarsEpilog(CodeGenFunction &CGF,
2391 bool WithSPMDCheck) {
Alexey Bataev2adecff2018-09-21 14:22:53 +00002392 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic &&
2393 getExecutionMode() != CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002394 return;
2395
Alexey Bataevc99042b2018-03-15 18:10:54 +00002396 const auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002397 if (I != FunctionGlobalizedDecls.end()) {
Alexey Bataevc99042b2018-03-15 18:10:54 +00002398 I->getSecond().MappedParams->restore(CGF);
2399 if (!CGF.HaveInsertPoint())
2400 return;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002401 for (llvm::Value *Addr :
2402 llvm::reverse(I->getSecond().EscapedVariableLengthDeclsAddrs)) {
2403 CGF.EmitRuntimeCall(
2404 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2405 Addr);
2406 }
2407 if (I->getSecond().GlobalRecordAddr) {
Alexey Bataeve4090182018-11-02 14:54:07 +00002408 if (!IsInTTDRegion &&
2409 (WithSPMDCheck ||
2410 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_Unknown)) {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002411 CGBuilderTy &Bld = CGF.Builder;
2412 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
2413 llvm::BasicBlock *NonSPMDBB = CGF.createBasicBlock(".non-spmd");
2414 Bld.CreateCondBr(I->getSecond().IsInSPMDModeFlag, ExitBB, NonSPMDBB);
2415 // There is no need to emit line number for unconditional branch.
2416 (void)ApplyDebugLocation::CreateEmpty(CGF);
2417 CGF.EmitBlock(NonSPMDBB);
2418 CGF.EmitRuntimeCall(
2419 createNVPTXRuntimeFunction(
2420 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2421 CGF.EmitCastToVoidPtr(I->getSecond().GlobalRecordAddr));
2422 CGF.EmitBlock(ExitBB);
Alexey Bataeve4090182018-11-02 14:54:07 +00002423 } else if (IsInTTDRegion) {
2424 assert(GlobalizedRecords.back().RegionCounter > 0 &&
2425 "region counter must be > 0.");
2426 --GlobalizedRecords.back().RegionCounter;
2427 // Emit the restore function only in the target region.
2428 if (GlobalizedRecords.back().RegionCounter == 0) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00002429 QualType Int16Ty = CGM.getContext().getIntTypeForBitwidth(
2430 /*DestWidth=*/16, /*Signed=*/0);
2431 llvm::Value *IsInSharedMemory = CGF.EmitLoadOfScalar(
2432 Address(GlobalizedRecords.back().UseSharedMemory,
2433 CGM.getContext().getTypeAlignInChars(Int16Ty)),
2434 /*Volatile=*/false, Int16Ty, GlobalizedRecords.back().Loc);
Alexey Bataev8e009032019-01-04 17:25:09 +00002435 llvm::Value *Args[] = {
2436 llvm::ConstantInt::get(
2437 CGM.Int16Ty,
2438 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD ? 1 : 0),
2439 IsInSharedMemory};
Alexey Bataeve4090182018-11-02 14:54:07 +00002440 CGF.EmitRuntimeCall(
2441 createNVPTXRuntimeFunction(
2442 OMPRTL_NVPTX__kmpc_restore_team_static_memory),
Alexey Bataev8e009032019-01-04 17:25:09 +00002443 Args);
Alexey Bataeve4090182018-11-02 14:54:07 +00002444 }
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002445 } else {
Alexey Bataev8d8e1232018-08-29 18:32:21 +00002446 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2447 OMPRTL_NVPTX__kmpc_data_sharing_pop_stack),
2448 I->getSecond().GlobalRecordAddr);
2449 }
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002450 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00002451 }
2452}
2453
Carlo Bertollic6872252016-04-04 15:55:02 +00002454void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF,
2455 const OMPExecutableDirective &D,
2456 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002457 llvm::Function *OutlinedFn,
Carlo Bertollic6872252016-04-04 15:55:02 +00002458 ArrayRef<llvm::Value *> CapturedVars) {
2459 if (!CGF.HaveInsertPoint())
2460 return;
2461
Alexey Bataevf89cf212019-10-16 16:59:01 +00002462 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2463 /*Name=*/".zero.addr");
Carlo Bertollic6872252016-04-04 15:55:02 +00002464 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
2465 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00002466 OutlinedFnArgs.push_back(emitThreadIDAddress(CGF, Loc).getPointer());
Carlo Bertollic6872252016-04-04 15:55:02 +00002467 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2468 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002469 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Carlo Bertollic6872252016-04-04 15:55:02 +00002470}
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002471
2472void CGOpenMPRuntimeNVPTX::emitParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002473 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002474 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2475 if (!CGF.HaveInsertPoint())
2476 return;
2477
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002478 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002479 emitSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002480 else
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002481 emitNonSPMDParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002482}
2483
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002484void CGOpenMPRuntimeNVPTX::emitNonSPMDParallelCall(
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002485 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
2486 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2487 llvm::Function *Fn = cast<llvm::Function>(OutlinedFn);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002488
2489 // Force inline this outlined function at its call site.
2490 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
2491
Alexey Bataevf89cf212019-10-16 16:59:01 +00002492 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2493 /*Name=*/".zero.addr");
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002494 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002495 // ThreadId for serialized parallels is 0.
2496 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002497 auto &&CodeGen = [this, Fn, CapturedVars, Loc, &ThreadIDAddr](
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002498 CodeGenFunction &CGF, PrePostActionTy &Action) {
2499 Action.Enter(CGF);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002500
Alexey Bataevf89cf212019-10-16 16:59:01 +00002501 Address ZeroAddr =
2502 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2503 /*Name=*/".bound.zero.addr");
2504 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002505 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2506 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2507 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2508 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2509 emitOutlinedFunctionCall(CGF, Loc, Fn, OutlinedFnArgs);
2510 };
2511 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2512 PrePostActionTy &) {
2513
2514 RegionCodeGenTy RCG(CodeGen);
2515 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2516 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2517 llvm::Value *Args[] = {RTLoc, ThreadID};
2518
2519 NVPTXActionTy Action(
2520 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2521 Args,
2522 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2523 Args);
2524 RCG.setAction(Action);
2525 RCG(CGF);
2526 };
2527
2528 auto &&L0ParallelGen = [this, CapturedVars, Fn](CodeGenFunction &CGF,
2529 PrePostActionTy &Action) {
2530 CGBuilderTy &Bld = CGF.Builder;
2531 llvm::Function *WFn = WrapperFunctionsMap[Fn];
2532 assert(WFn && "Wrapper function does not exist!");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002533 llvm::Value *ID = Bld.CreateBitOrPointerCast(WFn, CGM.Int8PtrTy);
2534
2535 // Prepare for parallel region. Indicate the outlined function.
2536 llvm::Value *Args[] = {ID, /*RequiresOMPRuntime=*/Bld.getInt16(1)};
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002537 CGF.EmitRuntimeCall(
2538 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel),
2539 Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002540
2541 // Create a private scope that will globalize the arguments
2542 // passed from the outside of the target region.
2543 CodeGenFunction::OMPPrivateScope PrivateArgScope(CGF);
2544
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002545 // There's something to share.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002546 if (!CapturedVars.empty()) {
2547 // Prepare for parallel region. Indicate the outlined function.
2548 Address SharedArgs =
2549 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "shared_arg_refs");
2550 llvm::Value *SharedArgsPtr = SharedArgs.getPointer();
2551
2552 llvm::Value *DataSharingArgs[] = {
2553 SharedArgsPtr,
2554 llvm::ConstantInt::get(CGM.SizeTy, CapturedVars.size())};
2555 CGF.EmitRuntimeCall(createNVPTXRuntimeFunction(
2556 OMPRTL_NVPTX__kmpc_begin_sharing_variables),
2557 DataSharingArgs);
2558
2559 // Store variable address in a list of references to pass to workers.
2560 unsigned Idx = 0;
2561 ASTContext &Ctx = CGF.getContext();
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002562 Address SharedArgListAddress = CGF.EmitLoadOfPointer(
2563 SharedArgs, Ctx.getPointerType(Ctx.getPointerType(Ctx.VoidPtrTy))
2564 .castAs<PointerType>());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002565 for (llvm::Value *V : CapturedVars) {
James Y Knight751fe282019-02-09 22:22:28 +00002566 Address Dst = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002567 llvm::Value *PtrV;
Alexey Bataev17314212018-03-20 15:41:05 +00002568 if (V->getType()->isIntegerTy())
2569 PtrV = Bld.CreateIntToPtr(V, CGF.VoidPtrTy);
2570 else
2571 PtrV = Bld.CreatePointerBitCastOrAddrSpaceCast(V, CGF.VoidPtrTy);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002572 CGF.EmitStoreOfScalar(PtrV, Dst, /*Volatile=*/false,
2573 Ctx.getPointerType(Ctx.VoidPtrTy));
Alexey Bataevc99042b2018-03-15 18:10:54 +00002574 ++Idx;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002575 }
2576 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002577
2578 // Activate workers. This barrier is used by the master to signal
2579 // work for the workers.
2580 syncCTAThreads(CGF);
2581
2582 // OpenMP [2.5, Parallel Construct, p.49]
2583 // There is an implied barrier at the end of a parallel region. After the
2584 // end of a parallel region, only the master thread of the team resumes
2585 // execution of the enclosing task region.
2586 //
2587 // The master waits at this barrier until all workers are done.
2588 syncCTAThreads(CGF);
2589
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002590 if (!CapturedVars.empty())
2591 CGF.EmitRuntimeCall(
2592 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_sharing_variables));
2593
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002594 // Remember for post-processing in worker loop.
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002595 Work.emplace_back(WFn);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002596 };
2597
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002598 auto &&LNParallelGen = [this, Loc, &SeqGen, &L0ParallelGen](
2599 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002600 if (IsInParallelRegion) {
2601 SeqGen(CGF, Action);
2602 } else if (IsInTargetMasterThreadRegion) {
2603 L0ParallelGen(CGF, Action);
2604 } else {
2605 // Check for master and then parallelism:
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002606 // if (__kmpc_is_spmd_exec_mode() || __kmpc_parallel_level(loc, gtid)) {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002607 // Serialized execution.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002608 // } else {
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002609 // Worker call.
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002610 // }
2611 CGBuilderTy &Bld = CGF.Builder;
2612 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit");
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002613 llvm::BasicBlock *SeqBB = CGF.createBasicBlock(".sequential");
2614 llvm::BasicBlock *ParallelCheckBB = CGF.createBasicBlock(".parcheck");
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002615 llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master");
Alexey Bataev673110d2018-05-16 13:36:30 +00002616 llvm::Value *IsSPMD = Bld.CreateIsNotNull(CGF.EmitNounwindRuntimeCall(
2617 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_is_spmd_exec_mode)));
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002618 Bld.CreateCondBr(IsSPMD, SeqBB, ParallelCheckBB);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002619 // There is no need to emit line number for unconditional branch.
2620 (void)ApplyDebugLocation::CreateEmpty(CGF);
2621 CGF.EmitBlock(ParallelCheckBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002622 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2623 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2624 llvm::Value *PL = CGF.EmitRuntimeCall(
2625 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_parallel_level),
2626 {RTLoc, ThreadID});
2627 llvm::Value *Res = Bld.CreateIsNotNull(PL);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002628 Bld.CreateCondBr(Res, SeqBB, MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002629 CGF.EmitBlock(SeqBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002630 SeqGen(CGF, Action);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002631 CGF.EmitBranch(ExitBB);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002632 // There is no need to emit line number for unconditional branch.
2633 (void)ApplyDebugLocation::CreateEmpty(CGF);
Jonas Hahnfeld3ca47012018-10-02 19:12:54 +00002634 CGF.EmitBlock(MasterBB);
Alexey Bataev0baba9e2018-05-25 20:16:03 +00002635 L0ParallelGen(CGF, Action);
2636 CGF.EmitBranch(ExitBB);
2637 // There is no need to emit line number for unconditional branch.
2638 (void)ApplyDebugLocation::CreateEmpty(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002639 // Emit the continuation block for code after the if.
2640 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2641 }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002642 };
2643
Alexey Bataev9ff80832018-04-16 20:16:21 +00002644 if (IfCond) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002645 emitOMPIfClause(CGF, IfCond, LNParallelGen, SeqGen);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002646 } else {
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002647 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002648 RegionCodeGenTy ThenRCG(LNParallelGen);
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002649 ThenRCG(CGF);
2650 }
2651}
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002652
Alexey Bataev4065b9a2018-06-21 20:26:33 +00002653void CGOpenMPRuntimeNVPTX::emitSPMDParallelCall(
James Y Knight9871db02019-02-05 16:42:33 +00002654 CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn,
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002655 ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) {
2656 // Just call the outlined function to execute the parallel region.
2657 // OutlinedFn(&GTid, &zero, CapturedStruct);
2658 //
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002659 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Carlo Bertolli79712092018-02-28 20:48:35 +00002660
Alexey Bataevf89cf212019-10-16 16:59:01 +00002661 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2662 /*Name=*/".zero.addr");
Carlo Bertolli79712092018-02-28 20:48:35 +00002663 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev8521ff62018-07-25 20:03:01 +00002664 // ThreadId for serialized parallels is 0.
2665 Address ThreadIDAddr = ZeroAddr;
Alexey Bataevf89cf212019-10-16 16:59:01 +00002666 auto &&CodeGen = [this, OutlinedFn, CapturedVars, Loc, &ThreadIDAddr](
2667 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002668 Action.Enter(CGF);
2669
Alexey Bataevf89cf212019-10-16 16:59:01 +00002670 Address ZeroAddr =
2671 CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2672 /*Name=*/".bound.zero.addr");
2673 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002674 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2675 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2676 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2677 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2678 emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2679 };
2680 auto &&SeqGen = [this, &CodeGen, Loc](CodeGenFunction &CGF,
2681 PrePostActionTy &) {
2682
2683 RegionCodeGenTy RCG(CodeGen);
2684 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2685 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2686 llvm::Value *Args[] = {RTLoc, ThreadID};
2687
2688 NVPTXActionTy Action(
2689 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel),
2690 Args,
2691 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel),
2692 Args);
2693 RCG.setAction(Action);
2694 RCG(CGF);
2695 };
2696
2697 if (IsInTargetMasterThreadRegion) {
Alexey Bataev8521ff62018-07-25 20:03:01 +00002698 // In the worker need to use the real thread id.
2699 ThreadIDAddr = emitThreadIDAddress(CGF, Loc);
Alexey Bataevbf5c8482018-05-10 18:32:08 +00002700 RegionCodeGenTy RCG(CodeGen);
2701 RCG(CGF);
2702 } else {
2703 // If we are not in the target region, it is definitely L2 parallelism or
2704 // more, because for SPMD mode we always has L1 parallel level, sowe don't
2705 // need to check for orphaned directives.
2706 RegionCodeGenTy RCG(SeqGen);
2707 RCG(CGF);
2708 }
Arpith Chacko Jacob44a87c92017-01-18 19:35:00 +00002709}
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002710
Alexey Bataeva3924b52019-01-03 16:25:35 +00002711void CGOpenMPRuntimeNVPTX::syncCTAThreads(CodeGenFunction &CGF) {
2712 // Always emit simple barriers!
2713 if (!CGF.HaveInsertPoint())
2714 return;
2715 // Build call __kmpc_barrier_simple_spmd(nullptr, 0);
2716 // This function does not use parameters, so we can emit just default values.
2717 llvm::Value *Args[] = {
2718 llvm::ConstantPointerNull::get(
2719 cast<llvm::PointerType>(getIdentTyPointerTy())),
2720 llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/0, /*isSigned=*/true)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002721 llvm::CallInst *Call = CGF.EmitRuntimeCall(
Alexey Bataeva3924b52019-01-03 16:25:35 +00002722 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier_simple_spmd), Args);
Alexey Bataeva44b2162019-07-18 13:49:24 +00002723 Call->setConvergent();
Alexey Bataeva3924b52019-01-03 16:25:35 +00002724}
2725
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002726void CGOpenMPRuntimeNVPTX::emitBarrierCall(CodeGenFunction &CGF,
2727 SourceLocation Loc,
2728 OpenMPDirectiveKind Kind, bool,
2729 bool) {
2730 // Always emit simple barriers!
2731 if (!CGF.HaveInsertPoint())
2732 return;
2733 // Build call __kmpc_cancel_barrier(loc, thread_id);
2734 unsigned Flags = getDefaultFlagsForBarriers(Kind);
2735 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2736 getThreadID(CGF, Loc)};
Alexey Bataeva44b2162019-07-18 13:49:24 +00002737 llvm::CallInst *Call = CGF.EmitRuntimeCall(
2738 createNVPTXRuntimeFunction(OMPRTL__kmpc_barrier), Args);
2739 Call->setConvergent();
Alexey Bataevc3028ca2018-12-04 15:03:25 +00002740}
2741
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002742void CGOpenMPRuntimeNVPTX::emitCriticalRegion(
2743 CodeGenFunction &CGF, StringRef CriticalName,
2744 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
2745 const Expr *Hint) {
2746 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.critical.loop");
2747 llvm::BasicBlock *TestBB = CGF.createBasicBlock("omp.critical.test");
2748 llvm::BasicBlock *SyncBB = CGF.createBasicBlock("omp.critical.sync");
2749 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.critical.body");
2750 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.critical.exit");
2751
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002752 // Get the mask of active threads in the warp.
2753 llvm::Value *Mask = CGF.EmitRuntimeCall(
2754 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_warp_active_thread_mask));
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002755 // Fetch team-local id of the thread.
2756 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
2757
2758 // Get the width of the team.
2759 llvm::Value *TeamWidth = getNVPTXNumThreads(CGF);
2760
2761 // Initialize the counter variable for the loop.
2762 QualType Int32Ty =
2763 CGF.getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/0);
2764 Address Counter = CGF.CreateMemTemp(Int32Ty, "critical_counter");
2765 LValue CounterLVal = CGF.MakeAddrLValue(Counter, Int32Ty);
2766 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty), CounterLVal,
2767 /*isInit=*/true);
2768
2769 // Block checks if loop counter exceeds upper bound.
2770 CGF.EmitBlock(LoopBB);
2771 llvm::Value *CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2772 llvm::Value *CmpLoopBound = CGF.Builder.CreateICmpSLT(CounterVal, TeamWidth);
2773 CGF.Builder.CreateCondBr(CmpLoopBound, TestBB, ExitBB);
2774
2775 // Block tests which single thread should execute region, and which threads
2776 // should go straight to synchronisation point.
2777 CGF.EmitBlock(TestBB);
2778 CounterVal = CGF.EmitLoadOfScalar(CounterLVal, Loc);
2779 llvm::Value *CmpThreadToCounter =
2780 CGF.Builder.CreateICmpEQ(ThreadID, CounterVal);
2781 CGF.Builder.CreateCondBr(CmpThreadToCounter, BodyBB, SyncBB);
2782
2783 // Block emits the body of the critical region.
2784 CGF.EmitBlock(BodyBB);
2785
2786 // Output the critical statement.
Alexey Bataev2c1ff9d2018-12-04 15:25:01 +00002787 CGOpenMPRuntime::emitCriticalRegion(CGF, CriticalName, CriticalOpGen, Loc,
2788 Hint);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002789
2790 // After the body surrounded by the critical region, the single executing
2791 // thread will jump to the synchronisation point.
2792 // Block waits for all threads in current team to finish then increments the
2793 // counter variable and returns to the loop.
2794 CGF.EmitBlock(SyncBB);
Alexey Bataev2cd7faf2019-08-26 19:07:48 +00002795 // Reconverge active threads in the warp.
2796 (void)CGF.EmitRuntimeCall(
2797 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_syncwarp), Mask);
Alexey Bataev504fc2d2018-05-07 17:23:05 +00002798
2799 llvm::Value *IncCounterVal =
2800 CGF.Builder.CreateNSWAdd(CounterVal, CGF.Builder.getInt32(1));
2801 CGF.EmitStoreOfScalar(IncCounterVal, CounterLVal);
2802 CGF.EmitBranch(LoopBB);
2803
2804 // Block that is reached when all threads in the team complete the region.
2805 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2806}
2807
Alexey Bataevb2575932018-01-04 20:18:55 +00002808/// Cast value to the specified type.
Alexey Bataeva453f362018-03-19 17:53:56 +00002809static llvm::Value *castValueToType(CodeGenFunction &CGF, llvm::Value *Val,
2810 QualType ValTy, QualType CastTy,
2811 SourceLocation Loc) {
2812 assert(!CGF.getContext().getTypeSizeInChars(CastTy).isZero() &&
2813 "Cast type must sized.");
2814 assert(!CGF.getContext().getTypeSizeInChars(ValTy).isZero() &&
2815 "Val type must sized.");
2816 llvm::Type *LLVMCastTy = CGF.ConvertTypeForMem(CastTy);
2817 if (ValTy == CastTy)
Alexey Bataevb2575932018-01-04 20:18:55 +00002818 return Val;
Alexey Bataeva453f362018-03-19 17:53:56 +00002819 if (CGF.getContext().getTypeSizeInChars(ValTy) ==
2820 CGF.getContext().getTypeSizeInChars(CastTy))
2821 return CGF.Builder.CreateBitCast(Val, LLVMCastTy);
2822 if (CastTy->isIntegerType() && ValTy->isIntegerType())
2823 return CGF.Builder.CreateIntCast(Val, LLVMCastTy,
2824 CastTy->hasSignedIntegerRepresentation());
2825 Address CastItem = CGF.CreateMemTemp(CastTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00002826 Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2827 CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
Alexey Bataeva453f362018-03-19 17:53:56 +00002828 CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy);
2829 return CGF.EmitLoadOfScalar(CastItem, /*Volatile=*/false, CastTy, Loc);
Alexey Bataevb2575932018-01-04 20:18:55 +00002830}
2831
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002832/// This function creates calls to one of two shuffle functions to copy
2833/// variables between lanes in a warp.
2834static llvm::Value *createRuntimeShuffleFunction(CodeGenFunction &CGF,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002835 llvm::Value *Elem,
Alexey Bataeva453f362018-03-19 17:53:56 +00002836 QualType ElemType,
2837 llvm::Value *Offset,
2838 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00002839 CodeGenModule &CGM = CGF.CGM;
2840 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002841 CGOpenMPRuntimeNVPTX &RT =
2842 *(static_cast<CGOpenMPRuntimeNVPTX *>(&CGM.getOpenMPRuntime()));
2843
Alexey Bataeva453f362018-03-19 17:53:56 +00002844 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2845 assert(Size.getQuantity() <= 8 &&
2846 "Unsupported bitwidth in shuffle instruction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002847
Alexey Bataeva453f362018-03-19 17:53:56 +00002848 OpenMPRTLFunctionNVPTX ShuffleFn = Size.getQuantity() <= 4
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002849 ? OMPRTL_NVPTX__kmpc_shuffle_int32
2850 : OMPRTL_NVPTX__kmpc_shuffle_int64;
2851
2852 // Cast all types to 32- or 64-bit values before calling shuffle routines.
Alexey Bataeva453f362018-03-19 17:53:56 +00002853 QualType CastTy = CGF.getContext().getIntTypeForBitwidth(
2854 Size.getQuantity() <= 4 ? 32 : 64, /*Signed=*/1);
2855 llvm::Value *ElemCast = castValueToType(CGF, Elem, ElemType, CastTy, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00002856 llvm::Value *WarpSize =
Alexey Bataevb2575932018-01-04 20:18:55 +00002857 Bld.CreateIntCast(getNVPTXWarpSize(CGF), CGM.Int16Ty, /*isSigned=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002858
Alexey Bataev9ff80832018-04-16 20:16:21 +00002859 llvm::Value *ShuffledVal = CGF.EmitRuntimeCall(
2860 RT.createNVPTXRuntimeFunction(ShuffleFn), {ElemCast, Offset, WarpSize});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002861
Alexey Bataeva453f362018-03-19 17:53:56 +00002862 return castValueToType(CGF, ShuffledVal, CastTy, ElemType, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002863}
2864
Alexey Bataev12c62902018-06-22 19:10:38 +00002865static void shuffleAndStore(CodeGenFunction &CGF, Address SrcAddr,
2866 Address DestAddr, QualType ElemType,
2867 llvm::Value *Offset, SourceLocation Loc) {
2868 CGBuilderTy &Bld = CGF.Builder;
2869
2870 CharUnits Size = CGF.getContext().getTypeSizeInChars(ElemType);
2871 // Create the loop over the big sized data.
2872 // ptr = (void*)Elem;
2873 // ptrEnd = (void*) Elem + 1;
2874 // Step = 8;
2875 // while (ptr + Step < ptrEnd)
2876 // shuffle((int64_t)*ptr);
2877 // Step = 4;
2878 // while (ptr + Step < ptrEnd)
2879 // shuffle((int32_t)*ptr);
2880 // ...
2881 Address ElemPtr = DestAddr;
2882 Address Ptr = SrcAddr;
2883 Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00002884 Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
Alexey Bataev12c62902018-06-22 19:10:38 +00002885 for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
2886 if (Size < CharUnits::fromQuantity(IntSize))
2887 continue;
2888 QualType IntType = CGF.getContext().getIntTypeForBitwidth(
2889 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
2890 /*Signed=*/1);
2891 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
2892 Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
2893 ElemPtr =
2894 Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
2895 if (Size.getQuantity() / IntSize > 1) {
2896 llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
2897 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
2898 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".shuffle.exit");
2899 llvm::BasicBlock *CurrentBB = Bld.GetInsertBlock();
2900 CGF.EmitBlock(PreCondBB);
2901 llvm::PHINode *PhiSrc =
2902 Bld.CreatePHI(Ptr.getType(), /*NumReservedValues=*/2);
2903 PhiSrc->addIncoming(Ptr.getPointer(), CurrentBB);
2904 llvm::PHINode *PhiDest =
2905 Bld.CreatePHI(ElemPtr.getType(), /*NumReservedValues=*/2);
2906 PhiDest->addIncoming(ElemPtr.getPointer(), CurrentBB);
2907 Ptr = Address(PhiSrc, Ptr.getAlignment());
2908 ElemPtr = Address(PhiDest, ElemPtr.getAlignment());
2909 llvm::Value *PtrDiff = Bld.CreatePtrDiff(
2910 PtrEnd.getPointer(), Bld.CreatePointerBitCastOrAddrSpaceCast(
2911 Ptr.getPointer(), CGF.VoidPtrTy));
2912 Bld.CreateCondBr(Bld.CreateICmpSGT(PtrDiff, Bld.getInt64(IntSize - 1)),
2913 ThenBB, ExitBB);
2914 CGF.EmitBlock(ThenBB);
2915 llvm::Value *Res = createRuntimeShuffleFunction(
2916 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2917 IntType, Offset, Loc);
2918 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002919 Address LocalPtr = Bld.CreateConstGEP(Ptr, 1);
2920 Address LocalElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00002921 PhiSrc->addIncoming(LocalPtr.getPointer(), ThenBB);
2922 PhiDest->addIncoming(LocalElemPtr.getPointer(), ThenBB);
Alexey Bataev12c62902018-06-22 19:10:38 +00002923 CGF.EmitBranch(PreCondBB);
2924 CGF.EmitBlock(ExitBB);
2925 } else {
2926 llvm::Value *Res = createRuntimeShuffleFunction(
2927 CGF, CGF.EmitLoadOfScalar(Ptr, /*Volatile=*/false, IntType, Loc),
2928 IntType, Offset, Loc);
2929 CGF.EmitStoreOfScalar(Res, ElemPtr, /*Volatile=*/false, IntType);
James Y Knight751fe282019-02-09 22:22:28 +00002930 Ptr = Bld.CreateConstGEP(Ptr, 1);
2931 ElemPtr = Bld.CreateConstGEP(ElemPtr, 1);
Alexey Bataev12c62902018-06-22 19:10:38 +00002932 }
2933 Size = Size % IntSize;
2934 }
2935}
2936
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002937namespace {
2938enum CopyAction : unsigned {
2939 // RemoteLaneToThread: Copy over a Reduce list from a remote lane in
2940 // the warp using shuffle instructions.
2941 RemoteLaneToThread,
2942 // ThreadCopy: Make a copy of a Reduce list on the thread's stack.
2943 ThreadCopy,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002944 // ThreadToScratchpad: Copy a team-reduced array to the scratchpad.
2945 ThreadToScratchpad,
2946 // ScratchpadToThread: Copy from a scratchpad array in global memory
2947 // containing team-reduced data to a thread's stack.
2948 ScratchpadToThread,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002949};
2950} // namespace
2951
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002952struct CopyOptionsTy {
2953 llvm::Value *RemoteLaneOffset;
2954 llvm::Value *ScratchpadIndex;
2955 llvm::Value *ScratchpadWidth;
2956};
2957
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002958/// Emit instructions to copy a Reduce list, which contains partially
2959/// aggregated values, in the specified direction.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002960static void emitReductionListCopy(
2961 CopyAction Action, CodeGenFunction &CGF, QualType ReductionArrayTy,
2962 ArrayRef<const Expr *> Privates, Address SrcBase, Address DestBase,
2963 CopyOptionsTy CopyOptions = {nullptr, nullptr, nullptr}) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002964
Alexey Bataev9ff80832018-04-16 20:16:21 +00002965 CodeGenModule &CGM = CGF.CGM;
2966 ASTContext &C = CGM.getContext();
2967 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002968
Alexey Bataev9ff80832018-04-16 20:16:21 +00002969 llvm::Value *RemoteLaneOffset = CopyOptions.RemoteLaneOffset;
2970 llvm::Value *ScratchpadIndex = CopyOptions.ScratchpadIndex;
2971 llvm::Value *ScratchpadWidth = CopyOptions.ScratchpadWidth;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002972
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002973 // Iterates, element-by-element, through the source Reduce list and
2974 // make a copy.
2975 unsigned Idx = 0;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002976 unsigned Size = Privates.size();
Alexey Bataev9ff80832018-04-16 20:16:21 +00002977 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002978 Address SrcElementAddr = Address::invalid();
2979 Address DestElementAddr = Address::invalid();
2980 Address DestElementPtrAddr = Address::invalid();
2981 // Should we shuffle in an element from a remote lane?
2982 bool ShuffleInElement = false;
2983 // Set to true to update the pointer in the dest Reduce list to a
2984 // newly created element.
2985 bool UpdateDestListPtr = false;
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00002986 // Increment the src or dest pointer to the scratchpad, for each
2987 // new element.
2988 bool IncrScratchpadSrc = false;
2989 bool IncrScratchpadDest = false;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002990
2991 switch (Action) {
2992 case RemoteLaneToThread: {
2993 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00002994 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00002995 SrcElementAddr = CGF.EmitLoadOfPointer(
2996 SrcElementPtrAddr,
2997 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00002998
2999 // Step 1.2: Create a temporary to store the element in the destination
3000 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003001 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003002 DestElementAddr =
3003 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3004 ShuffleInElement = true;
3005 UpdateDestListPtr = true;
3006 break;
3007 }
3008 case ThreadCopy: {
3009 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003010 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003011 SrcElementAddr = CGF.EmitLoadOfPointer(
3012 SrcElementPtrAddr,
3013 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003014
3015 // Step 1.2: Get the address for dest element. The destination
3016 // element has already been created on the thread's stack.
James Y Knight751fe282019-02-09 22:22:28 +00003017 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003018 DestElementAddr = CGF.EmitLoadOfPointer(
3019 DestElementPtrAddr,
3020 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003021 break;
3022 }
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003023 case ThreadToScratchpad: {
3024 // Step 1.1: Get the address for the src element in the Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003025 Address SrcElementPtrAddr = Bld.CreateConstArrayGEP(SrcBase, Idx);
Alexey Bataevb2575932018-01-04 20:18:55 +00003026 SrcElementAddr = CGF.EmitLoadOfPointer(
3027 SrcElementPtrAddr,
3028 C.getPointerType(Private->getType())->castAs<PointerType>());
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003029
3030 // Step 1.2: Get the address for dest element:
3031 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003032 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003033 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003034 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003035 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003036 Bld.CreateNUWAdd(DestBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003037 ScratchPadElemAbsolutePtrVal =
3038 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
Alexey Bataevb2575932018-01-04 20:18:55 +00003039 DestElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3040 C.getTypeAlignInChars(Private->getType()));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003041 IncrScratchpadDest = true;
3042 break;
3043 }
3044 case ScratchpadToThread: {
3045 // Step 1.1: Get the address for the src element in the scratchpad.
3046 // address = base + index * ElementSizeInChars.
Alexey Bataeve290ec02018-04-06 16:03:36 +00003047 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
Alexey Bataev9ff80832018-04-16 20:16:21 +00003048 llvm::Value *CurrentOffset =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003049 Bld.CreateNUWMul(ElementSizeInChars, ScratchpadIndex);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003050 llvm::Value *ScratchPadElemAbsolutePtrVal =
Alexey Bataeve290ec02018-04-06 16:03:36 +00003051 Bld.CreateNUWAdd(SrcBase.getPointer(), CurrentOffset);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003052 ScratchPadElemAbsolutePtrVal =
3053 Bld.CreateIntToPtr(ScratchPadElemAbsolutePtrVal, CGF.VoidPtrTy);
3054 SrcElementAddr = Address(ScratchPadElemAbsolutePtrVal,
3055 C.getTypeAlignInChars(Private->getType()));
3056 IncrScratchpadSrc = true;
3057
3058 // Step 1.2: Create a temporary to store the element in the destination
3059 // Reduce list.
James Y Knight751fe282019-02-09 22:22:28 +00003060 DestElementPtrAddr = Bld.CreateConstArrayGEP(DestBase, Idx);
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003061 DestElementAddr =
3062 CGF.CreateMemTemp(Private->getType(), ".omp.reduction.element");
3063 UpdateDestListPtr = true;
3064 break;
3065 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003066 }
3067
3068 // Regardless of src and dest of copy, we emit the load of src
3069 // element as this is required in all directions
3070 SrcElementAddr = Bld.CreateElementBitCast(
3071 SrcElementAddr, CGF.ConvertTypeForMem(Private->getType()));
Alexey Bataev12c62902018-06-22 19:10:38 +00003072 DestElementAddr = Bld.CreateElementBitCast(DestElementAddr,
3073 SrcElementAddr.getElementType());
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003074
3075 // Now that all active lanes have read the element in the
3076 // Reduce list, shuffle over the value from the remote lane.
Alexey Bataeva453f362018-03-19 17:53:56 +00003077 if (ShuffleInElement) {
Alexey Bataev12c62902018-06-22 19:10:38 +00003078 shuffleAndStore(CGF, SrcElementAddr, DestElementAddr, Private->getType(),
3079 RemoteLaneOffset, Private->getExprLoc());
3080 } else {
Alexey Bataev8061acd2019-02-20 16:36:22 +00003081 switch (CGF.getEvaluationKind(Private->getType())) {
3082 case TEK_Scalar: {
Alexey Bataev12c62902018-06-22 19:10:38 +00003083 llvm::Value *Elem =
3084 CGF.EmitLoadOfScalar(SrcElementAddr, /*Volatile=*/false,
3085 Private->getType(), Private->getExprLoc());
3086 // Store the source element value to the dest element address.
3087 CGF.EmitStoreOfScalar(Elem, DestElementAddr, /*Volatile=*/false,
3088 Private->getType());
Alexey Bataev8061acd2019-02-20 16:36:22 +00003089 break;
3090 }
3091 case TEK_Complex: {
3092 CodeGenFunction::ComplexPairTy Elem = CGF.EmitLoadOfComplex(
3093 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3094 Private->getExprLoc());
3095 CGF.EmitStoreOfComplex(
3096 Elem, CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3097 /*isInit=*/false);
3098 break;
3099 }
3100 case TEK_Aggregate:
Alexey Bataev12c62902018-06-22 19:10:38 +00003101 CGF.EmitAggregateCopy(
3102 CGF.MakeAddrLValue(DestElementAddr, Private->getType()),
3103 CGF.MakeAddrLValue(SrcElementAddr, Private->getType()),
3104 Private->getType(), AggValueSlot::DoesNotOverlap);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003105 break;
Alexey Bataev12c62902018-06-22 19:10:38 +00003106 }
Alexey Bataeva453f362018-03-19 17:53:56 +00003107 }
Alexey Bataevb2575932018-01-04 20:18:55 +00003108
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003109 // Step 3.1: Modify reference in dest Reduce list as needed.
3110 // Modifying the reference in Reduce list to point to the newly
3111 // created element. The element is live in the current function
3112 // scope and that of functions it invokes (i.e., reduce_function).
3113 // RemoteReduceData[i] = (void*)&RemoteElem
3114 if (UpdateDestListPtr) {
3115 CGF.EmitStoreOfScalar(Bld.CreatePointerBitCastOrAddrSpaceCast(
3116 DestElementAddr.getPointer(), CGF.VoidPtrTy),
3117 DestElementPtrAddr, /*Volatile=*/false,
3118 C.VoidPtrTy);
3119 }
3120
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003121 // Step 4.1: Increment SrcBase/DestBase so that it points to the starting
3122 // address of the next element in scratchpad memory, unless we're currently
3123 // processing the last one. Memory alignment is also taken care of here.
3124 if ((IncrScratchpadDest || IncrScratchpadSrc) && (Idx + 1 < Size)) {
3125 llvm::Value *ScratchpadBasePtr =
3126 IncrScratchpadDest ? DestBase.getPointer() : SrcBase.getPointer();
Alexey Bataeve290ec02018-04-06 16:03:36 +00003127 llvm::Value *ElementSizeInChars = CGF.getTypeSize(Private->getType());
3128 ScratchpadBasePtr = Bld.CreateNUWAdd(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003129 ScratchpadBasePtr,
Alexey Bataeve290ec02018-04-06 16:03:36 +00003130 Bld.CreateNUWMul(ScratchpadWidth, ElementSizeInChars));
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003131
3132 // Take care of global memory alignment for performance
Alexey Bataeve290ec02018-04-06 16:03:36 +00003133 ScratchpadBasePtr = Bld.CreateNUWSub(
3134 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3135 ScratchpadBasePtr = Bld.CreateUDiv(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003136 ScratchpadBasePtr,
3137 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
Alexey Bataeve290ec02018-04-06 16:03:36 +00003138 ScratchpadBasePtr = Bld.CreateNUWAdd(
3139 ScratchpadBasePtr, llvm::ConstantInt::get(CGM.SizeTy, 1));
3140 ScratchpadBasePtr = Bld.CreateNUWMul(
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003141 ScratchpadBasePtr,
3142 llvm::ConstantInt::get(CGM.SizeTy, GlobalMemoryAlignment));
3143
3144 if (IncrScratchpadDest)
3145 DestBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3146 else /* IncrScratchpadSrc = true */
3147 SrcBase = Address(ScratchpadBasePtr, CGF.getPointerAlign());
3148 }
3149
Alexey Bataev9ff80832018-04-16 20:16:21 +00003150 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003151 }
3152}
3153
3154/// This function emits a helper that gathers Reduce lists from the first
3155/// lane of every active warp to lanes in the first warp.
3156///
3157/// void inter_warp_copy_func(void* reduce_data, num_warps)
3158/// shared smem[warp_size];
3159/// For all data entries D in reduce_data:
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003160/// sync
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003161/// If (I am the first lane in each warp)
3162/// Copy my local D to smem[warp_id]
3163/// sync
3164/// if (I am the first warp)
3165/// Copy smem[thread_id] to my local D
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003166static llvm::Value *emitInterWarpCopyFunction(CodeGenModule &CGM,
3167 ArrayRef<const Expr *> Privates,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003168 QualType ReductionArrayTy,
3169 SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003170 ASTContext &C = CGM.getContext();
3171 llvm::Module &M = CGM.getModule();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003172
3173 // ReduceList: thread local Reduce list.
3174 // At the stage of the computation when this function is called, partially
3175 // aggregated values reside in the first lane of every active warp.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003176 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3177 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003178 // NumWarps: number of warps active in the parallel region. This could
3179 // be smaller than 32 (max warps in a CTA) for partial block reduction.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003180 ImplicitParamDecl NumWarpsArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003181 C.getIntTypeForBitwidth(32, /* Signed */ true),
3182 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003183 FunctionArgList Args;
3184 Args.push_back(&ReduceListArg);
3185 Args.push_back(&NumWarpsArg);
3186
Alexey Bataev9ff80832018-04-16 20:16:21 +00003187 const CGFunctionInfo &CGFI =
3188 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev8061acd2019-02-20 16:36:22 +00003189 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3190 llvm::GlobalValue::InternalLinkage,
3191 "_omp_reduction_inter_warp_copy_func", &M);
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003192 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003193 Fn->setDoesNotRecurse();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003194 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003195 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003196
Alexey Bataev9ff80832018-04-16 20:16:21 +00003197 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003198
3199 // This array is used as a medium to transfer, one reduce element at a time,
3200 // the data from the first lane of every warp to lanes in the first warp
3201 // in order to perform the final step of a reduction in a parallel region
3202 // (reduction across warps). The array is placed in NVPTX __shared__ memory
3203 // for reduced latency, as well as to have a distinct copy for concurrently
3204 // executing target regions. The array is declared with common linkage so
3205 // as to be shared across compilation units.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003206 StringRef TransferMediumName =
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003207 "__openmp_nvptx_data_transfer_temporary_storage";
3208 llvm::GlobalVariable *TransferMedium =
3209 M.getGlobalVariable(TransferMediumName);
3210 if (!TransferMedium) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003211 auto *Ty = llvm::ArrayType::get(CGM.Int32Ty, WarpSize);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003212 unsigned SharedAddressSpace = C.getTargetAddressSpace(LangAS::cuda_shared);
3213 TransferMedium = new llvm::GlobalVariable(
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003214 M, Ty, /*isConstant=*/false, llvm::GlobalVariable::CommonLinkage,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003215 llvm::Constant::getNullValue(Ty), TransferMediumName,
3216 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3217 SharedAddressSpace);
Alexey Bataev9ff80832018-04-16 20:16:21 +00003218 CGM.addCompilerUsedGlobal(TransferMedium);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003219 }
3220
3221 // Get the CUDA thread id of the current OpenMP thread on the GPU.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003222 llvm::Value *ThreadID = getNVPTXThreadID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003223 // nvptx_lane_id = nvptx_id % warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003224 llvm::Value *LaneID = getNVPTXLaneID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003225 // nvptx_warp_id = nvptx_id / warpsize
Alexey Bataev9ff80832018-04-16 20:16:21 +00003226 llvm::Value *WarpID = getNVPTXWarpID(CGF);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003227
3228 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3229 Address LocalReduceList(
3230 Bld.CreatePointerBitCastOrAddrSpaceCast(
3231 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003232 C.VoidPtrTy, Loc),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003233 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3234 CGF.getPointerAlign());
3235
3236 unsigned Idx = 0;
Alexey Bataev9ff80832018-04-16 20:16:21 +00003237 for (const Expr *Private : Privates) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003238 //
3239 // Warp master copies reduce element to transfer medium in __shared__
3240 // memory.
3241 //
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003242 unsigned RealTySize =
3243 C.getTypeSizeInChars(Private->getType())
3244 .alignTo(C.getTypeAlignInChars(Private->getType()))
3245 .getQuantity();
3246 for (unsigned TySize = 4; TySize > 0 && RealTySize > 0; TySize /=2) {
3247 unsigned NumIters = RealTySize / TySize;
3248 if (NumIters == 0)
3249 continue;
3250 QualType CType = C.getIntTypeForBitwidth(
3251 C.toBits(CharUnits::fromQuantity(TySize)), /*Signed=*/1);
3252 llvm::Type *CopyType = CGF.ConvertTypeForMem(CType);
3253 CharUnits Align = CharUnits::fromQuantity(TySize);
3254 llvm::Value *Cnt = nullptr;
3255 Address CntAddr = Address::invalid();
3256 llvm::BasicBlock *PrecondBB = nullptr;
3257 llvm::BasicBlock *ExitBB = nullptr;
3258 if (NumIters > 1) {
3259 CntAddr = CGF.CreateMemTemp(C.IntTy, ".cnt.addr");
3260 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.IntTy), CntAddr,
3261 /*Volatile=*/false, C.IntTy);
3262 PrecondBB = CGF.createBasicBlock("precond");
3263 ExitBB = CGF.createBasicBlock("exit");
3264 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("body");
3265 // There is no need to emit line number for unconditional branch.
3266 (void)ApplyDebugLocation::CreateEmpty(CGF);
3267 CGF.EmitBlock(PrecondBB);
3268 Cnt = CGF.EmitLoadOfScalar(CntAddr, /*Volatile=*/false, C.IntTy, Loc);
3269 llvm::Value *Cmp =
3270 Bld.CreateICmpULT(Cnt, llvm::ConstantInt::get(CGM.IntTy, NumIters));
3271 Bld.CreateCondBr(Cmp, BodyBB, ExitBB);
3272 CGF.EmitBlock(BodyBB);
3273 }
Alexey Bataev29d47fc2018-12-18 19:20:15 +00003274 // kmpc_barrier.
3275 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3276 /*EmitChecks=*/false,
3277 /*ForceSimpleCall=*/true);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003278 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3279 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3280 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003281
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003282 // if (lane_id == 0)
3283 llvm::Value *IsWarpMaster = Bld.CreateIsNull(LaneID, "warp_master");
3284 Bld.CreateCondBr(IsWarpMaster, ThenBB, ElseBB);
3285 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003286
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003287 // Reduce element = LocalReduceList[i]
James Y Knight751fe282019-02-09 22:22:28 +00003288 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003289 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3290 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3291 // elemptr = ((CopyType*)(elemptrptr)) + I
3292 Address ElemPtr = Address(ElemPtrPtr, Align);
3293 ElemPtr = Bld.CreateElementBitCast(ElemPtr, CopyType);
3294 if (NumIters > 1) {
3295 ElemPtr = Address(Bld.CreateGEP(ElemPtr.getPointer(), Cnt),
3296 ElemPtr.getAlignment());
3297 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003298
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003299 // Get pointer to location in transfer medium.
3300 // MediumPtr = &medium[warp_id]
3301 llvm::Value *MediumPtrVal = Bld.CreateInBoundsGEP(
3302 TransferMedium, {llvm::Constant::getNullValue(CGM.Int64Ty), WarpID});
3303 Address MediumPtr(MediumPtrVal, Align);
3304 // Casting to actual data type.
3305 // MediumPtr = (CopyType*)MediumPtrAddr;
3306 MediumPtr = Bld.CreateElementBitCast(MediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003307
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003308 // elem = *elemptr
3309 //*MediumPtr = elem
3310 llvm::Value *Elem =
3311 CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003312 // Store the source element value to the dest element address.
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003313 CGF.EmitStoreOfScalar(Elem, MediumPtr, /*Volatile=*/true, CType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003314
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003315 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003316
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003317 CGF.EmitBlock(ElseBB);
3318 Bld.CreateBr(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003319
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003320 CGF.EmitBlock(MergeBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003321
Alexey Bataevae51b962018-12-14 21:00:58 +00003322 // kmpc_barrier.
3323 CGM.getOpenMPRuntime().emitBarrierCall(CGF, Loc, OMPD_unknown,
3324 /*EmitChecks=*/false,
3325 /*ForceSimpleCall=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003326
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003327 //
3328 // Warp 0 copies reduce element from transfer medium.
3329 //
3330 llvm::BasicBlock *W0ThenBB = CGF.createBasicBlock("then");
3331 llvm::BasicBlock *W0ElseBB = CGF.createBasicBlock("else");
3332 llvm::BasicBlock *W0MergeBB = CGF.createBasicBlock("ifcont");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003333
Alexey Bataevae51b962018-12-14 21:00:58 +00003334 Address AddrNumWarpsArg = CGF.GetAddrOfLocalVar(&NumWarpsArg);
3335 llvm::Value *NumWarpsVal = CGF.EmitLoadOfScalar(
3336 AddrNumWarpsArg, /*Volatile=*/false, C.IntTy, Loc);
3337
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003338 // Up to 32 threads in warp 0 are active.
3339 llvm::Value *IsActiveThread =
3340 Bld.CreateICmpULT(ThreadID, NumWarpsVal, "is_active_thread");
3341 Bld.CreateCondBr(IsActiveThread, W0ThenBB, W0ElseBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003342
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003343 CGF.EmitBlock(W0ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003344
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003345 // SrcMediumPtr = &medium[tid]
3346 llvm::Value *SrcMediumPtrVal = Bld.CreateInBoundsGEP(
3347 TransferMedium,
3348 {llvm::Constant::getNullValue(CGM.Int64Ty), ThreadID});
3349 Address SrcMediumPtr(SrcMediumPtrVal, Align);
3350 // SrcMediumVal = *SrcMediumPtr;
3351 SrcMediumPtr = Bld.CreateElementBitCast(SrcMediumPtr, CopyType);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003352
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003353 // TargetElemPtr = (CopyType*)(SrcDataAddr[i]) + I
James Y Knight751fe282019-02-09 22:22:28 +00003354 Address TargetElemPtrPtr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003355 llvm::Value *TargetElemPtrVal = CGF.EmitLoadOfScalar(
3356 TargetElemPtrPtr, /*Volatile=*/false, C.VoidPtrTy, Loc);
3357 Address TargetElemPtr = Address(TargetElemPtrVal, Align);
3358 TargetElemPtr = Bld.CreateElementBitCast(TargetElemPtr, CopyType);
3359 if (NumIters > 1) {
3360 TargetElemPtr = Address(Bld.CreateGEP(TargetElemPtr.getPointer(), Cnt),
3361 TargetElemPtr.getAlignment());
3362 }
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003363
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003364 // *TargetElemPtr = SrcMediumVal;
3365 llvm::Value *SrcMediumValue =
3366 CGF.EmitLoadOfScalar(SrcMediumPtr, /*Volatile=*/true, CType, Loc);
Alexey Bataev12c62902018-06-22 19:10:38 +00003367 CGF.EmitStoreOfScalar(SrcMediumValue, TargetElemPtr, /*Volatile=*/false,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003368 CType);
3369 Bld.CreateBr(W0MergeBB);
3370
3371 CGF.EmitBlock(W0ElseBB);
3372 Bld.CreateBr(W0MergeBB);
3373
3374 CGF.EmitBlock(W0MergeBB);
3375
Alexey Bataevf2f39be2018-11-16 19:38:21 +00003376 if (NumIters > 1) {
3377 Cnt = Bld.CreateNSWAdd(Cnt, llvm::ConstantInt::get(CGM.IntTy, /*V=*/1));
3378 CGF.EmitStoreOfScalar(Cnt, CntAddr, /*Volatile=*/false, C.IntTy);
3379 CGF.EmitBranch(PrecondBB);
3380 (void)ApplyDebugLocation::CreateEmpty(CGF);
3381 CGF.EmitBlock(ExitBB);
3382 }
3383 RealTySize %= TySize;
Alexey Bataev12c62902018-06-22 19:10:38 +00003384 }
Alexey Bataev9ff80832018-04-16 20:16:21 +00003385 ++Idx;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003386 }
3387
3388 CGF.FinishFunction();
3389 return Fn;
3390}
3391
3392/// Emit a helper that reduces data across two OpenMP threads (lanes)
3393/// in the same warp. It uses shuffle instructions to copy over data from
3394/// a remote lane's stack. The reduction algorithm performed is specified
3395/// by the fourth parameter.
3396///
3397/// Algorithm Versions.
3398/// Full Warp Reduce (argument value 0):
3399/// This algorithm assumes that all 32 lanes are active and gathers
3400/// data from these 32 lanes, producing a single resultant value.
3401/// Contiguous Partial Warp Reduce (argument value 1):
3402/// This algorithm assumes that only a *contiguous* subset of lanes
3403/// are active. This happens for the last warp in a parallel region
3404/// when the user specified num_threads is not an integer multiple of
3405/// 32. This contiguous subset always starts with the zeroth lane.
3406/// Partial Warp Reduce (argument value 2):
3407/// This algorithm gathers data from any number of lanes at any position.
3408/// All reduced values are stored in the lowest possible lane. The set
3409/// of problems every algorithm addresses is a super set of those
3410/// addressable by algorithms with a lower version number. Overhead
3411/// increases as algorithm version increases.
3412///
3413/// Terminology
3414/// Reduce element:
3415/// Reduce element refers to the individual data field with primitive
3416/// data types to be combined and reduced across threads.
3417/// Reduce list:
3418/// Reduce list refers to a collection of local, thread-private
3419/// reduce elements.
3420/// Remote Reduce list:
3421/// Remote Reduce list refers to a collection of remote (relative to
3422/// the current thread) reduce elements.
3423///
3424/// We distinguish between three states of threads that are important to
3425/// the implementation of this function.
3426/// Alive threads:
3427/// Threads in a warp executing the SIMT instruction, as distinguished from
3428/// threads that are inactive due to divergent control flow.
3429/// Active threads:
3430/// The minimal set of threads that has to be alive upon entry to this
3431/// function. The computation is correct iff active threads are alive.
3432/// Some threads are alive but they are not active because they do not
3433/// contribute to the computation in any useful manner. Turning them off
3434/// may introduce control flow overheads without any tangible benefits.
3435/// Effective threads:
3436/// In order to comply with the argument requirements of the shuffle
3437/// function, we must keep all lanes holding data alive. But at most
3438/// half of them perform value aggregation; we refer to this half of
3439/// threads as effective. The other half is simply handing off their
3440/// data.
3441///
3442/// Procedure
3443/// Value shuffle:
3444/// In this step active threads transfer data from higher lane positions
3445/// in the warp to lower lane positions, creating Remote Reduce list.
3446/// Value aggregation:
3447/// In this step, effective threads combine their thread local Reduce list
3448/// with Remote Reduce list and store the result in the thread local
3449/// Reduce list.
3450/// Value copy:
3451/// In this step, we deal with the assumption made by algorithm 2
3452/// (i.e. contiguity assumption). When we have an odd number of lanes
3453/// active, say 2k+1, only k threads will be effective and therefore k
3454/// new values will be produced. However, the Reduce list owned by the
3455/// (2k+1)th thread is ignored in the value aggregation. Therefore
3456/// we copy the Reduce list from the (2k+1)th lane to (k+1)th lane so
3457/// that the contiguity assumption still holds.
James Y Knight9871db02019-02-05 16:42:33 +00003458static llvm::Function *emitShuffleAndReduceFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003459 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
James Y Knight9871db02019-02-05 16:42:33 +00003460 QualType ReductionArrayTy, llvm::Function *ReduceFn, SourceLocation Loc) {
Alexey Bataev9ff80832018-04-16 20:16:21 +00003461 ASTContext &C = CGM.getContext();
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003462
3463 // Thread local Reduce list used to host the values of data to be reduced.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003464 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3465 C.VoidPtrTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003466 // Current lane id; could be logical.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003467 ImplicitParamDecl LaneIDArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.ShortTy,
3468 ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003469 // Offset of the remote source lane relative to the current lane.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003470 ImplicitParamDecl RemoteLaneOffsetArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3471 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003472 // Algorithm version. This is expected to be known at compile time.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003473 ImplicitParamDecl AlgoVerArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3474 C.ShortTy, ImplicitParamDecl::Other);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003475 FunctionArgList Args;
3476 Args.push_back(&ReduceListArg);
3477 Args.push_back(&LaneIDArg);
3478 Args.push_back(&RemoteLaneOffsetArg);
3479 Args.push_back(&AlgoVerArg);
3480
Alexey Bataev9ff80832018-04-16 20:16:21 +00003481 const CGFunctionInfo &CGFI =
3482 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003483 auto *Fn = llvm::Function::Create(
3484 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3485 "_omp_reduction_shuffle_and_reduce_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003486 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003487 Fn->setDoesNotRecurse();
Alexey Bataev8c5555c2019-05-21 15:11:58 +00003488 if (CGM.getLangOpts().Optimize) {
3489 Fn->removeFnAttr(llvm::Attribute::NoInline);
3490 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
3491 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
3492 }
3493
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003494 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003495 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003496
Alexey Bataev9ff80832018-04-16 20:16:21 +00003497 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003498
3499 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3500 Address LocalReduceList(
3501 Bld.CreatePointerBitCastOrAddrSpaceCast(
3502 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3503 C.VoidPtrTy, SourceLocation()),
3504 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3505 CGF.getPointerAlign());
3506
3507 Address AddrLaneIDArg = CGF.GetAddrOfLocalVar(&LaneIDArg);
3508 llvm::Value *LaneIDArgVal = CGF.EmitLoadOfScalar(
3509 AddrLaneIDArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3510
3511 Address AddrRemoteLaneOffsetArg = CGF.GetAddrOfLocalVar(&RemoteLaneOffsetArg);
3512 llvm::Value *RemoteLaneOffsetArgVal = CGF.EmitLoadOfScalar(
3513 AddrRemoteLaneOffsetArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3514
3515 Address AddrAlgoVerArg = CGF.GetAddrOfLocalVar(&AlgoVerArg);
3516 llvm::Value *AlgoVerArgVal = CGF.EmitLoadOfScalar(
3517 AddrAlgoVerArg, /*Volatile=*/false, C.ShortTy, SourceLocation());
3518
3519 // Create a local thread-private variable to host the Reduce list
3520 // from a remote lane.
3521 Address RemoteReduceList =
3522 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.remote_reduce_list");
3523
3524 // This loop iterates through the list of reduce elements and copies,
3525 // element by element, from a remote lane in the warp to RemoteReduceList,
3526 // hosted on the thread's stack.
3527 emitReductionListCopy(RemoteLaneToThread, CGF, ReductionArrayTy, Privates,
3528 LocalReduceList, RemoteReduceList,
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00003529 {/*RemoteLaneOffset=*/RemoteLaneOffsetArgVal,
3530 /*ScratchpadIndex=*/nullptr,
3531 /*ScratchpadWidth=*/nullptr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003532
3533 // The actions to be performed on the Remote Reduce list is dependent
3534 // on the algorithm version.
3535 //
3536 // if (AlgoVer==0) || (AlgoVer==1 && (LaneId < Offset)) || (AlgoVer==2 &&
3537 // LaneId % 2 == 0 && Offset > 0):
3538 // do the reduction value aggregation
3539 //
3540 // The thread local variable Reduce list is mutated in place to host the
3541 // reduced data, which is the aggregated value produced from local and
3542 // remote lanes.
3543 //
3544 // Note that AlgoVer is expected to be a constant integer known at compile
3545 // time.
3546 // When AlgoVer==0, the first conjunction evaluates to true, making
3547 // the entire predicate true during compile time.
3548 // When AlgoVer==1, the second conjunction has only the second part to be
3549 // evaluated during runtime. Other conjunctions evaluates to false
3550 // during compile time.
3551 // When AlgoVer==2, the third conjunction has only the second part to be
3552 // evaluated during runtime. Other conjunctions evaluates to false
3553 // during compile time.
Alexey Bataev9ff80832018-04-16 20:16:21 +00003554 llvm::Value *CondAlgo0 = Bld.CreateIsNull(AlgoVerArgVal);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003555
Alexey Bataev9ff80832018-04-16 20:16:21 +00003556 llvm::Value *Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
3557 llvm::Value *CondAlgo1 = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003558 Algo1, Bld.CreateICmpULT(LaneIDArgVal, RemoteLaneOffsetArgVal));
3559
Alexey Bataev9ff80832018-04-16 20:16:21 +00003560 llvm::Value *Algo2 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(2));
3561 llvm::Value *CondAlgo2 = Bld.CreateAnd(
3562 Algo2, Bld.CreateIsNull(Bld.CreateAnd(LaneIDArgVal, Bld.getInt16(1))));
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003563 CondAlgo2 = Bld.CreateAnd(
3564 CondAlgo2, Bld.CreateICmpSGT(RemoteLaneOffsetArgVal, Bld.getInt16(0)));
3565
Alexey Bataev9ff80832018-04-16 20:16:21 +00003566 llvm::Value *CondReduce = Bld.CreateOr(CondAlgo0, CondAlgo1);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003567 CondReduce = Bld.CreateOr(CondReduce, CondAlgo2);
3568
3569 llvm::BasicBlock *ThenBB = CGF.createBasicBlock("then");
3570 llvm::BasicBlock *ElseBB = CGF.createBasicBlock("else");
3571 llvm::BasicBlock *MergeBB = CGF.createBasicBlock("ifcont");
3572 Bld.CreateCondBr(CondReduce, ThenBB, ElseBB);
3573
3574 CGF.EmitBlock(ThenBB);
3575 // reduce_function(LocalReduceList, RemoteReduceList)
3576 llvm::Value *LocalReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3577 LocalReduceList.getPointer(), CGF.VoidPtrTy);
3578 llvm::Value *RemoteReduceListPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3579 RemoteReduceList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003580 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3581 CGF, Loc, ReduceFn, {LocalReduceListPtr, RemoteReduceListPtr});
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003582 Bld.CreateBr(MergeBB);
3583
3584 CGF.EmitBlock(ElseBB);
3585 Bld.CreateBr(MergeBB);
3586
3587 CGF.EmitBlock(MergeBB);
3588
3589 // if (AlgoVer==1 && (LaneId >= Offset)) copy Remote Reduce list to local
3590 // Reduce list.
3591 Algo1 = Bld.CreateICmpEQ(AlgoVerArgVal, Bld.getInt16(1));
Alexey Bataev9ff80832018-04-16 20:16:21 +00003592 llvm::Value *CondCopy = Bld.CreateAnd(
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00003593 Algo1, Bld.CreateICmpUGE(LaneIDArgVal, RemoteLaneOffsetArgVal));
3594
3595 llvm::BasicBlock *CpyThenBB = CGF.createBasicBlock("then");
3596 llvm::BasicBlock *CpyElseBB = CGF.createBasicBlock("else");
3597 llvm::BasicBlock *CpyMergeBB = CGF.createBasicBlock("ifcont");
3598 Bld.CreateCondBr(CondCopy, CpyThenBB, CpyElseBB);
3599
3600 CGF.EmitBlock(CpyThenBB);
3601 emitReductionListCopy(ThreadCopy, CGF, ReductionArrayTy, Privates,
3602 RemoteReduceList, LocalReduceList);
3603 Bld.CreateBr(CpyMergeBB);
3604
3605 CGF.EmitBlock(CpyElseBB);
3606 Bld.CreateBr(CpyMergeBB);
3607
3608 CGF.EmitBlock(CpyMergeBB);
3609
3610 CGF.FinishFunction();
3611 return Fn;
3612}
3613
Alexey Bataev8061acd2019-02-20 16:36:22 +00003614/// This function emits a helper that copies all the reduction variables from
3615/// the team into the provided global buffer for the reduction variables.
3616///
3617/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3618/// For all data entries D in reduce_data:
3619/// Copy local D to buffer.D[Idx]
3620static llvm::Value *emitListToGlobalCopyFunction(
3621 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3622 QualType ReductionArrayTy, SourceLocation Loc,
3623 const RecordDecl *TeamReductionRec,
3624 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3625 &VarFieldMap) {
3626 ASTContext &C = CGM.getContext();
3627
3628 // Buffer: global reduction buffer.
3629 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3630 C.VoidPtrTy, ImplicitParamDecl::Other);
3631 // Idx: index of the buffer.
3632 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3633 ImplicitParamDecl::Other);
3634 // ReduceList: thread local Reduce list.
3635 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3636 C.VoidPtrTy, ImplicitParamDecl::Other);
3637 FunctionArgList Args;
3638 Args.push_back(&BufferArg);
3639 Args.push_back(&IdxArg);
3640 Args.push_back(&ReduceListArg);
3641
3642 const CGFunctionInfo &CGFI =
3643 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3644 auto *Fn = llvm::Function::Create(
3645 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3646 "_omp_reduction_list_to_global_copy_func", &CGM.getModule());
3647 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3648 Fn->setDoesNotRecurse();
3649 CodeGenFunction CGF(CGM);
3650 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3651
3652 CGBuilderTy &Bld = CGF.Builder;
3653
3654 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3655 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3656 Address LocalReduceList(
3657 Bld.CreatePointerBitCastOrAddrSpaceCast(
3658 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3659 C.VoidPtrTy, Loc),
3660 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3661 CGF.getPointerAlign());
3662 QualType StaticTy = C.getRecordType(TeamReductionRec);
3663 llvm::Type *LLVMReductionsBufferTy =
3664 CGM.getTypes().ConvertTypeForMem(StaticTy);
3665 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3666 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3667 LLVMReductionsBufferTy->getPointerTo());
3668 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3669 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3670 /*Volatile=*/false, C.IntTy,
3671 Loc)};
3672 unsigned Idx = 0;
3673 for (const Expr *Private : Privates) {
3674 // Reduce element = LocalReduceList[i]
3675 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3676 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3677 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3678 // elemptr = ((CopyType*)(elemptrptr)) + I
3679 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3680 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3681 Address ElemPtr =
3682 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3683 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3684 // Global = Buffer.VD[Idx];
3685 const FieldDecl *FD = VarFieldMap.lookup(VD);
3686 LValue GlobLVal = CGF.EmitLValueForField(
3687 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3688 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3689 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3690 switch (CGF.getEvaluationKind(Private->getType())) {
3691 case TEK_Scalar: {
3692 llvm::Value *V = CGF.EmitLoadOfScalar(ElemPtr, /*Volatile=*/false,
3693 Private->getType(), Loc);
3694 CGF.EmitStoreOfScalar(V, GlobLVal);
3695 break;
3696 }
3697 case TEK_Complex: {
3698 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(
3699 CGF.MakeAddrLValue(ElemPtr, Private->getType()), Loc);
3700 CGF.EmitStoreOfComplex(V, GlobLVal, /*isInit=*/false);
3701 break;
3702 }
3703 case TEK_Aggregate:
3704 CGF.EmitAggregateCopy(GlobLVal,
3705 CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3706 Private->getType(), AggValueSlot::DoesNotOverlap);
3707 break;
3708 }
3709 ++Idx;
3710 }
3711
3712 CGF.FinishFunction();
3713 return Fn;
3714}
3715
3716/// This function emits a helper that reduces all the reduction variables from
3717/// the team into the provided global buffer for the reduction variables.
3718///
3719/// void list_to_global_reduce_func(void *buffer, int Idx, void *reduce_data)
3720/// void *GlobPtrs[];
3721/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3722/// ...
3723/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3724/// reduce_function(GlobPtrs, reduce_data);
3725static llvm::Value *emitListToGlobalReduceFunction(
3726 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3727 QualType ReductionArrayTy, SourceLocation Loc,
3728 const RecordDecl *TeamReductionRec,
3729 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3730 &VarFieldMap,
3731 llvm::Function *ReduceFn) {
3732 ASTContext &C = CGM.getContext();
3733
3734 // Buffer: global reduction buffer.
3735 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3736 C.VoidPtrTy, ImplicitParamDecl::Other);
3737 // Idx: index of the buffer.
3738 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3739 ImplicitParamDecl::Other);
3740 // ReduceList: thread local Reduce list.
3741 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3742 C.VoidPtrTy, ImplicitParamDecl::Other);
3743 FunctionArgList Args;
3744 Args.push_back(&BufferArg);
3745 Args.push_back(&IdxArg);
3746 Args.push_back(&ReduceListArg);
3747
3748 const CGFunctionInfo &CGFI =
3749 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3750 auto *Fn = llvm::Function::Create(
3751 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3752 "_omp_reduction_list_to_global_reduce_func", &CGM.getModule());
3753 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3754 Fn->setDoesNotRecurse();
3755 CodeGenFunction CGF(CGM);
3756 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3757
3758 CGBuilderTy &Bld = CGF.Builder;
3759
3760 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3761 QualType StaticTy = C.getRecordType(TeamReductionRec);
3762 llvm::Type *LLVMReductionsBufferTy =
3763 CGM.getTypes().ConvertTypeForMem(StaticTy);
3764 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3765 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3766 LLVMReductionsBufferTy->getPointerTo());
3767
3768 // 1. Build a list of reduction variables.
3769 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3770 Address ReductionList =
3771 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3772 auto IPriv = Privates.begin();
3773 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3774 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3775 /*Volatile=*/false, C.IntTy,
3776 Loc)};
3777 unsigned Idx = 0;
3778 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3779 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3780 // Global = Buffer.VD[Idx];
3781 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3782 const FieldDecl *FD = VarFieldMap.lookup(VD);
3783 LValue GlobLVal = CGF.EmitLValueForField(
3784 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3785 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3786 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3787 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3788 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3789 // Store array size.
3790 ++Idx;
3791 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3792 llvm::Value *Size = CGF.Builder.CreateIntCast(
3793 CGF.getVLASize(
3794 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3795 .NumElts,
3796 CGF.SizeTy, /*isSigned=*/false);
3797 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3798 Elem);
3799 }
3800 }
3801
3802 // Call reduce_function(GlobalReduceList, ReduceList)
3803 llvm::Value *GlobalReduceList =
3804 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
3805 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3806 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
3807 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
3808 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
3809 CGF, Loc, ReduceFn, {GlobalReduceList, ReducedPtr});
3810 CGF.FinishFunction();
3811 return Fn;
3812}
3813
3814/// This function emits a helper that copies all the reduction variables from
3815/// the team into the provided global buffer for the reduction variables.
3816///
3817/// void list_to_global_copy_func(void *buffer, int Idx, void *reduce_data)
3818/// For all data entries D in reduce_data:
3819/// Copy buffer.D[Idx] to local D;
3820static llvm::Value *emitGlobalToListCopyFunction(
3821 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3822 QualType ReductionArrayTy, SourceLocation Loc,
3823 const RecordDecl *TeamReductionRec,
3824 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3825 &VarFieldMap) {
3826 ASTContext &C = CGM.getContext();
3827
3828 // Buffer: global reduction buffer.
3829 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3830 C.VoidPtrTy, ImplicitParamDecl::Other);
3831 // Idx: index of the buffer.
3832 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3833 ImplicitParamDecl::Other);
3834 // ReduceList: thread local Reduce list.
3835 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3836 C.VoidPtrTy, ImplicitParamDecl::Other);
3837 FunctionArgList Args;
3838 Args.push_back(&BufferArg);
3839 Args.push_back(&IdxArg);
3840 Args.push_back(&ReduceListArg);
3841
3842 const CGFunctionInfo &CGFI =
3843 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3844 auto *Fn = llvm::Function::Create(
3845 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3846 "_omp_reduction_global_to_list_copy_func", &CGM.getModule());
3847 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3848 Fn->setDoesNotRecurse();
3849 CodeGenFunction CGF(CGM);
3850 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3851
3852 CGBuilderTy &Bld = CGF.Builder;
3853
3854 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
3855 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3856 Address LocalReduceList(
3857 Bld.CreatePointerBitCastOrAddrSpaceCast(
3858 CGF.EmitLoadOfScalar(AddrReduceListArg, /*Volatile=*/false,
3859 C.VoidPtrTy, Loc),
3860 CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo()),
3861 CGF.getPointerAlign());
3862 QualType StaticTy = C.getRecordType(TeamReductionRec);
3863 llvm::Type *LLVMReductionsBufferTy =
3864 CGM.getTypes().ConvertTypeForMem(StaticTy);
3865 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3866 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3867 LLVMReductionsBufferTy->getPointerTo());
3868
3869 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3870 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3871 /*Volatile=*/false, C.IntTy,
3872 Loc)};
3873 unsigned Idx = 0;
3874 for (const Expr *Private : Privates) {
3875 // Reduce element = LocalReduceList[i]
3876 Address ElemPtrPtrAddr = Bld.CreateConstArrayGEP(LocalReduceList, Idx);
3877 llvm::Value *ElemPtrPtr = CGF.EmitLoadOfScalar(
3878 ElemPtrPtrAddr, /*Volatile=*/false, C.VoidPtrTy, SourceLocation());
3879 // elemptr = ((CopyType*)(elemptrptr)) + I
3880 ElemPtrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3881 ElemPtrPtr, CGF.ConvertTypeForMem(Private->getType())->getPointerTo());
3882 Address ElemPtr =
3883 Address(ElemPtrPtr, C.getTypeAlignInChars(Private->getType()));
3884 const ValueDecl *VD = cast<DeclRefExpr>(Private)->getDecl();
3885 // Global = Buffer.VD[Idx];
3886 const FieldDecl *FD = VarFieldMap.lookup(VD);
3887 LValue GlobLVal = CGF.EmitLValueForField(
3888 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3889 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3890 GlobLVal.setAddress(Address(BufferPtr, GlobLVal.getAlignment()));
3891 switch (CGF.getEvaluationKind(Private->getType())) {
3892 case TEK_Scalar: {
3893 llvm::Value *V = CGF.EmitLoadOfScalar(GlobLVal, Loc);
3894 CGF.EmitStoreOfScalar(V, ElemPtr, /*Volatile=*/false, Private->getType());
3895 break;
3896 }
3897 case TEK_Complex: {
3898 CodeGenFunction::ComplexPairTy V = CGF.EmitLoadOfComplex(GlobLVal, Loc);
3899 CGF.EmitStoreOfComplex(V, CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3900 /*isInit=*/false);
3901 break;
3902 }
3903 case TEK_Aggregate:
3904 CGF.EmitAggregateCopy(CGF.MakeAddrLValue(ElemPtr, Private->getType()),
3905 GlobLVal, Private->getType(),
3906 AggValueSlot::DoesNotOverlap);
3907 break;
3908 }
3909 ++Idx;
3910 }
3911
3912 CGF.FinishFunction();
3913 return Fn;
3914}
3915
3916/// This function emits a helper that reduces all the reduction variables from
3917/// the team into the provided global buffer for the reduction variables.
3918///
3919/// void global_to_list_reduce_func(void *buffer, int Idx, void *reduce_data)
3920/// void *GlobPtrs[];
3921/// GlobPtrs[0] = (void*)&buffer.D0[Idx];
3922/// ...
3923/// GlobPtrs[N] = (void*)&buffer.DN[Idx];
3924/// reduce_function(reduce_data, GlobPtrs);
3925static llvm::Value *emitGlobalToListReduceFunction(
3926 CodeGenModule &CGM, ArrayRef<const Expr *> Privates,
3927 QualType ReductionArrayTy, SourceLocation Loc,
3928 const RecordDecl *TeamReductionRec,
3929 const llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *>
3930 &VarFieldMap,
3931 llvm::Function *ReduceFn) {
3932 ASTContext &C = CGM.getContext();
3933
3934 // Buffer: global reduction buffer.
3935 ImplicitParamDecl BufferArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3936 C.VoidPtrTy, ImplicitParamDecl::Other);
3937 // Idx: index of the buffer.
3938 ImplicitParamDecl IdxArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3939 ImplicitParamDecl::Other);
3940 // ReduceList: thread local Reduce list.
3941 ImplicitParamDecl ReduceListArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3942 C.VoidPtrTy, ImplicitParamDecl::Other);
3943 FunctionArgList Args;
3944 Args.push_back(&BufferArg);
3945 Args.push_back(&IdxArg);
3946 Args.push_back(&ReduceListArg);
3947
3948 const CGFunctionInfo &CGFI =
3949 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3950 auto *Fn = llvm::Function::Create(
3951 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3952 "_omp_reduction_global_to_list_reduce_func", &CGM.getModule());
3953 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
3954 Fn->setDoesNotRecurse();
3955 CodeGenFunction CGF(CGM);
3956 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
3957
3958 CGBuilderTy &Bld = CGF.Builder;
3959
3960 Address AddrBufferArg = CGF.GetAddrOfLocalVar(&BufferArg);
3961 QualType StaticTy = C.getRecordType(TeamReductionRec);
3962 llvm::Type *LLVMReductionsBufferTy =
3963 CGM.getTypes().ConvertTypeForMem(StaticTy);
3964 llvm::Value *BufferArrPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
3965 CGF.EmitLoadOfScalar(AddrBufferArg, /*Volatile=*/false, C.VoidPtrTy, Loc),
3966 LLVMReductionsBufferTy->getPointerTo());
3967
3968 // 1. Build a list of reduction variables.
3969 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
3970 Address ReductionList =
3971 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
3972 auto IPriv = Privates.begin();
3973 llvm::Value *Idxs[] = {llvm::ConstantInt::getNullValue(CGF.Int32Ty),
3974 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(&IdxArg),
3975 /*Volatile=*/false, C.IntTy,
3976 Loc)};
3977 unsigned Idx = 0;
3978 for (unsigned I = 0, E = Privates.size(); I < E; ++I, ++IPriv, ++Idx) {
3979 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3980 // Global = Buffer.VD[Idx];
3981 const ValueDecl *VD = cast<DeclRefExpr>(*IPriv)->getDecl();
3982 const FieldDecl *FD = VarFieldMap.lookup(VD);
3983 LValue GlobLVal = CGF.EmitLValueForField(
3984 CGF.MakeNaturalAlignAddrLValue(BufferArrPtr, StaticTy), FD);
3985 llvm::Value *BufferPtr = Bld.CreateInBoundsGEP(GlobLVal.getPointer(), Idxs);
3986 llvm::Value *Ptr = CGF.EmitCastToVoidPtr(BufferPtr);
3987 CGF.EmitStoreOfScalar(Ptr, Elem, /*Volatile=*/false, C.VoidPtrTy);
3988 if ((*IPriv)->getType()->isVariablyModifiedType()) {
3989 // Store array size.
3990 ++Idx;
3991 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
3992 llvm::Value *Size = CGF.Builder.CreateIntCast(
3993 CGF.getVLASize(
3994 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
3995 .NumElts,
3996 CGF.SizeTy, /*isSigned=*/false);
3997 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
3998 Elem);
3999 }
4000 }
4001
4002 // Call reduce_function(ReduceList, GlobalReduceList)
4003 llvm::Value *GlobalReduceList =
4004 CGF.EmitCastToVoidPtr(ReductionList.getPointer());
4005 Address AddrReduceListArg = CGF.GetAddrOfLocalVar(&ReduceListArg);
4006 llvm::Value *ReducedPtr = CGF.EmitLoadOfScalar(
4007 AddrReduceListArg, /*Volatile=*/false, C.VoidPtrTy, Loc);
4008 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(
4009 CGF, Loc, ReduceFn, {ReducedPtr, GlobalReduceList});
4010 CGF.FinishFunction();
4011 return Fn;
4012}
4013
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004014///
4015/// Design of OpenMP reductions on the GPU
4016///
4017/// Consider a typical OpenMP program with one or more reduction
4018/// clauses:
4019///
4020/// float foo;
4021/// double bar;
4022/// #pragma omp target teams distribute parallel for \
4023/// reduction(+:foo) reduction(*:bar)
4024/// for (int i = 0; i < N; i++) {
4025/// foo += A[i]; bar *= B[i];
4026/// }
4027///
4028/// where 'foo' and 'bar' are reduced across all OpenMP threads in
4029/// all teams. In our OpenMP implementation on the NVPTX device an
4030/// OpenMP team is mapped to a CUDA threadblock and OpenMP threads
4031/// within a team are mapped to CUDA threads within a threadblock.
4032/// Our goal is to efficiently aggregate values across all OpenMP
4033/// threads such that:
4034///
4035/// - the compiler and runtime are logically concise, and
4036/// - the reduction is performed efficiently in a hierarchical
4037/// manner as follows: within OpenMP threads in the same warp,
4038/// across warps in a threadblock, and finally across teams on
4039/// the NVPTX device.
4040///
4041/// Introduction to Decoupling
4042///
4043/// We would like to decouple the compiler and the runtime so that the
4044/// latter is ignorant of the reduction variables (number, data types)
4045/// and the reduction operators. This allows a simpler interface
4046/// and implementation while still attaining good performance.
4047///
4048/// Pseudocode for the aforementioned OpenMP program generated by the
4049/// compiler is as follows:
4050///
4051/// 1. Create private copies of reduction variables on each OpenMP
4052/// thread: 'foo_private', 'bar_private'
4053/// 2. Each OpenMP thread reduces the chunk of 'A' and 'B' assigned
4054/// to it and writes the result in 'foo_private' and 'bar_private'
4055/// respectively.
4056/// 3. Call the OpenMP runtime on the GPU to reduce within a team
4057/// and store the result on the team master:
4058///
Alexey Bataev8e009032019-01-04 17:25:09 +00004059/// __kmpc_nvptx_parallel_reduce_nowait_v2(...,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004060/// reduceData, shuffleReduceFn, interWarpCpyFn)
4061///
4062/// where:
4063/// struct ReduceData {
4064/// double *foo;
4065/// double *bar;
4066/// } reduceData
4067/// reduceData.foo = &foo_private
4068/// reduceData.bar = &bar_private
4069///
4070/// 'shuffleReduceFn' and 'interWarpCpyFn' are pointers to two
4071/// auxiliary functions generated by the compiler that operate on
4072/// variables of type 'ReduceData'. They aid the runtime perform
4073/// algorithmic steps in a data agnostic manner.
4074///
4075/// 'shuffleReduceFn' is a pointer to a function that reduces data
4076/// of type 'ReduceData' across two OpenMP threads (lanes) in the
4077/// same warp. It takes the following arguments as input:
4078///
4079/// a. variable of type 'ReduceData' on the calling lane,
4080/// b. its lane_id,
4081/// c. an offset relative to the current lane_id to generate a
4082/// remote_lane_id. The remote lane contains the second
4083/// variable of type 'ReduceData' that is to be reduced.
4084/// d. an algorithm version parameter determining which reduction
4085/// algorithm to use.
4086///
4087/// 'shuffleReduceFn' retrieves data from the remote lane using
4088/// efficient GPU shuffle intrinsics and reduces, using the
4089/// algorithm specified by the 4th parameter, the two operands
4090/// element-wise. The result is written to the first operand.
4091///
4092/// Different reduction algorithms are implemented in different
4093/// runtime functions, all calling 'shuffleReduceFn' to perform
4094/// the essential reduction step. Therefore, based on the 4th
4095/// parameter, this function behaves slightly differently to
4096/// cooperate with the runtime to ensure correctness under
4097/// different circumstances.
4098///
4099/// 'InterWarpCpyFn' is a pointer to a function that transfers
4100/// reduced variables across warps. It tunnels, through CUDA
4101/// shared memory, the thread-private data of type 'ReduceData'
4102/// from lane 0 of each warp to a lane in the first warp.
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004103/// 4. Call the OpenMP runtime on the GPU to reduce across teams.
4104/// The last team writes the global reduced value to memory.
4105///
4106/// ret = __kmpc_nvptx_teams_reduce_nowait(...,
4107/// reduceData, shuffleReduceFn, interWarpCpyFn,
4108/// scratchpadCopyFn, loadAndReduceFn)
4109///
4110/// 'scratchpadCopyFn' is a helper that stores reduced
4111/// data from the team master to a scratchpad array in
4112/// global memory.
4113///
4114/// 'loadAndReduceFn' is a helper that loads data from
4115/// the scratchpad array and reduces it with the input
4116/// operand.
4117///
4118/// These compiler generated functions hide address
4119/// calculation and alignment information from the runtime.
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004120/// 5. if ret == 1:
4121/// The team master of the last team stores the reduced
4122/// result to the globals in memory.
4123/// foo += reduceData.foo; bar *= reduceData.bar
4124///
4125///
4126/// Warp Reduction Algorithms
4127///
4128/// On the warp level, we have three algorithms implemented in the
4129/// OpenMP runtime depending on the number of active lanes:
4130///
4131/// Full Warp Reduction
4132///
4133/// The reduce algorithm within a warp where all lanes are active
4134/// is implemented in the runtime as follows:
4135///
4136/// full_warp_reduce(void *reduce_data,
4137/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4138/// for (int offset = WARPSIZE/2; offset > 0; offset /= 2)
4139/// ShuffleReduceFn(reduce_data, 0, offset, 0);
4140/// }
4141///
4142/// The algorithm completes in log(2, WARPSIZE) steps.
4143///
4144/// 'ShuffleReduceFn' is used here with lane_id set to 0 because it is
4145/// not used therefore we save instructions by not retrieving lane_id
4146/// from the corresponding special registers. The 4th parameter, which
4147/// represents the version of the algorithm being used, is set to 0 to
4148/// signify full warp reduction.
4149///
4150/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4151///
4152/// #reduce_elem refers to an element in the local lane's data structure
4153/// #remote_elem is retrieved from a remote lane
4154/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4155/// reduce_elem = reduce_elem REDUCE_OP remote_elem;
4156///
4157/// Contiguous Partial Warp Reduction
4158///
4159/// This reduce algorithm is used within a warp where only the first
4160/// 'n' (n <= WARPSIZE) lanes are active. It is typically used when the
4161/// number of OpenMP threads in a parallel region is not a multiple of
4162/// WARPSIZE. The algorithm is implemented in the runtime as follows:
4163///
4164/// void
4165/// contiguous_partial_reduce(void *reduce_data,
4166/// kmp_ShuffleReductFctPtr ShuffleReduceFn,
4167/// int size, int lane_id) {
4168/// int curr_size;
4169/// int offset;
4170/// curr_size = size;
4171/// mask = curr_size/2;
4172/// while (offset>0) {
4173/// ShuffleReduceFn(reduce_data, lane_id, offset, 1);
4174/// curr_size = (curr_size+1)/2;
4175/// offset = curr_size/2;
4176/// }
4177/// }
4178///
4179/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4180///
4181/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4182/// if (lane_id < offset)
4183/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4184/// else
4185/// reduce_elem = remote_elem
4186///
4187/// This algorithm assumes that the data to be reduced are located in a
4188/// contiguous subset of lanes starting from the first. When there is
4189/// an odd number of active lanes, the data in the last lane is not
4190/// aggregated with any other lane's dat but is instead copied over.
4191///
4192/// Dispersed Partial Warp Reduction
4193///
4194/// This algorithm is used within a warp when any discontiguous subset of
4195/// lanes are active. It is used to implement the reduction operation
4196/// across lanes in an OpenMP simd region or in a nested parallel region.
4197///
4198/// void
4199/// dispersed_partial_reduce(void *reduce_data,
4200/// kmp_ShuffleReductFctPtr ShuffleReduceFn) {
4201/// int size, remote_id;
4202/// int logical_lane_id = number_of_active_lanes_before_me() * 2;
4203/// do {
4204/// remote_id = next_active_lane_id_right_after_me();
4205/// # the above function returns 0 of no active lane
4206/// # is present right after the current lane.
4207/// size = number_of_active_lanes_in_this_warp();
4208/// logical_lane_id /= 2;
4209/// ShuffleReduceFn(reduce_data, logical_lane_id,
4210/// remote_id-1-threadIdx.x, 2);
4211/// } while (logical_lane_id % 2 == 0 && size > 1);
4212/// }
4213///
4214/// There is no assumption made about the initial state of the reduction.
4215/// Any number of lanes (>=1) could be active at any position. The reduction
4216/// result is returned in the first active lane.
4217///
4218/// In this version, 'ShuffleReduceFn' behaves, per element, as follows:
4219///
4220/// remote_elem = shuffle_down(reduce_elem, offset, WARPSIZE);
4221/// if (lane_id % 2 == 0 && offset > 0)
4222/// reduce_elem = reduce_elem REDUCE_OP remote_elem
4223/// else
4224/// reduce_elem = remote_elem
4225///
4226///
4227/// Intra-Team Reduction
4228///
4229/// This function, as implemented in the runtime call
Alexey Bataev8e009032019-01-04 17:25:09 +00004230/// '__kmpc_nvptx_parallel_reduce_nowait_v2', aggregates data across OpenMP
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004231/// threads in a team. It first reduces within a warp using the
4232/// aforementioned algorithms. We then proceed to gather all such
4233/// reduced values at the first warp.
4234///
4235/// The runtime makes use of the function 'InterWarpCpyFn', which copies
4236/// data from each of the "warp master" (zeroth lane of each warp, where
4237/// warp-reduced data is held) to the zeroth warp. This step reduces (in
4238/// a mathematical sense) the problem of reduction across warp masters in
4239/// a block to the problem of warp reduction.
4240///
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004241///
4242/// Inter-Team Reduction
4243///
4244/// Once a team has reduced its data to a single value, it is stored in
4245/// a global scratchpad array. Since each team has a distinct slot, this
4246/// can be done without locking.
4247///
4248/// The last team to write to the scratchpad array proceeds to reduce the
4249/// scratchpad array. One or more workers in the last team use the helper
4250/// 'loadAndReduceDataFn' to load and reduce values from the array, i.e.,
4251/// the k'th worker reduces every k'th element.
4252///
Alexey Bataev8e009032019-01-04 17:25:09 +00004253/// Finally, a call is made to '__kmpc_nvptx_parallel_reduce_nowait_v2' to
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004254/// reduce across workers and compute a globally reduced value.
4255///
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004256void CGOpenMPRuntimeNVPTX::emitReduction(
4257 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
4258 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4259 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
4260 if (!CGF.HaveInsertPoint())
4261 return;
4262
4263 bool ParallelReduction = isOpenMPParallelDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004264#ifndef NDEBUG
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004265 bool TeamsReduction = isOpenMPTeamsDirective(Options.ReductionKind);
David L. Jones085ec012018-11-17 04:48:54 +00004266#endif
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004267
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004268 if (Options.SimpleReduction) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004269 assert(!TeamsReduction && !ParallelReduction &&
4270 "Invalid reduction selection in emitReduction.");
Alexey Bataev7b55d2d2018-06-18 17:11:45 +00004271 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
4272 ReductionOps, Options);
4273 return;
4274 }
4275
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004276 assert((TeamsReduction || ParallelReduction) &&
4277 "Invalid reduction selection in emitReduction.");
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004278
Alexey Bataeva1166022018-11-27 21:24:54 +00004279 // Build res = __kmpc_reduce{_nowait}(<gtid>, <n>, sizeof(RedList),
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004280 // RedList, shuffle_reduce_func, interwarp_copy_func);
Alexey Bataeva1166022018-11-27 21:24:54 +00004281 // or
4282 // Build res = __kmpc_reduce_teams_nowait_simple(<loc>, <gtid>, <lck>);
Alexey Bataev8e009032019-01-04 17:25:09 +00004283 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004284 llvm::Value *ThreadId = getThreadID(CGF, Loc);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004285
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004286 llvm::Value *Res;
Alexey Bataev8061acd2019-02-20 16:36:22 +00004287 ASTContext &C = CGM.getContext();
4288 // 1. Build a list of reduction variables.
4289 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
4290 auto Size = RHSExprs.size();
4291 for (const Expr *E : Privates) {
4292 if (E->getType()->isVariablyModifiedType())
4293 // Reserve place for array size.
4294 ++Size;
4295 }
4296 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
4297 QualType ReductionArrayTy =
Richard Smith772e2662019-10-04 01:25:59 +00004298 C.getConstantArrayType(C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
Alexey Bataev8061acd2019-02-20 16:36:22 +00004299 /*IndexTypeQuals=*/0);
4300 Address ReductionList =
4301 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
4302 auto IPriv = Privates.begin();
4303 unsigned Idx = 0;
4304 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
4305 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4306 CGF.Builder.CreateStore(
4307 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4308 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4309 Elem);
4310 if ((*IPriv)->getType()->isVariablyModifiedType()) {
4311 // Store array size.
4312 ++Idx;
4313 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
4314 llvm::Value *Size = CGF.Builder.CreateIntCast(
4315 CGF.getVLASize(
4316 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4317 .NumElts,
4318 CGF.SizeTy, /*isSigned=*/false);
4319 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4320 Elem);
4321 }
4322 }
4323
4324 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4325 ReductionList.getPointer(), CGF.VoidPtrTy);
4326 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev982a35e2019-03-19 17:09:52 +00004327 Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4328 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev8061acd2019-02-20 16:36:22 +00004329 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
4330 llvm::Function *ShuffleAndReduceFn = emitShuffleAndReduceFunction(
4331 CGM, Privates, ReductionArrayTy, ReductionFn, Loc);
4332 llvm::Value *InterWarpCopyFn =
4333 emitInterWarpCopyFunction(CGM, Privates, ReductionArrayTy, Loc);
4334
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004335 if (ParallelReduction) {
Alexey Bataev8e009032019-01-04 17:25:09 +00004336 llvm::Value *Args[] = {RTLoc,
4337 ThreadId,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004338 CGF.Builder.getInt32(RHSExprs.size()),
4339 ReductionArrayTySize,
4340 RL,
4341 ShuffleAndReduceFn,
4342 InterWarpCopyFn};
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004343
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004344 Res = CGF.EmitRuntimeCall(
Alexey Bataeva1166022018-11-27 21:24:54 +00004345 createNVPTXRuntimeFunction(
Alexey Bataev8061acd2019-02-20 16:36:22 +00004346 OMPRTL_NVPTX__kmpc_nvptx_parallel_reduce_nowait_v2),
4347 Args);
4348 } else {
4349 assert(TeamsReduction && "expected teams reduction.");
4350 llvm::SmallDenseMap<const ValueDecl *, const FieldDecl *> VarFieldMap;
4351 llvm::SmallVector<const ValueDecl *, 4> PrivatesReductions(Privates.size());
4352 int Cnt = 0;
4353 for (const Expr *DRE : Privates) {
4354 PrivatesReductions[Cnt] = cast<DeclRefExpr>(DRE)->getDecl();
4355 ++Cnt;
4356 }
4357 const RecordDecl *TeamReductionRec = ::buildRecordForGlobalizedVars(
4358 CGM.getContext(), PrivatesReductions, llvm::None, VarFieldMap,
4359 C.getLangOpts().OpenMPCUDAReductionBufNum);
4360 TeamsReductions.push_back(TeamReductionRec);
4361 if (!KernelTeamsReductionPtr) {
4362 KernelTeamsReductionPtr = new llvm::GlobalVariable(
4363 CGM.getModule(), CGM.VoidPtrTy, /*isConstant=*/true,
4364 llvm::GlobalValue::InternalLinkage, nullptr,
4365 "_openmp_teams_reductions_buffer_$_$ptr");
4366 }
4367 llvm::Value *GlobalBufferPtr = CGF.EmitLoadOfScalar(
4368 Address(KernelTeamsReductionPtr, CGM.getPointerAlign()),
4369 /*Volatile=*/false, C.getPointerType(C.VoidPtrTy), Loc);
4370 llvm::Value *GlobalToBufferCpyFn = ::emitListToGlobalCopyFunction(
4371 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4372 llvm::Value *GlobalToBufferRedFn = ::emitListToGlobalReduceFunction(
4373 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4374 ReductionFn);
4375 llvm::Value *BufferToGlobalCpyFn = ::emitGlobalToListCopyFunction(
4376 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap);
4377 llvm::Value *BufferToGlobalRedFn = ::emitGlobalToListReduceFunction(
4378 CGM, Privates, ReductionArrayTy, Loc, TeamReductionRec, VarFieldMap,
4379 ReductionFn);
4380
4381 llvm::Value *Args[] = {
4382 RTLoc,
4383 ThreadId,
4384 GlobalBufferPtr,
4385 CGF.Builder.getInt32(C.getLangOpts().OpenMPCUDAReductionBufNum),
4386 RL,
4387 ShuffleAndReduceFn,
4388 InterWarpCopyFn,
4389 GlobalToBufferCpyFn,
4390 GlobalToBufferRedFn,
4391 BufferToGlobalCpyFn,
4392 BufferToGlobalRedFn};
4393
4394 Res = CGF.EmitRuntimeCall(
4395 createNVPTXRuntimeFunction(
4396 OMPRTL_NVPTX__kmpc_nvptx_teams_reduce_nowait_v2),
Arpith Chacko Jacobfc711b12017-02-16 16:48:49 +00004397 Args);
4398 }
4399
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004400 // 5. Build if (res == 1)
4401 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.reduction.done");
4402 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.then");
4403 llvm::Value *Cond = CGF.Builder.CreateICmpEQ(
4404 Res, llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1));
4405 CGF.Builder.CreateCondBr(Cond, ThenBB, ExitBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004406
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004407 // 6. Build then branch: where we have reduced values in the master
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004408 // thread in each team.
4409 // __kmpc_end_reduce{_nowait}(<gtid>);
4410 // break;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004411 CGF.EmitBlock(ThenBB);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004412
4413 // Add emission of __kmpc_end_reduce{_nowait}(<gtid>);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004414 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004415 this](CodeGenFunction &CGF, PrePostActionTy &Action) {
4416 auto IPriv = Privates.begin();
4417 auto ILHS = LHSExprs.begin();
4418 auto IRHS = RHSExprs.begin();
Alexey Bataev9ff80832018-04-16 20:16:21 +00004419 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004420 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4421 cast<DeclRefExpr>(*IRHS));
4422 ++IPriv;
4423 ++ILHS;
4424 ++IRHS;
4425 }
4426 };
Alexey Bataev8061acd2019-02-20 16:36:22 +00004427 llvm::Value *EndArgs[] = {ThreadId};
4428 RegionCodeGenTy RCG(CodeGen);
4429 NVPTXActionTy Action(
4430 nullptr, llvm::None,
4431 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_reduce_nowait),
4432 EndArgs);
4433 RCG.setAction(Action);
4434 RCG(CGF);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004435 // There is no need to emit line number for unconditional branch.
4436 (void)ApplyDebugLocation::CreateEmpty(CGF);
4437 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004438}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004439
4440const VarDecl *
4441CGOpenMPRuntimeNVPTX::translateParameter(const FieldDecl *FD,
4442 const VarDecl *NativeParam) const {
4443 if (!NativeParam->getType()->isReferenceType())
4444 return NativeParam;
4445 QualType ArgType = NativeParam->getType();
4446 QualifierCollector QC;
4447 const Type *NonQualTy = QC.strip(ArgType);
4448 QualType PointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4449 if (const auto *Attr = FD->getAttr<OMPCaptureKindAttr>()) {
4450 if (Attr->getCaptureKind() == OMPC_map) {
4451 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4452 LangAS::opencl_global);
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004453 } else if (Attr->getCaptureKind() == OMPC_firstprivate &&
4454 PointeeTy.isConstant(CGM.getContext())) {
4455 PointeeTy = CGM.getContext().getAddrSpaceQualType(PointeeTy,
4456 LangAS::opencl_generic);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004457 }
4458 }
4459 ArgType = CGM.getContext().getPointerType(PointeeTy);
4460 QC.addRestrict();
4461 enum { NVPTX_local_addr = 5 };
Alexander Richardson6d989432017-10-15 18:48:14 +00004462 QC.addAddressSpace(getLangASFromTargetAS(NVPTX_local_addr));
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004463 ArgType = QC.apply(CGM.getContext(), ArgType);
Alexey Bataev9ff80832018-04-16 20:16:21 +00004464 if (isa<ImplicitParamDecl>(NativeParam))
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004465 return ImplicitParamDecl::Create(
4466 CGM.getContext(), /*DC=*/nullptr, NativeParam->getLocation(),
4467 NativeParam->getIdentifier(), ArgType, ImplicitParamDecl::Other);
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004468 return ParmVarDecl::Create(
4469 CGM.getContext(),
4470 const_cast<DeclContext *>(NativeParam->getDeclContext()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004471 NativeParam->getBeginLoc(), NativeParam->getLocation(),
Alexey Bataevb45d43c2017-11-22 16:02:03 +00004472 NativeParam->getIdentifier(), ArgType,
4473 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004474}
4475
4476Address
4477CGOpenMPRuntimeNVPTX::getParameterAddress(CodeGenFunction &CGF,
4478 const VarDecl *NativeParam,
4479 const VarDecl *TargetParam) const {
4480 assert(NativeParam != TargetParam &&
4481 NativeParam->getType()->isReferenceType() &&
4482 "Native arg must not be the same as target arg.");
4483 Address LocalAddr = CGF.GetAddrOfLocalVar(TargetParam);
4484 QualType NativeParamType = NativeParam->getType();
4485 QualifierCollector QC;
4486 const Type *NonQualTy = QC.strip(NativeParamType);
4487 QualType NativePointeeTy = cast<ReferenceType>(NonQualTy)->getPointeeType();
4488 unsigned NativePointeeAddrSpace =
Alexander Richardson6d989432017-10-15 18:48:14 +00004489 CGF.getContext().getTargetAddressSpace(NativePointeeTy);
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004490 QualType TargetTy = TargetParam->getType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004491 llvm::Value *TargetAddr = CGF.EmitLoadOfScalar(
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004492 LocalAddr, /*Volatile=*/false, TargetTy, SourceLocation());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004493 // First cast to generic.
4494 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4495 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4496 /*AddrSpace=*/0));
4497 // Cast from generic to native address space.
4498 TargetAddr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4499 TargetAddr, TargetAddr->getType()->getPointerElementType()->getPointerTo(
4500 NativePointeeAddrSpace));
4501 Address NativeParamAddr = CGF.CreateMemTemp(NativeParamType);
4502 CGF.EmitStoreOfScalar(TargetAddr, NativeParamAddr, /*Volatile=*/false,
Alexey Bataev36f2c4d2017-09-13 20:20:59 +00004503 NativeParamType);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004504 return NativeParamAddr;
4505}
4506
4507void CGOpenMPRuntimeNVPTX::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00004508 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004509 ArrayRef<llvm::Value *> Args) const {
4510 SmallVector<llvm::Value *, 4> TargetArgs;
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004511 TargetArgs.reserve(Args.size());
James Y Knight9871db02019-02-05 16:42:33 +00004512 auto *FnType = OutlinedFn.getFunctionType();
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004513 for (unsigned I = 0, E = Args.size(); I < E; ++I) {
Alexey Bataev07ed94a2017-08-15 14:34:04 +00004514 if (FnType->isVarArg() && FnType->getNumParams() <= I) {
4515 TargetArgs.append(std::next(Args.begin(), I), Args.end());
4516 break;
4517 }
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004518 llvm::Type *TargetType = FnType->getParamType(I);
4519 llvm::Value *NativeArg = Args[I];
4520 if (!TargetType->isPointerTy()) {
4521 TargetArgs.emplace_back(NativeArg);
4522 continue;
4523 }
4524 llvm::Value *TargetArg = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataevc99042b2018-03-15 18:10:54 +00004525 NativeArg,
4526 NativeArg->getType()->getPointerElementType()->getPointerTo());
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004527 TargetArgs.emplace_back(
4528 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TargetArg, TargetType));
4529 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00004530 CGOpenMPRuntime::emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, TargetArgs);
Alexey Bataev3b8d5582017-08-08 18:04:06 +00004531}
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004532
4533/// Emit function which wraps the outline parallel region
4534/// and controls the arguments which are passed to this function.
4535/// The wrapper ensures that the outlined function is called
4536/// with the correct arguments when data is shared.
4537llvm::Function *CGOpenMPRuntimeNVPTX::createParallelDataSharingWrapper(
4538 llvm::Function *OutlinedParallelFn, const OMPExecutableDirective &D) {
4539 ASTContext &Ctx = CGM.getContext();
4540 const auto &CS = *D.getCapturedStmt(OMPD_parallel);
4541
4542 // Create a function that takes as argument the source thread.
4543 FunctionArgList WrapperArgs;
4544 QualType Int16QTy =
4545 Ctx.getIntTypeForBitwidth(/*DestWidth=*/16, /*Signed=*/false);
4546 QualType Int32QTy =
4547 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004548 ImplicitParamDecl ParallelLevelArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004549 /*Id=*/nullptr, Int16QTy,
4550 ImplicitParamDecl::Other);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004551 ImplicitParamDecl WrapperArg(Ctx, /*DC=*/nullptr, D.getBeginLoc(),
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004552 /*Id=*/nullptr, Int32QTy,
4553 ImplicitParamDecl::Other);
4554 WrapperArgs.emplace_back(&ParallelLevelArg);
4555 WrapperArgs.emplace_back(&WrapperArg);
4556
Alexey Bataev9ff80832018-04-16 20:16:21 +00004557 const CGFunctionInfo &CGFI =
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004558 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, WrapperArgs);
4559
4560 auto *Fn = llvm::Function::Create(
4561 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
Alexey Bataev9ff80832018-04-16 20:16:21 +00004562 Twine(OutlinedParallelFn->getName(), "_wrapper"), &CGM.getModule());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004563 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004564 Fn->setLinkage(llvm::GlobalValue::InternalLinkage);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004565 Fn->setDoesNotRecurse();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004566
4567 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true);
4568 CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, Fn, CGFI, WrapperArgs,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004569 D.getBeginLoc(), D.getBeginLoc());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004570
4571 const auto *RD = CS.getCapturedRecordDecl();
4572 auto CurField = RD->field_begin();
4573
Alexey Bataevf89cf212019-10-16 16:59:01 +00004574 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
4575 /*Name=*/".zero.addr");
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004576 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004577 // Get the array of arguments.
4578 SmallVector<llvm::Value *, 8> Args;
4579
Alexey Bataevb7f3cba2018-03-19 17:04:07 +00004580 Args.emplace_back(CGF.GetAddrOfLocalVar(&WrapperArg).getPointer());
4581 Args.emplace_back(ZeroAddr.getPointer());
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004582
4583 CGBuilderTy &Bld = CGF.Builder;
4584 auto CI = CS.capture_begin();
4585
4586 // Use global memory for data sharing.
4587 // Handle passing of global args to workers.
4588 Address GlobalArgs =
4589 CGF.CreateDefaultAlignTempAlloca(CGF.VoidPtrPtrTy, "global_args");
4590 llvm::Value *GlobalArgsPtr = GlobalArgs.getPointer();
4591 llvm::Value *DataSharingArgs[] = {GlobalArgsPtr};
4592 CGF.EmitRuntimeCall(
4593 createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_get_shared_variables),
4594 DataSharingArgs);
4595
4596 // Retrieve the shared variables from the list of references returned
4597 // by the runtime. Pass the variables to the outlined function.
Alexey Bataev17314212018-03-20 15:41:05 +00004598 Address SharedArgListAddress = Address::invalid();
4599 if (CS.capture_size() > 0 ||
4600 isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
4601 SharedArgListAddress = CGF.EmitLoadOfPointer(
4602 GlobalArgs, CGF.getContext()
4603 .getPointerType(CGF.getContext().getPointerType(
4604 CGF.getContext().VoidPtrTy))
4605 .castAs<PointerType>());
4606 }
4607 unsigned Idx = 0;
4608 if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
James Y Knight751fe282019-02-09 22:22:28 +00004609 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004610 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4611 Src, CGF.SizeTy->getPointerTo());
4612 llvm::Value *LB = CGF.EmitLoadOfScalar(
4613 TypedAddress,
4614 /*Volatile=*/false,
4615 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4616 cast<OMPLoopDirective>(D).getLowerBoundVariable()->getExprLoc());
4617 Args.emplace_back(LB);
4618 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00004619 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004620 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
4621 Src, CGF.SizeTy->getPointerTo());
4622 llvm::Value *UB = CGF.EmitLoadOfScalar(
4623 TypedAddress,
4624 /*Volatile=*/false,
4625 CGF.getContext().getPointerType(CGF.getContext().getSizeType()),
4626 cast<OMPLoopDirective>(D).getUpperBoundVariable()->getExprLoc());
4627 Args.emplace_back(UB);
4628 ++Idx;
4629 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004630 if (CS.capture_size() > 0) {
4631 ASTContext &CGFContext = CGF.getContext();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004632 for (unsigned I = 0, E = CS.capture_size(); I < E; ++I, ++CI, ++CurField) {
4633 QualType ElemTy = CurField->getType();
James Y Knight751fe282019-02-09 22:22:28 +00004634 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
Alexey Bataev17314212018-03-20 15:41:05 +00004635 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004636 Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
4637 llvm::Value *Arg = CGF.EmitLoadOfScalar(TypedAddress,
4638 /*Volatile=*/false,
4639 CGFContext.getPointerType(ElemTy),
4640 CI->getLocation());
Alexey Bataev2091ca62018-04-23 17:33:41 +00004641 if (CI->capturesVariableByCopy() &&
4642 !CI->getCapturedVar()->getType()->isAnyPointerType()) {
Alexey Bataev17314212018-03-20 15:41:05 +00004643 Arg = castValueToType(CGF, Arg, ElemTy, CGFContext.getUIntPtrType(),
4644 CI->getLocation());
4645 }
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004646 Args.emplace_back(Arg);
4647 }
4648 }
4649
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004650 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedParallelFn, Args);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004651 CGF.FinishFunction();
4652 return Fn;
4653}
4654
4655void CGOpenMPRuntimeNVPTX::emitFunctionProlog(CodeGenFunction &CGF,
4656 const Decl *D) {
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004657 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4658 return;
4659
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004660 assert(D && "Expected function or captured|block decl.");
4661 assert(FunctionGlobalizedDecls.count(CGF.CurFn) == 0 &&
4662 "Function is registered already.");
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004663 assert((!TeamAndReductions.first || TeamAndReductions.first == D) &&
4664 "Team is set but not processed.");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004665 const Stmt *Body = nullptr;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004666 bool NeedToDelayGlobalization = false;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004667 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4668 Body = FD->getBody();
4669 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
4670 Body = BD->getBody();
4671 } else if (const auto *CD = dyn_cast<CapturedDecl>(D)) {
4672 Body = CD->getBody();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004673 NeedToDelayGlobalization = CGF.CapturedStmtInfo->getKind() == CR_OpenMP;
Alexey Bataev2adecff2018-09-21 14:22:53 +00004674 if (NeedToDelayGlobalization &&
4675 getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD)
4676 return;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004677 }
4678 if (!Body)
4679 return;
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004680 CheckVarsEscapingDeclContext VarChecker(CGF, TeamAndReductions.second);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004681 VarChecker.Visit(Body);
Alexey Bataevff23bb62018-10-11 18:30:31 +00004682 const RecordDecl *GlobalizedVarsRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004683 VarChecker.getGlobalizedRecord(IsInTTDRegion);
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004684 TeamAndReductions.first = nullptr;
4685 TeamAndReductions.second.clear();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004686 ArrayRef<const ValueDecl *> EscapedVariableLengthDecls =
4687 VarChecker.getEscapedVariableLengthDecls();
4688 if (!GlobalizedVarsRecord && EscapedVariableLengthDecls.empty())
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004689 return;
Alexey Bataevc99042b2018-03-15 18:10:54 +00004690 auto I = FunctionGlobalizedDecls.try_emplace(CGF.CurFn).first;
4691 I->getSecond().MappedParams =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00004692 std::make_unique<CodeGenFunction::OMPMapVars>();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004693 I->getSecond().GlobalRecord = GlobalizedVarsRecord;
4694 I->getSecond().EscapedParameters.insert(
4695 VarChecker.getEscapedParameters().begin(),
4696 VarChecker.getEscapedParameters().end());
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004697 I->getSecond().EscapedVariableLengthDecls.append(
4698 EscapedVariableLengthDecls.begin(), EscapedVariableLengthDecls.end());
Alexey Bataevc99042b2018-03-15 18:10:54 +00004699 DeclToAddrMapTy &Data = I->getSecond().LocalVarData;
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004700 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004701 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004702 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004703 Data.insert(std::make_pair(VD, MappedVarData(FD, IsInTTDRegion)));
Alexey Bataevc99042b2018-03-15 18:10:54 +00004704 }
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004705 if (!IsInTTDRegion && !NeedToDelayGlobalization && !IsInParallelRegion) {
Alexey Bataevf2f39be2018-11-16 19:38:21 +00004706 CheckVarsEscapingDeclContext VarChecker(CGF, llvm::None);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004707 VarChecker.Visit(Body);
4708 I->getSecond().SecondaryGlobalRecord =
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004709 VarChecker.getGlobalizedRecord(/*IsInTTDRegion=*/true);
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004710 I->getSecond().SecondaryLocalVarData.emplace();
4711 DeclToAddrMapTy &Data = I->getSecond().SecondaryLocalVarData.getValue();
4712 for (const ValueDecl *VD : VarChecker.getEscapedDecls()) {
4713 assert(VD->isCanonicalDecl() && "Expected canonical declaration");
4714 const FieldDecl *FD = VarChecker.getFieldForGlobalizedVar(VD);
Alexey Bataev4ac58d12018-10-12 20:19:59 +00004715 Data.insert(
4716 std::make_pair(VD, MappedVarData(FD, /*IsInTTDRegion=*/true)));
Alexey Bataev9bfe91d2018-10-12 16:04:20 +00004717 }
4718 }
Alexey Bataevc99042b2018-03-15 18:10:54 +00004719 if (!NeedToDelayGlobalization) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004720 emitGenericVarsProlog(CGF, D->getBeginLoc(), /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004721 struct GlobalizationScope final : EHScopeStack::Cleanup {
4722 GlobalizationScope() = default;
4723
4724 void Emit(CodeGenFunction &CGF, Flags flags) override {
4725 static_cast<CGOpenMPRuntimeNVPTX &>(CGF.CGM.getOpenMPRuntime())
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00004726 .emitGenericVarsEpilog(CGF, /*WithSPMDCheck=*/true);
Alexey Bataevc99042b2018-03-15 18:10:54 +00004727 }
4728 };
4729 CGF.EHStack.pushCleanup<GlobalizationScope>(NormalAndEHCleanup);
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004730 }
4731}
4732
4733Address CGOpenMPRuntimeNVPTX::getAddressOfLocalVariable(CodeGenFunction &CGF,
4734 const VarDecl *VD) {
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004735 if (VD && VD->hasAttr<OMPAllocateDeclAttr>()) {
4736 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4737 switch (A->getAllocatorType()) {
4738 // Use the default allocator here as by default local vars are
4739 // threadlocal.
4740 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4741 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004742 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4743 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004744 // Follow the user decision - use default allocation.
4745 return Address::invalid();
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004746 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004747 // TODO: implement aupport for user-defined allocators.
4748 return Address::invalid();
4749 case OMPAllocateDeclAttr::OMPConstMemAlloc: {
4750 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4751 auto *GV = new llvm::GlobalVariable(
4752 CGM.getModule(), VarTy, /*isConstant=*/false,
4753 llvm::GlobalValue::InternalLinkage,
4754 llvm::Constant::getNullValue(VarTy), VD->getName(),
4755 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4756 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant));
4757 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004758 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004759 return Address(GV, Align);
4760 }
4761 case OMPAllocateDeclAttr::OMPPTeamMemAlloc: {
4762 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4763 auto *GV = new llvm::GlobalVariable(
4764 CGM.getModule(), VarTy, /*isConstant=*/false,
4765 llvm::GlobalValue::InternalLinkage,
4766 llvm::Constant::getNullValue(VarTy), VD->getName(),
4767 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal,
4768 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared));
4769 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004770 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004771 return Address(GV, Align);
4772 }
4773 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4774 case OMPAllocateDeclAttr::OMPCGroupMemAlloc: {
4775 llvm::Type *VarTy = CGF.ConvertTypeForMem(VD->getType());
4776 auto *GV = new llvm::GlobalVariable(
4777 CGM.getModule(), VarTy, /*isConstant=*/false,
4778 llvm::GlobalValue::InternalLinkage,
4779 llvm::Constant::getNullValue(VarTy), VD->getName());
4780 CharUnits Align = CGM.getContext().getDeclAlign(VD);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00004781 GV->setAlignment(Align.getAsAlign());
Alexey Bataev1db9bfe2019-04-08 16:53:57 +00004782 return Address(GV, Align);
4783 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004784 }
4785 }
4786
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00004787 if (getDataSharingMode(CGM) != CGOpenMPRuntimeNVPTX::Generic)
4788 return Address::invalid();
4789
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004790 VD = VD->getCanonicalDecl();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004791 auto I = FunctionGlobalizedDecls.find(CGF.CurFn);
4792 if (I == FunctionGlobalizedDecls.end())
4793 return Address::invalid();
Alexey Bataevc99042b2018-03-15 18:10:54 +00004794 auto VDI = I->getSecond().LocalVarData.find(VD);
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004795 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004796 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004797 if (VD->hasAttrs()) {
4798 for (specific_attr_iterator<OMPReferencedVarAttr> IT(VD->attr_begin()),
4799 E(VD->attr_end());
4800 IT != E; ++IT) {
4801 auto VDI = I->getSecond().LocalVarData.find(
4802 cast<VarDecl>(cast<DeclRefExpr>(IT->getRef())->getDecl())
4803 ->getCanonicalDecl());
4804 if (VDI != I->getSecond().LocalVarData.end())
Alexey Bataev9ea3c382018-10-09 14:49:00 +00004805 return VDI->second.PrivateAddr;
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004806 }
4807 }
Alexey Bataev084b0c2f02019-03-21 20:36:16 +00004808
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004809 return Address::invalid();
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004810}
4811
4812void CGOpenMPRuntimeNVPTX::functionFinished(CodeGenFunction &CGF) {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00004813 FunctionGlobalizedDecls.erase(CGF.CurFn);
4814 CGOpenMPRuntime::functionFinished(CGF);
4815}
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004816
4817void CGOpenMPRuntimeNVPTX::getDefaultDistScheduleAndChunk(
4818 CodeGenFunction &CGF, const OMPLoopDirective &S,
4819 OpenMPDistScheduleClauseKind &ScheduleKind,
4820 llvm::Value *&Chunk) const {
4821 if (getExecutionMode() == CGOpenMPRuntimeNVPTX::EM_SPMD) {
4822 ScheduleKind = OMPC_DIST_SCHEDULE_static;
4823 Chunk = CGF.EmitScalarConversion(getNVPTXNumThreads(CGF),
4824 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4825 S.getIterationVariable()->getType(), S.getBeginLoc());
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004826 return;
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004827 }
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004828 CGOpenMPRuntime::getDefaultDistScheduleAndChunk(
4829 CGF, S, ScheduleKind, Chunk);
Gheorghe-Teodor Bercea02650d42018-09-27 19:22:56 +00004830}
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004831
4832void CGOpenMPRuntimeNVPTX::getDefaultScheduleAndChunk(
4833 CodeGenFunction &CGF, const OMPLoopDirective &S,
4834 OpenMPScheduleClauseKind &ScheduleKind,
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004835 const Expr *&ChunkExpr) const {
Gheorghe-Teodor Bercea669dbde2018-10-29 15:23:23 +00004836 ScheduleKind = OMPC_SCHEDULE_static;
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00004837 // Chunk size is 1 in this case.
4838 llvm::APInt ChunkSize(32, 1);
4839 ChunkExpr = IntegerLiteral::Create(CGF.getContext(), ChunkSize,
4840 CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
4841 SourceLocation());
Gheorghe-Teodor Bercea8233af92018-09-27 20:29:00 +00004842}
Alexey Bataev60705422018-10-30 15:50:12 +00004843
4844void CGOpenMPRuntimeNVPTX::adjustTargetSpecificDataForLambdas(
4845 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
4846 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
4847 " Expected target-based directive.");
4848 const CapturedStmt *CS = D.getCapturedStmt(OMPD_target);
4849 for (const CapturedStmt::Capture &C : CS->captures()) {
4850 // Capture variables captured by reference in lambdas for target-based
4851 // directives.
4852 if (!C.capturesVariable())
4853 continue;
4854 const VarDecl *VD = C.getCapturedVar();
4855 const auto *RD = VD->getType()
4856 .getCanonicalType()
4857 .getNonReferenceType()
4858 ->getAsCXXRecordDecl();
4859 if (!RD || !RD->isLambda())
4860 continue;
4861 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4862 LValue VDLVal;
4863 if (VD->getType().getCanonicalType()->isReferenceType())
4864 VDLVal = CGF.EmitLoadOfReferenceLValue(VDAddr, VD->getType());
4865 else
4866 VDLVal = CGF.MakeAddrLValue(
4867 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
4868 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4869 FieldDecl *ThisCapture = nullptr;
4870 RD->getCaptureFields(Captures, ThisCapture);
4871 if (ThisCapture && CGF.CapturedStmtInfo->isCXXThisExprCaptured()) {
4872 LValue ThisLVal =
4873 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
4874 llvm::Value *CXXThis = CGF.LoadCXXThis();
4875 CGF.EmitStoreOfScalar(CXXThis, ThisLVal);
4876 }
4877 for (const LambdaCapture &LC : RD->captures()) {
4878 if (LC.getCaptureKind() != LCK_ByRef)
4879 continue;
4880 const VarDecl *VD = LC.getCapturedVar();
4881 if (!CS->capturesVariable(VD))
4882 continue;
4883 auto It = Captures.find(VD);
4884 assert(It != Captures.end() && "Found lambda capture without field.");
4885 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
4886 Address VDAddr = CGF.GetAddrOfLocalVar(VD);
4887 if (VD->getType().getCanonicalType()->isReferenceType())
4888 VDAddr = CGF.EmitLoadOfReferenceLValue(VDAddr,
4889 VD->getType().getCanonicalType())
4890 .getAddress();
4891 CGF.EmitStoreOfScalar(VDAddr.getPointer(), VarLVal);
4892 }
4893 }
4894}
4895
Alexey Bataev1af5bd52019-03-05 17:47:18 +00004896unsigned CGOpenMPRuntimeNVPTX::getDefaultFirstprivateAddressSpace() const {
4897 return CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4898}
4899
Alexey Bataevc5687252019-03-21 19:35:27 +00004900bool CGOpenMPRuntimeNVPTX::hasAllocateAttributeForGlobalVar(const VarDecl *VD,
4901 LangAS &AS) {
4902 if (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())
4903 return false;
4904 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
4905 switch(A->getAllocatorType()) {
4906 case OMPAllocateDeclAttr::OMPDefaultMemAlloc:
4907 // Not supported, fallback to the default mem space.
4908 case OMPAllocateDeclAttr::OMPThreadMemAlloc:
4909 case OMPAllocateDeclAttr::OMPLargeCapMemAlloc:
4910 case OMPAllocateDeclAttr::OMPCGroupMemAlloc:
4911 case OMPAllocateDeclAttr::OMPHighBWMemAlloc:
4912 case OMPAllocateDeclAttr::OMPLowLatMemAlloc:
4913 AS = LangAS::Default;
4914 return true;
4915 case OMPAllocateDeclAttr::OMPConstMemAlloc:
4916 AS = LangAS::cuda_constant;
4917 return true;
4918 case OMPAllocateDeclAttr::OMPPTeamMemAlloc:
4919 AS = LangAS::cuda_shared;
4920 return true;
4921 case OMPAllocateDeclAttr::OMPUserDefinedMemAlloc:
4922 llvm_unreachable("Expected predefined allocator for the variables with the "
4923 "static storage.");
4924 }
4925 return false;
4926}
4927
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004928// Get current CudaArch and ignore any unknown values
4929static CudaArch getCudaArch(CodeGenModule &CGM) {
4930 if (!CGM.getTarget().hasFeature("ptx"))
4931 return CudaArch::UNKNOWN;
4932 llvm::StringMap<bool> Features;
4933 CGM.getTarget().initFeatureMap(Features, CGM.getDiags(),
4934 CGM.getTarget().getTargetOpts().CPU,
4935 CGM.getTarget().getTargetOpts().Features);
4936 for (const auto &Feature : Features) {
4937 if (Feature.getValue()) {
4938 CudaArch Arch = StringToCudaArch(Feature.getKey());
4939 if (Arch != CudaArch::UNKNOWN)
4940 return Arch;
4941 }
4942 }
4943 return CudaArch::UNKNOWN;
4944}
4945
4946/// Check to see if target architecture supports unified addressing which is
4947/// a restriction for OpenMP requires clause "unified_shared_memory".
4948void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004949 const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004950 for (const OMPClause *Clause : D->clauselists()) {
4951 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
4952 switch (getCudaArch(CGM)) {
4953 case CudaArch::SM_20:
4954 case CudaArch::SM_21:
4955 case CudaArch::SM_30:
4956 case CudaArch::SM_32:
4957 case CudaArch::SM_35:
4958 case CudaArch::SM_37:
4959 case CudaArch::SM_50:
4960 case CudaArch::SM_52:
4961 case CudaArch::SM_53:
4962 case CudaArch::SM_60:
4963 case CudaArch::SM_61:
4964 case CudaArch::SM_62:
4965 CGM.Error(Clause->getBeginLoc(),
4966 "Target architecture does not support unified addressing");
4967 return;
4968 case CudaArch::SM_70:
4969 case CudaArch::SM_72:
4970 case CudaArch::SM_75:
4971 case CudaArch::GFX600:
4972 case CudaArch::GFX601:
4973 case CudaArch::GFX700:
4974 case CudaArch::GFX701:
4975 case CudaArch::GFX702:
4976 case CudaArch::GFX703:
4977 case CudaArch::GFX704:
4978 case CudaArch::GFX801:
4979 case CudaArch::GFX802:
4980 case CudaArch::GFX803:
4981 case CudaArch::GFX810:
4982 case CudaArch::GFX900:
4983 case CudaArch::GFX902:
4984 case CudaArch::GFX904:
4985 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00004986 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004987 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00004988 case CudaArch::GFX1010:
4989 case CudaArch::GFX1011:
4990 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004991 case CudaArch::UNKNOWN:
4992 break;
4993 case CudaArch::LAST:
4994 llvm_unreachable("Unexpected Cuda arch.");
4995 }
4996 }
4997 }
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +00004998 CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
Patrick Lyster8f7f5862018-11-19 15:09:33 +00004999}
5000
Alexey Bataeve4090182018-11-02 14:54:07 +00005001/// Get number of SMs and number of blocks per SM.
5002static std::pair<unsigned, unsigned> getSMsBlocksPerSM(CodeGenModule &CGM) {
5003 std::pair<unsigned, unsigned> Data;
5004 if (CGM.getLangOpts().OpenMPCUDANumSMs)
5005 Data.first = CGM.getLangOpts().OpenMPCUDANumSMs;
5006 if (CGM.getLangOpts().OpenMPCUDABlocksPerSM)
5007 Data.second = CGM.getLangOpts().OpenMPCUDABlocksPerSM;
5008 if (Data.first && Data.second)
5009 return Data;
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005010 switch (getCudaArch(CGM)) {
5011 case CudaArch::SM_20:
5012 case CudaArch::SM_21:
5013 case CudaArch::SM_30:
5014 case CudaArch::SM_32:
5015 case CudaArch::SM_35:
5016 case CudaArch::SM_37:
5017 case CudaArch::SM_50:
5018 case CudaArch::SM_52:
5019 case CudaArch::SM_53:
5020 return {16, 16};
5021 case CudaArch::SM_60:
5022 case CudaArch::SM_61:
5023 case CudaArch::SM_62:
5024 return {56, 32};
5025 case CudaArch::SM_70:
5026 case CudaArch::SM_72:
5027 case CudaArch::SM_75:
5028 return {84, 32};
5029 case CudaArch::GFX600:
5030 case CudaArch::GFX601:
5031 case CudaArch::GFX700:
5032 case CudaArch::GFX701:
5033 case CudaArch::GFX702:
5034 case CudaArch::GFX703:
5035 case CudaArch::GFX704:
5036 case CudaArch::GFX801:
5037 case CudaArch::GFX802:
5038 case CudaArch::GFX803:
5039 case CudaArch::GFX810:
5040 case CudaArch::GFX900:
5041 case CudaArch::GFX902:
5042 case CudaArch::GFX904:
5043 case CudaArch::GFX906:
Stanislav Mekhanoshin0cfd75a2019-07-09 18:19:00 +00005044 case CudaArch::GFX908:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005045 case CudaArch::GFX909:
Yaxun Liu6add24a2019-07-11 17:50:09 +00005046 case CudaArch::GFX1010:
5047 case CudaArch::GFX1011:
5048 case CudaArch::GFX1012:
Patrick Lyster8f7f5862018-11-19 15:09:33 +00005049 case CudaArch::UNKNOWN:
5050 break;
5051 case CudaArch::LAST:
5052 llvm_unreachable("Unexpected Cuda arch.");
Alexey Bataeve4090182018-11-02 14:54:07 +00005053 }
5054 llvm_unreachable("Unexpected NVPTX target without ptx feature.");
5055}
5056
5057void CGOpenMPRuntimeNVPTX::clear() {
5058 if (!GlobalizedRecords.empty()) {
5059 ASTContext &C = CGM.getContext();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005060 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> GlobalRecs;
5061 llvm::SmallVector<const GlobalPtrSizeRecsTy *, 4> SharedRecs;
Alexey Bataeve4090182018-11-02 14:54:07 +00005062 RecordDecl *StaticRD = C.buildImplicitRecord(
5063 "_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5064 StaticRD->startDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005065 RecordDecl *SharedStaticRD = C.buildImplicitRecord(
5066 "_shared_openmp_static_memory_type_$_", RecordDecl::TagKind::TTK_Union);
5067 SharedStaticRD->startDefinition();
Alexey Bataeve4090182018-11-02 14:54:07 +00005068 for (const GlobalPtrSizeRecsTy &Records : GlobalizedRecords) {
5069 if (Records.Records.empty())
5070 continue;
5071 unsigned Size = 0;
5072 unsigned RecAlignment = 0;
5073 for (const RecordDecl *RD : Records.Records) {
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005074 QualType RDTy = C.getRecordType(RD);
5075 unsigned Alignment = C.getTypeAlignInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005076 RecAlignment = std::max(RecAlignment, Alignment);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005077 unsigned RecSize = C.getTypeSizeInChars(RDTy).getQuantity();
Alexey Bataeve4090182018-11-02 14:54:07 +00005078 Size =
5079 llvm::alignTo(llvm::alignTo(Size, Alignment) + RecSize, Alignment);
5080 }
5081 Size = llvm::alignTo(Size, RecAlignment);
5082 llvm::APInt ArySize(/*numBits=*/64, Size);
5083 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005084 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005085 const bool UseSharedMemory = Size <= SharedMemorySize;
5086 auto *Field =
5087 FieldDecl::Create(C, UseSharedMemory ? SharedStaticRD : StaticRD,
5088 SourceLocation(), SourceLocation(), nullptr, SubTy,
5089 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5090 /*BW=*/nullptr, /*Mutable=*/false,
5091 /*InitStyle=*/ICIS_NoInit);
Alexey Bataeve4090182018-11-02 14:54:07 +00005092 Field->setAccess(AS_public);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005093 if (UseSharedMemory) {
5094 SharedStaticRD->addDecl(Field);
5095 SharedRecs.push_back(&Records);
5096 } else {
5097 StaticRD->addDecl(Field);
5098 GlobalRecs.push_back(&Records);
5099 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005100 Records.RecSize->setInitializer(llvm::ConstantInt::get(CGM.SizeTy, Size));
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005101 Records.UseSharedMemory->setInitializer(
5102 llvm::ConstantInt::get(CGM.Int16Ty, UseSharedMemory ? 1 : 0));
5103 }
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005104 // Allocate SharedMemorySize buffer for the shared memory.
5105 // FIXME: nvlink does not handle weak linkage correctly (object with the
5106 // different size are reported as erroneous).
5107 // Restore this code as sson as nvlink is fixed.
5108 if (!SharedStaticRD->field_empty()) {
5109 llvm::APInt ArySize(/*numBits=*/64, SharedMemorySize);
5110 QualType SubTy = C.getConstantArrayType(
Richard Smith772e2662019-10-04 01:25:59 +00005111 C.CharTy, ArySize, nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
Alexey Bataev6a1b06b2018-12-18 21:01:42 +00005112 auto *Field = FieldDecl::Create(
5113 C, SharedStaticRD, SourceLocation(), SourceLocation(), nullptr, SubTy,
5114 C.getTrivialTypeSourceInfo(SubTy, SourceLocation()),
5115 /*BW=*/nullptr, /*Mutable=*/false,
5116 /*InitStyle=*/ICIS_NoInit);
5117 Field->setAccess(AS_public);
5118 SharedStaticRD->addDecl(Field);
5119 }
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005120 SharedStaticRD->completeDefinition();
5121 if (!SharedStaticRD->field_empty()) {
5122 QualType StaticTy = C.getRecordType(SharedStaticRD);
5123 llvm::Type *LLVMStaticTy = CGM.getTypes().ConvertTypeForMem(StaticTy);
5124 auto *GV = new llvm::GlobalVariable(
5125 CGM.getModule(), LLVMStaticTy,
Alexey Bataevf2f39be2018-11-16 19:38:21 +00005126 /*isConstant=*/false, llvm::GlobalValue::CommonLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005127 llvm::Constant::getNullValue(LLVMStaticTy),
5128 "_openmp_shared_static_glob_rd_$_", /*InsertBefore=*/nullptr,
5129 llvm::GlobalValue::NotThreadLocal,
5130 C.getTargetAddressSpace(LangAS::cuda_shared));
5131 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5132 GV, CGM.VoidPtrTy);
5133 for (const GlobalPtrSizeRecsTy *Rec : SharedRecs) {
5134 Rec->Buffer->replaceAllUsesWith(Replacement);
5135 Rec->Buffer->eraseFromParent();
5136 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005137 }
5138 StaticRD->completeDefinition();
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005139 if (!StaticRD->field_empty()) {
5140 QualType StaticTy = C.getRecordType(StaticRD);
5141 std::pair<unsigned, unsigned> SMsBlockPerSM = getSMsBlocksPerSM(CGM);
5142 llvm::APInt Size1(32, SMsBlockPerSM.second);
5143 QualType Arr1Ty =
Richard Smith772e2662019-10-04 01:25:59 +00005144 C.getConstantArrayType(StaticTy, Size1, nullptr, ArrayType::Normal,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005145 /*IndexTypeQuals=*/0);
5146 llvm::APInt Size2(32, SMsBlockPerSM.first);
Richard Smith772e2662019-10-04 01:25:59 +00005147 QualType Arr2Ty =
5148 C.getConstantArrayType(Arr1Ty, Size2, nullptr, ArrayType::Normal,
5149 /*IndexTypeQuals=*/0);
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005150 llvm::Type *LLVMArr2Ty = CGM.getTypes().ConvertTypeForMem(Arr2Ty);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005151 // FIXME: nvlink does not handle weak linkage correctly (object with the
5152 // different size are reported as erroneous).
5153 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005154 auto *GV = new llvm::GlobalVariable(
5155 CGM.getModule(), LLVMArr2Ty,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005156 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev09c9eea2018-11-09 16:18:04 +00005157 llvm::Constant::getNullValue(LLVMArr2Ty),
5158 "_openmp_static_glob_rd_$_");
5159 auto *Replacement = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
5160 GV, CGM.VoidPtrTy);
5161 for (const GlobalPtrSizeRecsTy *Rec : GlobalRecs) {
5162 Rec->Buffer->replaceAllUsesWith(Replacement);
5163 Rec->Buffer->eraseFromParent();
5164 }
5165 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005166 }
Alexey Bataev8061acd2019-02-20 16:36:22 +00005167 if (!TeamsReductions.empty()) {
5168 ASTContext &C = CGM.getContext();
5169 RecordDecl *StaticRD = C.buildImplicitRecord(
5170 "_openmp_teams_reduction_type_$_", RecordDecl::TagKind::TTK_Union);
5171 StaticRD->startDefinition();
5172 for (const RecordDecl *TeamReductionRec : TeamsReductions) {
5173 QualType RecTy = C.getRecordType(TeamReductionRec);
5174 auto *Field = FieldDecl::Create(
5175 C, StaticRD, SourceLocation(), SourceLocation(), nullptr, RecTy,
5176 C.getTrivialTypeSourceInfo(RecTy, SourceLocation()),
5177 /*BW=*/nullptr, /*Mutable=*/false,
5178 /*InitStyle=*/ICIS_NoInit);
5179 Field->setAccess(AS_public);
5180 StaticRD->addDecl(Field);
5181 }
5182 StaticRD->completeDefinition();
5183 QualType StaticTy = C.getRecordType(StaticRD);
5184 llvm::Type *LLVMReductionsBufferTy =
5185 CGM.getTypes().ConvertTypeForMem(StaticTy);
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005186 // FIXME: nvlink does not handle weak linkage correctly (object with the
5187 // different size are reported as erroneous).
5188 // Restore CommonLinkage as soon as nvlink is fixed.
Alexey Bataev8061acd2019-02-20 16:36:22 +00005189 auto *GV = new llvm::GlobalVariable(
5190 CGM.getModule(), LLVMReductionsBufferTy,
Alexey Bataev7b3eabd2019-03-13 18:21:10 +00005191 /*isConstant=*/false, llvm::GlobalValue::InternalLinkage,
Alexey Bataev8061acd2019-02-20 16:36:22 +00005192 llvm::Constant::getNullValue(LLVMReductionsBufferTy),
5193 "_openmp_teams_reductions_buffer_$_");
5194 KernelTeamsReductionPtr->setInitializer(
5195 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
5196 CGM.VoidPtrTy));
5197 }
Alexey Bataeve4090182018-11-02 14:54:07 +00005198 CGOpenMPRuntime::clear();
5199}